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