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