]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiApplication.cpp
Simplify
[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 void Application::applyPrefs()
1272 {
1273         if (lyxrc.ui_style != "default")
1274                 lyx::frontend::GuiApplication::setStyle(toqstr(lyxrc.ui_style));
1275 }
1276
1277 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1278 {
1279         FuncStatus status;
1280
1281         BufferView * bv = nullptr;
1282         BufferView * doc_bv = nullptr;
1283
1284         if (cmd.action() == LFUN_NOACTION) {
1285                 status.message(from_utf8(N_("Nothing to do")));
1286                 status.setEnabled(false);
1287         }
1288
1289         else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1290                 status.setUnknown(true);
1291                 status.message(from_utf8(N_("Unknown action")));
1292                 status.setEnabled(false);
1293         }
1294
1295         // Does the GuiApplication know something?
1296         else if (getStatus(cmd, status)) { }
1297
1298         // If we do not have a GuiView, then other functions are disabled
1299         else if (!current_view_)
1300                 status.setEnabled(false);
1301
1302         // Does the GuiView know something?
1303         else if (current_view_->getStatus(cmd, status)) { }
1304
1305         // In LyX/Mac, when a dialog is open, the menus of the
1306         // application can still be accessed without giving focus to
1307         // the main window. In this case, we want to disable the menu
1308         // entries that are buffer or view-related.
1309         //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1310         /*
1311         else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1312                 status.setEnabled(false);
1313         */
1314
1315         // If we do not have a BufferView, then other functions are disabled
1316         else if (!(bv = current_view_->currentBufferView()))
1317                 status.setEnabled(false);
1318
1319         // Does the current BufferView know something?
1320         else if (bv->getStatus(cmd, status)) { }
1321
1322         // Does the current Buffer know something?
1323         else if (bv->buffer().getStatus(cmd, status)) { }
1324
1325         // If we do not have a document BufferView, different from the
1326         // current BufferView, then other functions are disabled
1327         else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1328                 status.setEnabled(false);
1329
1330         // Does the document Buffer know something?
1331         else if (doc_bv->buffer().getStatus(cmd, status)) { }
1332
1333         else {
1334                 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1335                 status.message(from_utf8(N_("Command not handled")));
1336                 status.setEnabled(false);
1337         }
1338
1339         // the default error message if we disable the command
1340         if (!status.enabled() && status.message().empty())
1341                 status.message(from_utf8(N_("Command disabled")));
1342
1343         return status;
1344 }
1345
1346
1347 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1348 {
1349         // I would really like to avoid having this switch and rather try to
1350         // encode this in the function itself.
1351         // -- And I'd rather let an inset decide which LFUNs it is willing
1352         // to handle (Andre')
1353         bool enable = true;
1354         switch (cmd.action()) {
1355
1356         // This could be used for the no-GUI version. The GUI version is handled in
1357         // GuiView::getStatus(). See above.
1358         /*
1359         case LFUN_BUFFER_WRITE:
1360         case LFUN_BUFFER_WRITE_AS:
1361         case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1362                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1363                 enable = b && (b->isUnnamed() || !b->isClean());
1364                 break;
1365         }
1366         */
1367
1368         case LFUN_BOOKMARK_GOTO: {
1369                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1370                 enable = theSession().bookmarks().isValid(num);
1371                 break;
1372         }
1373
1374         case LFUN_BOOKMARK_CLEAR:
1375                 enable = theSession().bookmarks().hasValid();
1376                 break;
1377
1378         // this one is difficult to get right. As a half-baked
1379         // solution, we consider only the first action of the sequence
1380         case LFUN_COMMAND_SEQUENCE: {
1381                 // argument contains ';'-terminated commands
1382                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1383                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1384                 func.setOrigin(cmd.origin());
1385                 flag = getStatus(func);
1386                 break;
1387         }
1388
1389         // we want to check if at least one of these is enabled
1390         case LFUN_COMMAND_ALTERNATIVES: {
1391                 // argument contains ';'-terminated commands
1392                 string arg = to_utf8(cmd.argument());
1393                 while (!arg.empty()) {
1394                         string first;
1395                         arg = split(arg, first, ';');
1396                         FuncRequest func(lyxaction.lookupFunc(first));
1397                         func.setOrigin(cmd.origin());
1398                         flag = getStatus(func);
1399                         // if this one is enabled, the whole thing is
1400                         if (flag.enabled())
1401                                 break;
1402                 }
1403                 break;
1404         }
1405
1406         case LFUN_CALL: {
1407                 FuncRequest func;
1408                 string name = to_utf8(cmd.argument());
1409                 if (theTopLevelCmdDef().lock(name, func)) {
1410                         func.setOrigin(cmd.origin());
1411                         flag = getStatus(func);
1412                         theTopLevelCmdDef().release(name);
1413                 } else {
1414                         // catch recursion or unknown command
1415                         // definition. all operations until the
1416                         // recursion or unknown command definition
1417                         // occurs are performed, so set the state to
1418                         // enabled
1419                         enable = true;
1420                 }
1421                 break;
1422         }
1423
1424         case LFUN_IF_RELATIVES: {
1425                 string const lfun = to_utf8(cmd.argument());
1426                 BufferView const * bv =
1427                         current_view_ ? current_view_->currentBufferView() : nullptr;
1428                 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1429                         enable = false;
1430                         break;
1431                 }
1432                 FuncRequest func(lyxaction.lookupFunc(lfun));
1433                 func.setOrigin(cmd.origin());
1434                 flag = getStatus(func);
1435                 break;
1436         }
1437
1438         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1439         case LFUN_REPEAT:
1440         case LFUN_PREFERENCES_SAVE:
1441         case LFUN_BUFFER_SAVE_AS_DEFAULT:
1442                 // these are handled in our dispatch()
1443                 break;
1444
1445         case LFUN_DEBUG_LEVEL_SET: {
1446                 string bad = Debug::badValue(to_utf8(cmd.argument()));
1447                 enable = bad.empty();
1448                 if (!bad.empty())
1449                         flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1450                 break;
1451         }
1452
1453         case LFUN_WINDOW_CLOSE:
1454                 enable = !d->views_.empty();
1455                 break;
1456
1457         case LFUN_BUFFER_NEW:
1458         case LFUN_BUFFER_NEW_TEMPLATE:
1459         case LFUN_FILE_OPEN:
1460         case LFUN_LYXFILES_OPEN:
1461         case LFUN_HELP_OPEN:
1462         case LFUN_SCREEN_FONT_UPDATE:
1463         case LFUN_SET_COLOR:
1464         case LFUN_WINDOW_NEW:
1465         case LFUN_LYX_QUIT:
1466         case LFUN_LYXRC_APPLY:
1467         case LFUN_COMMAND_PREFIX:
1468         case LFUN_CANCEL:
1469         case LFUN_META_PREFIX:
1470         case LFUN_RECONFIGURE:
1471         case LFUN_SERVER_GET_FILENAME:
1472         case LFUN_SERVER_NOTIFY:
1473                 enable = true;
1474                 break;
1475
1476         case LFUN_BUFFER_FORALL: {
1477                 if (theBufferList().empty()) {
1478                         flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1479                         flag.setEnabled(false);
1480                         break;
1481                 }
1482
1483                 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1484                 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1485                         flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1486                         flag.setEnabled(false);
1487                 }
1488                 break;
1489         }
1490
1491         case LFUN_DIALOG_SHOW: {
1492                 string const name = cmd.getArg(0);
1493                 return name == "aboutlyx"
1494                         || name == "lyxfiles"
1495                         || name == "prefs"
1496                         || name == "texinfo"
1497                         || name == "progress"
1498                         || name == "compare";
1499         }
1500
1501         default:
1502                 return false;
1503         }
1504
1505         if (!enable)
1506                 flag.setEnabled(false);
1507         return true;
1508 }
1509
1510 /// make a post-dispatch status message
1511 static docstring makeDispatchMessage(docstring const & msg,
1512                                      FuncRequest const & cmd)
1513 {
1514         const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1515                               || cmd.origin() == FuncRequest::TOOLBAR
1516                               || cmd.origin() == FuncRequest::COMMANDBUFFER);
1517
1518         if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1519                 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1520                 return msg;
1521         }
1522
1523         docstring dispatch_msg = msg;
1524         if (!dispatch_msg.empty())
1525                 dispatch_msg += ' ';
1526
1527         docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1528
1529         bool argsadded = false;
1530
1531         if (!cmd.argument().empty()) {
1532                 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1533                         comname += ' ' + cmd.argument();
1534                         argsadded = true;
1535                 }
1536         }
1537         docstring const shortcuts = theTopLevelKeymap().
1538                 printBindings(cmd, KeySequence::ForGui);
1539
1540         if (!shortcuts.empty())
1541                 comname += ": " + shortcuts;
1542         else if (!argsadded && !cmd.argument().empty())
1543                 comname += ' ' + cmd.argument();
1544
1545         if (!comname.empty()) {
1546                 comname = rtrim(comname);
1547                 dispatch_msg += '(' + rtrim(comname) + ')';
1548         }
1549         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1550         return dispatch_msg;
1551 }
1552
1553
1554 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1555 {
1556         DispatchResult dr;
1557
1558         Buffer * buffer = nullptr;
1559         if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1560                 //setCurrentView(cmd.view_origin); //does not work
1561                 dr.setError(true);
1562                 dr.setMessage(_("Wrong focus!"));
1563                 d->dispatch_result_ = dr;
1564                 return d->dispatch_result_;
1565         }
1566         if (current_view_ && current_view_->currentBufferView()) {
1567                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1568                 buffer = &current_view_->currentBufferView()->buffer();
1569         }
1570
1571         dr.screenUpdate(Update::FitCursor);
1572         {
1573                 // All the code is kept inside the undo group because
1574                 // updateBuffer can create undo actions (see #11292)
1575                 UndoGroupHelper ugh(buffer);
1576                 dispatch(cmd, dr);
1577                 if (dr.screenUpdate() & Update::ForceAll) {
1578                         for (Buffer const * b : theBufferList())
1579                                 b->changed(true);
1580                         dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1581                 }
1582
1583                 updateCurrentView(cmd, dr);
1584         }
1585
1586         d->dispatch_result_ = dr;
1587         return d->dispatch_result_;
1588 }
1589
1590
1591 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1592 {
1593         if (!current_view_)
1594                 return;
1595
1596         BufferView * bv = current_view_->currentBufferView();
1597         if (bv) {
1598                 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1599                         bv->cursor().clearBufferUpdate();
1600                         bv->buffer().updateBuffer();
1601                 }
1602                 // BufferView::update() updates the ViewMetricsInfo and
1603                 // also initializes the position cache for all insets in
1604                 // (at least partially) visible top-level paragraphs.
1605                 // We will redraw the screen only if needed.
1606                 bv->processUpdateFlags(dr.screenUpdate());
1607
1608                 // Do we have a selection?
1609                 theSelection().haveSelection(bv->cursor().selection());
1610
1611                 // update gui
1612                 current_view_->restartCaret();
1613         }
1614         if (dr.needMessageUpdate()) {
1615                 // Some messages may already be translated, so we cannot use _()
1616                 current_view_->message(makeDispatchMessage(
1617                                 translateIfPossible(dr.message()), cmd));
1618         }
1619 }
1620
1621
1622 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1623         bool switchToBuffer)
1624 {
1625         if (!theSession().bookmarks().isValid(idx))
1626                 return;
1627         BookmarksSection::Bookmark const & bm =
1628                 theSession().bookmarks().bookmark(idx);
1629         LASSERT(!bm.filename.empty(), return);
1630         string const file = bm.filename.absFileName();
1631         // if the file is not opened, open it.
1632         if (!theBufferList().exists(bm.filename)) {
1633                 if (openFile)
1634                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1635                 else
1636                         return;
1637         }
1638         // open may fail, so we need to test it again
1639         if (!theBufferList().exists(bm.filename))
1640                 return;
1641
1642         // bm can be changed when saving
1643         BookmarksSection::Bookmark tmp = bm;
1644
1645         // Special case idx == 0 used for back-from-back jump navigation
1646         if (idx == 0)
1647                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1648
1649         // if the current buffer is not that one, switch to it.
1650         BufferView * doc_bv = current_view_ ?
1651                 current_view_->documentBufferView() : nullptr;
1652         Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1653         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1654                 if (switchToBuffer) {
1655                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1656                         if (!current_view_)
1657                                 return;
1658                         doc_bv = current_view_->documentBufferView();
1659                 } else
1660                         return;
1661         }
1662
1663         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1664         if (!doc_bv || !doc_bv->moveToPosition(
1665                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1666                 return;
1667
1668         Cursor & cur = doc_bv->cursor();
1669         if (old && cur != *old)
1670                 notifyCursorLeavesOrEnters(*old, cur);
1671
1672         // bm changed
1673         if (idx == 0)
1674                 return;
1675
1676         // Cursor jump succeeded!
1677         pit_type new_pit = cur.pit();
1678         pos_type new_pos = cur.pos();
1679         int new_id = cur.paragraph().id();
1680
1681         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1682         // see http://www.lyx.org/trac/ticket/3092
1683         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1684                 || bm.top_id != new_id) {
1685                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1686                         new_pit, new_pos, new_id);
1687         }
1688 }
1689
1690 // This function runs "configure" and then rereads lyx.defaults to
1691 // reconfigure the automatic settings.
1692 void GuiApplication::reconfigure(string const & option)
1693 {
1694         // emit message signal.
1695         if (current_view_) {
1696                 current_view_->message(_("Running configure..."));
1697                 current_view_->setCursor(Qt::WaitCursor);
1698         }
1699
1700         // Run configure in user lyx directory
1701         string const lock_file = package().getConfigureLockName();
1702         int fd = fileLock(lock_file.c_str());
1703         int const ret = package().reconfigureUserLyXDir(option);
1704         // emit message signal.
1705         if (current_view_)
1706                 current_view_->message(_("Reloading configuration..."));
1707         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1708         // Re-read packages.lst
1709         LaTeXPackages::getAvailable();
1710         fileUnlock(fd, lock_file.c_str());
1711
1712         if (current_view_)
1713                 current_view_->unsetCursor();
1714
1715         if (ret)
1716                 Alert::information(_("System reconfiguration failed"),
1717                            _("The system reconfiguration has failed.\n"
1718                                   "Default textclass is used but LyX may\n"
1719                                   "not be able to work properly.\n"
1720                                   "Please reconfigure again if needed."));
1721         else
1722                 Alert::information(_("System reconfigured"),
1723                            _("The system has been reconfigured.\n"
1724                              "You need to restart LyX to make use of any\n"
1725                              "updated document class specifications."));
1726 }
1727
1728 void GuiApplication::validateCurrentView()
1729 {
1730         if (!d->views_.empty() && !current_view_) {
1731                 // currently at least one view exists but no view has the focus.
1732                 // choose the last view to make it current.
1733                 // a view without any open document is preferred.
1734                 GuiView * candidate = nullptr;
1735                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1736                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1737                 for (; it != end; ++it) {
1738                         candidate = *it;
1739                         if (!candidate->documentBufferView())
1740                                 break;
1741                 }
1742                 setCurrentView(candidate);
1743         }
1744 }
1745
1746 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1747 {
1748         string const argument = to_utf8(cmd.argument());
1749         FuncCode const action = cmd.action();
1750
1751         LYXERR(Debug::ACTION, "cmd: " << cmd);
1752
1753         // we have not done anything wrong yet.
1754         dr.setError(false);
1755
1756         FuncStatus const flag = getStatus(cmd);
1757         if (!flag.enabled()) {
1758                 // We cannot use this function here
1759                 LYXERR(Debug::ACTION, "action "
1760                        << lyxaction.getActionName(action)
1761                        << " [" << action << "] is disabled at this location");
1762                 dr.setMessage(flag.message());
1763                 dr.setError(true);
1764                 dr.dispatched(false);
1765                 dr.screenUpdate(Update::None);
1766                 dr.clearBufferUpdate();
1767                 return;
1768         };
1769
1770         if (cmd.origin() == FuncRequest::LYXSERVER) {
1771                 if (current_view_ && current_view_->currentBufferView())
1772                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1773                 // we will also need to redraw the screen at the end
1774                 dr.screenUpdate(Update::FitCursor);
1775         }
1776
1777         // Assumes that the action will be dispatched.
1778         dr.dispatched(true);
1779
1780         switch (cmd.action()) {
1781
1782         case LFUN_WINDOW_NEW:
1783                 createView(toqstr(cmd.argument()));
1784                 break;
1785
1786         case LFUN_WINDOW_CLOSE:
1787                 // FIXME: this is done also in GuiView::closeBuffer()!
1788                 // update bookmark pit of the current buffer before window close
1789                 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1790                         gotoBookmark(i, false, false);
1791                 // clear the last opened list, because
1792                 // maybe this will end the session
1793                 theSession().lastOpened().clear();
1794                 // check for valid current_view_
1795                 validateCurrentView();
1796                 if (current_view_)
1797                         current_view_->closeScheduled();
1798                 break;
1799
1800         case LFUN_LYX_QUIT:
1801                 // quitting is triggered by the gui code
1802                 // (leaving the event loop).
1803                 if (current_view_)
1804                         current_view_->message(from_utf8(N_("Exiting.")));
1805                 if (closeAllViews())
1806                         quit();
1807                 break;
1808
1809         case LFUN_SCREEN_FONT_UPDATE: {
1810                 // handle the screen font changes.
1811                 /* FIXME: this only updates the current document, whereas all
1812                  * documents should see their metrics updated.
1813                  */
1814                 d->font_loader_.update();
1815                 dr.screenUpdate(Update::Force | Update::FitCursor);
1816                 break;
1817         }
1818
1819         case LFUN_BUFFER_NEW:
1820                 validateCurrentView();
1821                 if (!current_view_
1822                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1823                         createView(QString(), false); // keep hidden
1824                         current_view_->newDocument(to_utf8(cmd.argument()));
1825                         current_view_->show();
1826                         current_view_->activateWindow();
1827                 } else {
1828                         current_view_->newDocument(to_utf8(cmd.argument()));
1829                 }
1830                 break;
1831
1832         case LFUN_BUFFER_NEW_TEMPLATE: {
1833                 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1834                 string const temp = cmd.getArg(1);
1835                 validateCurrentView();
1836                 if (!current_view_
1837                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1838                         createView();
1839                         current_view_->newDocument(file, temp, true);
1840                         if (!current_view_->documentBufferView())
1841                                 current_view_->close();
1842                 } else {
1843                         current_view_->newDocument(file, temp, true);
1844                 }
1845                 break;
1846         }
1847
1848         case LFUN_FILE_OPEN: {
1849                 // FIXME: normally the code below is not needed, since getStatus makes sure that
1850                 //   current_view_ is not null.
1851                 validateCurrentView();
1852                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1853                 string const fname = trim(to_utf8(cmd.argument()), "\"");
1854                 bool const is_open = FileName::isAbsolute(fname)
1855                         && theBufferList().getBuffer(FileName(fname));
1856                 if (!current_view_
1857                     || (!lyxrc.open_buffers_in_tabs
1858                         && current_view_->documentBufferView() != nullptr
1859                         && !is_open)) {
1860                         // We want the ui session to be saved per document and not per
1861                         // window number. The filename crc is a good enough identifier.
1862                         createView(support::checksum(fname));
1863                         current_view_->openDocuments(fname, cmd.origin());
1864                         if (!current_view_->documentBufferView())
1865                                 current_view_->close();
1866                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1867                                 current_view_->raise();
1868                                 current_view_->activateWindow();
1869                                 current_view_->showNormal();
1870                         }
1871                 } else {
1872                         current_view_->openDocuments(fname, cmd.origin());
1873                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1874                                 current_view_->raise();
1875                                 current_view_->activateWindow();
1876                                 current_view_->showNormal();
1877                         }
1878                 }
1879                 break;
1880         }
1881
1882         case LFUN_HELP_OPEN: {
1883                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1884                 if (current_view_ == nullptr)
1885                         createView();
1886                 string const arg = to_utf8(cmd.argument());
1887                 if (arg.empty()) {
1888                         current_view_->message(_("Missing argument"));
1889                         break;
1890                 }
1891                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1892                 if (fname.empty())
1893                         fname = i18nLibFileSearch("examples", arg, "lyx");
1894
1895                 if (fname.empty()) {
1896                         lyxerr << "LyX: unable to find documentation file `"
1897                                << arg << "'. Bad installation?" << endl;
1898                         break;
1899                 }
1900                 current_view_->message(bformat(_("Opening help file %1$s..."),
1901                                                makeDisplayPath(fname.absFileName())));
1902                 Buffer * buf = current_view_->loadDocument(fname, false);
1903                 if (buf)
1904                         buf->setReadonly(!current_view_->develMode());
1905                 break;
1906         }
1907
1908         case LFUN_LYXFILES_OPEN: {
1909                 string arg = to_utf8(cmd.argument());
1910                 if (arg.empty())
1911                         // set default
1912                         arg = "templates";
1913                 if (arg != "templates" && arg != "examples") {
1914                         current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1915                         break;
1916                 }
1917                 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1918                 break;
1919         }
1920
1921         case LFUN_SET_COLOR: {
1922                 string const lyx_name = cmd.getArg(0);
1923                 string x11_name = cmd.getArg(1);
1924                 string x11_darkname = cmd.getArg(2);
1925                 if (lyx_name.empty() || x11_name.empty()) {
1926                         if (current_view_)
1927                                 current_view_->message(
1928                                         _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1929                         break;
1930                 }
1931
1932 #if 0
1933                 // FIXME: The graphics cache no longer has a changeDisplay method.
1934                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1935                 bool const graphicsbg_changed =
1936                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1937                 if (graphicsbg_changed)
1938                         graphics::GCache::get().changeDisplay(true);
1939 #endif
1940
1941                 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1942                         x11_darkname = x11_name;
1943                         x11_name.clear();
1944                 }
1945                 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1946                         if (current_view_)
1947                                 current_view_->message(
1948                                         bformat(_("Set-color \"%1$s\" failed "
1949                                         "- color is undefined or "
1950                                         "may not be redefined"),
1951                                         from_utf8(lyx_name)));
1952                         break;
1953                 }
1954                 // Make sure we don't keep old colors in cache.
1955                 d->color_cache_.clear();
1956                 // Update the current view
1957                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1958                 break;
1959         }
1960
1961         case LFUN_LYXRC_APPLY: {
1962                 // reset active key sequences, since the bindings
1963                 // are updated (bug 6064)
1964                 d->keyseq.reset();
1965                 LyXRC const lyxrc_orig = lyxrc;
1966
1967                 istringstream ss(to_utf8(cmd.argument()));
1968                 bool const success = lyxrc.read(ss);
1969
1970                 if (!success) {
1971                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1972                                         << "Unable to read lyxrc data"
1973                                         << endl;
1974                         break;
1975                 }
1976
1977                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1978
1979                 // If the request comes from the minibuffer, then we can't reset
1980                 // the GUI, since that would destroy the minibuffer itself and
1981                 // cause a crash, since we are currently in one of the methods of
1982                 // GuiCommandBuffer. See bug #8540.
1983                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1984                         resetGui();
1985                 // else
1986                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1987                 //   reset the GUI in this case. If the changes to lyxrc affected the
1988                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1989                 //   it definitely is a bug.
1990
1991                 dr.forceBufferUpdate();
1992                 break;
1993         }
1994
1995         case LFUN_COMMAND_PREFIX:
1996                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1997                 break;
1998
1999         case LFUN_CANCEL: {
2000                 d->keyseq.reset();
2001                 d->meta_fake_bit = NoModifier;
2002                 GuiView * gv = currentView();
2003                 if (gv && gv->currentBufferView())
2004                         // cancel any selection
2005                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2006                 dr.setMessage(from_ascii(N_("Cancel")));
2007                 break;
2008         }
2009         case LFUN_META_PREFIX:
2010                 d->meta_fake_bit = AltModifier;
2011                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2012                 break;
2013
2014         // --- Menus -----------------------------------------------
2015         case LFUN_RECONFIGURE:
2016                 // argument is any additional parameter to the configure.py command
2017                 reconfigure(to_utf8(cmd.argument()));
2018                 break;
2019
2020         // --- lyxserver commands ----------------------------
2021         case LFUN_SERVER_GET_FILENAME: {
2022                 if (current_view_ && current_view_->documentBufferView()) {
2023                         docstring const fname = from_utf8(
2024                                 current_view_->documentBufferView()->buffer().absFileName());
2025                         dr.setMessage(fname);
2026                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2027                 } else {
2028                         dr.setMessage(docstring());
2029                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2030                 }
2031                 break;
2032         }
2033
2034         case LFUN_SERVER_NOTIFY: {
2035                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2036                 dr.setMessage(dispatch_buffer);
2037                 theServer().notifyClient(to_utf8(dispatch_buffer));
2038                 break;
2039         }
2040
2041         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2042                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2043                 break;
2044
2045         case LFUN_REPEAT: {
2046                 // repeat command
2047                 string countstr;
2048                 string rest = split(argument, countstr, ' ');
2049                 int const count = convert<int>(countstr);
2050                 // an arbitrary number to limit number of iterations
2051                 int const max_iter = 10000;
2052                 if (count > max_iter) {
2053                         dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2054                         dr.setError(true);
2055                 } else {
2056                         for (int i = 0; i < count; ++i) {
2057                                 FuncRequest lfun = lyxaction.lookupFunc(rest);
2058                                 lfun.allowAsync(false);
2059                                 dispatch(lfun);
2060                         }
2061                 }
2062                 break;
2063         }
2064
2065         case LFUN_COMMAND_SEQUENCE: {
2066                 // argument contains ';'-terminated commands
2067                 string arg = argument;
2068                 // FIXME: this LFUN should also work without any view.
2069                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2070                                   ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2071                 // This handles undo groups automagically
2072                 UndoGroupHelper ugh(buffer);
2073                 while (!arg.empty()) {
2074                         string first;
2075                         arg = split(arg, first, ';');
2076                         FuncRequest func(lyxaction.lookupFunc(first));
2077                         func.allowAsync(false);
2078                         func.setOrigin(cmd.origin());
2079                         dispatch(func);
2080                 }
2081                 break;
2082         }
2083
2084         case LFUN_BUFFER_FORALL: {
2085                 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2086                 funcToRun.allowAsync(false);
2087
2088                 map<Buffer *, GuiView *> views_lVisible;
2089                 map<GuiView *, Buffer *> activeBuffers;
2090
2091                 QList<GuiView *> allViews = d->views_.values();
2092
2093                 // this for does not modify any buffer. It just collects info on local
2094                 // visibility of buffers and on which buffer is active in each view.
2095                 Buffer * const last = theBufferList().last();
2096                 for(GuiView * view : allViews) {
2097                         // all of the buffers might be locally hidden. That is, there is no
2098                         // active buffer.
2099                         if (!view || !view->currentBufferView())
2100                                 activeBuffers[view] = nullptr;
2101                         else
2102                                 activeBuffers[view] = &view->currentBufferView()->buffer();
2103
2104                         // find out if each is locally visible or locally hidden.
2105                         // we don't use a for loop as the buffer list cycles.
2106                         Buffer * b = theBufferList().first();
2107                         while (true) {
2108                                 bool const locallyVisible = view && view->workArea(*b);
2109                                 if (locallyVisible) {
2110                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2111                                         // only need to overwrite/add if we don't already know a buffer is globally
2112                                         // visible or we do know but we would prefer to dispatch LFUN from the
2113                                         // current view because of cursor position issues.
2114                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2115                                                 views_lVisible[b] = view;
2116                                 }
2117                                 if (b == last)
2118                                         break;
2119                                 b = theBufferList().next(b);
2120                         }
2121                 }
2122
2123                 GuiView * const homeView = currentView();
2124                 Buffer * b = theBufferList().first();
2125                 Buffer * nextBuf = nullptr;
2126                 int numProcessed = 0;
2127                 while (true) {
2128                         if (b != last)
2129                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2130
2131                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2132                         if (visible) {
2133                                 // first change to a view where b is locally visible, preferably current_view_.
2134                                 GuiView * const vLv = views_lVisible[b];
2135                                 vLv->setBuffer(b);
2136                                 lyx::dispatch(funcToRun);
2137                                 numProcessed++;
2138                         }
2139                         if (b == last)
2140                                 break;
2141                         b = nextBuf;
2142                 }
2143
2144                 // put things back to how they were (if possible).
2145                 for (GuiView * view : allViews) {
2146                         Buffer * originalBuf = activeBuffers[view];
2147                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2148                         if (theBufferList().isLoaded(originalBuf))
2149                                 view->setBuffer(originalBuf);
2150                 }
2151                 homeView->setFocus();
2152
2153                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2154                 break;
2155         }
2156
2157         case LFUN_COMMAND_ALTERNATIVES: {
2158                 // argument contains ';'-terminated commands
2159                 string arg = argument;
2160                 while (!arg.empty()) {
2161                         string first;
2162                         arg = split(arg, first, ';');
2163                         FuncRequest func(lyxaction.lookupFunc(first));
2164                         func.setOrigin(cmd.origin());
2165                         FuncStatus const stat = getStatus(func);
2166                         if (stat.enabled()) {
2167                                 dispatch(func);
2168                                 break;
2169                         }
2170                 }
2171                 break;
2172         }
2173
2174         case LFUN_CALL: {
2175                 FuncRequest func;
2176                 if (theTopLevelCmdDef().lock(argument, func)) {
2177                         func.setOrigin(cmd.origin());
2178                         dispatch(func);
2179                         theTopLevelCmdDef().release(argument);
2180                 } else {
2181                         if (func.action() == LFUN_UNKNOWN_ACTION) {
2182                                 // unknown command definition
2183                                 lyxerr << "Warning: unknown command definition `"
2184                                                 << argument << "'"
2185                                                 << endl;
2186                         } else {
2187                                 // recursion detected
2188                                 lyxerr << "Warning: Recursion in the command definition `"
2189                                                 << argument << "' detected"
2190                                                 << endl;
2191                         }
2192                 }
2193                 break;
2194         }
2195
2196         case LFUN_IF_RELATIVES: {
2197                 string const lfun = to_utf8(cmd.argument());
2198                 FuncRequest func(lyxaction.lookupFunc(lfun));
2199                 func.setOrigin(cmd.origin());
2200                 FuncStatus const stat = getStatus(func);
2201                 if (stat.enabled()) {
2202                         dispatch(func);
2203                         break;
2204                 }
2205                 break;
2206         }
2207
2208         case LFUN_PREFERENCES_SAVE:
2209                 lyxrc.write(support::makeAbsPath("preferences",
2210                         package().user_support().absFileName()), false);
2211                 break;
2212
2213         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2214                 string const fname = addName(addPath(package().user_support().absFileName(),
2215                         "templates/"), "defaults.lyx");
2216                 Buffer defaults(fname);
2217
2218                 istringstream ss(argument);
2219                 Lexer lex;
2220                 lex.setStream(ss);
2221
2222                 // See #9236
2223                 // We need to make sure that, after we recreat the DocumentClass,
2224                 // which we do in readHeader, we apply it to the document itself.
2225                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2226                 int const unknown_tokens = defaults.readHeader(lex);
2227                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2228                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2229                 cap::switchBetweenClasses(olddc, newdc, theinset);
2230
2231                 if (unknown_tokens != 0) {
2232                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2233                                << unknown_tokens << " unknown token"
2234                                << (unknown_tokens == 1 ? "" : "s")
2235                                << endl;
2236                 }
2237
2238                 if (defaults.writeFile(FileName(defaults.absFileName())))
2239                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2240                                               makeDisplayPath(fname)));
2241                 else {
2242                         dr.setError(true);
2243                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2244                 }
2245                 break;
2246         }
2247
2248         case LFUN_BOOKMARK_GOTO:
2249                 // go to bookmark, open unopened file and switch to buffer if necessary
2250                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2251                 dr.screenUpdate(Update::Force | Update::FitCursor);
2252                 break;
2253
2254         case LFUN_BOOKMARK_CLEAR:
2255                 theSession().bookmarks().clear();
2256                 dr.screenUpdate(Update::Force);
2257                 break;
2258
2259         case LFUN_DEBUG_LEVEL_SET:
2260                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2261                 break;
2262
2263         case LFUN_DIALOG_SHOW: {
2264                 string const name = cmd.getArg(0);
2265                 // Workaround: on Mac OS the application
2266                 // is not terminated when closing the last view.
2267                 // With the following dialogs which should still
2268                 // be usable, create a new one to be able
2269                 // to dispatch LFUN_DIALOG_SHOW to this view.
2270                 if (name == "aboutlyx" || name == "compare"
2271                     || name == "lyxfiles" || name == "prefs"
2272                     || name == "progress" || name == "texinfo")
2273                 {
2274                         if (current_view_ == nullptr)
2275                                 createView();
2276                 }
2277         }
2278         // fall through
2279         default:
2280                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2281                 // let's try that:
2282                 if (current_view_)
2283                         current_view_->dispatch(cmd, dr);
2284                 break;
2285         }
2286
2287         if (current_view_ && current_view_->isFullScreen()) {
2288                 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2289                         current_view_->menuBar()->hide();
2290         }
2291
2292         if (cmd.origin() == FuncRequest::LYXSERVER)
2293                 updateCurrentView(cmd, dr);
2294 }
2295
2296
2297 docstring GuiApplication::viewStatusMessage()
2298 {
2299         // When meta-fake key is pressed, show the key sequence so far + "M-".
2300         if (d->meta_fake_bit != NoModifier)
2301                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2302
2303         // Else, when a non-complete key sequence is pressed,
2304         // show the available options.
2305         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2306                 return d->keyseq.printOptions(true);
2307
2308         return docstring();
2309 }
2310
2311
2312 string GuiApplication::inputLanguageCode() const
2313 {
2314         QLocale loc = inputMethod()->locale();
2315         //LYXERR0("input lang = " << fromqstr(loc.name()));
2316         return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2317 }
2318
2319
2320 void GuiApplication::onLocaleChanged()
2321 {
2322         //LYXERR0("Change language to " << inputLanguage()->lang());
2323         if (currentView() && currentView()->currentBufferView())
2324                 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2325 }
2326
2327
2328 void GuiApplication::onPaletteChanged()
2329 {
2330         colorCache().setPalette(palette());
2331 }
2332
2333
2334 void GuiApplication::handleKeyFunc(FuncCode action)
2335 {
2336         char_type c = 0;
2337
2338         if (d->keyseq.length())
2339                 c = 0;
2340         GuiView * gv = currentView();
2341         LASSERT(gv && gv->currentBufferView(), return);
2342         BufferView * bv = gv->currentBufferView();
2343         bv->getIntl().getTransManager().deadkey(
2344                 c, get_accent(action).accent, bv->cursor().innerText(),
2345                 bv->cursor());
2346         // Need to clear, in case the minibuffer calls these
2347         // actions
2348         d->keyseq.clear();
2349         // copied verbatim from do_accent_char
2350         bv->cursor().resetAnchor();
2351 }
2352
2353
2354 //Keep this in sync with GuiApplication::processKeySym below
2355 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2356                                  KeyModifier state) const
2357 {
2358         // Do nothing if we have nothing
2359         if (!keysym.isOK() || keysym.isModifier())
2360                 return false;
2361         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2362         KeySequence seq;
2363         FuncRequest func = seq.addkey(keysym, state);
2364         // When not cancel or meta-fake, do the normal lookup.
2365         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2366                 seq = d->keyseq;
2367                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2368         }
2369         // Maybe user can only reach the key via holding down shift.
2370         // Let's see. But only if shift is the only modifier
2371         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2372                 // If addkey looked up a command and did not find further commands then
2373                 // seq has been reset at this point
2374                 func = seq.addkey(keysym, NoModifier);
2375
2376         LYXERR(Debug::KEY, " Key (queried) [action="
2377                << lyxaction.getActionName(func.action()) << "]["
2378                << seq.print(KeySequence::Portable) << ']');
2379         return func.action() != LFUN_UNKNOWN_ACTION;
2380 }
2381
2382
2383 //Keep this in sync with GuiApplication::queryKeySym above
2384 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2385 {
2386         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2387
2388         // Do nothing if we have nothing (JMarc)
2389         if (!keysym.isOK() || keysym.isModifier()) {
2390                 if (!keysym.isOK())
2391                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2392                 if (current_view_)
2393                         current_view_->restartCaret();
2394                 return;
2395         }
2396
2397         char_type encoded_last_key = keysym.getUCSEncoded();
2398
2399         // Do a one-deep top-level lookup for
2400         // cancel and meta-fake keys. RVDK_PATCH_5
2401         d->cancel_meta_seq.reset();
2402
2403         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2404         LYXERR(Debug::KEY, "action first set to ["
2405                << lyxaction.getActionName(func.action()) << ']');
2406
2407         // When not cancel or meta-fake, do the normal lookup.
2408         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2409         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2410         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2411                 // remove Caps Lock and Mod2 as a modifiers
2412                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2413                 LYXERR(Debug::KEY, "action now set to ["
2414                        << lyxaction.getActionName(func.action()) << ']');
2415         }
2416
2417         // Don't remove this unless you know what you are doing.
2418         d->meta_fake_bit = NoModifier;
2419
2420         // Can this happen now ?
2421         if (func.action() == LFUN_NOACTION)
2422                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2423
2424         LYXERR(Debug::KEY, " Key [action="
2425                << lyxaction.getActionName(func.action()) << "]["
2426                << d->keyseq.print(KeySequence::Portable) << ']');
2427
2428         // already here we know if it any point in going further
2429         // why not return already here if action == -1 and
2430         // num_bytes == 0? (Lgb)
2431
2432         if (d->keyseq.length() > 1 && current_view_)
2433                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2434
2435
2436         // Maybe user can only reach the key via holding down shift.
2437         // Let's see. But only if shift is the only modifier
2438         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2439                 LYXERR(Debug::KEY, "Trying without shift");
2440                 // If addkey looked up a command and did not find further commands then
2441                 // seq has been reset at this point
2442                 func = d->keyseq.addkey(keysym, NoModifier);
2443                 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2444         }
2445
2446         if (func.action() == LFUN_UNKNOWN_ACTION) {
2447                 // We didn't match any of the key sequences.
2448                 // See if it's normal insertable text not already
2449                 // covered by a binding
2450                 if (keysym.isText() && d->keyseq.length() == 1) {
2451                         // Non-printable characters (such as ASCII control characters)
2452                         // must not be inserted (#5704)
2453                         if (!isPrintable(encoded_last_key)) {
2454                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2455                                 if (current_view_)
2456                                         current_view_->restartCaret();
2457                                 return;
2458                         }
2459                         // The following modifier check is not needed on Mac.
2460                         // The keysym is either not text or it is different
2461                         // from the non-modifier keysym. See #9875 for the
2462                         // broken alt-modifier effect of having this code active.
2463 #if !defined(Q_OS_MAC)
2464                         // If a non-Shift Modifier is used we have a non-bound key sequence
2465                         // (such as Alt+j = j). This should be omitted (#5575).
2466                         // On Windows, AltModifier and ControlModifier are both
2467                         // set when AltGr is pressed. Therefore, in order to not
2468                         // break AltGr-bound symbols (see #5575 for details),
2469                         // unbound Ctrl+Alt key sequences are allowed.
2470                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2471 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2472                             && !(state & AltModifier && state & ControlModifier)
2473 #endif
2474                             )
2475                         {
2476                                 if (current_view_) {
2477                                         current_view_->message(_("Unknown function."));
2478                                         current_view_->restartCaret();
2479                                 }
2480                                 return;
2481                         }
2482 #endif
2483                         // Since all checks above were passed, we now really have text that
2484                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2485                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2486                         // below.
2487                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2488                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2489                 } else {
2490                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2491                         if (current_view_) {
2492                                 current_view_->message(_("Unknown function."));
2493                                 current_view_->restartCaret();
2494                         }
2495                         return;
2496                 }
2497         }
2498
2499         if (func.action() == LFUN_SELF_INSERT) {
2500                 if (encoded_last_key != 0) {
2501                         docstring const arg(1, encoded_last_key);
2502                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2503                                              FuncRequest::KEYBOARD));
2504                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2505                 }
2506         } else
2507                 processFuncRequest(func);
2508 }
2509
2510
2511 void GuiApplication::processFuncRequest(FuncRequest const & func)
2512 {
2513         lyx::dispatch(func);
2514 }
2515
2516
2517 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2518 {
2519         addToFuncRequestQueue(func);
2520         processFuncRequestQueueAsync();
2521 }
2522
2523
2524 void GuiApplication::processFuncRequestQueue()
2525 {
2526         while (!d->func_request_queue_.empty()) {
2527                 // take the item from the stack _before_ processing the
2528                 // request in order to avoid race conditions from nested
2529                 // or parallel requests (see #10406)
2530                 FuncRequest const fr(d->func_request_queue_.front());
2531                 d->func_request_queue_.pop();
2532                 processFuncRequest(fr);
2533         }
2534 }
2535
2536
2537 void GuiApplication::processFuncRequestQueueAsync()
2538 {
2539         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2540 }
2541
2542
2543 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2544 {
2545         d->func_request_queue_.push(func);
2546 }
2547
2548
2549 void GuiApplication::resetGui()
2550 {
2551         // Set the language defined by the user.
2552         setGuiLanguage();
2553
2554         // Read menus
2555         if (!readUIFile(toqstr(lyxrc.ui_file)))
2556                 // Gives some error box here.
2557                 return;
2558
2559         if (d->global_menubar_)
2560                 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2561
2562         QHash<int, GuiView *>::iterator it;
2563         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2564                 GuiView * gv = *it;
2565                 setCurrentView(gv);
2566                 gv->setLayoutDirection(layoutDirection());
2567                 gv->resetDialogs();
2568         }
2569
2570         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2571 }
2572
2573
2574 bool GuiApplication::rtlContext() const
2575 {
2576         if (current_view_ && current_view_->currentBufferView()) {
2577                 BufferView const * bv = current_view_->currentBufferView();
2578                 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2579         } else
2580                 return layoutDirection() == Qt::RightToLeft;
2581 }
2582
2583
2584 void GuiApplication::createView(int view_id)
2585 {
2586         createView(QString(), true, view_id);
2587 }
2588
2589
2590 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2591         int view_id)
2592 {
2593         // release the keyboard which might have been grabbed by the global
2594         // menubar on Mac to catch shortcuts even without any GuiView.
2595         if (d->global_menubar_)
2596                 d->global_menubar_->releaseKeyboard();
2597
2598         // create new view
2599         int id = view_id;
2600         while (d->views_.find(id) != d->views_.end())
2601                 id++;
2602
2603         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2604         GuiView * view = new GuiView(id);
2605         // `view' is the new current_view_. Tell coverity that is is not 0.
2606         LATTEST(current_view_);
2607         // register view
2608         d->views_[id] = view;
2609
2610         if (autoShow) {
2611                 view->show();
2612                 view->activateWindow();
2613         }
2614
2615         if (!geometry_arg.isEmpty()) {
2616 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2617                 int x, y;
2618                 int w, h;
2619                 QChar sx, sy;
2620                 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2621                 QRegularExpressionMatch match = re.match(geometry_arg);
2622                 w = match.captured(1).toInt();
2623                 h = match.captured(2).toInt();
2624                 x = match.captured(3).toInt();
2625                 y = match.captured(4).toInt();
2626                 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2627                 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2628
2629                 // Set initial geometry such that we can get the frame size.
2630                 view->setGeometry(x, y, w, h);
2631                 int framewidth = view->geometry().x() - view->x();
2632                 int titleheight = view->geometry().y() - view->y();
2633                 // Negative displacements must be interpreted as distances
2634                 // from the right or bottom screen borders.
2635                 if (sx == '-' || sy == '-') {
2636                         QRect rec = QGuiApplication::primaryScreen()->geometry();
2637                         if (sx == '-')
2638                                 x += rec.width() - w - framewidth;
2639                         if (sy == '-')
2640                                 y += rec.height() - h - titleheight;
2641                         view->setGeometry(x, y, w, h);
2642                 }
2643                 // Make sure that the left and top frame borders are visible.
2644                 if (view->x() < 0 || view->y() < 0) {
2645                         if (view->x() < 0)
2646                                 x = framewidth;
2647                         if (view->y() < 0)
2648                                 y = titleheight;
2649                         view->setGeometry(x, y, w, h);
2650                 }
2651 #endif
2652         }
2653         view->setFocus();
2654 }
2655
2656
2657 bool GuiApplication::unhide(Buffer * buf)
2658 {
2659         if (!currentView())
2660                 return false;
2661         currentView()->setBuffer(buf, false);
2662         return true;
2663 }
2664
2665
2666 QPixmap GuiApplication::getScaledPixmap(QString imagedir, QString name) const
2667 {
2668         qreal dpr = 1.0;
2669         // Consider device/pixel ratio (HiDPI)
2670         if (currentView())
2671                 dpr = currentView()->devicePixelRatio();
2672         // We render SVG directly for HiDPI scalability
2673         QPixmap pm = getPixmap(imagedir, name, "svgz,png");
2674         FileName fname = imageLibFileSearch(imagedir, name, "svgz,png");
2675         QString fpath = toqstr(fname.absFileName());
2676         if (!fpath.isEmpty() && !fpath.endsWith(".png")) {
2677                 QSvgRenderer svgRenderer(fpath);
2678                 if (svgRenderer.isValid()) {
2679                         pm = QPixmap(pm.size() * dpr);
2680                         pm.fill(Qt::transparent);
2681                         QPainter painter(&pm);
2682                         svgRenderer.render(&painter);
2683                         pm.setDevicePixelRatio(dpr);
2684                 }
2685         }
2686         return pm;
2687 }
2688
2689
2690 Clipboard & GuiApplication::clipboard()
2691 {
2692         return d->clipboard_;
2693 }
2694
2695
2696 Selection & GuiApplication::selection()
2697 {
2698         return d->selection_;
2699 }
2700
2701
2702 FontLoader & GuiApplication::fontLoader()
2703 {
2704         return d->font_loader_;
2705 }
2706
2707
2708 Toolbars const & GuiApplication::toolbars() const
2709 {
2710         return d->toolbars_;
2711 }
2712
2713
2714 Toolbars & GuiApplication::toolbars()
2715 {
2716         return d->toolbars_;
2717 }
2718
2719
2720 Menus const & GuiApplication::menus() const
2721 {
2722         return d->menus_;
2723 }
2724
2725
2726 Menus & GuiApplication::menus()
2727 {
2728         return d->menus_;
2729 }
2730
2731
2732 bool GuiApplication::needsBackingStore() const
2733 {
2734         /* Qt on macOS and Wayland does not respect the
2735          * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2736          * store at each update. Therefore, we use our own backing store
2737          * in these two cases. It is also possible to force the use of the
2738          * backing store for cases like x11 with transparent WM themes.
2739          */
2740         return platformName() == "cocoa" || platformName().contains("wayland");
2741 }
2742
2743
2744 QList<int> GuiApplication::viewIds() const
2745 {
2746         return d->views_.keys();
2747 }
2748
2749
2750 ColorCache & GuiApplication::colorCache()
2751 {
2752         return d->color_cache_;
2753 }
2754
2755
2756 int GuiApplication::exec()
2757 {
2758         // asynchronously handle batch commands. This event will be in
2759         // the event queue in front of other asynchronous events. Hence,
2760         // we can assume in the latter that the gui is setup already.
2761         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2762
2763         return QApplication::exec();
2764 }
2765
2766
2767 void GuiApplication::exit(int status)
2768 {
2769         QApplication::exit(status);
2770 }
2771
2772
2773 void GuiApplication::setGuiLanguage()
2774 {
2775         setLocale();
2776         QLocale theLocale;
2777         // install translation file for Qt built-in dialogs
2778         QString const language_name = QString("qt_") + theLocale.name();
2779         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2780         // Short-named translator can be loaded from a long name, but not the
2781         // opposite. Therefore, long name should be used without truncation.
2782         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2783         if (!d->qt_trans_.load(language_name,
2784 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2785                         QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2786 #else
2787                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2788 #endif
2789                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2790                         << language_name);
2791         } else {
2792                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2793                         << language_name);
2794         }
2795
2796         switch (theLocale.language()) {
2797         case QLocale::Arabic :
2798         case QLocale::Hebrew :
2799         case QLocale::Persian :
2800         case QLocale::Urdu :
2801                 setLayoutDirection(Qt::RightToLeft);
2802                 break;
2803         default:
2804                 setLayoutDirection(Qt::LeftToRight);
2805         }
2806 }
2807
2808
2809 void GuiApplication::execBatchCommands()
2810 {
2811         setGuiLanguage();
2812
2813         // Read menus
2814         if (!readUIFile(toqstr(lyxrc.ui_file)))
2815                 // Gives some error box here.
2816                 return;
2817
2818 #ifdef Q_OS_MAC
2819         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2820 #  if QT_VERSION < 0x060000
2821         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2822 #  endif
2823         // Create the global default menubar which is shown for the dialogs
2824         // and if no GuiView is visible.
2825         // This must be done after the session was recovered to know the "last files".
2826         d->global_menubar_ = new QMenuBar(0);
2827         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2828 #endif
2829
2830         lyx::execBatchCommands();
2831 }
2832
2833
2834 QAbstractItemModel * GuiApplication::languageModel()
2835 {
2836         if (d->language_model_)
2837                 return d->language_model_;
2838
2839         QStandardItemModel * lang_model = new QStandardItemModel(this);
2840         lang_model->insertColumns(0, 3);
2841         QIcon speller(guiApp ? guiApp->getScaledPixmap("images/", "dialog-show_spellchecker")
2842                           : getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2843         QIcon saurus(guiApp ? guiApp->getScaledPixmap("images/", "thesaurus-entry")
2844                           : getPixmap("images/", "thesaurus-entry", "svgz,png"));
2845         Languages::const_iterator it = lyx::languages.begin();
2846         Languages::const_iterator end = lyx::languages.end();
2847         for (; it != end; ++it) {
2848                 int current_row = lang_model->rowCount();
2849                 lang_model->insertRows(current_row, 1);
2850                 QModelIndex pl_item = lang_model->index(current_row, 0);
2851                 QModelIndex sp_item = lang_model->index(current_row, 1);
2852                 QModelIndex th_item = lang_model->index(current_row, 2);
2853                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2854                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2855                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2856                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2857                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2858                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2859                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2860                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2861                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2862                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2863         }
2864         d->language_model_ = new QSortFilterProxyModel(this);
2865         d->language_model_->setSourceModel(lang_model);
2866         d->language_model_->setSortLocaleAware(true);
2867         return d->language_model_;
2868 }
2869
2870
2871 void GuiApplication::restoreGuiSession()
2872 {
2873         if (!lyxrc.load_session)
2874                 return;
2875
2876         Session & session = theSession();
2877         LastOpenedSection::LastOpened const & lastopened =
2878                 session.lastOpened().getfiles();
2879
2880         validateCurrentView();
2881
2882         FileName active_file;
2883         // do not add to the lastfile list since these files are restored from
2884         // last session, and should be already there (regular files), or should
2885         // not be added at all (help files).
2886         for (auto const & last : lastopened) {
2887                 FileName const & file_name = last.file_name;
2888                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2889                           && current_view_->documentBufferView() != nullptr)) {
2890                         string const & fname = file_name.absFileName();
2891                         createView(support::checksum(fname));
2892                 }
2893                 current_view_->loadDocument(file_name, false);
2894
2895                 if (last.active)
2896                         active_file = file_name;
2897         }
2898
2899         // Restore last active buffer
2900         Buffer * buffer = theBufferList().getBuffer(active_file);
2901         if (buffer && current_view_)
2902                 current_view_->setBuffer(buffer);
2903
2904         // clear this list to save a few bytes of RAM
2905         session.lastOpened().clear();
2906 }
2907
2908
2909 QString const GuiApplication::romanFontName()
2910 {
2911         QFont font;
2912         font.setStyleHint(QFont::Serif);
2913         font.setFamily("serif");
2914
2915         return QFontInfo(font).family();
2916 }
2917
2918
2919 QString const GuiApplication::sansFontName()
2920 {
2921         QFont font;
2922         font.setStyleHint(QFont::SansSerif);
2923         font.setFamily("sans");
2924
2925         return QFontInfo(font).family();
2926 }
2927
2928
2929 QString const GuiApplication::typewriterFontName()
2930 {
2931         return QFontInfo(typewriterSystemFont()).family();
2932 }
2933
2934
2935 namespace {
2936         // We cannot use QFont::fixedPitch() because it doesn't
2937         // return the fact but only if it is requested.
2938         static bool isFixedPitch(const QFont & font) {
2939                 const QFontInfo fi(font);
2940                 return fi.fixedPitch();
2941         }
2942 } // namespace
2943
2944
2945 QFont const GuiApplication::typewriterSystemFont()
2946 {
2947         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2948         if (!isFixedPitch(font)) {
2949                 // try to enforce a real monospaced font
2950                 font.setStyleHint(QFont::Monospace);
2951                 if (!isFixedPitch(font)) {
2952                         font.setStyleHint(QFont::TypeWriter);
2953                         if (!isFixedPitch(font)) font.setFamily("courier");
2954                 }
2955         }
2956 #ifdef Q_OS_MAC
2957         // On a Mac the result is too small and it's not practical to
2958         // rely on Qtconfig utility to change the system settings of Qt.
2959         font.setPointSize(12);
2960 #endif
2961         return font;
2962 }
2963
2964
2965 void GuiApplication::handleRegularEvents()
2966 {
2967         ForkedCallsController::handleCompletedProcesses();
2968 }
2969
2970
2971 bool GuiApplication::event(QEvent * e)
2972 {
2973         switch(e->type()) {
2974         case QEvent::FileOpen: {
2975                 // Open a file; this happens only on Mac OS X for now.
2976                 //
2977                 // We do this asynchronously because on startup the batch
2978                 // commands are not executed here yet and the gui is not ready
2979                 // therefore.
2980                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2981                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2982                 processFuncRequestAsync(fr);
2983                 e->accept();
2984                 return true;
2985         }
2986         case QEvent::ApplicationPaletteChange: {
2987                 // runtime switch from/to dark mode
2988                 onPaletteChanged();
2989                 return QApplication::event(e);
2990         }
2991         default:
2992                 return QApplication::event(e);
2993         }
2994 }
2995
2996
2997 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2998 {
2999         try {
3000                 return QApplication::notify(receiver, event);
3001         }
3002         catch (ExceptionMessage const & e) {
3003                 switch(e.type_) {
3004                 case ErrorException:
3005                         emergencyCleanup();
3006                         setQuitOnLastWindowClosed(false);
3007                         closeAllViews();
3008                         Alert::error(e.title_, e.details_);
3009 #ifndef NDEBUG
3010                         // Properly crash in debug mode in order to get a useful backtrace.
3011                         abort();
3012 #endif
3013                         // In release mode, try to exit gracefully.
3014                         this->exit(1);
3015                         // FIXME: GCC 7 thinks we can fall through here. Can we?
3016                         // fall through
3017                 case BufferException: {
3018                         if (!current_view_ || !current_view_->documentBufferView())
3019                                 return false;
3020                         Buffer * buf = &current_view_->documentBufferView()->buffer();
3021                         docstring details = e.details_ + '\n';
3022                         details += buf->emergencyWrite();
3023                         theBufferList().release(buf);
3024                         details += "\n" + _("The current document was closed.");
3025                         Alert::error(e.title_, details);
3026                         return false;
3027                 }
3028                 case WarningException:
3029                         Alert::warning(e.title_, e.details_);
3030                         return false;
3031                 }
3032         }
3033         catch (exception const & e) {
3034                 docstring s = _("LyX has caught an exception, it will now "
3035                         "attempt to save all unsaved documents and exit."
3036                         "\n\nException: ");
3037                 s += from_ascii(e.what());
3038                 Alert::error(_("Software exception Detected"), s);
3039                 lyx_exit(1);
3040         }
3041         catch (...) {
3042                 docstring s = _("LyX has caught some really weird exception, it will "
3043                         "now attempt to save all unsaved documents and exit.");
3044                 Alert::error(_("Software exception Detected"), s);
3045                 lyx_exit(1);
3046         }
3047
3048         return false;
3049 }
3050
3051 bool GuiApplication::isInDarkMode()
3052 {
3053         return colorCache().isDarkMode();
3054 }
3055
3056
3057 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3058 {
3059         QColor const & qcol = d->color_cache_.get(col);
3060         if (!qcol.isValid()) {
3061                 rgbcol.r = 0;
3062                 rgbcol.g = 0;
3063                 rgbcol.b = 0;
3064                 return false;
3065         }
3066         rgbcol.r = qcol.red();
3067         rgbcol.g = qcol.green();
3068         rgbcol.b = qcol.blue();
3069         return true;
3070 }
3071
3072
3073 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3074 {
3075         QColor const qcol(lcolor.getX11HexName(col).c_str());
3076         if (!qcol.isValid()) {
3077                 rgbcol.r = 0;
3078                 rgbcol.g = 0;
3079                 rgbcol.b = 0;
3080                 return false;
3081         }
3082         rgbcol.r = qcol.red();
3083         rgbcol.g = qcol.green();
3084         rgbcol.b = qcol.blue();
3085         return true;
3086 }
3087
3088
3089 string const GuiApplication::hexName(ColorCode col)
3090 {
3091         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3092 }
3093
3094
3095 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3096 {
3097         SocketNotifier * sn = new SocketNotifier(this, fd, func);
3098         d->socket_notifiers_[fd] = sn;
3099         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3100 }
3101
3102
3103 void GuiApplication::socketDataReceived(int fd)
3104 {
3105         d->socket_notifiers_[fd]->func_();
3106 }
3107
3108
3109 void GuiApplication::unregisterSocketCallback(int fd)
3110 {
3111         d->socket_notifiers_.take(fd)->setEnabled(false);
3112 }
3113
3114
3115 void GuiApplication::commitData(QSessionManager & sm)
3116 {
3117         /** The implementation is required to avoid an application exit
3118          ** when session state save is triggered by session manager.
3119          ** The default implementation sends a close event to all
3120          ** visible top level widgets when session management allows
3121          ** interaction.
3122          ** We are changing that to check the state of each buffer in all
3123          ** views and ask the users what to do if buffers are dirty.
3124          ** Furthermore, we save the session state.
3125          ** We do NOT close the views here since the user still can cancel
3126          ** the logout process (see #9277); also, this would hide LyX from
3127          ** an OSes own session handling (application restoration).
3128          **/
3129         #ifdef QT_NO_SESSIONMANAGER
3130                 #ifndef _MSC_VER
3131                         #warning Qt is compiled without session manager
3132                 #else
3133                         #pragma message("warning: Qt is compiled without session manager")
3134                 #endif
3135                 (void) sm;
3136         #else
3137                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3138                         sm.cancel();
3139                 else
3140                         sm.release();
3141         #endif
3142 }
3143
3144
3145 void GuiApplication::unregisterView(GuiView * gv)
3146 {
3147         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3148                 d->views_.remove(gv->id());
3149                 if (current_view_ == gv)
3150                         current_view_ = nullptr;
3151         }
3152 }
3153
3154
3155 bool GuiApplication::closeAllViews()
3156 {
3157         if (d->views_.empty())
3158                 return true;
3159
3160         // When a view/window was closed before without quitting LyX, there
3161         // are already entries in the lastOpened list.
3162         theSession().lastOpened().clear();
3163
3164         QList<GuiView *> const views = d->views_.values();
3165         for (GuiView * view : views) {
3166                 if (!view->closeScheduled())
3167                         return false;
3168         }
3169
3170         d->views_.clear();
3171         return true;
3172 }
3173
3174
3175 bool GuiApplication::prepareAllViewsForLogout()
3176 {
3177         if (d->views_.empty())
3178                 return true;
3179
3180         QList<GuiView *> const views = d->views_.values();
3181         for (GuiView * view : views) {
3182                 if (!view->prepareAllBuffersForLogout())
3183                         return false;
3184         }
3185
3186         return true;
3187 }
3188
3189
3190 GuiView & GuiApplication::view(int id) const
3191 {
3192         LAPPERR(d->views_.contains(id));
3193         return *d->views_.value(id);
3194 }
3195
3196
3197 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3198 {
3199         QList<GuiView *> const views = d->views_.values();
3200         for (GuiView * view : views)
3201                 view->hideDialog(name, inset);
3202 }
3203
3204
3205 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3206 {
3207         Buffer const * buf = nullptr;
3208         QHash<int, GuiView *>::const_iterator end = d->views_.end();
3209         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3210                 if (Buffer const * ptr = (*it)->updateInset(inset))
3211                         buf = ptr;
3212         }
3213         return buf;
3214 }
3215
3216
3217 bool GuiApplication::searchMenu(FuncRequest const & func,
3218         docstring_list & names) const
3219 {
3220         BufferView * bv = nullptr;
3221         if (current_view_)
3222                 bv = current_view_->currentBufferView();
3223         return d->menus_.searchMenu(func, names, bv);
3224 }
3225
3226
3227 bool GuiApplication::hasBufferView() const
3228 {
3229         return (current_view_ && current_view_->currentBufferView());
3230 }
3231
3232
3233 // Ensure that a file is read only once (prevents include loops)
3234 static QStringList uifiles;
3235 // store which ui files define Toolbars
3236 static QStringList toolbar_uifiles;
3237
3238
3239 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3240 {
3241         enum {
3242                 ui_menuset = 1,
3243                 ui_toolbars,
3244                 ui_toolbarset,
3245                 ui_include,
3246                 ui_format,
3247                 ui_last
3248         };
3249
3250         LexerKeyword uitags[] = {
3251                 { "format", ui_format },
3252                 { "include", ui_include },
3253                 { "menuset", ui_menuset },
3254                 { "toolbars", ui_toolbars },
3255                 { "toolbarset", ui_toolbarset }
3256         };
3257
3258         Lexer lex(uitags);
3259         lex.setFile(ui_path);
3260         if (!lex.isOK()) {
3261                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3262                                          << endl;
3263         }
3264
3265         if (lyxerr.debugging(Debug::PARSER))
3266                 lex.printTable(lyxerr);
3267
3268         bool error = false;
3269         // format before introduction of format tag
3270         unsigned int format = 0;
3271         while (lex.isOK()) {
3272                 int const status = lex.lex();
3273
3274                 // we have to do this check here, outside the switch,
3275                 // because otherwise we would start reading include files,
3276                 // e.g., if the first tag we hit was an include tag.
3277                 if (status == ui_format)
3278                         if (lex.next()) {
3279                                 format = lex.getInteger();
3280                                 continue;
3281                         }
3282
3283                 // this will trigger unless the first tag we hit is a format
3284                 // tag, with the right format.
3285                 if (format != LFUN_FORMAT)
3286                         return FormatMismatch;
3287
3288                 switch (status) {
3289                 case Lexer::LEX_FEOF:
3290                         continue;
3291
3292                 case ui_include: {
3293                         lex.next(true);
3294                         QString const file = toqstr(lex.getString());
3295                         bool const success = readUIFile(file, true);
3296                         if (!success) {
3297                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3298                                 return ReadError;
3299                         }
3300                         break;
3301                 }
3302
3303                 case ui_menuset:
3304                         d->menus_.read(lex);
3305                         break;
3306
3307                 case ui_toolbarset:
3308                         d->toolbars_.readToolbars(lex);
3309                         break;
3310
3311                 case ui_toolbars:
3312                         d->toolbars_.readToolbarSettings(lex);
3313                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3314                         break;
3315
3316                 default:
3317                         if (!rtrim(lex.getString()).empty())
3318                                 lex.printError("LyX::ReadUIFile: "
3319                                                "Unknown menu tag: `$$Token'");
3320                         else
3321                                 LYXERR0("Error with status: " << status);
3322                         error = true;
3323                         break;
3324                 }
3325
3326         }
3327         return (error ? ReadError : ReadOK);
3328 }
3329
3330
3331 bool GuiApplication::readUIFile(QString const & name, bool include)
3332 {
3333         LYXERR(Debug::INIT, "About to read " << name << "...");
3334
3335         FileName ui_path;
3336         if (include) {
3337                 ui_path = libFileSearch("ui", name, "inc");
3338                 if (ui_path.empty())
3339                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3340         } else {
3341                 ui_path = libFileSearch("ui", name, "ui");
3342         }
3343
3344         if (ui_path.empty()) {
3345                 static const QString defaultUIFile = "default";
3346                 LYXERR(Debug::INIT, "Could not find " << name);
3347                 if (include) {
3348                         Alert::warning(_("Could not find UI definition file"),
3349                                 bformat(_("Error while reading the included file\n%1$s\n"
3350                                         "Please check your installation."), qstring_to_ucs4(name)));
3351                         return false;
3352                 }
3353                 if (name == defaultUIFile) {
3354                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3355                         Alert::warning(_("Could not find default UI file"),
3356                                 _("LyX could not find the default UI file!\n"
3357                                   "Please check your installation."));
3358                         return false;
3359                 }
3360                 Alert::warning(_("Could not find UI definition file"),
3361                 bformat(_("Error while reading the configuration file\n%1$s\n"
3362                         "Falling back to default.\n"
3363                         "Please look under Tools>Preferences>User Interface and\n"
3364                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3365                 return readUIFile(defaultUIFile, false);
3366         }
3367
3368         QString const uifile = toqstr(ui_path.absFileName());
3369         if (uifiles.contains(uifile)) {
3370                 if (!include) {
3371                         // We are reading again the top uifile so reset the safeguard:
3372                         uifiles.clear();
3373                         d->menus_.reset();
3374                         d->toolbars_.reset();
3375                 } else {
3376                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3377                                 << "Is this an include loop?");
3378                         return false;
3379                 }
3380         }
3381         uifiles.push_back(uifile);
3382
3383         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3384
3385         ReturnValues retval = readUIFile(ui_path);
3386
3387         if (retval == FormatMismatch) {
3388                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3389                 TempFile tmp("convertXXXXXX.ui");
3390                 FileName const tempfile = tmp.name();
3391                 bool const success = prefs2prefs(ui_path, tempfile, true);
3392                 if (!success) {
3393                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3394                                 " to format " << LFUN_FORMAT << ".");
3395                 } else {
3396                         retval = readUIFile(tempfile);
3397                 }
3398         }
3399
3400         if (retval != ReadOK) {
3401                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3402                 return false;
3403         }
3404
3405         if (include)
3406                 return true;
3407
3408         QSettings settings;
3409         settings.beginGroup("ui_files");
3410         bool touched = false;
3411         for (int i = 0; i != uifiles.size(); ++i) {
3412                 QFileInfo fi(uifiles[i]);
3413                 QDateTime const date_value = fi.lastModified();
3414                 QString const name_key = QString::number(i);
3415                 // if an ui file which defines Toolbars has changed,
3416                 // we have to reset the settings
3417                 if (toolbar_uifiles.contains(uifiles[i])
3418                  && (!settings.contains(name_key)
3419                  || settings.value(name_key).toString() != uifiles[i]
3420                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3421                         touched = true;
3422                         settings.setValue(name_key, uifiles[i]);
3423                         settings.setValue(name_key + "/date", date_value);
3424                 }
3425         }
3426         settings.endGroup();
3427         if (touched)
3428                 settings.remove("views");
3429
3430         return true;
3431 }
3432
3433
3434 void GuiApplication::onLastWindowClosed()
3435 {
3436         if (d->global_menubar_)
3437                 d->global_menubar_->grabKeyboard();
3438 }
3439
3440
3441 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3442 {
3443         std::string name = "unknown";
3444         switch (state) {
3445         case Qt::ApplicationSuspended:
3446                 name = "ApplicationSuspended";
3447                 break;
3448         case Qt::ApplicationHidden:
3449                 name = "ApplicationHidden";
3450                 break;
3451         case Qt::ApplicationInactive:
3452                 name = "ApplicationInactive";
3453                 break;
3454         case Qt::ApplicationActive:
3455                 name = "ApplicationActive";
3456                 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3457                 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3458                 if (d->views_.empty() && d->last_state_ == state) {
3459                         LYXERR(Debug::GUI, "Open new window...");
3460                         createView();
3461                 }
3462                 break;
3463         }
3464         LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3465         d->last_state_ = state;
3466 }
3467
3468
3469 void GuiApplication::startLongOperation() {
3470         d->key_checker_.start();
3471 }
3472
3473
3474 bool GuiApplication::longOperationCancelled() {
3475         return d->key_checker_.pressed();
3476 }
3477
3478
3479 void GuiApplication::stopLongOperation() {
3480         d->key_checker_.stop();
3481 }
3482
3483
3484 bool GuiApplication::longOperationStarted() {
3485         return d->key_checker_.started();
3486 }
3487
3488
3489 ////////////////////////////////////////////////////////////////////////
3490 //
3491 // X11 specific stuff goes here...
3492
3493 #if defined(QPA_XCB)
3494 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3495                                        void * message, QINTPTR *)
3496 {
3497         if (!current_view_ || eventType != "xcb_generic_event_t")
3498                 return false;
3499
3500         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3501
3502         switch (ev->response_type) {
3503         case XCB_SELECTION_REQUEST: {
3504                 xcb_selection_request_event_t * srev =
3505                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3506                 if (srev->selection != XCB_ATOM_PRIMARY)
3507                         break;
3508                 LYXERR(Debug::SELECTION, "X requested selection.");
3509                 BufferView * bv = current_view_->currentBufferView();
3510                 if (bv) {
3511                         docstring const sel = bv->requestSelection();
3512                         if (!sel.empty()) {
3513                                 d->selection_.put(sel);
3514 #ifdef HAVE_QT5_X11_EXTRAS
3515                                 // Refresh the selection request timestamp.
3516                                 // We have to do this by ourselves as Qt seems
3517                                 // not doing that, maybe because of our
3518                                 // "persistent selection" implementation
3519                                 // (see comments in GuiSelection.cpp).
3520                                 // It is expected that every X11 event is
3521                                 // 32 bytes long, even if not all 32 bytes are
3522                                 // needed. See:
3523                                 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3524                                 struct alignas(32) padded_event
3525                                         : xcb_selection_notify_event_t {};
3526                                 padded_event nev = {};
3527                                 nev.response_type = XCB_SELECTION_NOTIFY;
3528                                 nev.requestor = srev->requestor;
3529                                 nev.selection = srev->selection;
3530                                 nev.target = srev->target;
3531                                 nev.property = XCB_NONE;
3532                                 nev.time = XCB_CURRENT_TIME;
3533                                 xcb_connection_t * con = QX11Info::connection();
3534                                 xcb_send_event(con, 0, srev->requestor,
3535                                         XCB_EVENT_MASK_NO_EVENT,
3536                                         reinterpret_cast<char const *>(&nev));
3537                                 xcb_flush(con);
3538 #endif
3539                                 return true;
3540                         }
3541                 }
3542                 break;
3543         }
3544         case XCB_SELECTION_CLEAR: {
3545                 xcb_selection_clear_event_t * scev =
3546                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3547                 if (scev->selection != XCB_ATOM_PRIMARY)
3548                         break;
3549                 LYXERR(Debug::SELECTION, "Lost selection.");
3550                 BufferView * bv = current_view_->currentBufferView();
3551                 if (bv)
3552                         bv->clearSelection();
3553                 break;
3554         }
3555         }
3556         return false;
3557 }
3558 #endif
3559
3560 } // namespace frontend
3561
3562
3563 void hideDialogs(std::string const & name, Inset * inset)
3564 {
3565         if (theApp())
3566                 frontend::guiApp->hideDialogs(name, inset);
3567 }
3568
3569
3570 ////////////////////////////////////////////////////////////////////
3571 //
3572 // Font stuff
3573 //
3574 ////////////////////////////////////////////////////////////////////
3575
3576 frontend::FontLoader & theFontLoader()
3577 {
3578         LAPPERR(frontend::guiApp);
3579         return frontend::guiApp->fontLoader();
3580 }
3581
3582
3583 frontend::FontMetrics const & theFontMetrics(Font const & f)
3584 {
3585         return theFontMetrics(f.fontInfo());
3586 }
3587
3588
3589 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3590 {
3591         LAPPERR(frontend::guiApp);
3592         return frontend::guiApp->fontLoader().metrics(f);
3593 }
3594
3595
3596 ////////////////////////////////////////////////////////////////////
3597 //
3598 // Misc stuff
3599 //
3600 ////////////////////////////////////////////////////////////////////
3601
3602 frontend::Clipboard & theClipboard()
3603 {
3604         LAPPERR(frontend::guiApp);
3605         return frontend::guiApp->clipboard();
3606 }
3607
3608
3609 frontend::Selection & theSelection()
3610 {
3611         LAPPERR(frontend::guiApp);
3612         return frontend::guiApp->selection();
3613 }
3614
3615
3616 } // namespace lyx
3617
3618 #include "moc_GuiApplication.cpp"