]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiApplication.cpp
ed201301a7de9784091ab41560d8e4ead8e4923a
[features.git] / src / frontends / qt / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
21 #include "GuiView.h"
22 #include "Menus.h"
23 #include "qt_helpers.h"
24 #include "Toolbars.h"
25
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
30
31 #include "Buffer.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
35 #include "CmdDef.h"
36 #include "Color.h"
37 #include "Converter.h"
38 #include "Cursor.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
41 #include "Font.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
45 #include "Intl.h"
46 #include "KeyMap.h"
47 #include "Language.h"
48 #include "LaTeXPackages.h"
49 #include "Lexer.h"
50 #include "LyX.h"
51 #include "LyXAction.h"
52 #include "LyXRC.h"
53 #include "Paragraph.h"
54 #include "Server.h"
55 #include "Session.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
58 #include "version.h"
59
60 #include "insets/InsetText.h"
61
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/environment.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/ForkedCalls.h"
70 #include "support/gettext.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/lyxalgo.h" // sorted
74 #include "support/textutils.h"
75 #include "support/Messages.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/TempFile.h"
79
80 #ifdef Q_OS_MAC
81 #include "support/AppleScript.h"
82 #include "support/AppleSupport.h"
83 #include "support/linkback/LinkBackProxy.h"
84 #endif
85
86 #include <queue>
87 #include <tuple>
88
89 #include <QByteArray>
90 #include <QBitmap>
91 #include <QDateTime>
92 #if QT_VERSION < 0x060000
93 #include <QDesktopWidget>
94 #endif
95 #include <QEvent>
96 #include <QFileOpenEvent>
97 #include <QFileInfo>
98 #include <QFontDatabase>
99 #include <QHash>
100 #include <QIcon>
101 #include <QImageReader>
102 #include <QKeyEvent>
103 #include <QLocale>
104 #include <QLibraryInfo>
105 #include <QList>
106 #include <QMenuBar>
107 #include <QMimeData>
108 #include <QObject>
109 #include <QPainter>
110 #include <QPixmap>
111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
112 #include <QRandomGenerator>
113 #endif
114 #include <QRegExp>
115 #include <QSessionManager>
116 #include <QSettings>
117 #include <QSocketNotifier>
118 #include <QSortFilterProxyModel>
119 #include <QStandardItemModel>
120 #include <QTimer>
121 #include <QTranslator>
122 #include <QThreadPool>
123 #include <QWidget>
124
125 #ifdef Q_WS_X11
126 #include <X11/Xatom.h>
127 #include <X11/Xlib.h>
128 #include <QX11Info>
129 #undef CursorShape
130 #undef None
131 #elif defined(QPA_XCB)
132 #include <xcb/xcb.h>
133 #ifdef HAVE_QT5_X11_EXTRAS
134 #include <QtX11Extras/QX11Info>
135 #endif
136 #endif
137
138 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
139 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
140 #if (QT_VERSION < 0x050000)
141 #include <QWindowsMime>
142 #define QWINDOWSMIME QWindowsMime
143 #define QVARIANTTYPE QVariant::Type
144 #elif (QT_VERSION >= 0x060000)
145 #include <QtGui/private/qguiapplication_p.h>
146 #include <QtGui/private/qwindowsmime_p.h>
147 #include <QtGui/qpa/qplatformintegration.h>
148 #define QWINDOWSMIME QWindowsMime
149 #define QVARIANTTYPE QMetaType
150 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
151 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
152 #else
153 #include <QWinMime>
154 #define QWINDOWSMIME QWinMime
155 #define QVARIANTTYPE QVariant::Type
156 #endif
157 #ifdef Q_CC_GNU
158 #include <wtypes.h>
159 #endif
160 #include <objidl.h>
161 #endif
162 #endif
163
164 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
165 #include <QMacPasteboardMime>
166 #endif // Q_OS_MAC
167
168 #include <exception>
169 #include <sstream>
170 #include <vector>
171
172 using namespace std;
173 using namespace lyx::support;
174
175
176 namespace lyx {
177
178 frontend::Application * createApplication(int & argc, char * argv[])
179 {
180 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
181         // prune -geometry argument(s) by shifting
182         // the following ones 2 places down.
183         for (int i = 0 ; i < argc ; ++i) {
184                 if (strcmp(argv[i], "-geometry") == 0) {
185                         int const remove = (i+1) < argc ? 2 : 1;
186                         argc -= remove;
187                         for (int j = i; j < argc; ++j)
188                                 argv[j] = argv[j + remove];
189                         --i;
190                 }
191         }
192 #endif
193
194 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
195         // On Windows, allow bringing the LyX window to top
196         AllowSetForegroundWindow(ASFW_ANY);
197 #endif
198
199
200 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
201 // macOS does it by itself.
202 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
203 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
204     // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
205     if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
206                 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
207         QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
208 #endif
209
210 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
211     // HighDPI scale factor policy must be set before QGuiApplication is created
212     if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
213         QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
214 #endif
215 #endif
216
217         frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
218         // I'd rather do that in the constructor, but I do not think that
219         // the palette is accessible there.
220         guiApp->colorCache().setPalette(guiApp->palette());
221         return guiApp;
222 }
223
224
225 void setLocale()
226 {
227         QLocale theLocale;
228         string code;
229         if (lyxrc.gui_language == "auto") {
230                 theLocale = QLocale::system();
231                 code = fromqstr(theLocale.name());
232         } else {
233                 Language const * l = languages.getLanguage(lyxrc.gui_language);
234                 code = l ? l->code() : "C";
235                 theLocale = QLocale(toqstr(code));
236         }
237         // Qt tries to outsmart us and transforms en_US to C.
238         Messages::guiLanguage((code == "C") ? "en_US" : code);
239         QLocale::setDefault(theLocale);
240         setlocale(LC_NUMERIC, "C");
241 }
242
243
244 namespace frontend {
245
246
247 /// Return the list of loadable formats.
248 vector<string> loadableImageFormats()
249 {
250         vector<string> fmts;
251
252         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
253
254         LYXERR(Debug::GRAPHICS,
255                 "\nThe image loader can load the following directly:\n");
256
257         if (qt_formats.empty())
258                 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
259
260         bool jpeg_found = false;
261         bool jpg_found = false;
262         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
263
264                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
265
266                 string ext = ascii_lowercase((const char *) *it);
267                 // special case
268                 if (ext == "jpeg") {
269                         jpeg_found = true;
270                         if (jpg_found)
271                                 continue;
272                         ext = "jpg";
273                 }
274                 else if (ext == "jpg") {
275                         jpg_found = true;
276                         if (jpeg_found)
277                                 continue;
278                 }
279                 else if (lyxrc.use_converter_cache &&
280                          (ext == "svg" || ext == "svgz") &&
281                           theConverters().isReachable("svg", "png"))
282                         // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
283                         // the SVG as in the output. However we require that the converter
284                         // cache is enabled since this is expensive. We also require that
285                         // an explicit svg->png converter is defined, since the default
286                         // converter could produce bad quality as well. This assumes that
287                         // png can always be loaded.
288                         continue;
289                 fmts.push_back(ext);
290         }
291
292         return fmts;
293 }
294
295
296 ////////////////////////////////////////////////////////////////////////
297 //
298 // Icon loading support code
299 //
300 ////////////////////////////////////////////////////////////////////////
301
302 namespace {
303
304 struct ImgMap {
305         QString key;
306         QString value;
307 };
308
309
310 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
311 {
312         return lhs.key < rhs.key;
313 }
314
315
316 class CompareKey {
317 public:
318         CompareKey(QString const & name) : name_(name) {}
319         bool operator()(ImgMap const & other) const { return other.key == name_; }
320 private:
321         QString const name_;
322 };
323
324
325 // this must be sorted alphabetically
326 // Upper case comes before lower case
327 // Please don't change the formatting, this list is parsed by
328 // development/tools/generate_symbols_images.py.
329 ImgMap sorted_img_map[] = {
330         { "Arrownot", "arrownot2"},
331         { "Arrowvert", "arrowvert2"},
332         { "Bowtie", "bowtie2" },
333         { "Box", "box2" },
334         { "Bumpeq", "bumpeq2" },
335         { "CIRCLE", "circle3" },
336         { "Cap", "cap2" },
337         { "CheckedBox", "checkedbox2" },
338         { "Circle", "circle2" },
339         { "Colonapprox", "colonapprox2" },
340         { "Coloneq", "coloneq2" },
341         { "Coloneqq", "coloneqq2" },
342         { "Colonsim", "colonsim2" },
343         { "Cup", "cup2" },
344         { "DOWNarrow", "downarrow3" },
345         { "Delta", "delta2" },
346         { "Diamond", "diamond2" },
347         { "Doteq", "doteq2" },
348         { "Downarrow", "downarrow2" },
349         { "Eqcolon", "eqcolon2" },
350         { "Eqqcolon", "eqqcolon2" },
351         { "Gamma", "gamma2" },
352         { "Join", "join2" },
353         { "LEFTCIRCLE", "leftcircle3" },
354         { "LEFTarrow", "leftarrow3" },
355         { "LEFTcircle", "leftcircle4" },
356         { "LHD", "lhd2" },
357         { "Lambda", "lambda2" },
358         { "Lbag", "lbag2"},
359         { "Leftarrow", "leftarrow2" },
360         { "Leftcircle", "leftcircle2" },
361         { "Leftrightarrow", "leftrightarrow2" },
362         { "Longarrownot", "longarrownot2"},
363         { "Longleftarrow", "longleftarrow2" },
364         { "Longleftrightarrow", "longleftrightarrow2" },
365         { "Longmapsfrom", "longmapsfrom2"},
366         { "Longmapsto", "longmapsto2"},
367         { "Longrightarrow", "longrightarrow2" },
368         { "Mapsfrom", "mapsfrom2"},
369         { "Mapsfromchar", "mapsfromchar2"},
370         { "Mapsto", "mapsto2"},
371         { "Mapstochar", "mapstochar2"},
372         { "Omega", "omega2" },
373         { "Phi", "phi2" },
374         { "Pi", "pi2" },
375         { "Psi", "psi2" },
376         { "RHD", "rhd2" },
377         { "RIGHTCIRCLE", "rightcircle3" },
378         { "RIGHTarrow", "rightarrow3" },
379         { "RIGHTcircle", "rightcircle4" },
380         { "Rbag", "rbag2"},
381         { "Rightarrow", "rightarrow2" },
382         { "Rightcircle", "rightcircle2" },
383         { "Sigma", "sigma2" },
384         { "Square", "square2" },
385         { "Subset", "subset2" },
386         { "Supset", "supset2" },
387         { "Theta", "theta2" },
388         { "Thorn", "thorn2" },
389         { "UParrow", "uparrow3" },
390         { "Uparrow", "uparrow2" },
391         { "Updownarrow", "updownarrow2" },
392         { "Upsilon", "upsilon2" },
393         { "Vdash", "vdash3" },
394         { "Vert", "vert2" },
395         { "XBox", "xbox3" },
396         { "Xbox", "xbox2" },
397         { "Xi", "xi2" },
398         { "lVert", "vert2" },
399         { "lvert", "vert" },
400         { "nLeftarrow", "nleftarrow2" },
401         { "nLeftrightarrow", "nleftrightarrow2" },
402         { "nRightarrow", "nrightarrow2" },
403         { "nVDash", "nvdash3" },
404         { "nVdash", "nvdash4" },
405         { "nvDash", "nvdash2" },
406         { "rVert", "vert2" },
407         { "rvert", "vert" },
408         { "textrm \\AA", "textrm_AA"},
409         { "textrm \\O", "textrm_O"},
410         { "vDash", "vdash2" },
411         { "varDelta", "vardelta2" },
412         { "varGamma", "vargamma2" },
413         { "varLambda", "varlambda2" },
414         { "varOmega", "varomega2" },
415         { "varPhi", "varphi2" },
416         { "varPi", "varpi2" },
417         { "varPsi", "varpsi2" },
418         { "varSigma", "varsigma2" },
419         { "varTheta", "vartheta2" },
420         { "varUpsilon", "varupsilon2" },
421         { "varXi", "varxi2" }
422 };
423
424
425 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
426
427 // This list specifies which system's theme icon is related to which lyx
428 // command. It was based on:
429 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
430 // this must be sorted alphabetically
431 // Upper case comes before lower case
432 ImgMap sorted_theme_icon_map[] = {
433         { "bookmark-goto 0", "go-jump" },
434         { "buffer-new", "document-new" },
435         { "buffer-write", "document-save" },
436         { "buffer-write-as", "document-save-as" },
437         { "buffer-zoom-in", "zoom-in" },
438         { "buffer-zoom-out", "zoom-out" },
439         { "copy", "edit-copy" },
440         { "cut", "edit-cut" },
441         { "depth-decrement", "format-indent-less" },
442         { "depth-increment", "format-indent-more" },
443         { "dialog-show spellchecker", "tools-check-spelling" },
444         { "dialog-show-new-inset graphics", "insert-image" },
445         { "dialog-toggle findreplaceadv", "edit-find-replace" },
446         { "file-open", "document-open" },
447         { "font-bold", "format-text-bold" },
448         { "font-ital", "format-text-italic" },
449         { "font-strikeout", "format-text-strikethrough" },
450         { "font-underline", "format-text-underline" },
451         { "lyx-quit", "application-exit" },
452         { "paste", "edit-paste" },
453         { "redo", "edit-redo" },
454         { "undo", "edit-undo" },
455         { "window-close", "window-close" },
456         { "window-new", "window-new" }
457 };
458
459 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
460
461
462 QString findImg(QString const & name)
463 {
464         ImgMap const * const begin = sorted_img_map;
465         ImgMap const * const end = begin + nr_sorted_img_map;
466         LATTEST(sorted(begin, end));
467
468         ImgMap const * const it = find_if(begin, end, CompareKey(name));
469
470         QString img_name;
471         if (it != end) {
472                 img_name = it->value;
473         } else {
474                 img_name = name;
475                 img_name.replace('_', "underscore");
476                 img_name.replace(' ', '_');
477
478                 // This way we can have "math-delim { }" on the toolbar.
479                 img_name.replace('(', "lparen");
480                 img_name.replace(')', "rparen");
481                 img_name.replace('[', "lbracket");
482                 img_name.replace(']', "rbracket");
483                 img_name.replace('{', "lbrace");
484                 img_name.replace('}', "rbrace");
485                 img_name.replace('|', "bars");
486                 img_name.replace(',', "thinspace");
487                 img_name.replace(':', "mediumspace");
488                 img_name.replace(';', "thickspace");
489                 img_name.replace('!', "negthinspace");
490         }
491
492         LYXERR(Debug::GUI, "findImg(" << name << ")\n"
493                 << "Looking for math icon called \"" << img_name << '"');
494         return img_name;
495 }
496
497 } // namespace
498
499
500 QString themeIconName(QString const & action)
501 {
502         ImgMap const * const begin = sorted_theme_icon_map;
503         ImgMap const * const end = begin + nr_sorted_theme_icon_map;
504         LASSERT(sorted(begin, end), /**/);
505
506         ImgMap const * const it = find_if(begin, end, CompareKey(action));
507
508         if (it != end)
509                 return it->value;
510         return QString();
511 }
512
513
514 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
515 {
516         IconInfo res;
517
518         QStringList names;
519         QString lfunname = toqstr(lyxaction.getActionName(f.action()));
520
521         if (!f.argument().empty()) {
522                 // if there are arguments, first search an icon which name is the full thing
523                 QString name = lfunname  + ' ' + toqstr(f.argument());
524                 name.replace(' ', '_');
525                 name.replace(';', '_');
526                 name.replace('\\', "backslash");
527                 // avoid duplication for these
528                 name.replace("dialog-toggle", "dialog-show");
529                 names << name;
530
531                 // then special default icon for some lfuns
532                 switch (f.action()) {
533                 case LFUN_MATH_INSERT:
534                         names <<  "math/" + findImg(toqstr(f.argument()).mid(1));
535                         break;
536                 case LFUN_MATH_DELIM:
537                 case LFUN_MATH_BIGDELIM:
538                         names << "math/" + findImg(toqstr(f.argument()));
539                         break;
540                 case LFUN_CALL:
541                         names << "commands/" + toqstr(f.argument());
542                         break;
543                 case LFUN_COMMAND_ALTERNATIVES: {
544                         // use the first of the alternative commands
545                         docstring firstcom;
546                         docstring dummy = split(f.argument(), firstcom, ';');
547                         QString name1 = toqstr(firstcom);
548                         name1.replace(' ', '_');
549                         name1.replace(';', '_');
550                         name1.replace('\\', "backslash");
551                         names << name1;
552                         break;
553                 }
554                 default:
555                         break;
556                 }
557         }
558
559         // next thing to try is function name alone
560         names << lfunname;
561
562         // and finally maybe the unknown icon
563         if (unknown)
564                 names << "unknown";
565
566         search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
567         // The folders where icons are searched for
568         QStringList imagedirs;
569         imagedirs << "images/ipa/" << "images/";
570         // This is used to search for rtl version of icons which have the +rtl suffix.
571         QStringList suffixes;
572         if (rtl)
573                 suffixes << "+rtl";
574         suffixes << QString();
575
576         for (QString const & imagedir : imagedirs)
577                 for (QString const & name : names)
578                         for (QString const & suffix : suffixes) {
579                                 QString id = imagedir;
580                                 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
581                                 if (fname.exists()) {
582                                         docstring const fpath = fname.absoluteFilePath();
583                                         res.filepath = toqstr(fname.absFileName());
584                                         // these icons are subject to inversion in dark mode
585                                         res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
586                                                       || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
587                                         res.swap = rtl && suffix.isEmpty();
588                                         return res;
589                                 }
590                         }
591
592         LYXERR(Debug::GUI, "Cannot find icon for command \""
593                            << lyxaction.getActionName(f.action())
594                            << '(' << to_utf8(f.argument()) << ")\"");
595
596         return res;
597 }
598
599
600 QPixmap prepareForDarkMode(QPixmap pixmap)
601 {
602         QPalette palette = QPalette();
603         QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
604         QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
605
606         // guess whether we are in dark mode
607         if (text_color.black() > bg_color.black())
608                 // not in dark mode, do nothing
609                 return pixmap;
610
611         // create a layer with black text turned to QPalette::WindowText
612         QPixmap black_overlay(pixmap.size());
613         black_overlay.fill(text_color);
614         black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
615
616         // create a layer with blue text turned to lighter blue
617         QPixmap blue_overlay(pixmap.size());
618         QColor math_blue(0, 0, 255);
619         blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
620         blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
621
622         // create a layer with ("latex") red text turned to lighter red
623         QPixmap red_overlay(pixmap.size());
624         QColor math_red(128, 0, 0);
625         red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
626         red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
627
628         // put layers on top of existing pixmap
629         QPainter painter(&pixmap);
630         painter.drawPixmap(pixmap.rect(), black_overlay);
631         painter.drawPixmap(pixmap.rect(), blue_overlay);
632         painter.drawPixmap(pixmap.rect(), red_overlay);
633
634         return pixmap;
635 }
636
637
638 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
639 {
640         QString imagedir = path;
641         FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
642         QString fpath = toqstr(fname.absFileName());
643         QPixmap pixmap = QPixmap();
644
645         if (pixmap.load(fpath)) {
646                 if (fpath.contains("math") || fpath.contains("ipa")
647                     || fpath.contains("bullets"))
648                         return prepareForDarkMode(pixmap);
649                 return pixmap;
650         }
651
652         bool const list = ext.contains(",");
653         LYXERR(Debug::GUI, "Cannot load pixmap \""
654                         << path << "/" << name << "." << (list ? "{" : "") << ext
655                 << (list ? "}" : "") << "\".");
656
657         return QPixmap();
658 }
659
660
661 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
662 {
663 #if (QT_VERSION >= 0x040600)
664         if (lyxrc.use_system_theme_icons) {
665                 // use the icons from system theme that are available
666                 QString action = toqstr(lyxaction.getActionName(f.action()));
667                 if (!f.argument().empty())
668                         action += " " + toqstr(f.argument());
669                 QString const theme_icon = themeIconName(action);
670                 if (QIcon::hasThemeIcon(theme_icon)) {
671                         QIcon const thmicn = QIcon::fromTheme(theme_icon);
672                         if (!thmicn.isNull())
673                                 return thmicn;
674                 }
675         }
676 #endif
677
678         IconInfo icondata = iconInfo(f, unknown, rtl);
679         if (icondata.filepath.isEmpty())
680                 return QIcon();
681
682         //LYXERR(Debug::GUI, "Found icon: " << icon);
683         QPixmap pixmap = QPixmap();
684         if (!pixmap.load(icondata.filepath)) {
685                 LYXERR0("Cannot load icon " << icondata.filepath << ".");
686                 return QIcon();
687         }
688
689         if (icondata.invert)
690                 pixmap = prepareForDarkMode(pixmap);
691
692         if (icondata.swap)
693                 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
694         else
695                 return QIcon(pixmap);
696 }
697
698
699 ////////////////////////////////////////////////////////////////////////
700 //
701 // LyX server support code.
702 //
703 ////////////////////////////////////////////////////////////////////////
704
705 class SocketNotifier : public QSocketNotifier
706 {
707 public:
708         /// connect a connection notification from the LyXServerSocket
709         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
710                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
711         {}
712
713 public:
714         /// The callback function
715         Application::SocketCallback func_;
716 };
717
718
719 class GuiTranslator : public QTranslator
720 {
721 public:
722         GuiTranslator(QObject * parent = nullptr)
723                 : QTranslator(parent)
724         {}
725
726         QString translate(const char * /* context */,
727                 const char *sourceText,
728 #if QT_VERSION >= 0x050000
729                 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
730 #else
731                 const char * /*comment*/ = 0) const override
732 #endif
733         {
734                 // Here we declare the strings that need to be translated from Qt own GUI
735                 // This is needed to include these strings to po files
736                 _("About %1");
737                 _("Preferences");
738                 _("Reconfigure");
739                 _("Restore Defaults");
740                 _("Quit %1");
741                 _("&OK");
742                 // Already in po: "Cancel", "&Cancel"
743                 _("Apply"); // Already in po: "&Apply"
744                 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
745                 _("Open");
746
747                 docstring s = getGuiMessages().getIfFound(sourceText);
748                 // This test should eventually be removed when translations are updated
749                 if (s.empty())
750                         LYXERR(Debug::LOCALE, "Missing translation for `"
751                                << string(sourceText) << "'");
752                 return toqstr(s);
753         }
754 };
755
756
757 ////////////////////////////////////////////////////////////////////////
758 //
759 // Mac specific stuff goes here...
760 //
761 ////////////////////////////////////////////////////////////////////////
762
763 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
764 // QMacPasteboardMimeGraphics can only be compiled on Mac.
765
766 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
767 {
768 public:
769         QMacPasteboardMimeGraphics()
770                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
771         {}
772
773         QString convertorName() { return "Graphics"; }
774
775         QString flavorFor(QString const & mime)
776         {
777                 LYXERR(Debug::ACTION, "flavorFor " << mime);
778                 if (mime == pdfMimeType())
779                         return QLatin1String("com.adobe.pdf");
780                 return QString();
781         }
782
783         QString mimeFor(QString flav)
784         {
785                 LYXERR(Debug::ACTION, "mimeFor " << flav);
786                 if (flav == QLatin1String("com.adobe.pdf"))
787                         return pdfMimeType();
788                 return QString();
789         }
790
791         bool canConvert(QString const & mime, QString flav)
792         {
793                 return mimeFor(flav) == mime;
794         }
795
796         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
797                 QString /*flav*/)
798         {
799                 if(data.count() > 1)
800                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
801                 return data.first();
802         }
803
804         QList<QByteArray> convertFromMime(QString const & /*mime*/,
805                 QVariant data, QString /*flav*/)
806         {
807                 QList<QByteArray> ret;
808                 ret.append(data.toByteArray());
809                 return ret;
810         }
811 };
812 #endif
813
814 ///////////////////////////////////////////////////////////////
815 //
816 // You can find more platform specific stuff at the end of this file...
817 //
818 ///////////////////////////////////////////////////////////////
819
820 ////////////////////////////////////////////////////////////////////////
821 // Windows specific stuff goes here...
822
823 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
824 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
825 // QWindowsMimeMetafile can only be compiled on Windows.
826
827 static FORMATETC cfFromMime(QString const & mimetype)
828 {
829         FORMATETC formatetc;
830         if (mimetype == emfMimeType()) {
831                 formatetc.cfFormat = CF_ENHMETAFILE;
832                 formatetc.tymed = TYMED_ENHMF;
833         } else if (mimetype == wmfMimeType()) {
834                 formatetc.cfFormat = CF_METAFILEPICT;
835                 formatetc.tymed = TYMED_MFPICT;
836         }
837         formatetc.ptd = 0;
838         formatetc.dwAspect = DVASPECT_CONTENT;
839         formatetc.lindex = -1;
840         return formatetc;
841 }
842
843
844 class QWindowsMimeMetafile : public QWINDOWSMIME {
845 public:
846         QWindowsMimeMetafile() {}
847
848         bool canConvertFromMime(FORMATETC const & /*formatetc*/,
849                 QMimeData const * /*mimedata*/) const override
850         {
851                 return false;
852         }
853
854         bool canConvertToMime(QString const & mimetype,
855                 IDataObject * pDataObj) const override
856         {
857                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
858                         return false;
859                 FORMATETC formatetc = cfFromMime(mimetype);
860                 return pDataObj->QueryGetData(&formatetc) == S_OK;
861         }
862
863         bool convertFromMime(FORMATETC const & /*formatetc*/,
864                 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
865         {
866                 return false;
867         }
868
869         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
870                 QVARIANTTYPE /*preferredType*/) const override
871         {
872                 QByteArray data;
873                 if (!canConvertToMime(mimetype, pDataObj))
874                         return data;
875
876                 FORMATETC formatetc = cfFromMime(mimetype);
877                 STGMEDIUM s;
878                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
879                         return data;
880
881                 int dataSize;
882                 if (s.tymed == TYMED_ENHMF) {
883                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
884                         data.resize(dataSize);
885                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
886                                 (LPBYTE)data.data());
887                 } else if (s.tymed == TYMED_MFPICT) {
888                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
889                         data.resize(dataSize);
890                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
891                                 (LPBYTE)data.data());
892                 }
893                 data.detach();
894                 ReleaseStgMedium(&s);
895
896                 return data;
897         }
898
899
900         QVector<FORMATETC> formatsForMime(QString const & mimetype,
901                 QMimeData const * /*mimedata*/) const override
902         {
903                 QVector<FORMATETC> formats;
904                 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
905                         formats += cfFromMime(mimetype);
906                 return formats;
907         }
908
909         QString mimeForFormat(FORMATETC const & formatetc) const override
910         {
911                 switch (formatetc.cfFormat) {
912                 case CF_ENHMETAFILE:
913                         return emfMimeType();
914                 case CF_METAFILEPICT:
915                         return wmfMimeType();
916                 }
917                 return QString();
918         }
919 };
920
921 #endif
922 #endif
923
924
925 /// Allows to check whether ESC was pressed during a long operation
926 class KeyChecker : public QObject {
927 private:
928         bool pressed_;
929         bool started_;
930 public:
931         KeyChecker() : pressed_(false), started_(false) {}
932
933         void start() {
934                 QCoreApplication::instance()->installEventFilter(this);
935                 pressed_ = false;
936                 started_ = true;
937         }
938         void stop() {
939                 QCoreApplication::instance()->removeEventFilter(this);
940                 started_ = false;
941         }
942         bool pressed() {
943                 QCoreApplication::processEvents();
944                 return pressed_;
945         }
946         bool started() const {
947                 return started_;
948         }
949         bool eventFilter(QObject *obj, QEvent *event) override {
950                 LYXERR(Debug::ACTION, "Event Type: " << event->type());
951                 switch (event->type()) {
952                 case QEvent::Show:
953                 case QEvent::Hide:
954                 case QEvent::Resize:
955                 case QEvent::UpdateRequest:
956                 case QEvent::CursorChange:
957                 case QEvent::ActionChanged:
958                 case QEvent::EnabledChange:
959                 case QEvent::SockAct:
960                 case QEvent::Timer:
961                 case QEvent::Paint:
962                 case QEvent::ToolTipChange:
963                 case QEvent::LayoutRequest:
964                 case QEvent::MetaCall:
965                         return QObject::eventFilter(obj, event);
966                 default:
967                         // FIXME Blocking all these events is a bad idea.
968                         QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
969                         if (keyEvent && keyEvent->key() == Qt::Key_Escape)
970                                 pressed_ = true;
971                         return true;
972                 }
973         }
974 };
975
976
977 ////////////////////////////////////////////////////////////////////////
978 // GuiApplication::Private definition and implementation.
979 ////////////////////////////////////////////////////////////////////////
980
981 struct GuiApplication::Private
982 {
983         Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
984                 global_menubar_(nullptr)
985         #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
986                 , last_state_(Qt::ApplicationInactive)
987         #endif
988         {
989         #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
990         #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
991                 /// WMF Mime handler for Windows clipboard.
992                 wmf_mime_ = new QWindowsMimeMetafile;
993         #if (QT_VERSION >= 0x060000)
994                 win_app_ = dynamic_cast<QWindowsApplication *>
995                         (QGuiApplicationPrivate::platformIntegration());
996                 win_app_->registerMime(wmf_mime_);
997         #endif
998         #endif
999         #endif
1000                 initKeySequences(&theTopLevelKeymap());
1001         }
1002
1003         #if (QT_VERSION >= 0x060000)
1004         #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1005         ~Private()
1006         {
1007                 win_app_->unregisterMime(wmf_mime_);
1008         }
1009         #endif
1010         #endif
1011
1012         void initKeySequences(KeyMap * kb)
1013         {
1014                 keyseq = KeySequence(kb, kb);
1015                 cancel_meta_seq = KeySequence(kb, kb);
1016         }
1017
1018         ///
1019         QSortFilterProxyModel * language_model_;
1020         ///
1021         GuiClipboard clipboard_;
1022         ///
1023         GuiSelection selection_;
1024         ///
1025         FontLoader font_loader_;
1026         ///
1027         ColorCache color_cache_;
1028         /// the built-in Qt translation mechanism
1029         QTranslator qt_trans_;
1030         /// LyX gettext-based translation for Qt elements
1031         GuiTranslator gui_trans_;
1032         ///
1033         QHash<int, SocketNotifier *> socket_notifiers_;
1034         ///
1035         Menus menus_;
1036         ///
1037         /// The global instance
1038         Toolbars toolbars_;
1039
1040         /// this timer is used for any regular events one wants to
1041         /// perform. at present it is used to check if forked processes
1042         /// are done.
1043         QTimer general_timer_;
1044
1045         /// delayed FuncRequests
1046         std::queue<FuncRequest> func_request_queue_;
1047
1048         ///
1049         KeySequence keyseq;
1050         ///
1051         KeySequence cancel_meta_seq;
1052         ///
1053         KeyModifier meta_fake_bit;
1054
1055         /// The result of last dispatch action
1056         DispatchResult dispatch_result_;
1057
1058         /// Multiple views container.
1059         /**
1060         * Warning: This must not be a smart pointer as the destruction of the
1061         * object is handled by Qt when the view is closed
1062         * \sa Qt::WA_DeleteOnClose attribute.
1063         */
1064         QHash<int, GuiView *> views_;
1065
1066         /// Only used on mac.
1067         QMenuBar * global_menubar_;
1068 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1069         /// Holds previous application state on Mac
1070         Qt::ApplicationState last_state_;
1071 #endif
1072
1073 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1074         /// Linkback mime handler for MacOSX.
1075         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1076 #endif
1077
1078 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1079 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1080         /// WMF Mime handler for Windows clipboard.
1081         QWindowsMimeMetafile * wmf_mime_;
1082 #if (QT_VERSION >= 0x060000)
1083         QWindowsApplication * win_app_;
1084 #endif
1085 #endif
1086 #endif
1087
1088         /// Allows to check whether ESC was pressed during a long operation
1089         KeyChecker key_checker_;
1090 };
1091
1092
1093 GuiApplication * guiApp;
1094
1095 GuiApplication::~GuiApplication()
1096 {
1097 #ifdef Q_OS_MAC
1098         closeAllLinkBackLinks();
1099 #endif
1100         delete d;
1101 }
1102
1103
1104 GuiApplication::GuiApplication(int & argc, char ** argv)
1105         : QApplication(argc, argv), current_view_(nullptr),
1106           d(new GuiApplication::Private)
1107 {
1108         QString app_name = "LyX";
1109         QCoreApplication::setOrganizationName(app_name);
1110         QCoreApplication::setOrganizationDomain("lyx.org");
1111         QCoreApplication::setApplicationName(lyx_package);
1112 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
1113         QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1114 #endif
1115
1116 #if QT_VERSION >= 0x050700
1117         setDesktopFileName(lyx_package);
1118 #endif
1119
1120 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1121         QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1122 #else
1123         qsrand(QDateTime::currentDateTime().toTime_t());
1124 #endif
1125
1126         // Install LyX translator for missing Qt translations
1127         installTranslator(&d->gui_trans_);
1128         // Install Qt native translator for GUI elements.
1129         installTranslator(&d->qt_trans_);
1130
1131 #ifdef QPA_XCB
1132         // Enable reception of XCB events.
1133         installNativeEventFilter(this);
1134 #endif
1135
1136         // FIXME: quitOnLastWindowClosed is true by default. We should have a
1137         // lyxrc setting for this in order to let the application stay resident.
1138         // But then we need some kind of dock icon, at least on Windows.
1139         /*
1140         if (lyxrc.quit_on_last_window_closed)
1141                 setQuitOnLastWindowClosed(false);
1142         */
1143 #ifdef Q_OS_MAC
1144         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1145         // seems to be the default case for applications like LyX.
1146         setQuitOnLastWindowClosed(false);
1147         ///
1148         setupApplescript();
1149         appleCleanupEditMenu();
1150         appleCleanupViewMenu();
1151 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1152         connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1153                         this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1154 #endif
1155 #endif
1156
1157 #if defined(Q_WS_X11) || defined(QPA_XCB)
1158         // doubleClickInterval() is 400 ms on X11 which is just too long.
1159         // On Windows and Mac OS X, the operating system's value is used.
1160         // On Microsoft Windows, calling this function sets the double
1161         // click interval for all applications. So we don't!
1162         QApplication::setDoubleClickInterval(300);
1163 #endif
1164
1165         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1166
1167         // needs to be done before reading lyxrc
1168         QWidget w;
1169         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1170
1171         guiApp = this;
1172
1173         // Initialize RC Fonts
1174         if (lyxrc.roman_font_name.empty())
1175                 lyxrc.roman_font_name = fromqstr(romanFontName());
1176
1177         if (lyxrc.sans_font_name.empty())
1178                 lyxrc.sans_font_name = fromqstr(sansFontName());
1179
1180         if (lyxrc.typewriter_font_name.empty())
1181                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1182
1183 #if (QT_VERSION >= 0x050000)
1184         // Qt4 does this in event(), see below.
1185         // Track change of keyboard
1186         connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1187 #endif
1188
1189         d->general_timer_.setInterval(500);
1190         connect(&d->general_timer_, SIGNAL(timeout()),
1191                 this, SLOT(handleRegularEvents()));
1192         d->general_timer_.start();
1193
1194         // maxThreadCount() defaults in general to 2 on single or dual-processor.
1195         // This is clearly not enough in a time where we use threads for
1196         // document preview and/or export. 20 should be OK.
1197         QThreadPool::globalInstance()->setMaxThreadCount(20);
1198
1199         // make sure tooltips are formatted
1200         installEventFilter(new ToolTipFormatter(this));
1201 }
1202
1203
1204 GuiApplication * theGuiApp()
1205 {
1206         return dynamic_cast<GuiApplication *>(theApp());
1207 }
1208
1209
1210 #if QT_VERSION < 0x050000
1211 // Emulate platformName() for Qt4
1212
1213 // FIXME: when ditching this method, remove all tests
1214 //     platformName() == "qt4x11"
1215 // in the code
1216 QString GuiApplication::platformName() const
1217 {
1218 # if defined(Q_WS_X11)
1219         // Note that this one does not really exist
1220         return "qt4x11";
1221 # elif defined(Q_OS_MAC)
1222         return "cocoa";
1223 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1224         return "windows";
1225 # else
1226         LYXERR0("Unknown platform!");
1227         return "unknown";
1228 # endif
1229 }
1230 #endif
1231
1232
1233 double GuiApplication::pixelRatio() const
1234 {
1235 #if QT_VERSION >= 0x050000
1236         return qt_scale_factor * devicePixelRatio();
1237 #else
1238         return 1.0;
1239 #endif
1240 }
1241
1242
1243 void GuiApplication::clearSession()
1244 {
1245         QSettings settings;
1246         settings.clear();
1247 }
1248
1249
1250 docstring Application::iconName(FuncRequest const & f, bool unknown)
1251 {
1252         return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1253 }
1254
1255
1256 docstring Application::mathIcon(docstring const & c)
1257 {
1258         return qstring_to_ucs4(findImg(toqstr(c)));
1259 }
1260
1261
1262 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1263 {
1264         FuncStatus status;
1265
1266         BufferView * bv = nullptr;
1267         BufferView * doc_bv = nullptr;
1268
1269         if (cmd.action() == LFUN_NOACTION) {
1270                 status.message(from_utf8(N_("Nothing to do")));
1271                 status.setEnabled(false);
1272         }
1273
1274         else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1275                 status.setUnknown(true);
1276                 status.message(from_utf8(N_("Unknown action")));
1277                 status.setEnabled(false);
1278         }
1279
1280         // Does the GuiApplication know something?
1281         else if (getStatus(cmd, status)) { }
1282
1283         // If we do not have a GuiView, then other functions are disabled
1284         else if (!current_view_)
1285                 status.setEnabled(false);
1286
1287         // Does the GuiView know something?
1288         else if (current_view_->getStatus(cmd, status)) { }
1289
1290         // In LyX/Mac, when a dialog is open, the menus of the
1291         // application can still be accessed without giving focus to
1292         // the main window. In this case, we want to disable the menu
1293         // entries that are buffer or view-related.
1294         //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1295         /*
1296         else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1297                 status.setEnabled(false);
1298         */
1299
1300         // If we do not have a BufferView, then other functions are disabled
1301         else if (!(bv = current_view_->currentBufferView()))
1302                 status.setEnabled(false);
1303
1304         // Does the current BufferView know something?
1305         else if (bv->getStatus(cmd, status)) { }
1306
1307         // Does the current Buffer know something?
1308         else if (bv->buffer().getStatus(cmd, status)) { }
1309
1310         // If we do not have a document BufferView, different from the
1311         // current BufferView, then other functions are disabled
1312         else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1313                 status.setEnabled(false);
1314
1315         // Does the document Buffer know something?
1316         else if (doc_bv->buffer().getStatus(cmd, status)) { }
1317
1318         else {
1319                 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1320                 status.message(from_utf8(N_("Command not handled")));
1321                 status.setEnabled(false);
1322         }
1323
1324         // the default error message if we disable the command
1325         if (!status.enabled() && status.message().empty())
1326                 status.message(from_utf8(N_("Command disabled")));
1327
1328         return status;
1329 }
1330
1331
1332 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1333 {
1334         // I would really like to avoid having this switch and rather try to
1335         // encode this in the function itself.
1336         // -- And I'd rather let an inset decide which LFUNs it is willing
1337         // to handle (Andre')
1338         bool enable = true;
1339         switch (cmd.action()) {
1340
1341         // This could be used for the no-GUI version. The GUI version is handled in
1342         // GuiView::getStatus(). See above.
1343         /*
1344         case LFUN_BUFFER_WRITE:
1345         case LFUN_BUFFER_WRITE_AS:
1346         case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1347                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1348                 enable = b && (b->isUnnamed() || !b->isClean());
1349                 break;
1350         }
1351         */
1352
1353         case LFUN_BOOKMARK_GOTO: {
1354                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1355                 enable = theSession().bookmarks().isValid(num);
1356                 break;
1357         }
1358
1359         case LFUN_BOOKMARK_CLEAR:
1360                 enable = theSession().bookmarks().hasValid();
1361                 break;
1362
1363         // this one is difficult to get right. As a half-baked
1364         // solution, we consider only the first action of the sequence
1365         case LFUN_COMMAND_SEQUENCE: {
1366                 // argument contains ';'-terminated commands
1367                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1368                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1369                 func.setOrigin(cmd.origin());
1370                 flag = getStatus(func);
1371                 break;
1372         }
1373
1374         // we want to check if at least one of these is enabled
1375         case LFUN_COMMAND_ALTERNATIVES: {
1376                 // argument contains ';'-terminated commands
1377                 string arg = to_utf8(cmd.argument());
1378                 while (!arg.empty()) {
1379                         string first;
1380                         arg = split(arg, first, ';');
1381                         FuncRequest func(lyxaction.lookupFunc(first));
1382                         func.setOrigin(cmd.origin());
1383                         flag = getStatus(func);
1384                         // if this one is enabled, the whole thing is
1385                         if (flag.enabled())
1386                                 break;
1387                 }
1388                 break;
1389         }
1390
1391         case LFUN_CALL: {
1392                 FuncRequest func;
1393                 string name = to_utf8(cmd.argument());
1394                 if (theTopLevelCmdDef().lock(name, func)) {
1395                         func.setOrigin(cmd.origin());
1396                         flag = getStatus(func);
1397                         theTopLevelCmdDef().release(name);
1398                 } else {
1399                         // catch recursion or unknown command
1400                         // definition. all operations until the
1401                         // recursion or unknown command definition
1402                         // occurs are performed, so set the state to
1403                         // enabled
1404                         enable = true;
1405                 }
1406                 break;
1407         }
1408
1409         case LFUN_IF_RELATIVES: {
1410                 string const lfun = to_utf8(cmd.argument());
1411                 BufferView const * bv =
1412                         current_view_ ? current_view_->currentBufferView() : nullptr;
1413                 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1414                         enable = false;
1415                         break;
1416                 }
1417                 FuncRequest func(lyxaction.lookupFunc(lfun));
1418                 func.setOrigin(cmd.origin());
1419                 flag = getStatus(func);
1420                 break;
1421         }
1422
1423         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1424         case LFUN_REPEAT:
1425         case LFUN_PREFERENCES_SAVE:
1426         case LFUN_BUFFER_SAVE_AS_DEFAULT:
1427                 // these are handled in our dispatch()
1428                 break;
1429
1430         case LFUN_DEBUG_LEVEL_SET: {
1431                 string bad = Debug::badValue(to_utf8(cmd.argument()));
1432                 enable = bad.empty();
1433                 if (!bad.empty())
1434                         flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1435                 break;
1436         }
1437
1438         case LFUN_WINDOW_CLOSE:
1439                 enable = !d->views_.empty();
1440                 break;
1441
1442         case LFUN_BUFFER_NEW:
1443         case LFUN_BUFFER_NEW_TEMPLATE:
1444         case LFUN_FILE_OPEN:
1445         case LFUN_LYXFILES_OPEN:
1446         case LFUN_HELP_OPEN:
1447         case LFUN_SCREEN_FONT_UPDATE:
1448         case LFUN_SET_COLOR:
1449         case LFUN_WINDOW_NEW:
1450         case LFUN_LYX_QUIT:
1451         case LFUN_LYXRC_APPLY:
1452         case LFUN_COMMAND_PREFIX:
1453         case LFUN_CANCEL:
1454         case LFUN_META_PREFIX:
1455         case LFUN_RECONFIGURE:
1456         case LFUN_SERVER_GET_FILENAME:
1457         case LFUN_SERVER_NOTIFY:
1458                 enable = true;
1459                 break;
1460
1461         case LFUN_BUFFER_FORALL: {
1462                 if (theBufferList().empty()) {
1463                         flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1464                         flag.setEnabled(false);
1465                         break;
1466                 }
1467
1468                 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1469                 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1470                         flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1471                         flag.setEnabled(false);
1472                 }
1473                 break;
1474         }
1475
1476         case LFUN_DIALOG_SHOW: {
1477                 string const name = cmd.getArg(0);
1478                 return name == "aboutlyx"
1479                         || name == "lyxfiles"
1480                         || name == "prefs"
1481                         || name == "texinfo"
1482                         || name == "progress"
1483                         || name == "compare";
1484         }
1485
1486         default:
1487                 return false;
1488         }
1489
1490         if (!enable)
1491                 flag.setEnabled(false);
1492         return true;
1493 }
1494
1495 /// make a post-dispatch status message
1496 static docstring makeDispatchMessage(docstring const & msg,
1497                                      FuncRequest const & cmd)
1498 {
1499         const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1500                               || cmd.origin() == FuncRequest::TOOLBAR
1501                               || cmd.origin() == FuncRequest::COMMANDBUFFER);
1502
1503         if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1504                 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1505                 return msg;
1506         }
1507
1508         docstring dispatch_msg = msg;
1509         if (!dispatch_msg.empty())
1510                 dispatch_msg += ' ';
1511
1512         docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1513
1514         bool argsadded = false;
1515
1516         if (!cmd.argument().empty()) {
1517                 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1518                         comname += ' ' + cmd.argument();
1519                         argsadded = true;
1520                 }
1521         }
1522         docstring const shortcuts = theTopLevelKeymap().
1523                 printBindings(cmd, KeySequence::ForGui);
1524
1525         if (!shortcuts.empty())
1526                 comname += ": " + shortcuts;
1527         else if (!argsadded && !cmd.argument().empty())
1528                 comname += ' ' + cmd.argument();
1529
1530         if (!comname.empty()) {
1531                 comname = rtrim(comname);
1532                 dispatch_msg += '(' + rtrim(comname) + ')';
1533         }
1534         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1535         return dispatch_msg;
1536 }
1537
1538
1539 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1540 {
1541         DispatchResult dr;
1542
1543         Buffer * buffer = nullptr;
1544         if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1545                 //setCurrentView(cmd.view_origin); //does not work
1546                 dr.setError(true);
1547                 dr.setMessage(_("Wrong focus!"));
1548                 d->dispatch_result_ = dr;
1549                 return d->dispatch_result_;
1550         }
1551         if (current_view_ && current_view_->currentBufferView()) {
1552                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1553                 buffer = &current_view_->currentBufferView()->buffer();
1554         }
1555
1556         dr.screenUpdate(Update::FitCursor);
1557         {
1558                 // All the code is kept inside the undo group because
1559                 // updateBuffer can create undo actions (see #11292)
1560                 UndoGroupHelper ugh(buffer);
1561                 dispatch(cmd, dr);
1562                 if (dr.screenUpdate() & Update::ForceAll) {
1563                         for (Buffer const * b : theBufferList())
1564                                 b->changed(true);
1565                         dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1566                 }
1567
1568                 updateCurrentView(cmd, dr);
1569         }
1570
1571         d->dispatch_result_ = dr;
1572         return d->dispatch_result_;
1573 }
1574
1575
1576 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1577 {
1578         if (!current_view_)
1579                 return;
1580
1581         BufferView * bv = current_view_->currentBufferView();
1582         if (bv) {
1583                 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1584                         bv->cursor().clearBufferUpdate();
1585                         bv->buffer().updateBuffer();
1586                 }
1587                 // BufferView::update() updates the ViewMetricsInfo and
1588                 // also initializes the position cache for all insets in
1589                 // (at least partially) visible top-level paragraphs.
1590                 // We will redraw the screen only if needed.
1591                 bv->processUpdateFlags(dr.screenUpdate());
1592
1593                 // Do we have a selection?
1594                 theSelection().haveSelection(bv->cursor().selection());
1595
1596                 // update gui
1597                 current_view_->restartCaret();
1598         }
1599         if (dr.needMessageUpdate()) {
1600                 // Some messages may already be translated, so we cannot use _()
1601                 current_view_->message(makeDispatchMessage(
1602                                 translateIfPossible(dr.message()), cmd));
1603         }
1604 }
1605
1606
1607 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1608         bool switchToBuffer)
1609 {
1610         if (!theSession().bookmarks().isValid(idx))
1611                 return;
1612         BookmarksSection::Bookmark const & bm =
1613                 theSession().bookmarks().bookmark(idx);
1614         LASSERT(!bm.filename.empty(), return);
1615         string const file = bm.filename.absFileName();
1616         // if the file is not opened, open it.
1617         if (!theBufferList().exists(bm.filename)) {
1618                 if (openFile)
1619                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1620                 else
1621                         return;
1622         }
1623         // open may fail, so we need to test it again
1624         if (!theBufferList().exists(bm.filename))
1625                 return;
1626
1627         // bm can be changed when saving
1628         BookmarksSection::Bookmark tmp = bm;
1629
1630         // Special case idx == 0 used for back-from-back jump navigation
1631         if (idx == 0)
1632                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1633
1634         // if the current buffer is not that one, switch to it.
1635         BufferView * doc_bv = current_view_ ?
1636                 current_view_->documentBufferView() : nullptr;
1637         Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1638         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1639                 if (switchToBuffer) {
1640                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1641                         if (!current_view_)
1642                                 return;
1643                         doc_bv = current_view_->documentBufferView();
1644                 } else
1645                         return;
1646         }
1647
1648         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1649         if (!doc_bv || !doc_bv->moveToPosition(
1650                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1651                 return;
1652
1653         Cursor & cur = doc_bv->cursor();
1654         if (old && cur != *old)
1655                 notifyCursorLeavesOrEnters(*old, cur);
1656
1657         // bm changed
1658         if (idx == 0)
1659                 return;
1660
1661         // Cursor jump succeeded!
1662         pit_type new_pit = cur.pit();
1663         pos_type new_pos = cur.pos();
1664         int new_id = cur.paragraph().id();
1665
1666         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1667         // see http://www.lyx.org/trac/ticket/3092
1668         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1669                 || bm.top_id != new_id) {
1670                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1671                         new_pit, new_pos, new_id);
1672         }
1673 }
1674
1675 // This function runs "configure" and then rereads lyx.defaults to
1676 // reconfigure the automatic settings.
1677 void GuiApplication::reconfigure(string const & option)
1678 {
1679         // emit message signal.
1680         if (current_view_) {
1681                 current_view_->message(_("Running configure..."));
1682                 current_view_->setCursor(Qt::WaitCursor);
1683         }
1684
1685         // Run configure in user lyx directory
1686         string const lock_file = package().getConfigureLockName();
1687         int fd = fileLock(lock_file.c_str());
1688         int const ret = package().reconfigureUserLyXDir(option);
1689         // emit message signal.
1690         if (current_view_)
1691                 current_view_->message(_("Reloading configuration..."));
1692         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1693         // Re-read packages.lst
1694         LaTeXPackages::getAvailable();
1695         fileUnlock(fd, lock_file.c_str());
1696
1697         if (current_view_)
1698                 current_view_->unsetCursor();
1699
1700         if (ret)
1701                 Alert::information(_("System reconfiguration failed"),
1702                            _("The system reconfiguration has failed.\n"
1703                                   "Default textclass is used but LyX may\n"
1704                                   "not be able to work properly.\n"
1705                                   "Please reconfigure again if needed."));
1706         else
1707                 Alert::information(_("System reconfigured"),
1708                            _("The system has been reconfigured.\n"
1709                              "You need to restart LyX to make use of any\n"
1710                              "updated document class specifications."));
1711 }
1712
1713 void GuiApplication::validateCurrentView()
1714 {
1715         if (!d->views_.empty() && !current_view_) {
1716                 // currently at least one view exists but no view has the focus.
1717                 // choose the last view to make it current.
1718                 // a view without any open document is preferred.
1719                 GuiView * candidate = nullptr;
1720                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1721                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1722                 for (; it != end; ++it) {
1723                         candidate = *it;
1724                         if (!candidate->documentBufferView())
1725                                 break;
1726                 }
1727                 setCurrentView(candidate);
1728         }
1729 }
1730
1731 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1732 {
1733         string const argument = to_utf8(cmd.argument());
1734         FuncCode const action = cmd.action();
1735
1736         LYXERR(Debug::ACTION, "cmd: " << cmd);
1737
1738         // we have not done anything wrong yet.
1739         dr.setError(false);
1740
1741         FuncStatus const flag = getStatus(cmd);
1742         if (!flag.enabled()) {
1743                 // We cannot use this function here
1744                 LYXERR(Debug::ACTION, "action "
1745                        << lyxaction.getActionName(action)
1746                        << " [" << action << "] is disabled at this location");
1747                 dr.setMessage(flag.message());
1748                 dr.setError(true);
1749                 dr.dispatched(false);
1750                 dr.screenUpdate(Update::None);
1751                 dr.clearBufferUpdate();
1752                 return;
1753         };
1754
1755         if (cmd.origin() == FuncRequest::LYXSERVER) {
1756                 if (current_view_ && current_view_->currentBufferView())
1757                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1758                 // we will also need to redraw the screen at the end
1759                 dr.screenUpdate(Update::FitCursor);
1760         }
1761
1762         // Assumes that the action will be dispatched.
1763         dr.dispatched(true);
1764
1765         switch (cmd.action()) {
1766
1767         case LFUN_WINDOW_NEW:
1768                 createView(toqstr(cmd.argument()));
1769                 break;
1770
1771         case LFUN_WINDOW_CLOSE:
1772                 // FIXME: this is done also in GuiView::closeBuffer()!
1773                 // update bookmark pit of the current buffer before window close
1774                 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1775                         gotoBookmark(i, false, false);
1776                 // clear the last opened list, because
1777                 // maybe this will end the session
1778                 theSession().lastOpened().clear();
1779                 // check for valid current_view_
1780                 validateCurrentView();
1781                 if (current_view_)
1782                         current_view_->closeScheduled();
1783                 break;
1784
1785         case LFUN_LYX_QUIT:
1786                 // quitting is triggered by the gui code
1787                 // (leaving the event loop).
1788                 if (current_view_)
1789                         current_view_->message(from_utf8(N_("Exiting.")));
1790                 if (closeAllViews())
1791                         quit();
1792                 break;
1793
1794         case LFUN_SCREEN_FONT_UPDATE: {
1795                 // handle the screen font changes.
1796                 /* FIXME: this only updates the current document, whereas all
1797                  * documents should see their metrics updated.
1798                  */
1799                 d->font_loader_.update();
1800                 dr.screenUpdate(Update::Force | Update::FitCursor);
1801                 break;
1802         }
1803
1804         case LFUN_BUFFER_NEW:
1805                 validateCurrentView();
1806                 if (!current_view_
1807                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1808                         createView(QString(), false); // keep hidden
1809                         current_view_->newDocument(to_utf8(cmd.argument()));
1810                         current_view_->show();
1811                         setActiveWindow(current_view_);
1812                 } else {
1813                         current_view_->newDocument(to_utf8(cmd.argument()));
1814                 }
1815                 break;
1816
1817         case LFUN_BUFFER_NEW_TEMPLATE: {
1818                 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1819                 string const temp = cmd.getArg(1);
1820                 validateCurrentView();
1821                 if (!current_view_
1822                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1823                         createView();
1824                         current_view_->newDocument(file, temp, true);
1825                         if (!current_view_->documentBufferView())
1826                                 current_view_->close();
1827                 } else {
1828                         current_view_->newDocument(file, temp, true);
1829                 }
1830                 break;
1831         }
1832
1833         case LFUN_FILE_OPEN: {
1834                 // FIXME: normally the code below is not needed, since getStatus makes sure that
1835                 //   current_view_ is not null.
1836                 validateCurrentView();
1837                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1838                 string const fname = trim(to_utf8(cmd.argument()), "\"");
1839                 bool const is_open = FileName::isAbsolute(fname)
1840                         && theBufferList().getBuffer(FileName(fname));
1841                 if (!current_view_
1842                     || (!lyxrc.open_buffers_in_tabs
1843                         && current_view_->documentBufferView() != nullptr
1844                         && !is_open)) {
1845                         // We want the ui session to be saved per document and not per
1846                         // window number. The filename crc is a good enough identifier.
1847                         createView(support::checksum(fname));
1848                         current_view_->openDocument(fname);
1849                         if (!current_view_->documentBufferView())
1850                                 current_view_->close();
1851                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1852                                 current_view_->raise();
1853                                 current_view_->activateWindow();
1854                                 current_view_->showNormal();
1855                         }
1856                 } else {
1857                         current_view_->openDocument(fname);
1858                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1859                                 current_view_->raise();
1860                                 current_view_->activateWindow();
1861                                 current_view_->showNormal();
1862                         }
1863                 }
1864                 break;
1865         }
1866
1867         case LFUN_HELP_OPEN: {
1868                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1869                 if (current_view_ == nullptr)
1870                         createView();
1871                 string const arg = to_utf8(cmd.argument());
1872                 if (arg.empty()) {
1873                         current_view_->message(_("Missing argument"));
1874                         break;
1875                 }
1876                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1877                 if (fname.empty())
1878                         fname = i18nLibFileSearch("examples", arg, "lyx");
1879
1880                 if (fname.empty()) {
1881                         lyxerr << "LyX: unable to find documentation file `"
1882                                << arg << "'. Bad installation?" << endl;
1883                         break;
1884                 }
1885                 current_view_->message(bformat(_("Opening help file %1$s..."),
1886                                                makeDisplayPath(fname.absFileName())));
1887                 Buffer * buf = current_view_->loadDocument(fname, false);
1888                 if (buf)
1889                         buf->setReadonly(!current_view_->develMode());
1890                 break;
1891         }
1892
1893         case LFUN_LYXFILES_OPEN: {
1894                 // This is the actual reason for this method (#12106).
1895                 validateCurrentView();
1896                 if (!current_view_
1897                    || (!lyxrc.open_buffers_in_tabs
1898                        && current_view_->documentBufferView() != nullptr))
1899                         createView();
1900                 string arg = to_utf8(cmd.argument());
1901                 if (arg.empty())
1902                         // set default
1903                         arg = "templates";
1904                 if (arg != "templates" && arg != "examples") {
1905                         current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1906                         break;
1907                 }
1908                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1909                 break;
1910         }
1911
1912         case LFUN_SET_COLOR: {
1913                 string const lyx_name = cmd.getArg(0);
1914                 string x11_name = cmd.getArg(1);
1915                 string x11_darkname = cmd.getArg(2);
1916                 if (lyx_name.empty() || x11_name.empty()) {
1917                         if (current_view_)
1918                                 current_view_->message(
1919                                         _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1920                         break;
1921                 }
1922
1923 #if 0
1924                 // FIXME: The graphics cache no longer has a changeDisplay method.
1925                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1926                 bool const graphicsbg_changed =
1927                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1928                 if (graphicsbg_changed)
1929                         graphics::GCache::get().changeDisplay(true);
1930 #endif
1931
1932                 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1933                         x11_darkname = x11_name;
1934                         x11_name.clear();
1935                 }
1936                 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1937                         if (current_view_)
1938                                 current_view_->message(
1939                                         bformat(_("Set-color \"%1$s\" failed "
1940                                         "- color is undefined or "
1941                                         "may not be redefined"),
1942                                         from_utf8(lyx_name)));
1943                         break;
1944                 }
1945                 // Make sure we don't keep old colors in cache.
1946                 d->color_cache_.clear();
1947                 // Update the current view
1948                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1949                 break;
1950         }
1951
1952         case LFUN_LYXRC_APPLY: {
1953                 // reset active key sequences, since the bindings
1954                 // are updated (bug 6064)
1955                 d->keyseq.reset();
1956                 LyXRC const lyxrc_orig = lyxrc;
1957
1958                 istringstream ss(to_utf8(cmd.argument()));
1959                 bool const success = lyxrc.read(ss);
1960
1961                 if (!success) {
1962                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1963                                         << "Unable to read lyxrc data"
1964                                         << endl;
1965                         break;
1966                 }
1967
1968                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1969
1970                 // If the request comes from the minibuffer, then we can't reset
1971                 // the GUI, since that would destroy the minibuffer itself and
1972                 // cause a crash, since we are currently in one of the methods of
1973                 // GuiCommandBuffer. See bug #8540.
1974                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1975                         resetGui();
1976                 // else
1977                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1978                 //   reset the GUI in this case. If the changes to lyxrc affected the
1979                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1980                 //   it definitely is a bug.
1981
1982                 dr.forceBufferUpdate();
1983                 break;
1984         }
1985
1986         case LFUN_COMMAND_PREFIX:
1987                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1988                 break;
1989
1990         case LFUN_CANCEL: {
1991                 d->keyseq.reset();
1992                 d->meta_fake_bit = NoModifier;
1993                 GuiView * gv = currentView();
1994                 if (gv && gv->currentBufferView())
1995                         // cancel any selection
1996                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1997                 dr.setMessage(from_ascii(N_("Cancel")));
1998                 break;
1999         }
2000         case LFUN_META_PREFIX:
2001                 d->meta_fake_bit = AltModifier;
2002                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2003                 break;
2004
2005         // --- Menus -----------------------------------------------
2006         case LFUN_RECONFIGURE:
2007                 // argument is any additional parameter to the configure.py command
2008                 reconfigure(to_utf8(cmd.argument()));
2009                 break;
2010
2011         // --- lyxserver commands ----------------------------
2012         case LFUN_SERVER_GET_FILENAME: {
2013                 if (current_view_ && current_view_->documentBufferView()) {
2014                         docstring const fname = from_utf8(
2015                                 current_view_->documentBufferView()->buffer().absFileName());
2016                         dr.setMessage(fname);
2017                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2018                 } else {
2019                         dr.setMessage(docstring());
2020                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2021                 }
2022                 break;
2023         }
2024
2025         case LFUN_SERVER_NOTIFY: {
2026                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2027                 dr.setMessage(dispatch_buffer);
2028                 theServer().notifyClient(to_utf8(dispatch_buffer));
2029                 break;
2030         }
2031
2032         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2033                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2034                 break;
2035
2036         case LFUN_REPEAT: {
2037                 // repeat command
2038                 string countstr;
2039                 string rest = split(argument, countstr, ' ');
2040                 int const count = convert<int>(countstr);
2041                 // an arbitrary number to limit number of iterations
2042                 int const max_iter = 10000;
2043                 if (count > max_iter) {
2044                         dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2045                         dr.setError(true);
2046                 } else {
2047                         for (int i = 0; i < count; ++i) {
2048                                 FuncRequest lfun = lyxaction.lookupFunc(rest);
2049                                 lfun.allowAsync(false);
2050                                 dispatch(lfun);
2051                         }
2052                 }
2053                 break;
2054         }
2055
2056         case LFUN_COMMAND_SEQUENCE: {
2057                 // argument contains ';'-terminated commands
2058                 string arg = argument;
2059                 // FIXME: this LFUN should also work without any view.
2060                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2061                                   ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2062                 // This handles undo groups automagically
2063                 UndoGroupHelper ugh(buffer);
2064                 while (!arg.empty()) {
2065                         string first;
2066                         arg = split(arg, first, ';');
2067                         FuncRequest func(lyxaction.lookupFunc(first));
2068                         func.allowAsync(false);
2069                         func.setOrigin(cmd.origin());
2070                         dispatch(func);
2071                 }
2072                 break;
2073         }
2074
2075         case LFUN_BUFFER_FORALL: {
2076                 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2077                 funcToRun.allowAsync(false);
2078
2079                 map<Buffer *, GuiView *> views_lVisible;
2080                 map<GuiView *, Buffer *> activeBuffers;
2081
2082                 QList<GuiView *> allViews = d->views_.values();
2083
2084                 // this for does not modify any buffer. It just collects info on local
2085                 // visibility of buffers and on which buffer is active in each view.
2086                 Buffer * const last = theBufferList().last();
2087                 for(GuiView * view : allViews) {
2088                         // all of the buffers might be locally hidden. That is, there is no
2089                         // active buffer.
2090                         if (!view || !view->currentBufferView())
2091                                 activeBuffers[view] = nullptr;
2092                         else
2093                                 activeBuffers[view] = &view->currentBufferView()->buffer();
2094
2095                         // find out if each is locally visible or locally hidden.
2096                         // we don't use a for loop as the buffer list cycles.
2097                         Buffer * b = theBufferList().first();
2098                         while (true) {
2099                                 bool const locallyVisible = view && view->workArea(*b);
2100                                 if (locallyVisible) {
2101                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2102                                         // only need to overwrite/add if we don't already know a buffer is globally
2103                                         // visible or we do know but we would prefer to dispatch LFUN from the
2104                                         // current view because of cursor position issues.
2105                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2106                                                 views_lVisible[b] = view;
2107                                 }
2108                                 if (b == last)
2109                                         break;
2110                                 b = theBufferList().next(b);
2111                         }
2112                 }
2113
2114                 GuiView * const homeView = currentView();
2115                 Buffer * b = theBufferList().first();
2116                 Buffer * nextBuf = nullptr;
2117                 int numProcessed = 0;
2118                 while (true) {
2119                         if (b != last)
2120                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2121
2122                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2123                         if (visible) {
2124                                 // first change to a view where b is locally visible, preferably current_view_.
2125                                 GuiView * const vLv = views_lVisible[b];
2126                                 vLv->setBuffer(b);
2127                                 lyx::dispatch(funcToRun);
2128                                 numProcessed++;
2129                         }
2130                         if (b == last)
2131                                 break;
2132                         b = nextBuf;
2133                 }
2134
2135                 // put things back to how they were (if possible).
2136                 for (GuiView * view : allViews) {
2137                         Buffer * originalBuf = activeBuffers[view];
2138                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2139                         if (theBufferList().isLoaded(originalBuf))
2140                                 view->setBuffer(originalBuf);
2141                 }
2142                 homeView->setFocus();
2143
2144                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2145                 break;
2146         }
2147
2148         case LFUN_COMMAND_ALTERNATIVES: {
2149                 // argument contains ';'-terminated commands
2150                 string arg = argument;
2151                 while (!arg.empty()) {
2152                         string first;
2153                         arg = split(arg, first, ';');
2154                         FuncRequest func(lyxaction.lookupFunc(first));
2155                         func.setOrigin(cmd.origin());
2156                         FuncStatus const stat = getStatus(func);
2157                         if (stat.enabled()) {
2158                                 dispatch(func);
2159                                 break;
2160                         }
2161                 }
2162                 break;
2163         }
2164
2165         case LFUN_CALL: {
2166                 FuncRequest func;
2167                 if (theTopLevelCmdDef().lock(argument, func)) {
2168                         func.setOrigin(cmd.origin());
2169                         dispatch(func);
2170                         theTopLevelCmdDef().release(argument);
2171                 } else {
2172                         if (func.action() == LFUN_UNKNOWN_ACTION) {
2173                                 // unknown command definition
2174                                 lyxerr << "Warning: unknown command definition `"
2175                                                 << argument << "'"
2176                                                 << endl;
2177                         } else {
2178                                 // recursion detected
2179                                 lyxerr << "Warning: Recursion in the command definition `"
2180                                                 << argument << "' detected"
2181                                                 << endl;
2182                         }
2183                 }
2184                 break;
2185         }
2186
2187         case LFUN_IF_RELATIVES: {
2188                 string const lfun = to_utf8(cmd.argument());
2189                 FuncRequest func(lyxaction.lookupFunc(lfun));
2190                 func.setOrigin(cmd.origin());
2191                 FuncStatus const stat = getStatus(func);
2192                 if (stat.enabled()) {
2193                         dispatch(func);
2194                         break;
2195                 }
2196                 break;
2197         }
2198
2199         case LFUN_PREFERENCES_SAVE:
2200                 lyxrc.write(support::makeAbsPath("preferences",
2201                         package().user_support().absFileName()), false);
2202                 break;
2203
2204         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2205                 string const fname = addName(addPath(package().user_support().absFileName(),
2206                         "templates/"), "defaults.lyx");
2207                 Buffer defaults(fname);
2208
2209                 istringstream ss(argument);
2210                 Lexer lex;
2211                 lex.setStream(ss);
2212
2213                 // See #9236
2214                 // We need to make sure that, after we recreat the DocumentClass,
2215                 // which we do in readHeader, we apply it to the document itself.
2216                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2217                 int const unknown_tokens = defaults.readHeader(lex);
2218                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2219                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2220                 cap::switchBetweenClasses(olddc, newdc, theinset);
2221
2222                 if (unknown_tokens != 0) {
2223                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2224                                << unknown_tokens << " unknown token"
2225                                << (unknown_tokens == 1 ? "" : "s")
2226                                << endl;
2227                 }
2228
2229                 if (defaults.writeFile(FileName(defaults.absFileName())))
2230                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2231                                               makeDisplayPath(fname)));
2232                 else {
2233                         dr.setError(true);
2234                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2235                 }
2236                 break;
2237         }
2238
2239         case LFUN_BOOKMARK_GOTO:
2240                 // go to bookmark, open unopened file and switch to buffer if necessary
2241                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2242                 dr.screenUpdate(Update::Force | Update::FitCursor);
2243                 break;
2244
2245         case LFUN_BOOKMARK_CLEAR:
2246                 theSession().bookmarks().clear();
2247                 dr.screenUpdate(Update::Force);
2248                 break;
2249
2250         case LFUN_DEBUG_LEVEL_SET:
2251                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2252                 break;
2253
2254         case LFUN_DIALOG_SHOW: {
2255                 string const name = cmd.getArg(0);
2256
2257                 if ( name == "aboutlyx"
2258                         || name == "prefs"
2259                         || name == "texinfo"
2260                         || name == "progress"
2261                         || name == "compare")
2262                 {
2263                         // work around: on Mac OS the application
2264                         // is not terminated when closing the last view.
2265                         // Create a new one to be able to dispatch the
2266                         // LFUN_DIALOG_SHOW to this view.
2267                         if (current_view_ == nullptr)
2268                                 createView();
2269                 }
2270         }
2271         // fall through
2272         default:
2273                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2274                 // let's try that:
2275                 if (current_view_)
2276                         current_view_->dispatch(cmd, dr);
2277                 break;
2278         }
2279
2280         if (current_view_ && current_view_->isFullScreen()) {
2281                 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2282                         current_view_->menuBar()->hide();
2283         }
2284
2285         if (cmd.origin() == FuncRequest::LYXSERVER)
2286                 updateCurrentView(cmd, dr);
2287 }
2288
2289
2290 docstring GuiApplication::viewStatusMessage()
2291 {
2292         // When meta-fake key is pressed, show the key sequence so far + "M-".
2293         if (d->meta_fake_bit != NoModifier)
2294                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2295
2296         // Else, when a non-complete key sequence is pressed,
2297         // show the available options.
2298         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2299                 return d->keyseq.printOptions(true);
2300
2301         return docstring();
2302 }
2303
2304
2305 string GuiApplication::inputLanguageCode() const
2306 {
2307 #if (QT_VERSION < 0x050000)
2308         QLocale loc = keyboardInputLocale();
2309 #else
2310         QLocale loc = inputMethod()->locale();
2311 #endif
2312         //LYXERR0("input lang = " << fromqstr(loc.name()));
2313         return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2314 }
2315
2316
2317 void GuiApplication::onLocaleChanged()
2318 {
2319         //LYXERR0("Change language to " << inputLanguage()->lang());
2320         if (currentView() && currentView()->currentBufferView())
2321                 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2322 }
2323
2324
2325 void GuiApplication::handleKeyFunc(FuncCode action)
2326 {
2327         char_type c = 0;
2328
2329         if (d->keyseq.length())
2330                 c = 0;
2331         GuiView * gv = currentView();
2332         LASSERT(gv && gv->currentBufferView(), return);
2333         BufferView * bv = gv->currentBufferView();
2334         bv->getIntl().getTransManager().deadkey(
2335                 c, get_accent(action).accent, bv->cursor().innerText(),
2336                 bv->cursor());
2337         // Need to clear, in case the minibuffer calls these
2338         // actions
2339         d->keyseq.clear();
2340         // copied verbatim from do_accent_char
2341         bv->cursor().resetAnchor();
2342 }
2343
2344
2345 //Keep this in sync with GuiApplication::processKeySym below
2346 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2347                                  KeyModifier state) const
2348 {
2349         // Do nothing if we have nothing
2350         if (!keysym.isOK() || keysym.isModifier())
2351                 return false;
2352         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2353         KeySequence seq;
2354         FuncRequest func = seq.addkey(keysym, state);
2355         // When not cancel or meta-fake, do the normal lookup.
2356         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2357                 seq = d->keyseq;
2358                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2359         }
2360         // Maybe user can only reach the key via holding down shift.
2361         // Let's see. But only if shift is the only modifier
2362         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2363                 // If addkey looked up a command and did not find further commands then
2364                 // seq has been reset at this point
2365                 func = seq.addkey(keysym, NoModifier);
2366
2367         LYXERR(Debug::KEY, " Key (queried) [action="
2368                << lyxaction.getActionName(func.action()) << "]["
2369                << seq.print(KeySequence::Portable) << ']');
2370         return func.action() != LFUN_UNKNOWN_ACTION;
2371 }
2372
2373
2374 //Keep this in sync with GuiApplication::queryKeySym above
2375 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2376 {
2377         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2378
2379         // Do nothing if we have nothing (JMarc)
2380         if (!keysym.isOK() || keysym.isModifier()) {
2381                 if (!keysym.isOK())
2382                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2383                 if (current_view_)
2384                         current_view_->restartCaret();
2385                 return;
2386         }
2387
2388         char_type encoded_last_key = keysym.getUCSEncoded();
2389
2390         // Do a one-deep top-level lookup for
2391         // cancel and meta-fake keys. RVDK_PATCH_5
2392         d->cancel_meta_seq.reset();
2393
2394         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2395         LYXERR(Debug::KEY, "action first set to ["
2396                << lyxaction.getActionName(func.action()) << ']');
2397
2398         // When not cancel or meta-fake, do the normal lookup.
2399         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2400         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2401         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2402                 // remove Caps Lock and Mod2 as a modifiers
2403                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2404                 LYXERR(Debug::KEY, "action now set to ["
2405                        << lyxaction.getActionName(func.action()) << ']');
2406         }
2407
2408         // Don't remove this unless you know what you are doing.
2409         d->meta_fake_bit = NoModifier;
2410
2411         // Can this happen now ?
2412         if (func.action() == LFUN_NOACTION)
2413                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2414
2415         LYXERR(Debug::KEY, " Key [action="
2416                << lyxaction.getActionName(func.action()) << "]["
2417                << d->keyseq.print(KeySequence::Portable) << ']');
2418
2419         // already here we know if it any point in going further
2420         // why not return already here if action == -1 and
2421         // num_bytes == 0? (Lgb)
2422
2423         if (d->keyseq.length() > 1 && current_view_)
2424                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2425
2426
2427         // Maybe user can only reach the key via holding down shift.
2428         // Let's see. But only if shift is the only modifier
2429         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2430                 LYXERR(Debug::KEY, "Trying without shift");
2431                 // If addkey looked up a command and did not find further commands then
2432                 // seq has been reset at this point
2433                 func = d->keyseq.addkey(keysym, NoModifier);
2434                 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2435         }
2436
2437         if (func.action() == LFUN_UNKNOWN_ACTION) {
2438                 // We didn't match any of the key sequences.
2439                 // See if it's normal insertable text not already
2440                 // covered by a binding
2441                 if (keysym.isText() && d->keyseq.length() == 1) {
2442                         // Non-printable characters (such as ASCII control characters)
2443                         // must not be inserted (#5704)
2444                         if (!isPrintable(encoded_last_key)) {
2445                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2446                                 if (current_view_)
2447                                         current_view_->restartCaret();
2448                                 return;
2449                         }
2450                         // The following modifier check is not needed on Mac.
2451                         // The keysym is either not text or it is different
2452                         // from the non-modifier keysym. See #9875 for the
2453                         // broken alt-modifier effect of having this code active.
2454 #if !defined(Q_OS_MAC)
2455                         // If a non-Shift Modifier is used we have a non-bound key sequence
2456                         // (such as Alt+j = j). This should be omitted (#5575).
2457                         // On Windows, AltModifier and ControlModifier are both
2458                         // set when AltGr is pressed. Therefore, in order to not
2459                         // break AltGr-bound symbols (see #5575 for details),
2460                         // unbound Ctrl+Alt key sequences are allowed.
2461                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2462 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2463                             && !(state & AltModifier && state & ControlModifier)
2464 #endif
2465                             )
2466                         {
2467                                 if (current_view_) {
2468                                         current_view_->message(_("Unknown function."));
2469                                         current_view_->restartCaret();
2470                                 }
2471                                 return;
2472                         }
2473 #endif
2474                         // Since all checks above were passed, we now really have text that
2475                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2476                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2477                         // below.
2478                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2479                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2480                 } else {
2481                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2482                         if (current_view_) {
2483                                 current_view_->message(_("Unknown function."));
2484                                 current_view_->restartCaret();
2485                         }
2486                         return;
2487                 }
2488         }
2489
2490         if (func.action() == LFUN_SELF_INSERT) {
2491                 if (encoded_last_key != 0) {
2492                         docstring const arg(1, encoded_last_key);
2493                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2494                                              FuncRequest::KEYBOARD));
2495                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2496                 }
2497         } else
2498                 processFuncRequest(func);
2499 }
2500
2501
2502 void GuiApplication::processFuncRequest(FuncRequest const & func)
2503 {
2504         lyx::dispatch(func);
2505 }
2506
2507
2508 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2509 {
2510         addToFuncRequestQueue(func);
2511         processFuncRequestQueueAsync();
2512 }
2513
2514
2515 void GuiApplication::processFuncRequestQueue()
2516 {
2517         while (!d->func_request_queue_.empty()) {
2518                 // take the item from the stack _before_ processing the
2519                 // request in order to avoid race conditions from nested
2520                 // or parallel requests (see #10406)
2521                 FuncRequest const fr(d->func_request_queue_.front());
2522                 d->func_request_queue_.pop();
2523                 processFuncRequest(fr);
2524         }
2525 }
2526
2527
2528 void GuiApplication::processFuncRequestQueueAsync()
2529 {
2530         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2531 }
2532
2533
2534 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2535 {
2536         d->func_request_queue_.push(func);
2537 }
2538
2539
2540 void GuiApplication::resetGui()
2541 {
2542         // Set the language defined by the user.
2543         setGuiLanguage();
2544
2545         // Read menus
2546         if (!readUIFile(toqstr(lyxrc.ui_file)))
2547                 // Gives some error box here.
2548                 return;
2549
2550         if (d->global_menubar_)
2551                 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2552
2553         QHash<int, GuiView *>::iterator it;
2554         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2555                 GuiView * gv = *it;
2556                 setCurrentView(gv);
2557                 gv->setLayoutDirection(layoutDirection());
2558                 gv->resetDialogs();
2559         }
2560
2561         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2562 }
2563
2564
2565 bool GuiApplication::rtlContext() const
2566 {
2567         if (current_view_ && current_view_->currentBufferView()) {
2568                 BufferView const * bv = current_view_->currentBufferView();
2569                 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2570         } else
2571                 return layoutDirection() == Qt::RightToLeft;
2572 }
2573
2574
2575 void GuiApplication::createView(int view_id)
2576 {
2577         createView(QString(), true, view_id);
2578 }
2579
2580
2581 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2582         int view_id)
2583 {
2584         // release the keyboard which might have been grabbed by the global
2585         // menubar on Mac to catch shortcuts even without any GuiView.
2586         if (d->global_menubar_)
2587                 d->global_menubar_->releaseKeyboard();
2588
2589         // create new view
2590         int id = view_id;
2591         while (d->views_.find(id) != d->views_.end())
2592                 id++;
2593
2594         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2595         GuiView * view = new GuiView(id);
2596         // `view' is the new current_view_. Tell coverity that is is not 0.
2597         LATTEST(current_view_);
2598         // register view
2599         d->views_[id] = view;
2600
2601         if (autoShow) {
2602                 view->show();
2603                 setActiveWindow(view);
2604         }
2605
2606         if (!geometry_arg.isEmpty()) {
2607 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2608                 int x, y;
2609                 int w, h;
2610                 QChar sx, sy;
2611 #if QT_VERSION < 0x060000
2612                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2613                 re.indexIn(geometry_arg);
2614                 w = re.cap(1).toInt();
2615                 h = re.cap(2).toInt();
2616                 x = re.cap(3).toInt();
2617                 y = re.cap(4).toInt();
2618                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2619                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2620 #else
2621                 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2622                 QRegularExpressionMatch match = re.match(geometry_arg);
2623                 w = match.captured(1).toInt();
2624                 h = match.captured(2).toInt();
2625                 x = match.captured(3).toInt();
2626                 y = match.captured(4).toInt();
2627                 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2628                 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2629 #endif
2630                 // Set initial geometry such that we can get the frame size.
2631                 view->setGeometry(x, y, w, h);
2632                 int framewidth = view->geometry().x() - view->x();
2633                 int titleheight = view->geometry().y() - view->y();
2634                 // Negative displacements must be interpreted as distances
2635                 // from the right or bottom screen borders.
2636                 if (sx == '-' || sy == '-') {
2637 #if QT_VERSION < 0x060000
2638                         QRect rec = QApplication::desktop()->screenGeometry();
2639 #else
2640                         QRect rec = QGuiApplication::primaryScreen()->geometry();
2641 #endif
2642                         if (sx == '-')
2643                                 x += rec.width() - w - framewidth;
2644                         if (sy == '-')
2645                                 y += rec.height() - h - titleheight;
2646                         view->setGeometry(x, y, w, h);
2647                 }
2648                 // Make sure that the left and top frame borders are visible.
2649                 if (view->x() < 0 || view->y() < 0) {
2650                         if (view->x() < 0)
2651                                 x = framewidth;
2652                         if (view->y() < 0)
2653                                 y = titleheight;
2654                         view->setGeometry(x, y, w, h);
2655                 }
2656 #endif
2657         }
2658         view->setFocus();
2659 }
2660
2661
2662 bool GuiApplication::unhide(Buffer * buf)
2663 {
2664         if (!currentView())
2665                 return false;
2666         currentView()->setBuffer(buf, false);
2667         return true;
2668 }
2669
2670
2671 Clipboard & GuiApplication::clipboard()
2672 {
2673         return d->clipboard_;
2674 }
2675
2676
2677 Selection & GuiApplication::selection()
2678 {
2679         return d->selection_;
2680 }
2681
2682
2683 FontLoader & GuiApplication::fontLoader()
2684 {
2685         return d->font_loader_;
2686 }
2687
2688
2689 Toolbars const & GuiApplication::toolbars() const
2690 {
2691         return d->toolbars_;
2692 }
2693
2694
2695 Toolbars & GuiApplication::toolbars()
2696 {
2697         return d->toolbars_;
2698 }
2699
2700
2701 Menus const & GuiApplication::menus() const
2702 {
2703         return d->menus_;
2704 }
2705
2706
2707 Menus & GuiApplication::menus()
2708 {
2709         return d->menus_;
2710 }
2711
2712
2713 QList<int> GuiApplication::viewIds() const
2714 {
2715         return d->views_.keys();
2716 }
2717
2718
2719 ColorCache & GuiApplication::colorCache()
2720 {
2721         return d->color_cache_;
2722 }
2723
2724
2725 int GuiApplication::exec()
2726 {
2727         // asynchronously handle batch commands. This event will be in
2728         // the event queue in front of other asynchronous events. Hence,
2729         // we can assume in the latter that the gui is setup already.
2730         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2731
2732         return QApplication::exec();
2733 }
2734
2735
2736 void GuiApplication::exit(int status)
2737 {
2738         QApplication::exit(status);
2739 }
2740
2741
2742 void GuiApplication::setGuiLanguage()
2743 {
2744         setLocale();
2745         QLocale theLocale;
2746         // install translation file for Qt built-in dialogs
2747         QString const language_name = QString("qt_") + theLocale.name();
2748         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2749         // Short-named translator can be loaded from a long name, but not the
2750         // opposite. Therefore, long name should be used without truncation.
2751         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2752         if (!d->qt_trans_.load(language_name,
2753 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2754                         QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2755 #else
2756                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2757 #endif
2758                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2759                         << language_name);
2760         } else {
2761                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2762                         << language_name);
2763         }
2764
2765         switch (theLocale.language()) {
2766         case QLocale::Arabic :
2767         case QLocale::Hebrew :
2768         case QLocale::Persian :
2769         case QLocale::Urdu :
2770                 setLayoutDirection(Qt::RightToLeft);
2771                 break;
2772         default:
2773                 setLayoutDirection(Qt::LeftToRight);
2774         }
2775 }
2776
2777
2778 void GuiApplication::execBatchCommands()
2779 {
2780         setGuiLanguage();
2781
2782         // Read menus
2783         if (!readUIFile(toqstr(lyxrc.ui_file)))
2784                 // Gives some error box here.
2785                 return;
2786
2787 #ifdef Q_OS_MAC
2788 #if QT_VERSION > 0x040600
2789         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2790 #endif
2791 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2792         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2793 #endif
2794         // Create the global default menubar which is shown for the dialogs
2795         // and if no GuiView is visible.
2796         // This must be done after the session was recovered to know the "last files".
2797         d->global_menubar_ = new QMenuBar(0);
2798         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2799 #endif
2800
2801         lyx::execBatchCommands();
2802 }
2803
2804
2805 QAbstractItemModel * GuiApplication::languageModel()
2806 {
2807         if (d->language_model_)
2808                 return d->language_model_;
2809
2810         QStandardItemModel * lang_model = new QStandardItemModel(this);
2811         lang_model->insertColumns(0, 3);
2812         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2813         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2814         Languages::const_iterator it = lyx::languages.begin();
2815         Languages::const_iterator end = lyx::languages.end();
2816         for (; it != end; ++it) {
2817                 int current_row = lang_model->rowCount();
2818                 lang_model->insertRows(current_row, 1);
2819                 QModelIndex pl_item = lang_model->index(current_row, 0);
2820                 QModelIndex sp_item = lang_model->index(current_row, 1);
2821                 QModelIndex th_item = lang_model->index(current_row, 2);
2822                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2823                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2824                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2825                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2826                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2827                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2828                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2829                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2830                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2831                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2832         }
2833         d->language_model_ = new QSortFilterProxyModel(this);
2834         d->language_model_->setSourceModel(lang_model);
2835         d->language_model_->setSortLocaleAware(true);
2836         return d->language_model_;
2837 }
2838
2839
2840 void GuiApplication::restoreGuiSession()
2841 {
2842         if (!lyxrc.load_session)
2843                 return;
2844
2845         Session & session = theSession();
2846         LastOpenedSection::LastOpened const & lastopened =
2847                 session.lastOpened().getfiles();
2848
2849         validateCurrentView();
2850
2851         FileName active_file;
2852         // do not add to the lastfile list since these files are restored from
2853         // last session, and should be already there (regular files), or should
2854         // not be added at all (help files).
2855         for (auto const & last : lastopened) {
2856                 FileName const & file_name = last.file_name;
2857                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2858                           && current_view_->documentBufferView() != nullptr)) {
2859                         string const & fname = file_name.absFileName();
2860                         createView(support::checksum(fname));
2861                 }
2862                 current_view_->loadDocument(file_name, false);
2863
2864                 if (last.active)
2865                         active_file = file_name;
2866         }
2867
2868         // Restore last active buffer
2869         Buffer * buffer = theBufferList().getBuffer(active_file);
2870         if (buffer && current_view_)
2871                 current_view_->setBuffer(buffer);
2872
2873         // clear this list to save a few bytes of RAM
2874         session.lastOpened().clear();
2875 }
2876
2877
2878 QString const GuiApplication::romanFontName()
2879 {
2880         QFont font;
2881         font.setStyleHint(QFont::Serif);
2882         font.setFamily("serif");
2883
2884         return QFontInfo(font).family();
2885 }
2886
2887
2888 QString const GuiApplication::sansFontName()
2889 {
2890         QFont font;
2891         font.setStyleHint(QFont::SansSerif);
2892         font.setFamily("sans");
2893
2894         return QFontInfo(font).family();
2895 }
2896
2897
2898 QString const GuiApplication::typewriterFontName()
2899 {
2900         return QFontInfo(typewriterSystemFont()).family();
2901 }
2902
2903
2904 namespace {
2905         // We cannot use QFont::fixedPitch() because it doesn't
2906         // return the fact but only if it is requested.
2907         static bool isFixedPitch(const QFont & font) {
2908                 const QFontInfo fi(font);
2909                 return fi.fixedPitch();
2910         }
2911 } // namespace
2912
2913
2914 QFont const GuiApplication::typewriterSystemFont()
2915 {
2916 #if QT_VERSION >= 0x050200
2917         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2918 #else
2919         QFont font("monospace");
2920 #endif
2921         if (!isFixedPitch(font)) {
2922                 // try to enforce a real monospaced font
2923                 font.setStyleHint(QFont::Monospace);
2924                 if (!isFixedPitch(font)) {
2925                         font.setStyleHint(QFont::TypeWriter);
2926                         if (!isFixedPitch(font)) font.setFamily("courier");
2927                 }
2928         }
2929 #ifdef Q_OS_MAC
2930         // On a Mac the result is too small and it's not practical to
2931         // rely on Qtconfig utility to change the system settings of Qt.
2932         font.setPointSize(12);
2933 #endif
2934         return font;
2935 }
2936
2937
2938 void GuiApplication::handleRegularEvents()
2939 {
2940         ForkedCallsController::handleCompletedProcesses();
2941 }
2942
2943
2944 bool GuiApplication::event(QEvent * e)
2945 {
2946         switch(e->type()) {
2947         case QEvent::FileOpen: {
2948                 // Open a file; this happens only on Mac OS X for now.
2949                 //
2950                 // We do this asynchronously because on startup the batch
2951                 // commands are not executed here yet and the gui is not ready
2952                 // therefore.
2953                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2954                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2955                 processFuncRequestAsync(fr);
2956                 e->accept();
2957                 return true;
2958         }
2959 #if (QT_VERSION < 0x050000)
2960         // Qt5 uses a signal for that, see above.
2961         case QEvent::KeyboardLayoutChange:
2962                 //LYXERR0("keyboard change");
2963                 if (currentView() && currentView()->currentBufferView())
2964                         currentView()->currentBufferView()->cursor().setLanguageFromInput();
2965                 e->accept();
2966                 return true;
2967 #endif
2968         default:
2969                 return QApplication::event(e);
2970         }
2971 }
2972
2973
2974 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2975 {
2976         try {
2977                 return QApplication::notify(receiver, event);
2978         }
2979         catch (ExceptionMessage const & e) {
2980                 switch(e.type_) {
2981                 case ErrorException:
2982                         emergencyCleanup();
2983                         setQuitOnLastWindowClosed(false);
2984                         closeAllViews();
2985                         Alert::error(e.title_, e.details_);
2986 #ifndef NDEBUG
2987                         // Properly crash in debug mode in order to get a useful backtrace.
2988                         abort();
2989 #endif
2990                         // In release mode, try to exit gracefully.
2991                         this->exit(1);
2992                         // FIXME: GCC 7 thinks we can fall through here. Can we?
2993                         // fall through
2994                 case BufferException: {
2995                         if (!current_view_ || !current_view_->documentBufferView())
2996                                 return false;
2997                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2998                         docstring details = e.details_ + '\n';
2999                         details += buf->emergencyWrite();
3000                         theBufferList().release(buf);
3001                         details += "\n" + _("The current document was closed.");
3002                         Alert::error(e.title_, details);
3003                         return false;
3004                 }
3005                 case WarningException:
3006                         Alert::warning(e.title_, e.details_);
3007                         return false;
3008                 }
3009         }
3010         catch (exception const & e) {
3011                 docstring s = _("LyX has caught an exception, it will now "
3012                         "attempt to save all unsaved documents and exit."
3013                         "\n\nException: ");
3014                 s += from_ascii(e.what());
3015                 Alert::error(_("Software exception Detected"), s);
3016                 lyx_exit(1);
3017         }
3018         catch (...) {
3019                 docstring s = _("LyX has caught some really weird exception, it will "
3020                         "now attempt to save all unsaved documents and exit.");
3021                 Alert::error(_("Software exception Detected"), s);
3022                 lyx_exit(1);
3023         }
3024
3025         return false;
3026 }
3027
3028 bool GuiApplication::isInDarkMode()
3029 {
3030         return colorCache().isDarkMode();
3031 }
3032
3033
3034 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3035 {
3036         QColor const & qcol = d->color_cache_.get(col);
3037         if (!qcol.isValid()) {
3038                 rgbcol.r = 0;
3039                 rgbcol.g = 0;
3040                 rgbcol.b = 0;
3041                 return false;
3042         }
3043         rgbcol.r = qcol.red();
3044         rgbcol.g = qcol.green();
3045         rgbcol.b = qcol.blue();
3046         return true;
3047 }
3048
3049
3050 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3051 {
3052         QColor const qcol(lcolor.getX11HexName(col).c_str());
3053         if (!qcol.isValid()) {
3054                 rgbcol.r = 0;
3055                 rgbcol.g = 0;
3056                 rgbcol.b = 0;
3057                 return false;
3058         }
3059         rgbcol.r = qcol.red();
3060         rgbcol.g = qcol.green();
3061         rgbcol.b = qcol.blue();
3062         return true;
3063 }
3064
3065
3066 string const GuiApplication::hexName(ColorCode col)
3067 {
3068         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3069 }
3070
3071
3072 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3073 {
3074         SocketNotifier * sn = new SocketNotifier(this, fd, func);
3075         d->socket_notifiers_[fd] = sn;
3076         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3077 }
3078
3079
3080 void GuiApplication::socketDataReceived(int fd)
3081 {
3082         d->socket_notifiers_[fd]->func_();
3083 }
3084
3085
3086 void GuiApplication::unregisterSocketCallback(int fd)
3087 {
3088         d->socket_notifiers_.take(fd)->setEnabled(false);
3089 }
3090
3091
3092 void GuiApplication::commitData(QSessionManager & sm)
3093 {
3094         /** The implementation is required to avoid an application exit
3095          ** when session state save is triggered by session manager.
3096          ** The default implementation sends a close event to all
3097          ** visible top level widgets when session management allows
3098          ** interaction.
3099          ** We are changing that to check the state of each buffer in all
3100          ** views and ask the users what to do if buffers are dirty.
3101          ** Furthermore, we save the session state.
3102          ** We do NOT close the views here since the user still can cancel
3103          ** the logout process (see #9277); also, this would hide LyX from
3104          ** an OSes own session handling (application restoration).
3105          **/
3106         #ifdef QT_NO_SESSIONMANAGER
3107                 #ifndef _MSC_VER
3108                         #warning Qt is compiled without session manager
3109                 #else
3110                         #pragma message("warning: Qt is compiled without session manager")
3111                 #endif
3112                 (void) sm;
3113         #else
3114                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3115                         sm.cancel();
3116                 else
3117                         sm.release();
3118         #endif
3119 }
3120
3121
3122 void GuiApplication::unregisterView(GuiView * gv)
3123 {
3124         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3125                 d->views_.remove(gv->id());
3126                 if (current_view_ == gv)
3127                         current_view_ = nullptr;
3128         }
3129 }
3130
3131
3132 bool GuiApplication::closeAllViews()
3133 {
3134         if (d->views_.empty())
3135                 return true;
3136
3137         // When a view/window was closed before without quitting LyX, there
3138         // are already entries in the lastOpened list.
3139         theSession().lastOpened().clear();
3140
3141         QList<GuiView *> const views = d->views_.values();
3142         for (GuiView * view : views) {
3143                 if (!view->closeScheduled())
3144                         return false;
3145         }
3146
3147         d->views_.clear();
3148         return true;
3149 }
3150
3151
3152 bool GuiApplication::prepareAllViewsForLogout()
3153 {
3154         if (d->views_.empty())
3155                 return true;
3156
3157         QList<GuiView *> const views = d->views_.values();
3158         for (GuiView * view : views) {
3159                 if (!view->prepareAllBuffersForLogout())
3160                         return false;
3161         }
3162
3163         return true;
3164 }
3165
3166
3167 GuiView & GuiApplication::view(int id) const
3168 {
3169         LAPPERR(d->views_.contains(id));
3170         return *d->views_.value(id);
3171 }
3172
3173
3174 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3175 {
3176         QList<GuiView *> const views = d->views_.values();
3177         for (GuiView * view : views)
3178                 view->hideDialog(name, inset);
3179 }
3180
3181
3182 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3183 {
3184         Buffer const * buf = nullptr;
3185         QHash<int, GuiView *>::const_iterator end = d->views_.end();
3186         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3187                 if (Buffer const * ptr = (*it)->updateInset(inset))
3188                         buf = ptr;
3189         }
3190         return buf;
3191 }
3192
3193
3194 bool GuiApplication::searchMenu(FuncRequest const & func,
3195         docstring_list & names) const
3196 {
3197         BufferView * bv = nullptr;
3198         if (current_view_)
3199                 bv = current_view_->currentBufferView();
3200         return d->menus_.searchMenu(func, names, bv);
3201 }
3202
3203
3204 bool GuiApplication::hasBufferView() const
3205 {
3206         return (current_view_ && current_view_->currentBufferView());
3207 }
3208
3209
3210 // Ensure that a file is read only once (prevents include loops)
3211 static QStringList uifiles;
3212 // store which ui files define Toolbars
3213 static QStringList toolbar_uifiles;
3214
3215
3216 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3217 {
3218         enum {
3219                 ui_menuset = 1,
3220                 ui_toolbars,
3221                 ui_toolbarset,
3222                 ui_include,
3223                 ui_format,
3224                 ui_last
3225         };
3226
3227         LexerKeyword uitags[] = {
3228                 { "format", ui_format },
3229                 { "include", ui_include },
3230                 { "menuset", ui_menuset },
3231                 { "toolbars", ui_toolbars },
3232                 { "toolbarset", ui_toolbarset }
3233         };
3234
3235         Lexer lex(uitags);
3236         lex.setFile(ui_path);
3237         if (!lex.isOK()) {
3238                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3239                                          << endl;
3240         }
3241
3242         if (lyxerr.debugging(Debug::PARSER))
3243                 lex.printTable(lyxerr);
3244
3245         bool error = false;
3246         // format before introduction of format tag
3247         unsigned int format = 0;
3248         while (lex.isOK()) {
3249                 int const status = lex.lex();
3250
3251                 // we have to do this check here, outside the switch,
3252                 // because otherwise we would start reading include files,
3253                 // e.g., if the first tag we hit was an include tag.
3254                 if (status == ui_format)
3255                         if (lex.next()) {
3256                                 format = lex.getInteger();
3257                                 continue;
3258                         }
3259
3260                 // this will trigger unless the first tag we hit is a format
3261                 // tag, with the right format.
3262                 if (format != LFUN_FORMAT)
3263                         return FormatMismatch;
3264
3265                 switch (status) {
3266                 case Lexer::LEX_FEOF:
3267                         continue;
3268
3269                 case ui_include: {
3270                         lex.next(true);
3271                         QString const file = toqstr(lex.getString());
3272                         bool const success = readUIFile(file, true);
3273                         if (!success) {
3274                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3275                                 return ReadError;
3276                         }
3277                         break;
3278                 }
3279
3280                 case ui_menuset:
3281                         d->menus_.read(lex);
3282                         break;
3283
3284                 case ui_toolbarset:
3285                         d->toolbars_.readToolbars(lex);
3286                         break;
3287
3288                 case ui_toolbars:
3289                         d->toolbars_.readToolbarSettings(lex);
3290                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3291                         break;
3292
3293                 default:
3294                         if (!rtrim(lex.getString()).empty())
3295                                 lex.printError("LyX::ReadUIFile: "
3296                                                "Unknown menu tag: `$$Token'");
3297                         else
3298                                 LYXERR0("Error with status: " << status);
3299                         error = true;
3300                         break;
3301                 }
3302
3303         }
3304         return (error ? ReadError : ReadOK);
3305 }
3306
3307
3308 bool GuiApplication::readUIFile(QString const & name, bool include)
3309 {
3310         LYXERR(Debug::INIT, "About to read " << name << "...");
3311
3312         FileName ui_path;
3313         if (include) {
3314                 ui_path = libFileSearch("ui", name, "inc");
3315                 if (ui_path.empty())
3316                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3317         } else {
3318                 ui_path = libFileSearch("ui", name, "ui");
3319         }
3320
3321         if (ui_path.empty()) {
3322                 static const QString defaultUIFile = "default";
3323                 LYXERR(Debug::INIT, "Could not find " << name);
3324                 if (include) {
3325                         Alert::warning(_("Could not find UI definition file"),
3326                                 bformat(_("Error while reading the included file\n%1$s\n"
3327                                         "Please check your installation."), qstring_to_ucs4(name)));
3328                         return false;
3329                 }
3330                 if (name == defaultUIFile) {
3331                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3332                         Alert::warning(_("Could not find default UI file"),
3333                                 _("LyX could not find the default UI file!\n"
3334                                   "Please check your installation."));
3335                         return false;
3336                 }
3337                 Alert::warning(_("Could not find UI definition file"),
3338                 bformat(_("Error while reading the configuration file\n%1$s\n"
3339                         "Falling back to default.\n"
3340                         "Please look under Tools>Preferences>User Interface and\n"
3341                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3342                 return readUIFile(defaultUIFile, false);
3343         }
3344
3345         QString const uifile = toqstr(ui_path.absFileName());
3346         if (uifiles.contains(uifile)) {
3347                 if (!include) {
3348                         // We are reading again the top uifile so reset the safeguard:
3349                         uifiles.clear();
3350                         d->menus_.reset();
3351                         d->toolbars_.reset();
3352                 } else {
3353                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3354                                 << "Is this an include loop?");
3355                         return false;
3356                 }
3357         }
3358         uifiles.push_back(uifile);
3359
3360         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3361
3362         ReturnValues retval = readUIFile(ui_path);
3363
3364         if (retval == FormatMismatch) {
3365                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3366                 TempFile tmp("convertXXXXXX.ui");
3367                 FileName const tempfile = tmp.name();
3368                 bool const success = prefs2prefs(ui_path, tempfile, true);
3369                 if (!success) {
3370                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3371                                 " to format " << LFUN_FORMAT << ".");
3372                 } else {
3373                         retval = readUIFile(tempfile);
3374                 }
3375         }
3376
3377         if (retval != ReadOK) {
3378                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3379                 return false;
3380         }
3381
3382         if (include)
3383                 return true;
3384
3385         QSettings settings;
3386         settings.beginGroup("ui_files");
3387         bool touched = false;
3388         for (int i = 0; i != uifiles.size(); ++i) {
3389                 QFileInfo fi(uifiles[i]);
3390                 QDateTime const date_value = fi.lastModified();
3391                 QString const name_key = QString::number(i);
3392                 // if an ui file which defines Toolbars has changed,
3393                 // we have to reset the settings
3394                 if (toolbar_uifiles.contains(uifiles[i])
3395                  && (!settings.contains(name_key)
3396                  || settings.value(name_key).toString() != uifiles[i]
3397                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3398                         touched = true;
3399                         settings.setValue(name_key, uifiles[i]);
3400                         settings.setValue(name_key + "/date", date_value);
3401                 }
3402         }
3403         settings.endGroup();
3404         if (touched)
3405                 settings.remove("views");
3406
3407         return true;
3408 }
3409
3410
3411 void GuiApplication::onLastWindowClosed()
3412 {
3413         if (d->global_menubar_)
3414                 d->global_menubar_->grabKeyboard();
3415 }
3416
3417
3418 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3419 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3420 {
3421         std::string name = "unknown";
3422         switch (state) {
3423         case Qt::ApplicationSuspended:
3424                 name = "ApplicationSuspended";
3425                 break;
3426         case Qt::ApplicationHidden:
3427                 name = "ApplicationHidden";
3428                 break;
3429         case Qt::ApplicationInactive:
3430                 name = "ApplicationInactive";
3431                 break;
3432         case Qt::ApplicationActive:
3433                 name = "ApplicationActive";
3434                 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3435                 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3436                 if (d->views_.empty() && d->last_state_ == state) {
3437                         LYXERR(Debug::GUI, "Open new window...");
3438                         createView();
3439                 }
3440                 break;
3441         }
3442         LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3443         d->last_state_ = state;
3444 }
3445 #endif
3446
3447
3448 void GuiApplication::startLongOperation() {
3449         d->key_checker_.start();
3450 }
3451
3452
3453 bool GuiApplication::longOperationCancelled() {
3454         return d->key_checker_.pressed();
3455 }
3456
3457
3458 void GuiApplication::stopLongOperation() {
3459         d->key_checker_.stop();
3460 }
3461
3462
3463 bool GuiApplication::longOperationStarted() {
3464         return d->key_checker_.started();
3465 }
3466
3467
3468 ////////////////////////////////////////////////////////////////////////
3469 //
3470 // X11 specific stuff goes here...
3471
3472 #ifdef Q_WS_X11
3473 bool GuiApplication::x11EventFilter(XEvent * xev)
3474 {
3475         if (!current_view_)
3476                 return false;
3477
3478         switch (xev->type) {
3479         case SelectionRequest: {
3480                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3481                         break;
3482                 LYXERR(Debug::SELECTION, "X requested selection.");
3483                 BufferView * bv = current_view_->currentBufferView();
3484                 if (bv) {
3485                         docstring const sel = bv->requestSelection();
3486                         if (!sel.empty()) {
3487                                 d->selection_.put(sel);
3488                                 // Refresh the selection request timestamp.
3489                                 // We have to do this by ourselves as Qt seems
3490                                 // not doing that, maybe because of our
3491                                 // "persistent selection" implementation
3492                                 // (see comments in GuiSelection.cpp).
3493                                 XSelectionEvent nev;
3494                                 nev.type = SelectionNotify;
3495                                 nev.display = xev->xselectionrequest.display;
3496                                 nev.requestor = xev->xselectionrequest.requestor;
3497                                 nev.selection = xev->xselectionrequest.selection;
3498                                 nev.target = xev->xselectionrequest.target;
3499                                 nev.property = 0L; // None
3500                                 nev.time = CurrentTime;
3501                                 XSendEvent(QX11Info::display(),
3502                                         nev.requestor, False, 0,
3503                                         reinterpret_cast<XEvent *>(&nev));
3504                                 return true;
3505                         }
3506                 }
3507                 break;
3508         }
3509         case SelectionClear: {
3510                 if (xev->xselectionclear.selection != XA_PRIMARY)
3511                         break;
3512                 LYXERR(Debug::SELECTION, "Lost selection.");
3513                 BufferView * bv = current_view_->currentBufferView();
3514                 if (bv)
3515                         bv->clearSelection();
3516                 break;
3517         }
3518         }
3519         return false;
3520 }
3521 #elif defined(QPA_XCB)
3522 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3523                                        void * message, long *)
3524 {
3525         if (!current_view_ || eventType != "xcb_generic_event_t")
3526                 return false;
3527
3528         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3529
3530         switch (ev->response_type) {
3531         case XCB_SELECTION_REQUEST: {
3532                 xcb_selection_request_event_t * srev =
3533                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3534                 if (srev->selection != XCB_ATOM_PRIMARY)
3535                         break;
3536                 LYXERR(Debug::SELECTION, "X requested selection.");
3537                 BufferView * bv = current_view_->currentBufferView();
3538                 if (bv) {
3539                         docstring const sel = bv->requestSelection();
3540                         if (!sel.empty()) {
3541                                 d->selection_.put(sel);
3542 #ifdef HAVE_QT5_X11_EXTRAS
3543                                 // Refresh the selection request timestamp.
3544                                 // We have to do this by ourselves as Qt seems
3545                                 // not doing that, maybe because of our
3546                                 // "persistent selection" implementation
3547                                 // (see comments in GuiSelection.cpp).
3548                                 // It is expected that every X11 event is
3549                                 // 32 bytes long, even if not all 32 bytes are
3550                                 // needed. See:
3551                                 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3552                                 struct alignas(32) padded_event
3553                                         : xcb_selection_notify_event_t {};
3554                                 padded_event nev = {};
3555                                 nev.response_type = XCB_SELECTION_NOTIFY;
3556                                 nev.requestor = srev->requestor;
3557                                 nev.selection = srev->selection;
3558                                 nev.target = srev->target;
3559                                 nev.property = XCB_NONE;
3560                                 nev.time = XCB_CURRENT_TIME;
3561                                 xcb_connection_t * con = QX11Info::connection();
3562                                 xcb_send_event(con, 0, srev->requestor,
3563                                         XCB_EVENT_MASK_NO_EVENT,
3564                                         reinterpret_cast<char const *>(&nev));
3565                                 xcb_flush(con);
3566 #endif
3567                                 return true;
3568                         }
3569                 }
3570                 break;
3571         }
3572         case XCB_SELECTION_CLEAR: {
3573                 xcb_selection_clear_event_t * scev =
3574                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3575                 if (scev->selection != XCB_ATOM_PRIMARY)
3576                         break;
3577                 LYXERR(Debug::SELECTION, "Lost selection.");
3578                 BufferView * bv = current_view_->currentBufferView();
3579                 if (bv)
3580                         bv->clearSelection();
3581                 break;
3582         }
3583         }
3584         return false;
3585 }
3586 #endif
3587
3588 } // namespace frontend
3589
3590
3591 void hideDialogs(std::string const & name, Inset * inset)
3592 {
3593         if (theApp())
3594                 frontend::guiApp->hideDialogs(name, inset);
3595 }
3596
3597
3598 ////////////////////////////////////////////////////////////////////
3599 //
3600 // Font stuff
3601 //
3602 ////////////////////////////////////////////////////////////////////
3603
3604 frontend::FontLoader & theFontLoader()
3605 {
3606         LAPPERR(frontend::guiApp);
3607         return frontend::guiApp->fontLoader();
3608 }
3609
3610
3611 frontend::FontMetrics const & theFontMetrics(Font const & f)
3612 {
3613         return theFontMetrics(f.fontInfo());
3614 }
3615
3616
3617 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3618 {
3619         LAPPERR(frontend::guiApp);
3620         return frontend::guiApp->fontLoader().metrics(f);
3621 }
3622
3623
3624 ////////////////////////////////////////////////////////////////////
3625 //
3626 // Misc stuff
3627 //
3628 ////////////////////////////////////////////////////////////////////
3629
3630 frontend::Clipboard & theClipboard()
3631 {
3632         LAPPERR(frontend::guiApp);
3633         return frontend::guiApp->clipboard();
3634 }
3635
3636
3637 frontend::Selection & theSelection()
3638 {
3639         LAPPERR(frontend::guiApp);
3640         return frontend::guiApp->selection();
3641 }
3642
3643
3644 } // namespace lyx
3645
3646 #include "moc_GuiApplication.cpp"