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