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