]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiApplication.cpp
392c4b2914b0e456aa48ec79878badf8240b47b9
[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="
2321                << lyxaction.getActionName(func.action()) << "]["
2322                << seq.print(KeySequence::Portable) << ']');
2323         return func.action() != LFUN_UNKNOWN_ACTION;
2324 }
2325
2326
2327 //Keep this in sync with GuiApplication::queryKeySym above
2328 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2329 {
2330         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2331
2332         // Do nothing if we have nothing (JMarc)
2333         if (!keysym.isOK() || keysym.isModifier()) {
2334                 if (!keysym.isOK())
2335                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2336                 if (current_view_)
2337                         current_view_->restartCaret();
2338                 return;
2339         }
2340
2341         char_type encoded_last_key = keysym.getUCSEncoded();
2342
2343         // Do a one-deep top-level lookup for
2344         // cancel and meta-fake keys. RVDK_PATCH_5
2345         d->cancel_meta_seq.reset();
2346
2347         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2348         LYXERR(Debug::KEY, "action first set to ["
2349                << lyxaction.getActionName(func.action()) << ']');
2350
2351         // When not cancel or meta-fake, do the normal lookup.
2352         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2353         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2354         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2355                 // remove Caps Lock and Mod2 as a modifiers
2356                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2357                 LYXERR(Debug::KEY, "action now set to ["
2358                        << lyxaction.getActionName(func.action()) << ']');
2359         }
2360
2361         // Don't remove this unless you know what you are doing.
2362         d->meta_fake_bit = NoModifier;
2363
2364         // Can this happen now ?
2365         if (func.action() == LFUN_NOACTION)
2366                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2367
2368         LYXERR(Debug::KEY, " Key [action="
2369                << lyxaction.getActionName(func.action()) << "]["
2370                << d->keyseq.print(KeySequence::Portable) << ']');
2371
2372         // already here we know if it any point in going further
2373         // why not return already here if action == -1 and
2374         // num_bytes == 0? (Lgb)
2375
2376         if (d->keyseq.length() > 1 && current_view_)
2377                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2378
2379
2380         // Maybe user can only reach the key via holding down shift.
2381         // Let's see. But only if shift is the only modifier
2382         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2383                 LYXERR(Debug::KEY, "Trying without shift");
2384                 // If addkey looked up a command and did not find further commands then
2385                 // seq has been reset at this point
2386                 func = d->keyseq.addkey(keysym, NoModifier);
2387                 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2388         }
2389
2390         if (func.action() == LFUN_UNKNOWN_ACTION) {
2391                 // We didn't match any of the key sequences.
2392                 // See if it's normal insertable text not already
2393                 // covered by a binding
2394                 if (keysym.isText() && d->keyseq.length() == 1) {
2395                         // Non-printable characters (such as ASCII control characters)
2396                         // must not be inserted (#5704)
2397                         if (!isPrintable(encoded_last_key)) {
2398                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2399                                 if (current_view_)
2400                                         current_view_->restartCaret();
2401                                 return;
2402                         }
2403                         // The following modifier check is not needed on Mac.
2404                         // The keysym is either not text or it is different
2405                         // from the non-modifier keysym. See #9875 for the
2406                         // broken alt-modifier effect of having this code active.
2407 #if !defined(Q_OS_MAC)
2408                         // If a non-Shift Modifier is used we have a non-bound key sequence
2409                         // (such as Alt+j = j). This should be omitted (#5575).
2410                         // On Windows, AltModifier and ControlModifier are both
2411                         // set when AltGr is pressed. Therefore, in order to not
2412                         // break AltGr-bound symbols (see #5575 for details),
2413                         // unbound Ctrl+Alt key sequences are allowed.
2414                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2415 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2416                             && !(state & AltModifier && state & ControlModifier)
2417 #endif
2418                             )
2419                         {
2420                                 if (current_view_) {
2421                                         current_view_->message(_("Unknown function."));
2422                                         current_view_->restartCaret();
2423                                 }
2424                                 return;
2425                         }
2426 #endif
2427                         // Since all checks above were passed, we now really have text that
2428                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2429                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2430                         // below.
2431                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2432                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2433                 } else {
2434                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2435                         if (current_view_) {
2436                                 current_view_->message(_("Unknown function."));
2437                                 current_view_->restartCaret();
2438                         }
2439                         return;
2440                 }
2441         }
2442
2443         if (func.action() == LFUN_SELF_INSERT) {
2444                 if (encoded_last_key != 0) {
2445                         docstring const arg(1, encoded_last_key);
2446                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2447                                              FuncRequest::KEYBOARD));
2448                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2449                 }
2450         } else
2451                 processFuncRequest(func);
2452 }
2453
2454
2455 void GuiApplication::processFuncRequest(FuncRequest const & func)
2456 {
2457         lyx::dispatch(func);
2458 }
2459
2460
2461 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2462 {
2463         addToFuncRequestQueue(func);
2464         processFuncRequestQueueAsync();
2465 }
2466
2467
2468 void GuiApplication::processFuncRequestQueue()
2469 {
2470         while (!d->func_request_queue_.empty()) {
2471                 // take the item from the stack _before_ processing the
2472                 // request in order to avoid race conditions from nested
2473                 // or parallel requests (see #10406)
2474                 FuncRequest const fr(d->func_request_queue_.front());
2475                 d->func_request_queue_.pop();
2476                 processFuncRequest(fr);
2477         }
2478 }
2479
2480
2481 void GuiApplication::processFuncRequestQueueAsync()
2482 {
2483         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2484 }
2485
2486
2487 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2488 {
2489         d->func_request_queue_.push(func);
2490 }
2491
2492
2493 void GuiApplication::resetGui()
2494 {
2495         // Set the language defined by the user.
2496         setGuiLanguage();
2497
2498         // Read menus
2499         if (!readUIFile(toqstr(lyxrc.ui_file)))
2500                 // Gives some error box here.
2501                 return;
2502
2503         if (d->global_menubar_)
2504                 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2505
2506         QHash<int, GuiView *>::iterator it;
2507         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2508                 GuiView * gv = *it;
2509                 setCurrentView(gv);
2510                 gv->setLayoutDirection(layoutDirection());
2511                 gv->resetDialogs();
2512         }
2513
2514         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2515 }
2516
2517
2518 bool GuiApplication::rtlContext() const
2519 {
2520         if (current_view_ && current_view_->currentBufferView()) {
2521                 BufferView const * bv = current_view_->currentBufferView();
2522                 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2523         } else
2524                 return layoutDirection() == Qt::RightToLeft;
2525 }
2526
2527
2528 void GuiApplication::createView(int view_id)
2529 {
2530         createView(QString(), true, view_id);
2531 }
2532
2533
2534 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2535         int view_id)
2536 {
2537         // release the keyboard which might have been grabbed by the global
2538         // menubar on Mac to catch shortcuts even without any GuiView.
2539         if (d->global_menubar_)
2540                 d->global_menubar_->releaseKeyboard();
2541
2542         // create new view
2543         int id = view_id;
2544         while (d->views_.find(id) != d->views_.end())
2545                 id++;
2546
2547         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2548         GuiView * view = new GuiView(id);
2549         // `view' is the new current_view_. Tell coverity that is is not 0.
2550         LATTEST(current_view_);
2551         // register view
2552         d->views_[id] = view;
2553
2554         if (autoShow) {
2555                 view->show();
2556                 setActiveWindow(view);
2557         }
2558
2559         if (!geometry_arg.isEmpty()) {
2560 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2561                 int x, y;
2562                 int w, h;
2563                 QChar sx, sy;
2564                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2565                 re.indexIn(geometry_arg);
2566                 w = re.cap(1).toInt();
2567                 h = re.cap(2).toInt();
2568                 x = re.cap(3).toInt();
2569                 y = re.cap(4).toInt();
2570                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2571                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2572                 // Set initial geometry such that we can get the frame size.
2573                 view->setGeometry(x, y, w, h);
2574                 int framewidth = view->geometry().x() - view->x();
2575                 int titleheight = view->geometry().y() - view->y();
2576                 // Negative displacements must be interpreted as distances
2577                 // from the right or bottom screen borders.
2578                 if (sx == '-' || sy == '-') {
2579                         QRect rec = QApplication::desktop()->screenGeometry();
2580                         if (sx == '-')
2581                                 x += rec.width() - w - framewidth;
2582                         if (sy == '-')
2583                                 y += rec.height() - h - titleheight;
2584                         view->setGeometry(x, y, w, h);
2585                 }
2586                 // Make sure that the left and top frame borders are visible.
2587                 if (view->x() < 0 || view->y() < 0) {
2588                         if (view->x() < 0)
2589                                 x = framewidth;
2590                         if (view->y() < 0)
2591                                 y = titleheight;
2592                         view->setGeometry(x, y, w, h);
2593                 }
2594 #endif
2595         }
2596         view->setFocus();
2597 }
2598
2599
2600 bool GuiApplication::unhide(Buffer * buf)
2601 {
2602         if (!currentView())
2603                 return false;
2604         currentView()->setBuffer(buf, false);
2605         return true;
2606 }
2607
2608
2609 Clipboard & GuiApplication::clipboard()
2610 {
2611         return d->clipboard_;
2612 }
2613
2614
2615 Selection & GuiApplication::selection()
2616 {
2617         return d->selection_;
2618 }
2619
2620
2621 FontLoader & GuiApplication::fontLoader()
2622 {
2623         return d->font_loader_;
2624 }
2625
2626
2627 Toolbars const & GuiApplication::toolbars() const
2628 {
2629         return d->toolbars_;
2630 }
2631
2632
2633 Toolbars & GuiApplication::toolbars()
2634 {
2635         return d->toolbars_;
2636 }
2637
2638
2639 Menus const & GuiApplication::menus() const
2640 {
2641         return d->menus_;
2642 }
2643
2644
2645 Menus & GuiApplication::menus()
2646 {
2647         return d->menus_;
2648 }
2649
2650
2651 QList<int> GuiApplication::viewIds() const
2652 {
2653         return d->views_.keys();
2654 }
2655
2656
2657 ColorCache & GuiApplication::colorCache()
2658 {
2659         return d->color_cache_;
2660 }
2661
2662
2663 int GuiApplication::exec()
2664 {
2665         // asynchronously handle batch commands. This event will be in
2666         // the event queue in front of other asynchronous events. Hence,
2667         // we can assume in the latter that the gui is setup already.
2668         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2669
2670         return QApplication::exec();
2671 }
2672
2673
2674 void GuiApplication::exit(int status)
2675 {
2676         QApplication::exit(status);
2677 }
2678
2679
2680 void GuiApplication::setGuiLanguage()
2681 {
2682         setLocale();
2683         QLocale theLocale;
2684         // install translation file for Qt built-in dialogs
2685         QString const language_name = QString("qt_") + theLocale.name();
2686         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2687         // Short-named translator can be loaded from a long name, but not the
2688         // opposite. Therefore, long name should be used without truncation.
2689         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2690         if (!d->qt_trans_.load(language_name,
2691                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2692                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2693                         << language_name);
2694         } else {
2695                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2696                         << language_name);
2697         }
2698
2699         switch (theLocale.language()) {
2700         case QLocale::Arabic :
2701         case QLocale::Hebrew :
2702         case QLocale::Persian :
2703         case QLocale::Urdu :
2704                 setLayoutDirection(Qt::RightToLeft);
2705                 break;
2706         default:
2707                 setLayoutDirection(Qt::LeftToRight);
2708         }
2709 }
2710
2711
2712 void GuiApplication::execBatchCommands()
2713 {
2714         setGuiLanguage();
2715
2716         // Read menus
2717         if (!readUIFile(toqstr(lyxrc.ui_file)))
2718                 // Gives some error box here.
2719                 return;
2720
2721 #ifdef Q_OS_MAC
2722 #if QT_VERSION > 0x040600
2723         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2724 #endif
2725 #if QT_VERSION > 0x050100
2726         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2727 #endif
2728         // Create the global default menubar which is shown for the dialogs
2729         // and if no GuiView is visible.
2730         // This must be done after the session was recovered to know the "last files".
2731         d->global_menubar_ = new QMenuBar(0);
2732         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2733 #endif
2734
2735         lyx::execBatchCommands();
2736 }
2737
2738
2739 QAbstractItemModel * GuiApplication::languageModel()
2740 {
2741         if (d->language_model_)
2742                 return d->language_model_;
2743
2744         QStandardItemModel * lang_model = new QStandardItemModel(this);
2745         lang_model->insertColumns(0, 3);
2746         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2747         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2748         Languages::const_iterator it = lyx::languages.begin();
2749         Languages::const_iterator end = lyx::languages.end();
2750         for (; it != end; ++it) {
2751                 int current_row = lang_model->rowCount();
2752                 lang_model->insertRows(current_row, 1);
2753                 QModelIndex pl_item = lang_model->index(current_row, 0);
2754                 QModelIndex sp_item = lang_model->index(current_row, 1);
2755                 QModelIndex th_item = lang_model->index(current_row, 2);
2756                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2757                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2758                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2759                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2760                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2761                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2762                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2763                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2764                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2765                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2766         }
2767         d->language_model_ = new QSortFilterProxyModel(this);
2768         d->language_model_->setSourceModel(lang_model);
2769         d->language_model_->setSortLocaleAware(true);
2770         return d->language_model_;
2771 }
2772
2773
2774 void GuiApplication::restoreGuiSession()
2775 {
2776         if (!lyxrc.load_session)
2777                 return;
2778
2779         Session & session = theSession();
2780         LastOpenedSection::LastOpened const & lastopened =
2781                 session.lastOpened().getfiles();
2782
2783         validateCurrentView();
2784
2785         FileName active_file;
2786         // do not add to the lastfile list since these files are restored from
2787         // last session, and should be already there (regular files), or should
2788         // not be added at all (help files).
2789         for (auto const & last : lastopened) {
2790                 FileName const & file_name = last.file_name;
2791                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2792                           && current_view_->documentBufferView() != nullptr)) {
2793                         string const & fname = file_name.absFileName();
2794                         createView(support::checksum(fname));
2795                 }
2796                 current_view_->loadDocument(file_name, false);
2797
2798                 if (last.active)
2799                         active_file = file_name;
2800         }
2801
2802         // Restore last active buffer
2803         Buffer * buffer = theBufferList().getBuffer(active_file);
2804         if (buffer && current_view_)
2805                 current_view_->setBuffer(buffer);
2806
2807         // clear this list to save a few bytes of RAM
2808         session.lastOpened().clear();
2809 }
2810
2811
2812 QString const GuiApplication::romanFontName()
2813 {
2814         QFont font;
2815         font.setStyleHint(QFont::Serif);
2816         font.setFamily("serif");
2817
2818         return QFontInfo(font).family();
2819 }
2820
2821
2822 QString const GuiApplication::sansFontName()
2823 {
2824         QFont font;
2825         font.setStyleHint(QFont::SansSerif);
2826         font.setFamily("sans");
2827
2828         return QFontInfo(font).family();
2829 }
2830
2831
2832 QString const GuiApplication::typewriterFontName()
2833 {
2834         return QFontInfo(typewriterSystemFont()).family();
2835 }
2836
2837
2838 namespace {
2839         // We cannot use QFont::fixedPitch() because it doesn't
2840         // return the fact but only if it is requested.
2841         static bool isFixedPitch(const QFont & font) {
2842                 const QFontInfo fi(font);
2843                 return fi.fixedPitch();
2844         }
2845 } // namespace
2846
2847
2848 QFont const GuiApplication::typewriterSystemFont()
2849 {
2850 #if QT_VERSION >= 0x050200
2851         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2852 #else
2853         QFont font("monospace");
2854 #endif
2855         if (!isFixedPitch(font)) {
2856                 // try to enforce a real monospaced font
2857                 font.setStyleHint(QFont::Monospace);
2858                 if (!isFixedPitch(font)) {
2859                         font.setStyleHint(QFont::TypeWriter);
2860                         if (!isFixedPitch(font)) font.setFamily("courier");
2861                 }
2862         }
2863 #ifdef Q_OS_MAC
2864         // On a Mac the result is too small and it's not practical to
2865         // rely on Qtconfig utility to change the system settings of Qt.
2866         font.setPointSize(12);
2867 #endif
2868         return font;
2869 }
2870
2871
2872 void GuiApplication::handleRegularEvents()
2873 {
2874         ForkedCallsController::handleCompletedProcesses();
2875 }
2876
2877
2878 bool GuiApplication::event(QEvent * e)
2879 {
2880         switch(e->type()) {
2881         case QEvent::FileOpen: {
2882                 // Open a file; this happens only on Mac OS X for now.
2883                 //
2884                 // We do this asynchronously because on startup the batch
2885                 // commands are not executed here yet and the gui is not ready
2886                 // therefore.
2887                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2888                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2889                 processFuncRequestAsync(fr);
2890                 e->accept();
2891                 return true;
2892         }
2893 #if (QT_VERSION < 0x050000)
2894         // Qt5 uses a signal for that, see above.
2895         case QEvent::KeyboardLayoutChange:
2896                 //LYXERR0("keyboard change");
2897                 if (currentView() && currentView()->currentBufferView())
2898                         currentView()->currentBufferView()->cursor().setLanguageFromInput();
2899                 e->accept();
2900                 return true;
2901 #endif
2902         default:
2903                 return QApplication::event(e);
2904         }
2905 }
2906
2907
2908 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2909 {
2910         try {
2911                 return QApplication::notify(receiver, event);
2912         }
2913         catch (ExceptionMessage const & e) {
2914                 switch(e.type_) {
2915                 case ErrorException:
2916                         emergencyCleanup();
2917                         setQuitOnLastWindowClosed(false);
2918                         closeAllViews();
2919                         Alert::error(e.title_, e.details_);
2920 #ifndef NDEBUG
2921                         // Properly crash in debug mode in order to get a useful backtrace.
2922                         abort();
2923 #endif
2924                         // In release mode, try to exit gracefully.
2925                         this->exit(1);
2926                         // FIXME: GCC 7 thinks we can fall through here. Can we?
2927                         // fall through
2928                 case BufferException: {
2929                         if (!current_view_ || !current_view_->documentBufferView())
2930                                 return false;
2931                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2932                         docstring details = e.details_ + '\n';
2933                         details += buf->emergencyWrite();
2934                         theBufferList().release(buf);
2935                         details += "\n" + _("The current document was closed.");
2936                         Alert::error(e.title_, details);
2937                         return false;
2938                 }
2939                 case WarningException:
2940                         Alert::warning(e.title_, e.details_);
2941                         return false;
2942                 }
2943         }
2944         catch (exception const & e) {
2945                 docstring s = _("LyX has caught an exception, it will now "
2946                         "attempt to save all unsaved documents and exit."
2947                         "\n\nException: ");
2948                 s += from_ascii(e.what());
2949                 Alert::error(_("Software exception Detected"), s);
2950                 lyx_exit(1);
2951         }
2952         catch (...) {
2953                 docstring s = _("LyX has caught some really weird exception, it will "
2954                         "now attempt to save all unsaved documents and exit.");
2955                 Alert::error(_("Software exception Detected"), s);
2956                 lyx_exit(1);
2957         }
2958
2959         return false;
2960 }
2961
2962 bool GuiApplication::isInDarkMode()
2963 {
2964         return colorCache().isDarkMode();
2965 }
2966
2967
2968 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2969 {
2970         QColor const & qcol = d->color_cache_.get(col);
2971         if (!qcol.isValid()) {
2972                 rgbcol.r = 0;
2973                 rgbcol.g = 0;
2974                 rgbcol.b = 0;
2975                 return false;
2976         }
2977         rgbcol.r = qcol.red();
2978         rgbcol.g = qcol.green();
2979         rgbcol.b = qcol.blue();
2980         return true;
2981 }
2982
2983
2984 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2985 {
2986         QColor const qcol(lcolor.getX11HexName(col).c_str());
2987         if (!qcol.isValid()) {
2988                 rgbcol.r = 0;
2989                 rgbcol.g = 0;
2990                 rgbcol.b = 0;
2991                 return false;
2992         }
2993         rgbcol.r = qcol.red();
2994         rgbcol.g = qcol.green();
2995         rgbcol.b = qcol.blue();
2996         return true;
2997 }
2998
2999
3000 string const GuiApplication::hexName(ColorCode col)
3001 {
3002         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3003 }
3004
3005
3006 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3007 {
3008         SocketNotifier * sn = new SocketNotifier(this, fd, func);
3009         d->socket_notifiers_[fd] = sn;
3010         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3011 }
3012
3013
3014 void GuiApplication::socketDataReceived(int fd)
3015 {
3016         d->socket_notifiers_[fd]->func_();
3017 }
3018
3019
3020 void GuiApplication::unregisterSocketCallback(int fd)
3021 {
3022         d->socket_notifiers_.take(fd)->setEnabled(false);
3023 }
3024
3025
3026 void GuiApplication::commitData(QSessionManager & sm)
3027 {
3028         /** The implementation is required to avoid an application exit
3029          ** when session state save is triggered by session manager.
3030          ** The default implementation sends a close event to all
3031          ** visible top level widgets when session management allows
3032          ** interaction.
3033          ** We are changing that to check the state of each buffer in all
3034          ** views and ask the users what to do if buffers are dirty.
3035          ** Furthermore, we save the session state.
3036          ** We do NOT close the views here since the user still can cancel
3037          ** the logout process (see #9277); also, this would hide LyX from
3038          ** an OSes own session handling (application restoration).
3039          **/
3040         #ifdef QT_NO_SESSIONMANAGER
3041                 #ifndef _MSC_VER
3042                         #warning Qt is compiled without session manager
3043                 #else
3044                         #pragma message("warning: Qt is compiled without session manager")
3045                 #endif
3046                 (void) sm;
3047         #else
3048                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3049                         sm.cancel();
3050                 else
3051                         sm.release();
3052         #endif
3053 }
3054
3055
3056 void GuiApplication::unregisterView(GuiView * gv)
3057 {
3058         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3059                 d->views_.remove(gv->id());
3060                 if (current_view_ == gv)
3061                         current_view_ = nullptr;
3062         }
3063 }
3064
3065
3066 bool GuiApplication::closeAllViews()
3067 {
3068         if (d->views_.empty())
3069                 return true;
3070
3071         // When a view/window was closed before without quitting LyX, there
3072         // are already entries in the lastOpened list.
3073         theSession().lastOpened().clear();
3074
3075         QList<GuiView *> const views = d->views_.values();
3076         for (GuiView * view : views) {
3077                 if (!view->closeScheduled())
3078                         return false;
3079         }
3080
3081         d->views_.clear();
3082         return true;
3083 }
3084
3085
3086 bool GuiApplication::prepareAllViewsForLogout()
3087 {
3088         if (d->views_.empty())
3089                 return true;
3090
3091         QList<GuiView *> const views = d->views_.values();
3092         for (GuiView * view : views) {
3093                 if (!view->prepareAllBuffersForLogout())
3094                         return false;
3095         }
3096
3097         return true;
3098 }
3099
3100
3101 GuiView & GuiApplication::view(int id) const
3102 {
3103         LAPPERR(d->views_.contains(id));
3104         return *d->views_.value(id);
3105 }
3106
3107
3108 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3109 {
3110         QList<GuiView *> const views = d->views_.values();
3111         for (GuiView * view : views)
3112                 view->hideDialog(name, inset);
3113 }
3114
3115
3116 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3117 {
3118         Buffer const * buf = nullptr;
3119         QHash<int, GuiView *>::const_iterator end = d->views_.end();
3120         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3121                 if (Buffer const * ptr = (*it)->updateInset(inset))
3122                         buf = ptr;
3123         }
3124         return buf;
3125 }
3126
3127
3128 bool GuiApplication::searchMenu(FuncRequest const & func,
3129         docstring_list & names) const
3130 {
3131         BufferView * bv = nullptr;
3132         if (current_view_)
3133                 bv = current_view_->currentBufferView();
3134         return d->menus_.searchMenu(func, names, bv);
3135 }
3136
3137
3138 bool GuiApplication::hasBufferView() const
3139 {
3140         return (current_view_ && current_view_->currentBufferView());
3141 }
3142
3143
3144 // Ensure that a file is read only once (prevents include loops)
3145 static QStringList uifiles;
3146 // store which ui files define Toolbars
3147 static QStringList toolbar_uifiles;
3148
3149
3150 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3151 {
3152         enum {
3153                 ui_menuset = 1,
3154                 ui_toolbars,
3155                 ui_toolbarset,
3156                 ui_include,
3157                 ui_format,
3158                 ui_last
3159         };
3160
3161         LexerKeyword uitags[] = {
3162                 { "format", ui_format },
3163                 { "include", ui_include },
3164                 { "menuset", ui_menuset },
3165                 { "toolbars", ui_toolbars },
3166                 { "toolbarset", ui_toolbarset }
3167         };
3168
3169         Lexer lex(uitags);
3170         lex.setFile(ui_path);
3171         if (!lex.isOK()) {
3172                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3173                                          << endl;
3174         }
3175
3176         if (lyxerr.debugging(Debug::PARSER))
3177                 lex.printTable(lyxerr);
3178
3179         bool error = false;
3180         // format before introduction of format tag
3181         unsigned int format = 0;
3182         while (lex.isOK()) {
3183                 int const status = lex.lex();
3184
3185                 // we have to do this check here, outside the switch,
3186                 // because otherwise we would start reading include files,
3187                 // e.g., if the first tag we hit was an include tag.
3188                 if (status == ui_format)
3189                         if (lex.next()) {
3190                                 format = lex.getInteger();
3191                                 continue;
3192                         }
3193
3194                 // this will trigger unless the first tag we hit is a format
3195                 // tag, with the right format.
3196                 if (format != LFUN_FORMAT)
3197                         return FormatMismatch;
3198
3199                 switch (status) {
3200                 case Lexer::LEX_FEOF:
3201                         continue;
3202
3203                 case ui_include: {
3204                         lex.next(true);
3205                         QString const file = toqstr(lex.getString());
3206                         bool const success = readUIFile(file, true);
3207                         if (!success) {
3208                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3209                                 return ReadError;
3210                         }
3211                         break;
3212                 }
3213
3214                 case ui_menuset:
3215                         d->menus_.read(lex);
3216                         break;
3217
3218                 case ui_toolbarset:
3219                         d->toolbars_.readToolbars(lex);
3220                         break;
3221
3222                 case ui_toolbars:
3223                         d->toolbars_.readToolbarSettings(lex);
3224                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3225                         break;
3226
3227                 default:
3228                         if (!rtrim(lex.getString()).empty())
3229                                 lex.printError("LyX::ReadUIFile: "
3230                                                "Unknown menu tag: `$$Token'");
3231                         else
3232                                 LYXERR0("Error with status: " << status);
3233                         error = true;
3234                         break;
3235                 }
3236
3237         }
3238         return (error ? ReadError : ReadOK);
3239 }
3240
3241
3242 bool GuiApplication::readUIFile(QString const & name, bool include)
3243 {
3244         LYXERR(Debug::INIT, "About to read " << name << "...");
3245
3246         FileName ui_path;
3247         if (include) {
3248                 ui_path = libFileSearch("ui", name, "inc");
3249                 if (ui_path.empty())
3250                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3251         } else {
3252                 ui_path = libFileSearch("ui", name, "ui");
3253         }
3254
3255         if (ui_path.empty()) {
3256                 static const QString defaultUIFile = "default";
3257                 LYXERR(Debug::INIT, "Could not find " << name);
3258                 if (include) {
3259                         Alert::warning(_("Could not find UI definition file"),
3260                                 bformat(_("Error while reading the included file\n%1$s\n"
3261                                         "Please check your installation."), qstring_to_ucs4(name)));
3262                         return false;
3263                 }
3264                 if (name == defaultUIFile) {
3265                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3266                         Alert::warning(_("Could not find default UI file"),
3267                                 _("LyX could not find the default UI file!\n"
3268                                   "Please check your installation."));
3269                         return false;
3270                 }
3271                 Alert::warning(_("Could not find UI definition file"),
3272                 bformat(_("Error while reading the configuration file\n%1$s\n"
3273                         "Falling back to default.\n"
3274                         "Please look under Tools>Preferences>User Interface and\n"
3275                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3276                 return readUIFile(defaultUIFile, false);
3277         }
3278
3279         QString const uifile = toqstr(ui_path.absFileName());
3280         if (uifiles.contains(uifile)) {
3281                 if (!include) {
3282                         // We are reading again the top uifile so reset the safeguard:
3283                         uifiles.clear();
3284                         d->menus_.reset();
3285                         d->toolbars_.reset();
3286                 } else {
3287                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3288                                 << "Is this an include loop?");
3289                         return false;
3290                 }
3291         }
3292         uifiles.push_back(uifile);
3293
3294         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3295
3296         ReturnValues retval = readUIFile(ui_path);
3297
3298         if (retval == FormatMismatch) {
3299                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3300                 TempFile tmp("convertXXXXXX.ui");
3301                 FileName const tempfile = tmp.name();
3302                 bool const success = prefs2prefs(ui_path, tempfile, true);
3303                 if (!success) {
3304                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3305                                 " to format " << LFUN_FORMAT << ".");
3306                 } else {
3307                         retval = readUIFile(tempfile);
3308                 }
3309         }
3310
3311         if (retval != ReadOK) {
3312                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3313                 return false;
3314         }
3315
3316         if (include)
3317                 return true;
3318
3319         QSettings settings;
3320         settings.beginGroup("ui_files");
3321         bool touched = false;
3322         for (int i = 0; i != uifiles.size(); ++i) {
3323                 QFileInfo fi(uifiles[i]);
3324                 QDateTime const date_value = fi.lastModified();
3325                 QString const name_key = QString::number(i);
3326                 // if an ui file which defines Toolbars has changed,
3327                 // we have to reset the settings
3328                 if (toolbar_uifiles.contains(uifiles[i])
3329                  && (!settings.contains(name_key)
3330                  || settings.value(name_key).toString() != uifiles[i]
3331                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3332                         touched = true;
3333                         settings.setValue(name_key, uifiles[i]);
3334                         settings.setValue(name_key + "/date", date_value);
3335                 }
3336         }
3337         settings.endGroup();
3338         if (touched)
3339                 settings.remove("views");
3340
3341         return true;
3342 }
3343
3344
3345 void GuiApplication::onLastWindowClosed()
3346 {
3347         if (d->global_menubar_)
3348                 d->global_menubar_->grabKeyboard();
3349 }
3350
3351
3352 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3353 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3354 {
3355         std::string name = "unknown";
3356         switch (state) {
3357         case Qt::ApplicationSuspended:
3358                 name = "ApplicationSuspended";
3359                 break;
3360         case Qt::ApplicationHidden:
3361                 name = "ApplicationHidden";
3362                 break;
3363         case Qt::ApplicationInactive:
3364                 name = "ApplicationInactive";
3365                 break;
3366         case Qt::ApplicationActive:
3367                 name = "ApplicationActive";
3368                 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3369                 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3370                 if (d->views_.empty() && d->last_state_ == state) {
3371                         LYXERR(Debug::GUI, "Open new window...");
3372                         createView();
3373                 }
3374                 break;
3375         }
3376         LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3377         d->last_state_ = state;
3378 }
3379 #endif
3380
3381
3382 void GuiApplication::startLongOperation() {
3383         d->key_checker_.start();
3384 }
3385
3386
3387 bool GuiApplication::longOperationCancelled() {
3388         return d->key_checker_.pressed();
3389 }
3390
3391
3392 void GuiApplication::stopLongOperation() {
3393         d->key_checker_.stop();
3394 }
3395
3396
3397 bool GuiApplication::longOperationStarted() {
3398         return d->key_checker_.started();
3399 }
3400
3401
3402 ////////////////////////////////////////////////////////////////////////
3403 //
3404 // X11 specific stuff goes here...
3405
3406 #ifdef Q_WS_X11
3407 bool GuiApplication::x11EventFilter(XEvent * xev)
3408 {
3409         if (!current_view_)
3410                 return false;
3411
3412         switch (xev->type) {
3413         case SelectionRequest: {
3414                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3415                         break;
3416                 LYXERR(Debug::SELECTION, "X requested selection.");
3417                 BufferView * bv = current_view_->currentBufferView();
3418                 if (bv) {
3419                         docstring const sel = bv->requestSelection();
3420                         if (!sel.empty()) {
3421                                 d->selection_.put(sel);
3422                                 // Refresh the selection request timestamp.
3423                                 // We have to do this by ourselves as Qt seems
3424                                 // not doing that, maybe because of our
3425                                 // "persistent selection" implementation
3426                                 // (see comments in GuiSelection.cpp).
3427                                 XSelectionEvent nev;
3428                                 nev.type = SelectionNotify;
3429                                 nev.display = xev->xselectionrequest.display;
3430                                 nev.requestor = xev->xselectionrequest.requestor;
3431                                 nev.selection = xev->xselectionrequest.selection;
3432                                 nev.target = xev->xselectionrequest.target;
3433                                 nev.property = 0L; // None
3434                                 nev.time = CurrentTime;
3435                                 XSendEvent(QX11Info::display(),
3436                                         nev.requestor, False, 0,
3437                                         reinterpret_cast<XEvent *>(&nev));
3438                                 return true;
3439                         }
3440                 }
3441                 break;
3442         }
3443         case SelectionClear: {
3444                 if (xev->xselectionclear.selection != XA_PRIMARY)
3445                         break;
3446                 LYXERR(Debug::SELECTION, "Lost selection.");
3447                 BufferView * bv = current_view_->currentBufferView();
3448                 if (bv)
3449                         bv->clearSelection();
3450                 break;
3451         }
3452         }
3453         return false;
3454 }
3455 #elif defined(QPA_XCB)
3456 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3457                                        void * message, long *)
3458 {
3459         if (!current_view_ || eventType != "xcb_generic_event_t")
3460                 return false;
3461
3462         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3463
3464         switch (ev->response_type) {
3465         case XCB_SELECTION_REQUEST: {
3466                 xcb_selection_request_event_t * srev =
3467                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3468                 if (srev->selection != XCB_ATOM_PRIMARY)
3469                         break;
3470                 LYXERR(Debug::SELECTION, "X requested selection.");
3471                 BufferView * bv = current_view_->currentBufferView();
3472                 if (bv) {
3473                         docstring const sel = bv->requestSelection();
3474                         if (!sel.empty()) {
3475                                 d->selection_.put(sel);
3476 #ifdef HAVE_QT5_X11_EXTRAS
3477                                 // Refresh the selection request timestamp.
3478                                 // We have to do this by ourselves as Qt seems
3479                                 // not doing that, maybe because of our
3480                                 // "persistent selection" implementation
3481                                 // (see comments in GuiSelection.cpp).
3482                                 // It is expected that every X11 event is
3483                                 // 32 bytes long, even if not all 32 bytes are
3484                                 // needed. See:
3485                                 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3486                                 struct alignas(32) padded_event
3487                                         : xcb_selection_notify_event_t {};
3488                                 padded_event nev = {};
3489                                 nev.response_type = XCB_SELECTION_NOTIFY;
3490                                 nev.requestor = srev->requestor;
3491                                 nev.selection = srev->selection;
3492                                 nev.target = srev->target;
3493                                 nev.property = XCB_NONE;
3494                                 nev.time = XCB_CURRENT_TIME;
3495                                 xcb_connection_t * con = QX11Info::connection();
3496                                 xcb_send_event(con, 0, srev->requestor,
3497                                         XCB_EVENT_MASK_NO_EVENT,
3498                                         reinterpret_cast<char const *>(&nev));
3499                                 xcb_flush(con);
3500 #endif
3501                                 return true;
3502                         }
3503                 }
3504                 break;
3505         }
3506         case XCB_SELECTION_CLEAR: {
3507                 xcb_selection_clear_event_t * scev =
3508                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3509                 if (scev->selection != XCB_ATOM_PRIMARY)
3510                         break;
3511                 LYXERR(Debug::SELECTION, "Lost selection.");
3512                 BufferView * bv = current_view_->currentBufferView();
3513                 if (bv)
3514                         bv->clearSelection();
3515                 break;
3516         }
3517         }
3518         return false;
3519 }
3520 #endif
3521
3522 } // namespace frontend
3523
3524
3525 void hideDialogs(std::string const & name, Inset * inset)
3526 {
3527         if (theApp())
3528                 frontend::guiApp->hideDialogs(name, inset);
3529 }
3530
3531
3532 ////////////////////////////////////////////////////////////////////
3533 //
3534 // Font stuff
3535 //
3536 ////////////////////////////////////////////////////////////////////
3537
3538 frontend::FontLoader & theFontLoader()
3539 {
3540         LAPPERR(frontend::guiApp);
3541         return frontend::guiApp->fontLoader();
3542 }
3543
3544
3545 frontend::FontMetrics const & theFontMetrics(Font const & f)
3546 {
3547         return theFontMetrics(f.fontInfo());
3548 }
3549
3550
3551 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3552 {
3553         LAPPERR(frontend::guiApp);
3554         return frontend::guiApp->fontLoader().metrics(f);
3555 }
3556
3557
3558 ////////////////////////////////////////////////////////////////////
3559 //
3560 // Misc stuff
3561 //
3562 ////////////////////////////////////////////////////////////////////
3563
3564 frontend::Clipboard & theClipboard()
3565 {
3566         LAPPERR(frontend::guiApp);
3567         return frontend::guiApp->clipboard();
3568 }
3569
3570
3571 frontend::Selection & theSelection()
3572 {
3573         LAPPERR(frontend::guiApp);
3574         return frontend::guiApp->selection();
3575 }
3576
3577
3578 } // namespace lyx
3579
3580 #include "moc_GuiApplication.cpp"