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