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