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