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