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