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