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