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