]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiApplication.cpp
#12451 Adjust color cache on change of dark/light mode
[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 >= 0x050100 && 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::onPaletteChanged()
2326 {
2327         colorCache().setPalette(palette());
2328 }
2329
2330
2331 void GuiApplication::handleKeyFunc(FuncCode action)
2332 {
2333         char_type c = 0;
2334
2335         if (d->keyseq.length())
2336                 c = 0;
2337         GuiView * gv = currentView();
2338         LASSERT(gv && gv->currentBufferView(), return);
2339         BufferView * bv = gv->currentBufferView();
2340         bv->getIntl().getTransManager().deadkey(
2341                 c, get_accent(action).accent, bv->cursor().innerText(),
2342                 bv->cursor());
2343         // Need to clear, in case the minibuffer calls these
2344         // actions
2345         d->keyseq.clear();
2346         // copied verbatim from do_accent_char
2347         bv->cursor().resetAnchor();
2348 }
2349
2350
2351 //Keep this in sync with GuiApplication::processKeySym below
2352 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2353                                  KeyModifier state) const
2354 {
2355         // Do nothing if we have nothing
2356         if (!keysym.isOK() || keysym.isModifier())
2357                 return false;
2358         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2359         KeySequence seq;
2360         FuncRequest func = seq.addkey(keysym, state);
2361         // When not cancel or meta-fake, do the normal lookup.
2362         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2363                 seq = d->keyseq;
2364                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2365         }
2366         // Maybe user can only reach the key via holding down shift.
2367         // Let's see. But only if shift is the only modifier
2368         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2369                 // If addkey looked up a command and did not find further commands then
2370                 // seq has been reset at this point
2371                 func = seq.addkey(keysym, NoModifier);
2372
2373         LYXERR(Debug::KEY, " Key (queried) [action="
2374                << lyxaction.getActionName(func.action()) << "]["
2375                << seq.print(KeySequence::Portable) << ']');
2376         return func.action() != LFUN_UNKNOWN_ACTION;
2377 }
2378
2379
2380 //Keep this in sync with GuiApplication::queryKeySym above
2381 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2382 {
2383         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2384
2385         // Do nothing if we have nothing (JMarc)
2386         if (!keysym.isOK() || keysym.isModifier()) {
2387                 if (!keysym.isOK())
2388                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2389                 if (current_view_)
2390                         current_view_->restartCaret();
2391                 return;
2392         }
2393
2394         char_type encoded_last_key = keysym.getUCSEncoded();
2395
2396         // Do a one-deep top-level lookup for
2397         // cancel and meta-fake keys. RVDK_PATCH_5
2398         d->cancel_meta_seq.reset();
2399
2400         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2401         LYXERR(Debug::KEY, "action first set to ["
2402                << lyxaction.getActionName(func.action()) << ']');
2403
2404         // When not cancel or meta-fake, do the normal lookup.
2405         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2406         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2407         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2408                 // remove Caps Lock and Mod2 as a modifiers
2409                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2410                 LYXERR(Debug::KEY, "action now set to ["
2411                        << lyxaction.getActionName(func.action()) << ']');
2412         }
2413
2414         // Don't remove this unless you know what you are doing.
2415         d->meta_fake_bit = NoModifier;
2416
2417         // Can this happen now ?
2418         if (func.action() == LFUN_NOACTION)
2419                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2420
2421         LYXERR(Debug::KEY, " Key [action="
2422                << lyxaction.getActionName(func.action()) << "]["
2423                << d->keyseq.print(KeySequence::Portable) << ']');
2424
2425         // already here we know if it any point in going further
2426         // why not return already here if action == -1 and
2427         // num_bytes == 0? (Lgb)
2428
2429         if (d->keyseq.length() > 1 && current_view_)
2430                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2431
2432
2433         // Maybe user can only reach the key via holding down shift.
2434         // Let's see. But only if shift is the only modifier
2435         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2436                 LYXERR(Debug::KEY, "Trying without shift");
2437                 // If addkey looked up a command and did not find further commands then
2438                 // seq has been reset at this point
2439                 func = d->keyseq.addkey(keysym, NoModifier);
2440                 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2441         }
2442
2443         if (func.action() == LFUN_UNKNOWN_ACTION) {
2444                 // We didn't match any of the key sequences.
2445                 // See if it's normal insertable text not already
2446                 // covered by a binding
2447                 if (keysym.isText() && d->keyseq.length() == 1) {
2448                         // Non-printable characters (such as ASCII control characters)
2449                         // must not be inserted (#5704)
2450                         if (!isPrintable(encoded_last_key)) {
2451                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2452                                 if (current_view_)
2453                                         current_view_->restartCaret();
2454                                 return;
2455                         }
2456                         // The following modifier check is not needed on Mac.
2457                         // The keysym is either not text or it is different
2458                         // from the non-modifier keysym. See #9875 for the
2459                         // broken alt-modifier effect of having this code active.
2460 #if !defined(Q_OS_MAC)
2461                         // If a non-Shift Modifier is used we have a non-bound key sequence
2462                         // (such as Alt+j = j). This should be omitted (#5575).
2463                         // On Windows, AltModifier and ControlModifier are both
2464                         // set when AltGr is pressed. Therefore, in order to not
2465                         // break AltGr-bound symbols (see #5575 for details),
2466                         // unbound Ctrl+Alt key sequences are allowed.
2467                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2468 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2469                             && !(state & AltModifier && state & ControlModifier)
2470 #endif
2471                             )
2472                         {
2473                                 if (current_view_) {
2474                                         current_view_->message(_("Unknown function."));
2475                                         current_view_->restartCaret();
2476                                 }
2477                                 return;
2478                         }
2479 #endif
2480                         // Since all checks above were passed, we now really have text that
2481                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2482                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2483                         // below.
2484                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2485                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2486                 } else {
2487                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2488                         if (current_view_) {
2489                                 current_view_->message(_("Unknown function."));
2490                                 current_view_->restartCaret();
2491                         }
2492                         return;
2493                 }
2494         }
2495
2496         if (func.action() == LFUN_SELF_INSERT) {
2497                 if (encoded_last_key != 0) {
2498                         docstring const arg(1, encoded_last_key);
2499                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2500                                              FuncRequest::KEYBOARD));
2501                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2502                 }
2503         } else
2504                 processFuncRequest(func);
2505 }
2506
2507
2508 void GuiApplication::processFuncRequest(FuncRequest const & func)
2509 {
2510         lyx::dispatch(func);
2511 }
2512
2513
2514 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2515 {
2516         addToFuncRequestQueue(func);
2517         processFuncRequestQueueAsync();
2518 }
2519
2520
2521 void GuiApplication::processFuncRequestQueue()
2522 {
2523         while (!d->func_request_queue_.empty()) {
2524                 // take the item from the stack _before_ processing the
2525                 // request in order to avoid race conditions from nested
2526                 // or parallel requests (see #10406)
2527                 FuncRequest const fr(d->func_request_queue_.front());
2528                 d->func_request_queue_.pop();
2529                 processFuncRequest(fr);
2530         }
2531 }
2532
2533
2534 void GuiApplication::processFuncRequestQueueAsync()
2535 {
2536         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2537 }
2538
2539
2540 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2541 {
2542         d->func_request_queue_.push(func);
2543 }
2544
2545
2546 void GuiApplication::resetGui()
2547 {
2548         // Set the language defined by the user.
2549         setGuiLanguage();
2550
2551         // Read menus
2552         if (!readUIFile(toqstr(lyxrc.ui_file)))
2553                 // Gives some error box here.
2554                 return;
2555
2556         if (d->global_menubar_)
2557                 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2558
2559         QHash<int, GuiView *>::iterator it;
2560         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2561                 GuiView * gv = *it;
2562                 setCurrentView(gv);
2563                 gv->setLayoutDirection(layoutDirection());
2564                 gv->resetDialogs();
2565         }
2566
2567         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2568 }
2569
2570
2571 bool GuiApplication::rtlContext() const
2572 {
2573         if (current_view_ && current_view_->currentBufferView()) {
2574                 BufferView const * bv = current_view_->currentBufferView();
2575                 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2576         } else
2577                 return layoutDirection() == Qt::RightToLeft;
2578 }
2579
2580
2581 void GuiApplication::createView(int view_id)
2582 {
2583         createView(QString(), true, view_id);
2584 }
2585
2586
2587 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2588         int view_id)
2589 {
2590         // release the keyboard which might have been grabbed by the global
2591         // menubar on Mac to catch shortcuts even without any GuiView.
2592         if (d->global_menubar_)
2593                 d->global_menubar_->releaseKeyboard();
2594
2595         // create new view
2596         int id = view_id;
2597         while (d->views_.find(id) != d->views_.end())
2598                 id++;
2599
2600         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2601         GuiView * view = new GuiView(id);
2602         // `view' is the new current_view_. Tell coverity that is is not 0.
2603         LATTEST(current_view_);
2604         // register view
2605         d->views_[id] = view;
2606
2607         if (autoShow) {
2608                 view->show();
2609                 setActiveWindow(view);
2610         }
2611
2612         if (!geometry_arg.isEmpty()) {
2613 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2614                 int x, y;
2615                 int w, h;
2616                 QChar sx, sy;
2617 #if QT_VERSION < 0x060000
2618                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2619                 re.indexIn(geometry_arg);
2620                 w = re.cap(1).toInt();
2621                 h = re.cap(2).toInt();
2622                 x = re.cap(3).toInt();
2623                 y = re.cap(4).toInt();
2624                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2625                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2626 #else
2627                 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2628                 QRegularExpressionMatch match = re.match(geometry_arg);
2629                 w = match.captured(1).toInt();
2630                 h = match.captured(2).toInt();
2631                 x = match.captured(3).toInt();
2632                 y = match.captured(4).toInt();
2633                 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2634                 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2635 #endif
2636                 // Set initial geometry such that we can get the frame size.
2637                 view->setGeometry(x, y, w, h);
2638                 int framewidth = view->geometry().x() - view->x();
2639                 int titleheight = view->geometry().y() - view->y();
2640                 // Negative displacements must be interpreted as distances
2641                 // from the right or bottom screen borders.
2642                 if (sx == '-' || sy == '-') {
2643 #if QT_VERSION < 0x060000
2644                         QRect rec = QApplication::desktop()->screenGeometry();
2645 #else
2646                         QRect rec = QGuiApplication::primaryScreen()->geometry();
2647 #endif
2648                         if (sx == '-')
2649                                 x += rec.width() - w - framewidth;
2650                         if (sy == '-')
2651                                 y += rec.height() - h - titleheight;
2652                         view->setGeometry(x, y, w, h);
2653                 }
2654                 // Make sure that the left and top frame borders are visible.
2655                 if (view->x() < 0 || view->y() < 0) {
2656                         if (view->x() < 0)
2657                                 x = framewidth;
2658                         if (view->y() < 0)
2659                                 y = titleheight;
2660                         view->setGeometry(x, y, w, h);
2661                 }
2662 #endif
2663         }
2664         view->setFocus();
2665 }
2666
2667
2668 bool GuiApplication::unhide(Buffer * buf)
2669 {
2670         if (!currentView())
2671                 return false;
2672         currentView()->setBuffer(buf, false);
2673         return true;
2674 }
2675
2676
2677 Clipboard & GuiApplication::clipboard()
2678 {
2679         return d->clipboard_;
2680 }
2681
2682
2683 Selection & GuiApplication::selection()
2684 {
2685         return d->selection_;
2686 }
2687
2688
2689 FontLoader & GuiApplication::fontLoader()
2690 {
2691         return d->font_loader_;
2692 }
2693
2694
2695 Toolbars const & GuiApplication::toolbars() const
2696 {
2697         return d->toolbars_;
2698 }
2699
2700
2701 Toolbars & GuiApplication::toolbars()
2702 {
2703         return d->toolbars_;
2704 }
2705
2706
2707 Menus const & GuiApplication::menus() const
2708 {
2709         return d->menus_;
2710 }
2711
2712
2713 Menus & GuiApplication::menus()
2714 {
2715         return d->menus_;
2716 }
2717
2718
2719 bool GuiApplication::needsBackingStore() const
2720 {
2721         /* Qt on macOS and Wayland does not respect the
2722          * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2723          * store at each update. Therefore, we use our own backing store
2724          * in these two cases. It is also possible to force the use of the
2725          * backing store for cases like x11 with transparent WM themes.
2726          */
2727         return platformName() == "cocoa" || platformName().contains("wayland");
2728 }
2729
2730
2731 QList<int> GuiApplication::viewIds() const
2732 {
2733         return d->views_.keys();
2734 }
2735
2736
2737 ColorCache & GuiApplication::colorCache()
2738 {
2739         return d->color_cache_;
2740 }
2741
2742
2743 int GuiApplication::exec()
2744 {
2745         // asynchronously handle batch commands. This event will be in
2746         // the event queue in front of other asynchronous events. Hence,
2747         // we can assume in the latter that the gui is setup already.
2748         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2749
2750         return QApplication::exec();
2751 }
2752
2753
2754 void GuiApplication::exit(int status)
2755 {
2756         QApplication::exit(status);
2757 }
2758
2759
2760 void GuiApplication::setGuiLanguage()
2761 {
2762         setLocale();
2763         QLocale theLocale;
2764         // install translation file for Qt built-in dialogs
2765         QString const language_name = QString("qt_") + theLocale.name();
2766         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2767         // Short-named translator can be loaded from a long name, but not the
2768         // opposite. Therefore, long name should be used without truncation.
2769         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2770         if (!d->qt_trans_.load(language_name,
2771 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2772                         QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2773 #else
2774                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2775 #endif
2776                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2777                         << language_name);
2778         } else {
2779                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2780                         << language_name);
2781         }
2782
2783         switch (theLocale.language()) {
2784         case QLocale::Arabic :
2785         case QLocale::Hebrew :
2786         case QLocale::Persian :
2787         case QLocale::Urdu :
2788                 setLayoutDirection(Qt::RightToLeft);
2789                 break;
2790         default:
2791                 setLayoutDirection(Qt::LeftToRight);
2792         }
2793 }
2794
2795
2796 void GuiApplication::execBatchCommands()
2797 {
2798         setGuiLanguage();
2799
2800         // Read menus
2801         if (!readUIFile(toqstr(lyxrc.ui_file)))
2802                 // Gives some error box here.
2803                 return;
2804
2805 #ifdef Q_OS_MAC
2806 #if QT_VERSION > 0x040600
2807         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2808 #endif
2809 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2810         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2811 #endif
2812         // Create the global default menubar which is shown for the dialogs
2813         // and if no GuiView is visible.
2814         // This must be done after the session was recovered to know the "last files".
2815         d->global_menubar_ = new QMenuBar(0);
2816         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2817 #endif
2818
2819         lyx::execBatchCommands();
2820 }
2821
2822
2823 QAbstractItemModel * GuiApplication::languageModel()
2824 {
2825         if (d->language_model_)
2826                 return d->language_model_;
2827
2828         QStandardItemModel * lang_model = new QStandardItemModel(this);
2829         lang_model->insertColumns(0, 3);
2830         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2831         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2832         Languages::const_iterator it = lyx::languages.begin();
2833         Languages::const_iterator end = lyx::languages.end();
2834         for (; it != end; ++it) {
2835                 int current_row = lang_model->rowCount();
2836                 lang_model->insertRows(current_row, 1);
2837                 QModelIndex pl_item = lang_model->index(current_row, 0);
2838                 QModelIndex sp_item = lang_model->index(current_row, 1);
2839                 QModelIndex th_item = lang_model->index(current_row, 2);
2840                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2841                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2842                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2843                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2844                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2845                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2846                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2847                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2848                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2849                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2850         }
2851         d->language_model_ = new QSortFilterProxyModel(this);
2852         d->language_model_->setSourceModel(lang_model);
2853         d->language_model_->setSortLocaleAware(true);
2854         return d->language_model_;
2855 }
2856
2857
2858 void GuiApplication::restoreGuiSession()
2859 {
2860         if (!lyxrc.load_session)
2861                 return;
2862
2863         Session & session = theSession();
2864         LastOpenedSection::LastOpened const & lastopened =
2865                 session.lastOpened().getfiles();
2866
2867         validateCurrentView();
2868
2869         FileName active_file;
2870         // do not add to the lastfile list since these files are restored from
2871         // last session, and should be already there (regular files), or should
2872         // not be added at all (help files).
2873         for (auto const & last : lastopened) {
2874                 FileName const & file_name = last.file_name;
2875                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2876                           && current_view_->documentBufferView() != nullptr)) {
2877                         string const & fname = file_name.absFileName();
2878                         createView(support::checksum(fname));
2879                 }
2880                 current_view_->loadDocument(file_name, false);
2881
2882                 if (last.active)
2883                         active_file = file_name;
2884         }
2885
2886         // Restore last active buffer
2887         Buffer * buffer = theBufferList().getBuffer(active_file);
2888         if (buffer && current_view_)
2889                 current_view_->setBuffer(buffer);
2890
2891         // clear this list to save a few bytes of RAM
2892         session.lastOpened().clear();
2893 }
2894
2895
2896 QString const GuiApplication::romanFontName()
2897 {
2898         QFont font;
2899         font.setStyleHint(QFont::Serif);
2900         font.setFamily("serif");
2901
2902         return QFontInfo(font).family();
2903 }
2904
2905
2906 QString const GuiApplication::sansFontName()
2907 {
2908         QFont font;
2909         font.setStyleHint(QFont::SansSerif);
2910         font.setFamily("sans");
2911
2912         return QFontInfo(font).family();
2913 }
2914
2915
2916 QString const GuiApplication::typewriterFontName()
2917 {
2918         return QFontInfo(typewriterSystemFont()).family();
2919 }
2920
2921
2922 namespace {
2923         // We cannot use QFont::fixedPitch() because it doesn't
2924         // return the fact but only if it is requested.
2925         static bool isFixedPitch(const QFont & font) {
2926                 const QFontInfo fi(font);
2927                 return fi.fixedPitch();
2928         }
2929 } // namespace
2930
2931
2932 QFont const GuiApplication::typewriterSystemFont()
2933 {
2934 #if QT_VERSION >= 0x050200
2935         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2936 #else
2937         QFont font("monospace");
2938 #endif
2939         if (!isFixedPitch(font)) {
2940                 // try to enforce a real monospaced font
2941                 font.setStyleHint(QFont::Monospace);
2942                 if (!isFixedPitch(font)) {
2943                         font.setStyleHint(QFont::TypeWriter);
2944                         if (!isFixedPitch(font)) font.setFamily("courier");
2945                 }
2946         }
2947 #ifdef Q_OS_MAC
2948         // On a Mac the result is too small and it's not practical to
2949         // rely on Qtconfig utility to change the system settings of Qt.
2950         font.setPointSize(12);
2951 #endif
2952         return font;
2953 }
2954
2955
2956 void GuiApplication::handleRegularEvents()
2957 {
2958         ForkedCallsController::handleCompletedProcesses();
2959 }
2960
2961
2962 bool GuiApplication::event(QEvent * e)
2963 {
2964         switch(e->type()) {
2965         case QEvent::FileOpen: {
2966                 // Open a file; this happens only on Mac OS X for now.
2967                 //
2968                 // We do this asynchronously because on startup the batch
2969                 // commands are not executed here yet and the gui is not ready
2970                 // therefore.
2971                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2972                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2973                 processFuncRequestAsync(fr);
2974                 e->accept();
2975                 return true;
2976         }
2977 #if (QT_VERSION < 0x050000)
2978         // Qt5 uses a signal for that, see above.
2979         case QEvent::KeyboardLayoutChange:
2980                 //LYXERR0("keyboard change");
2981                 if (currentView() && currentView()->currentBufferView())
2982                         currentView()->currentBufferView()->cursor().setLanguageFromInput();
2983                 e->accept();
2984                 return true;
2985 #endif
2986         case QEvent::ApplicationPaletteChange: {
2987                 // runtime switch from/to dark mode
2988                 onPaletteChanged();
2989                 return QApplication::event(e);
2990         }
2991         default:
2992                 return QApplication::event(e);
2993         }
2994 }
2995
2996
2997 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2998 {
2999         try {
3000                 return QApplication::notify(receiver, event);
3001         }
3002         catch (ExceptionMessage const & e) {
3003                 switch(e.type_) {
3004                 case ErrorException:
3005                         emergencyCleanup();
3006                         setQuitOnLastWindowClosed(false);
3007                         closeAllViews();
3008                         Alert::error(e.title_, e.details_);
3009 #ifndef NDEBUG
3010                         // Properly crash in debug mode in order to get a useful backtrace.
3011                         abort();
3012 #endif
3013                         // In release mode, try to exit gracefully.
3014                         this->exit(1);
3015                         // FIXME: GCC 7 thinks we can fall through here. Can we?
3016                         // fall through
3017                 case BufferException: {
3018                         if (!current_view_ || !current_view_->documentBufferView())
3019                                 return false;
3020                         Buffer * buf = &current_view_->documentBufferView()->buffer();
3021                         docstring details = e.details_ + '\n';
3022                         details += buf->emergencyWrite();
3023                         theBufferList().release(buf);
3024                         details += "\n" + _("The current document was closed.");
3025                         Alert::error(e.title_, details);
3026                         return false;
3027                 }
3028                 case WarningException:
3029                         Alert::warning(e.title_, e.details_);
3030                         return false;
3031                 }
3032         }
3033         catch (exception const & e) {
3034                 docstring s = _("LyX has caught an exception, it will now "
3035                         "attempt to save all unsaved documents and exit."
3036                         "\n\nException: ");
3037                 s += from_ascii(e.what());
3038                 Alert::error(_("Software exception Detected"), s);
3039                 lyx_exit(1);
3040         }
3041         catch (...) {
3042                 docstring s = _("LyX has caught some really weird exception, it will "
3043                         "now attempt to save all unsaved documents and exit.");
3044                 Alert::error(_("Software exception Detected"), s);
3045                 lyx_exit(1);
3046         }
3047
3048         return false;
3049 }
3050
3051 bool GuiApplication::isInDarkMode()
3052 {
3053         return colorCache().isDarkMode();
3054 }
3055
3056
3057 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3058 {
3059         QColor const & qcol = d->color_cache_.get(col);
3060         if (!qcol.isValid()) {
3061                 rgbcol.r = 0;
3062                 rgbcol.g = 0;
3063                 rgbcol.b = 0;
3064                 return false;
3065         }
3066         rgbcol.r = qcol.red();
3067         rgbcol.g = qcol.green();
3068         rgbcol.b = qcol.blue();
3069         return true;
3070 }
3071
3072
3073 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3074 {
3075         QColor const qcol(lcolor.getX11HexName(col).c_str());
3076         if (!qcol.isValid()) {
3077                 rgbcol.r = 0;
3078                 rgbcol.g = 0;
3079                 rgbcol.b = 0;
3080                 return false;
3081         }
3082         rgbcol.r = qcol.red();
3083         rgbcol.g = qcol.green();
3084         rgbcol.b = qcol.blue();
3085         return true;
3086 }
3087
3088
3089 string const GuiApplication::hexName(ColorCode col)
3090 {
3091         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3092 }
3093
3094
3095 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3096 {
3097         SocketNotifier * sn = new SocketNotifier(this, fd, func);
3098         d->socket_notifiers_[fd] = sn;
3099         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3100 }
3101
3102
3103 void GuiApplication::socketDataReceived(int fd)
3104 {
3105         d->socket_notifiers_[fd]->func_();
3106 }
3107
3108
3109 void GuiApplication::unregisterSocketCallback(int fd)
3110 {
3111         d->socket_notifiers_.take(fd)->setEnabled(false);
3112 }
3113
3114
3115 void GuiApplication::commitData(QSessionManager & sm)
3116 {
3117         /** The implementation is required to avoid an application exit
3118          ** when session state save is triggered by session manager.
3119          ** The default implementation sends a close event to all
3120          ** visible top level widgets when session management allows
3121          ** interaction.
3122          ** We are changing that to check the state of each buffer in all
3123          ** views and ask the users what to do if buffers are dirty.
3124          ** Furthermore, we save the session state.
3125          ** We do NOT close the views here since the user still can cancel
3126          ** the logout process (see #9277); also, this would hide LyX from
3127          ** an OSes own session handling (application restoration).
3128          **/
3129         #ifdef QT_NO_SESSIONMANAGER
3130                 #ifndef _MSC_VER
3131                         #warning Qt is compiled without session manager
3132                 #else
3133                         #pragma message("warning: Qt is compiled without session manager")
3134                 #endif
3135                 (void) sm;
3136         #else
3137                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3138                         sm.cancel();
3139                 else
3140                         sm.release();
3141         #endif
3142 }
3143
3144
3145 void GuiApplication::unregisterView(GuiView * gv)
3146 {
3147         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3148                 d->views_.remove(gv->id());
3149                 if (current_view_ == gv)
3150                         current_view_ = nullptr;
3151         }
3152 }
3153
3154
3155 bool GuiApplication::closeAllViews()
3156 {
3157         if (d->views_.empty())
3158                 return true;
3159
3160         // When a view/window was closed before without quitting LyX, there
3161         // are already entries in the lastOpened list.
3162         theSession().lastOpened().clear();
3163
3164         QList<GuiView *> const views = d->views_.values();
3165         for (GuiView * view : views) {
3166                 if (!view->closeScheduled())
3167                         return false;
3168         }
3169
3170         d->views_.clear();
3171         return true;
3172 }
3173
3174
3175 bool GuiApplication::prepareAllViewsForLogout()
3176 {
3177         if (d->views_.empty())
3178                 return true;
3179
3180         QList<GuiView *> const views = d->views_.values();
3181         for (GuiView * view : views) {
3182                 if (!view->prepareAllBuffersForLogout())
3183                         return false;
3184         }
3185
3186         return true;
3187 }
3188
3189
3190 GuiView & GuiApplication::view(int id) const
3191 {
3192         LAPPERR(d->views_.contains(id));
3193         return *d->views_.value(id);
3194 }
3195
3196
3197 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3198 {
3199         QList<GuiView *> const views = d->views_.values();
3200         for (GuiView * view : views)
3201                 view->hideDialog(name, inset);
3202 }
3203
3204
3205 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3206 {
3207         Buffer const * buf = nullptr;
3208         QHash<int, GuiView *>::const_iterator end = d->views_.end();
3209         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3210                 if (Buffer const * ptr = (*it)->updateInset(inset))
3211                         buf = ptr;
3212         }
3213         return buf;
3214 }
3215
3216
3217 bool GuiApplication::searchMenu(FuncRequest const & func,
3218         docstring_list & names) const
3219 {
3220         BufferView * bv = nullptr;
3221         if (current_view_)
3222                 bv = current_view_->currentBufferView();
3223         return d->menus_.searchMenu(func, names, bv);
3224 }
3225
3226
3227 bool GuiApplication::hasBufferView() const
3228 {
3229         return (current_view_ && current_view_->currentBufferView());
3230 }
3231
3232
3233 // Ensure that a file is read only once (prevents include loops)
3234 static QStringList uifiles;
3235 // store which ui files define Toolbars
3236 static QStringList toolbar_uifiles;
3237
3238
3239 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3240 {
3241         enum {
3242                 ui_menuset = 1,
3243                 ui_toolbars,
3244                 ui_toolbarset,
3245                 ui_include,
3246                 ui_format,
3247                 ui_last
3248         };
3249
3250         LexerKeyword uitags[] = {
3251                 { "format", ui_format },
3252                 { "include", ui_include },
3253                 { "menuset", ui_menuset },
3254                 { "toolbars", ui_toolbars },
3255                 { "toolbarset", ui_toolbarset }
3256         };
3257
3258         Lexer lex(uitags);
3259         lex.setFile(ui_path);
3260         if (!lex.isOK()) {
3261                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3262                                          << endl;
3263         }
3264
3265         if (lyxerr.debugging(Debug::PARSER))
3266                 lex.printTable(lyxerr);
3267
3268         bool error = false;
3269         // format before introduction of format tag
3270         unsigned int format = 0;
3271         while (lex.isOK()) {
3272                 int const status = lex.lex();
3273
3274                 // we have to do this check here, outside the switch,
3275                 // because otherwise we would start reading include files,
3276                 // e.g., if the first tag we hit was an include tag.
3277                 if (status == ui_format)
3278                         if (lex.next()) {
3279                                 format = lex.getInteger();
3280                                 continue;
3281                         }
3282
3283                 // this will trigger unless the first tag we hit is a format
3284                 // tag, with the right format.
3285                 if (format != LFUN_FORMAT)
3286                         return FormatMismatch;
3287
3288                 switch (status) {
3289                 case Lexer::LEX_FEOF:
3290                         continue;
3291
3292                 case ui_include: {
3293                         lex.next(true);
3294                         QString const file = toqstr(lex.getString());
3295                         bool const success = readUIFile(file, true);
3296                         if (!success) {
3297                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3298                                 return ReadError;
3299                         }
3300                         break;
3301                 }
3302
3303                 case ui_menuset:
3304                         d->menus_.read(lex);
3305                         break;
3306
3307                 case ui_toolbarset:
3308                         d->toolbars_.readToolbars(lex);
3309                         break;
3310
3311                 case ui_toolbars:
3312                         d->toolbars_.readToolbarSettings(lex);
3313                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3314                         break;
3315
3316                 default:
3317                         if (!rtrim(lex.getString()).empty())
3318                                 lex.printError("LyX::ReadUIFile: "
3319                                                "Unknown menu tag: `$$Token'");
3320                         else
3321                                 LYXERR0("Error with status: " << status);
3322                         error = true;
3323                         break;
3324                 }
3325
3326         }
3327         return (error ? ReadError : ReadOK);
3328 }
3329
3330
3331 bool GuiApplication::readUIFile(QString const & name, bool include)
3332 {
3333         LYXERR(Debug::INIT, "About to read " << name << "...");
3334
3335         FileName ui_path;
3336         if (include) {
3337                 ui_path = libFileSearch("ui", name, "inc");
3338                 if (ui_path.empty())
3339                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3340         } else {
3341                 ui_path = libFileSearch("ui", name, "ui");
3342         }
3343
3344         if (ui_path.empty()) {
3345                 static const QString defaultUIFile = "default";
3346                 LYXERR(Debug::INIT, "Could not find " << name);
3347                 if (include) {
3348                         Alert::warning(_("Could not find UI definition file"),
3349                                 bformat(_("Error while reading the included file\n%1$s\n"
3350                                         "Please check your installation."), qstring_to_ucs4(name)));
3351                         return false;
3352                 }
3353                 if (name == defaultUIFile) {
3354                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3355                         Alert::warning(_("Could not find default UI file"),
3356                                 _("LyX could not find the default UI file!\n"
3357                                   "Please check your installation."));
3358                         return false;
3359                 }
3360                 Alert::warning(_("Could not find UI definition file"),
3361                 bformat(_("Error while reading the configuration file\n%1$s\n"
3362                         "Falling back to default.\n"
3363                         "Please look under Tools>Preferences>User Interface and\n"
3364                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3365                 return readUIFile(defaultUIFile, false);
3366         }
3367
3368         QString const uifile = toqstr(ui_path.absFileName());
3369         if (uifiles.contains(uifile)) {
3370                 if (!include) {
3371                         // We are reading again the top uifile so reset the safeguard:
3372                         uifiles.clear();
3373                         d->menus_.reset();
3374                         d->toolbars_.reset();
3375                 } else {
3376                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3377                                 << "Is this an include loop?");
3378                         return false;
3379                 }
3380         }
3381         uifiles.push_back(uifile);
3382
3383         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3384
3385         ReturnValues retval = readUIFile(ui_path);
3386
3387         if (retval == FormatMismatch) {
3388                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3389                 TempFile tmp("convertXXXXXX.ui");
3390                 FileName const tempfile = tmp.name();
3391                 bool const success = prefs2prefs(ui_path, tempfile, true);
3392                 if (!success) {
3393                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3394                                 " to format " << LFUN_FORMAT << ".");
3395                 } else {
3396                         retval = readUIFile(tempfile);
3397                 }
3398         }
3399
3400         if (retval != ReadOK) {
3401                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3402                 return false;
3403         }
3404
3405         if (include)
3406                 return true;
3407
3408         QSettings settings;
3409         settings.beginGroup("ui_files");
3410         bool touched = false;
3411         for (int i = 0; i != uifiles.size(); ++i) {
3412                 QFileInfo fi(uifiles[i]);
3413                 QDateTime const date_value = fi.lastModified();
3414                 QString const name_key = QString::number(i);
3415                 // if an ui file which defines Toolbars has changed,
3416                 // we have to reset the settings
3417                 if (toolbar_uifiles.contains(uifiles[i])
3418                  && (!settings.contains(name_key)
3419                  || settings.value(name_key).toString() != uifiles[i]
3420                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3421                         touched = true;
3422                         settings.setValue(name_key, uifiles[i]);
3423                         settings.setValue(name_key + "/date", date_value);
3424                 }
3425         }
3426         settings.endGroup();
3427         if (touched)
3428                 settings.remove("views");
3429
3430         return true;
3431 }
3432
3433
3434 void GuiApplication::onLastWindowClosed()
3435 {
3436         if (d->global_menubar_)
3437                 d->global_menubar_->grabKeyboard();
3438 }
3439
3440
3441 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3442 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3443 {
3444         std::string name = "unknown";
3445         switch (state) {
3446         case Qt::ApplicationSuspended:
3447                 name = "ApplicationSuspended";
3448                 break;
3449         case Qt::ApplicationHidden:
3450                 name = "ApplicationHidden";
3451                 break;
3452         case Qt::ApplicationInactive:
3453                 name = "ApplicationInactive";
3454                 break;
3455         case Qt::ApplicationActive:
3456                 name = "ApplicationActive";
3457                 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3458                 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3459                 if (d->views_.empty() && d->last_state_ == state) {
3460                         LYXERR(Debug::GUI, "Open new window...");
3461                         createView();
3462                 }
3463                 break;
3464         }
3465         LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3466         d->last_state_ = state;
3467 }
3468 #endif
3469
3470
3471 void GuiApplication::startLongOperation() {
3472         d->key_checker_.start();
3473 }
3474
3475
3476 bool GuiApplication::longOperationCancelled() {
3477         return d->key_checker_.pressed();
3478 }
3479
3480
3481 void GuiApplication::stopLongOperation() {
3482         d->key_checker_.stop();
3483 }
3484
3485
3486 bool GuiApplication::longOperationStarted() {
3487         return d->key_checker_.started();
3488 }
3489
3490
3491 ////////////////////////////////////////////////////////////////////////
3492 //
3493 // X11 specific stuff goes here...
3494
3495 #ifdef Q_WS_X11
3496 bool GuiApplication::x11EventFilter(XEvent * xev)
3497 {
3498         if (!current_view_)
3499                 return false;
3500
3501         switch (xev->type) {
3502         case SelectionRequest: {
3503                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3504                         break;
3505                 LYXERR(Debug::SELECTION, "X requested selection.");
3506                 BufferView * bv = current_view_->currentBufferView();
3507                 if (bv) {
3508                         docstring const sel = bv->requestSelection();
3509                         if (!sel.empty()) {
3510                                 d->selection_.put(sel);
3511                                 // Refresh the selection request timestamp.
3512                                 // We have to do this by ourselves as Qt seems
3513                                 // not doing that, maybe because of our
3514                                 // "persistent selection" implementation
3515                                 // (see comments in GuiSelection.cpp).
3516                                 XSelectionEvent nev;
3517                                 nev.type = SelectionNotify;
3518                                 nev.display = xev->xselectionrequest.display;
3519                                 nev.requestor = xev->xselectionrequest.requestor;
3520                                 nev.selection = xev->xselectionrequest.selection;
3521                                 nev.target = xev->xselectionrequest.target;
3522                                 nev.property = 0L; // None
3523                                 nev.time = CurrentTime;
3524                                 XSendEvent(QX11Info::display(),
3525                                         nev.requestor, False, 0,
3526                                         reinterpret_cast<XEvent *>(&nev));
3527                                 return true;
3528                         }
3529                 }
3530                 break;
3531         }
3532         case SelectionClear: {
3533                 if (xev->xselectionclear.selection != XA_PRIMARY)
3534                         break;
3535                 LYXERR(Debug::SELECTION, "Lost selection.");
3536                 BufferView * bv = current_view_->currentBufferView();
3537                 if (bv)
3538                         bv->clearSelection();
3539                 break;
3540         }
3541         }
3542         return false;
3543 }
3544 #elif defined(QPA_XCB)
3545 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3546                                        void * message, long *)
3547 {
3548         if (!current_view_ || eventType != "xcb_generic_event_t")
3549                 return false;
3550
3551         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3552
3553         switch (ev->response_type) {
3554         case XCB_SELECTION_REQUEST: {
3555                 xcb_selection_request_event_t * srev =
3556                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3557                 if (srev->selection != XCB_ATOM_PRIMARY)
3558                         break;
3559                 LYXERR(Debug::SELECTION, "X requested selection.");
3560                 BufferView * bv = current_view_->currentBufferView();
3561                 if (bv) {
3562                         docstring const sel = bv->requestSelection();
3563                         if (!sel.empty()) {
3564                                 d->selection_.put(sel);
3565 #ifdef HAVE_QT5_X11_EXTRAS
3566                                 // Refresh the selection request timestamp.
3567                                 // We have to do this by ourselves as Qt seems
3568                                 // not doing that, maybe because of our
3569                                 // "persistent selection" implementation
3570                                 // (see comments in GuiSelection.cpp).
3571                                 // It is expected that every X11 event is
3572                                 // 32 bytes long, even if not all 32 bytes are
3573                                 // needed. See:
3574                                 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3575                                 struct alignas(32) padded_event
3576                                         : xcb_selection_notify_event_t {};
3577                                 padded_event nev = {};
3578                                 nev.response_type = XCB_SELECTION_NOTIFY;
3579                                 nev.requestor = srev->requestor;
3580                                 nev.selection = srev->selection;
3581                                 nev.target = srev->target;
3582                                 nev.property = XCB_NONE;
3583                                 nev.time = XCB_CURRENT_TIME;
3584                                 xcb_connection_t * con = QX11Info::connection();
3585                                 xcb_send_event(con, 0, srev->requestor,
3586                                         XCB_EVENT_MASK_NO_EVENT,
3587                                         reinterpret_cast<char const *>(&nev));
3588                                 xcb_flush(con);
3589 #endif
3590                                 return true;
3591                         }
3592                 }
3593                 break;
3594         }
3595         case XCB_SELECTION_CLEAR: {
3596                 xcb_selection_clear_event_t * scev =
3597                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3598                 if (scev->selection != XCB_ATOM_PRIMARY)
3599                         break;
3600                 LYXERR(Debug::SELECTION, "Lost selection.");
3601                 BufferView * bv = current_view_->currentBufferView();
3602                 if (bv)
3603                         bv->clearSelection();
3604                 break;
3605         }
3606         }
3607         return false;
3608 }
3609 #endif
3610
3611 } // namespace frontend
3612
3613
3614 void hideDialogs(std::string const & name, Inset * inset)
3615 {
3616         if (theApp())
3617                 frontend::guiApp->hideDialogs(name, inset);
3618 }
3619
3620
3621 ////////////////////////////////////////////////////////////////////
3622 //
3623 // Font stuff
3624 //
3625 ////////////////////////////////////////////////////////////////////
3626
3627 frontend::FontLoader & theFontLoader()
3628 {
3629         LAPPERR(frontend::guiApp);
3630         return frontend::guiApp->fontLoader();
3631 }
3632
3633
3634 frontend::FontMetrics const & theFontMetrics(Font const & f)
3635 {
3636         return theFontMetrics(f.fontInfo());
3637 }
3638
3639
3640 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3641 {
3642         LAPPERR(frontend::guiApp);
3643         return frontend::guiApp->fontLoader().metrics(f);
3644 }
3645
3646
3647 ////////////////////////////////////////////////////////////////////
3648 //
3649 // Misc stuff
3650 //
3651 ////////////////////////////////////////////////////////////////////
3652
3653 frontend::Clipboard & theClipboard()
3654 {
3655         LAPPERR(frontend::guiApp);
3656         return frontend::guiApp->clipboard();
3657 }
3658
3659
3660 frontend::Selection & theSelection()
3661 {
3662         LAPPERR(frontend::guiApp);
3663         return frontend::guiApp->selection();
3664 }
3665
3666
3667 } // namespace lyx
3668
3669 #include "moc_GuiApplication.cpp"