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