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