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