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