]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiApplication.cpp
b0ec64ee0919d53f506239bd7754f689b3f42409
[lyx.git] / src / frontends / qt / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
21 #include "GuiView.h"
22 #include "Menus.h"
23 #include "qt_helpers.h"
24 #include "Toolbars.h"
25
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
30
31 #include "Buffer.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
35 #include "CmdDef.h"
36 #include "Color.h"
37 #include "Converter.h"
38 #include "Cursor.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
41 #include "Font.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
45 #include "Intl.h"
46 #include "KeyMap.h"
47 #include "Language.h"
48 #include "LaTeXPackages.h"
49 #include "Lexer.h"
50 #include "LyX.h"
51 #include "LyXAction.h"
52 #include "LyXRC.h"
53 #include "Paragraph.h"
54 #include "Server.h"
55 #include "Session.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
58 #include "version.h"
59
60 #include "insets/InsetText.h"
61
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/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)
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
1015 #ifdef Q_OS_MAC
1016         /// Linkback mime handler for MacOSX.
1017         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1018 #endif
1019
1020 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1021 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1022         /// WMF Mime handler for Windows clipboard.
1023         QWindowsMimeMetafile * wmf_mime_;
1024 #endif
1025 #endif
1026
1027         /// Allows to check whether ESC was pressed during a long operation
1028         KeyChecker key_checker_;
1029 };
1030
1031
1032 GuiApplication * guiApp;
1033
1034 GuiApplication::~GuiApplication()
1035 {
1036 #ifdef Q_OS_MAC
1037         closeAllLinkBackLinks();
1038 #endif
1039         delete d;
1040 }
1041
1042
1043 GuiApplication::GuiApplication(int & argc, char ** argv)
1044         : QApplication(argc, argv), current_view_(nullptr),
1045           d(new GuiApplication::Private)
1046 {
1047         QString app_name = "LyX";
1048         QCoreApplication::setOrganizationName(app_name);
1049         QCoreApplication::setOrganizationDomain("lyx.org");
1050         QCoreApplication::setApplicationName(lyx_package);
1051 #if QT_VERSION >= 0x050000
1052         QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1053 #endif
1054
1055 #if QT_VERSION >= 0x050700
1056         setDesktopFileName(lyx_package);
1057 #endif
1058
1059         qsrand(QDateTime::currentDateTime().toTime_t());
1060
1061         // Install LyX translator for missing Qt translations
1062         installTranslator(&d->gui_trans_);
1063         // Install Qt native translator for GUI elements.
1064         installTranslator(&d->qt_trans_);
1065
1066 #ifdef QPA_XCB
1067         // Enable reception of XCB events.
1068         installNativeEventFilter(this);
1069 #endif
1070
1071         // FIXME: quitOnLastWindowClosed is true by default. We should have a
1072         // lyxrc setting for this in order to let the application stay resident.
1073         // But then we need some kind of dock icon, at least on Windows.
1074         /*
1075         if (lyxrc.quit_on_last_window_closed)
1076                 setQuitOnLastWindowClosed(false);
1077         */
1078 #ifdef Q_OS_MAC
1079         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1080         // seems to be the default case for applications like LyX.
1081         setQuitOnLastWindowClosed(false);
1082         ///
1083         setupApplescript();
1084         appleCleanupEditMenu();
1085         appleCleanupViewMenu();
1086 #endif
1087
1088 #if defined(Q_WS_X11) || defined(QPA_XCB)
1089         // doubleClickInterval() is 400 ms on X11 which is just too long.
1090         // On Windows and Mac OS X, the operating system's value is used.
1091         // On Microsoft Windows, calling this function sets the double
1092         // click interval for all applications. So we don't!
1093         QApplication::setDoubleClickInterval(300);
1094 #endif
1095
1096         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1097
1098         // needs to be done before reading lyxrc
1099         QWidget w;
1100         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1101
1102         guiApp = this;
1103
1104         // Initialize RC Fonts
1105         if (lyxrc.roman_font_name.empty())
1106                 lyxrc.roman_font_name = fromqstr(romanFontName());
1107
1108         if (lyxrc.sans_font_name.empty())
1109                 lyxrc.sans_font_name = fromqstr(sansFontName());
1110
1111         if (lyxrc.typewriter_font_name.empty())
1112                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1113
1114 #if (QT_VERSION >= 0x050000)
1115         // Qt4 does this in event(), see below.
1116         // Track change of keyboard
1117         connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1118 #endif
1119
1120         d->general_timer_.setInterval(500);
1121         connect(&d->general_timer_, SIGNAL(timeout()),
1122                 this, SLOT(handleRegularEvents()));
1123         d->general_timer_.start();
1124
1125         // maxThreadCount() defaults in general to 2 on single or dual-processor.
1126         // This is clearly not enough in a time where we use threads for
1127         // document preview and/or export. 20 should be OK.
1128         QThreadPool::globalInstance()->setMaxThreadCount(20);
1129
1130         // make sure tooltips are formatted
1131         installEventFilter(new ToolTipFormatter(this));
1132 }
1133
1134
1135 GuiApplication * theGuiApp()
1136 {
1137         return dynamic_cast<GuiApplication *>(theApp());
1138 }
1139
1140
1141 #if QT_VERSION < 0x050000
1142 // Emulate platformName() for Qt4
1143
1144 // FIXME: when ditching this method, remove all tests
1145 //     platformName() == "qt4x11"
1146 // in the code
1147 QString GuiApplication::platformName() const
1148 {
1149 # if defined(Q_WS_X11)
1150         // Note that this one does not really exist
1151         return "qt4x11";
1152 # elif defined(Q_OS_MAC)
1153         return "cocoa";
1154 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1155         return "windows";
1156 # else
1157         LYXERR0("Unknown platform!");
1158         return "unknown";
1159 # endif
1160 }
1161 #endif
1162
1163
1164 double GuiApplication::pixelRatio() const
1165 {
1166 #if QT_VERSION >= 0x050000
1167         return qt_scale_factor * devicePixelRatio();
1168 #else
1169         return 1.0;
1170 #endif
1171 }
1172
1173
1174 void GuiApplication::clearSession()
1175 {
1176         QSettings settings;
1177         settings.clear();
1178 }
1179
1180
1181 docstring Application::iconName(FuncRequest const & f, bool unknown)
1182 {
1183         return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1184 }
1185
1186
1187 docstring Application::mathIcon(docstring const & c)
1188 {
1189         return qstring_to_ucs4(findImg(toqstr(c)));
1190 }
1191
1192
1193 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1194 {
1195         FuncStatus status;
1196
1197         BufferView * bv = nullptr;
1198         BufferView * doc_bv = nullptr;
1199
1200         if (cmd.action() == LFUN_NOACTION) {
1201                 status.message(from_utf8(N_("Nothing to do")));
1202                 status.setEnabled(false);
1203         }
1204
1205         else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1206                 status.setUnknown(true);
1207                 status.message(from_utf8(N_("Unknown action")));
1208                 status.setEnabled(false);
1209         }
1210
1211         // Does the GuiApplication know something?
1212         else if (getStatus(cmd, status)) { }
1213
1214         // If we do not have a GuiView, then other functions are disabled
1215         else if (!current_view_)
1216                 status.setEnabled(false);
1217
1218         // Does the GuiView know something?
1219         else if (current_view_->getStatus(cmd, status)) { }
1220
1221         // In LyX/Mac, when a dialog is open, the menus of the
1222         // application can still be accessed without giving focus to
1223         // the main window. In this case, we want to disable the menu
1224         // entries that are buffer or view-related.
1225         //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1226         /*
1227         else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1228                 status.setEnabled(false);
1229         */
1230
1231         // If we do not have a BufferView, then other functions are disabled
1232         else if (!(bv = current_view_->currentBufferView()))
1233                 status.setEnabled(false);
1234
1235         // Does the current BufferView know something?
1236         else if (bv->getStatus(cmd, status)) { }
1237
1238         // Does the current Buffer know something?
1239         else if (bv->buffer().getStatus(cmd, status)) { }
1240
1241         // If we do not have a document BufferView, different from the
1242         // current BufferView, then other functions are disabled
1243         else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1244                 status.setEnabled(false);
1245
1246         // Does the document Buffer know something?
1247         else if (doc_bv->buffer().getStatus(cmd, status)) { }
1248
1249         else {
1250                 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1251                 status.message(from_utf8(N_("Command not handled")));
1252                 status.setEnabled(false);
1253         }
1254
1255         // the default error message if we disable the command
1256         if (!status.enabled() && status.message().empty())
1257                 status.message(from_utf8(N_("Command disabled")));
1258
1259         return status;
1260 }
1261
1262
1263 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1264 {
1265         // I would really like to avoid having this switch and rather try to
1266         // encode this in the function itself.
1267         // -- And I'd rather let an inset decide which LFUNs it is willing
1268         // to handle (Andre')
1269         bool enable = true;
1270         switch (cmd.action()) {
1271
1272         // This could be used for the no-GUI version. The GUI version is handled in
1273         // GuiView::getStatus(). See above.
1274         /*
1275         case LFUN_BUFFER_WRITE:
1276         case LFUN_BUFFER_WRITE_AS:
1277         case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1278                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1279                 enable = b && (b->isUnnamed() || !b->isClean());
1280                 break;
1281         }
1282         */
1283
1284         case LFUN_BOOKMARK_GOTO: {
1285                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1286                 enable = theSession().bookmarks().isValid(num);
1287                 break;
1288         }
1289
1290         case LFUN_BOOKMARK_CLEAR:
1291                 enable = theSession().bookmarks().hasValid();
1292                 break;
1293
1294         // this one is difficult to get right. As a half-baked
1295         // solution, we consider only the first action of the sequence
1296         case LFUN_COMMAND_SEQUENCE: {
1297                 // argument contains ';'-terminated commands
1298                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1299                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1300                 func.setOrigin(cmd.origin());
1301                 flag = getStatus(func);
1302                 break;
1303         }
1304
1305         // we want to check if at least one of these is enabled
1306         case LFUN_COMMAND_ALTERNATIVES: {
1307                 // argument contains ';'-terminated commands
1308                 string arg = to_utf8(cmd.argument());
1309                 while (!arg.empty()) {
1310                         string first;
1311                         arg = split(arg, first, ';');
1312                         FuncRequest func(lyxaction.lookupFunc(first));
1313                         func.setOrigin(cmd.origin());
1314                         flag = getStatus(func);
1315                         // if this one is enabled, the whole thing is
1316                         if (flag.enabled())
1317                                 break;
1318                 }
1319                 break;
1320         }
1321
1322         case LFUN_CALL: {
1323                 FuncRequest func;
1324                 string name = to_utf8(cmd.argument());
1325                 if (theTopLevelCmdDef().lock(name, func)) {
1326                         func.setOrigin(cmd.origin());
1327                         flag = getStatus(func);
1328                         theTopLevelCmdDef().release(name);
1329                 } else {
1330                         // catch recursion or unknown command
1331                         // definition. all operations until the
1332                         // recursion or unknown command definition
1333                         // occurs are performed, so set the state to
1334                         // enabled
1335                         enable = true;
1336                 }
1337                 break;
1338         }
1339
1340         case LFUN_IF_RELATIVES: {
1341                 string const lfun = to_utf8(cmd.argument());
1342                 BufferView const * bv =
1343                         current_view_ ? current_view_->currentBufferView() : nullptr;
1344                 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1345                         enable = false;
1346                         break;
1347                 }
1348                 FuncRequest func(lyxaction.lookupFunc(lfun));
1349                 func.setOrigin(cmd.origin());
1350                 flag = getStatus(func);
1351                 break;
1352         }
1353
1354         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1355         case LFUN_REPEAT:
1356         case LFUN_PREFERENCES_SAVE:
1357         case LFUN_BUFFER_SAVE_AS_DEFAULT:
1358         case LFUN_DEBUG_LEVEL_SET:
1359                 // these are handled in our dispatch()
1360                 break;
1361
1362         case LFUN_WINDOW_CLOSE:
1363                 enable = !d->views_.empty();
1364                 break;
1365
1366         case LFUN_BUFFER_NEW:
1367         case LFUN_BUFFER_NEW_TEMPLATE:
1368         case LFUN_FILE_OPEN:
1369         case LFUN_HELP_OPEN:
1370         case LFUN_SCREEN_FONT_UPDATE:
1371         case LFUN_SET_COLOR:
1372         case LFUN_WINDOW_NEW:
1373         case LFUN_LYX_QUIT:
1374         case LFUN_LYXRC_APPLY:
1375         case LFUN_COMMAND_PREFIX:
1376         case LFUN_CANCEL:
1377         case LFUN_META_PREFIX:
1378         case LFUN_RECONFIGURE:
1379         case LFUN_SERVER_GET_FILENAME:
1380         case LFUN_SERVER_NOTIFY:
1381                 enable = true;
1382                 break;
1383
1384         case LFUN_BUFFER_FORALL: {
1385                 if (theBufferList().empty()) {
1386                         flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1387                         flag.setEnabled(false);
1388                         break;
1389                 }
1390
1391                 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1392                 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1393                         flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1394                         flag.setEnabled(false);
1395                 }
1396                 break;
1397         }
1398
1399         case LFUN_DIALOG_SHOW: {
1400                 string const name = cmd.getArg(0);
1401                 return name == "aboutlyx"
1402                         || name == "lyxfiles"
1403                         || name == "prefs"
1404                         || name == "texinfo"
1405                         || name == "progress"
1406                         || name == "compare";
1407         }
1408
1409         default:
1410                 return false;
1411         }
1412
1413         if (!enable)
1414                 flag.setEnabled(false);
1415         return true;
1416 }
1417
1418 /// make a post-dispatch status message
1419 static docstring makeDispatchMessage(docstring const & msg,
1420                                      FuncRequest const & cmd)
1421 {
1422         const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1423                               || cmd.origin() == FuncRequest::TOOLBAR
1424                               || cmd.origin() == FuncRequest::COMMANDBUFFER);
1425
1426         if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1427                 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1428                 return msg;
1429         }
1430
1431         docstring dispatch_msg = msg;
1432         if (!dispatch_msg.empty())
1433                 dispatch_msg += ' ';
1434
1435         docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1436
1437         bool argsadded = false;
1438
1439         if (!cmd.argument().empty()) {
1440                 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1441                         comname += ' ' + cmd.argument();
1442                         argsadded = true;
1443                 }
1444         }
1445         docstring const shortcuts = theTopLevelKeymap().
1446                 printBindings(cmd, KeySequence::ForGui);
1447
1448         if (!shortcuts.empty())
1449                 comname += ": " + shortcuts;
1450         else if (!argsadded && !cmd.argument().empty())
1451                 comname += ' ' + cmd.argument();
1452
1453         if (!comname.empty()) {
1454                 comname = rtrim(comname);
1455                 dispatch_msg += '(' + rtrim(comname) + ')';
1456         }
1457         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1458         return dispatch_msg;
1459 }
1460
1461
1462 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1463 {
1464         DispatchResult dr;
1465
1466         Buffer * buffer = nullptr;
1467         if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1468                 //setCurrentView(cmd.view_origin); //does not work
1469                 dr.setError(true);
1470                 dr.setMessage(_("Wrong focus!"));
1471                 d->dispatch_result_ = dr;
1472                 return d->dispatch_result_;
1473         }
1474         if (current_view_ && current_view_->currentBufferView()) {
1475                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1476                 buffer = &current_view_->currentBufferView()->buffer();
1477         }
1478
1479         dr.screenUpdate(Update::FitCursor);
1480         {
1481                 // This handles undo groups automagically
1482                 UndoGroupHelper ugh(buffer);
1483                 dispatch(cmd, dr);
1484                 // redraw the screen at the end (first of the two drawing steps).
1485                 // This is done unless explicitly requested otherwise.
1486                 // This code is kept inside the undo group because updateBuffer
1487                 // can create undo actions (see #11292)
1488                 updateCurrentView(cmd, dr);
1489         }
1490
1491         d->dispatch_result_ = dr;
1492         return d->dispatch_result_;
1493 }
1494
1495
1496 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1497 {
1498         if (!current_view_)
1499                 return;
1500
1501         BufferView * bv = current_view_->currentBufferView();
1502         if (bv) {
1503                 if (dr.needBufferUpdate()) {
1504                         bv->cursor().clearBufferUpdate();
1505                         bv->buffer().updateBuffer();
1506                 }
1507                 // BufferView::update() updates the ViewMetricsInfo and
1508                 // also initializes the position cache for all insets in
1509                 // (at least partially) visible top-level paragraphs.
1510                 // We will redraw the screen only if needed.
1511                 bv->processUpdateFlags(dr.screenUpdate());
1512
1513                 // Do we have a selection?
1514                 theSelection().haveSelection(bv->cursor().selection());
1515
1516                 // update gui
1517                 current_view_->restartCaret();
1518         }
1519         if (dr.needMessageUpdate()) {
1520                 // Some messages may already be translated, so we cannot use _()
1521                 current_view_->message(makeDispatchMessage(
1522                                 translateIfPossible(dr.message()), cmd));
1523         }
1524 }
1525
1526
1527 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1528         bool switchToBuffer)
1529 {
1530         if (!theSession().bookmarks().isValid(idx))
1531                 return;
1532         BookmarksSection::Bookmark const & bm =
1533                 theSession().bookmarks().bookmark(idx);
1534         LASSERT(!bm.filename.empty(), return);
1535         string const file = bm.filename.absFileName();
1536         // if the file is not opened, open it.
1537         if (!theBufferList().exists(bm.filename)) {
1538                 if (openFile)
1539                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1540                 else
1541                         return;
1542         }
1543         // open may fail, so we need to test it again
1544         if (!theBufferList().exists(bm.filename))
1545                 return;
1546
1547         // bm can be changed when saving
1548         BookmarksSection::Bookmark tmp = bm;
1549
1550         // Special case idx == 0 used for back-from-back jump navigation
1551         if (idx == 0)
1552                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1553
1554         // if the current buffer is not that one, switch to it.
1555         BufferView * doc_bv = current_view_ ?
1556                 current_view_->documentBufferView() : nullptr;
1557         Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1558         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1559                 if (switchToBuffer) {
1560                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1561                         if (!current_view_)
1562                                 return;
1563                         doc_bv = current_view_->documentBufferView();
1564                 } else
1565                         return;
1566         }
1567
1568         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1569         if (!doc_bv || !doc_bv->moveToPosition(
1570                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1571                 return;
1572
1573         Cursor & cur = doc_bv->cursor();
1574         if (old && cur != *old)
1575                 notifyCursorLeavesOrEnters(*old, cur);
1576
1577         // bm changed
1578         if (idx == 0)
1579                 return;
1580
1581         // Cursor jump succeeded!
1582         pit_type new_pit = cur.pit();
1583         pos_type new_pos = cur.pos();
1584         int new_id = cur.paragraph().id();
1585
1586         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1587         // see http://www.lyx.org/trac/ticket/3092
1588         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1589                 || bm.top_id != new_id) {
1590                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1591                         new_pit, new_pos, new_id);
1592         }
1593 }
1594
1595 // This function runs "configure" and then rereads lyx.defaults to
1596 // reconfigure the automatic settings.
1597 void GuiApplication::reconfigure(string const & option)
1598 {
1599         // emit message signal.
1600         if (current_view_)
1601                 current_view_->message(_("Running configure..."));
1602
1603         // Run configure in user lyx directory
1604         string const lock_file = package().getConfigureLockName();
1605         int fd = fileLock(lock_file.c_str());
1606         int const ret = package().reconfigureUserLyXDir(option);
1607         // emit message signal.
1608         if (current_view_)
1609                 current_view_->message(_("Reloading configuration..."));
1610         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1611         // Re-read packages.lst
1612         LaTeXPackages::getAvailable();
1613         fileUnlock(fd, lock_file.c_str());
1614
1615         if (ret)
1616                 Alert::information(_("System reconfiguration failed"),
1617                            _("The system reconfiguration has failed.\n"
1618                                   "Default textclass is used but LyX may\n"
1619                                   "not be able to work properly.\n"
1620                                   "Please reconfigure again if needed."));
1621         else
1622                 Alert::information(_("System reconfigured"),
1623                            _("The system has been reconfigured.\n"
1624                              "You need to restart LyX to make use of any\n"
1625                              "updated document class specifications."));
1626 }
1627
1628 void GuiApplication::validateCurrentView()
1629 {
1630         if (!d->views_.empty() && !current_view_) {
1631                 // currently at least one view exists but no view has the focus.
1632                 // choose the last view to make it current.
1633                 // a view without any open document is preferred.
1634                 GuiView * candidate = nullptr;
1635                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1636                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1637                 for (; it != end; ++it) {
1638                         candidate = *it;
1639                         if (!candidate->documentBufferView())
1640                                 break;
1641                 }
1642                 setCurrentView(candidate);
1643         }
1644 }
1645
1646 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1647 {
1648         string const argument = to_utf8(cmd.argument());
1649         FuncCode const action = cmd.action();
1650
1651         LYXERR(Debug::ACTION, "cmd: " << cmd);
1652
1653         // we have not done anything wrong yet.
1654         dr.setError(false);
1655
1656         FuncStatus const flag = getStatus(cmd);
1657         if (!flag.enabled()) {
1658                 // We cannot use this function here
1659                 LYXERR(Debug::ACTION, "action "
1660                        << lyxaction.getActionName(action)
1661                        << " [" << action << "] is disabled at this location");
1662                 dr.setMessage(flag.message());
1663                 dr.setError(true);
1664                 dr.dispatched(false);
1665                 dr.screenUpdate(Update::None);
1666                 dr.clearBufferUpdate();
1667                 return;
1668         };
1669
1670         if (cmd.origin() == FuncRequest::LYXSERVER) {
1671                 if (current_view_ && current_view_->currentBufferView())
1672                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1673                 // we will also need to redraw the screen at the end
1674                 dr.screenUpdate(Update::FitCursor);
1675         }
1676
1677         // Assumes that the action will be dispatched.
1678         dr.dispatched(true);
1679
1680         switch (cmd.action()) {
1681
1682         case LFUN_WINDOW_NEW:
1683                 createView(toqstr(cmd.argument()));
1684                 break;
1685
1686         case LFUN_WINDOW_CLOSE:
1687                 // FIXME: this is done also in GuiView::closeBuffer()!
1688                 // update bookmark pit of the current buffer before window close
1689                 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1690                         gotoBookmark(i, false, false);
1691                 // clear the last opened list, because
1692                 // maybe this will end the session
1693                 theSession().lastOpened().clear();
1694                 // check for valid current_view_
1695                 validateCurrentView();
1696                 if (current_view_)
1697                         current_view_->closeScheduled();
1698                 break;
1699
1700         case LFUN_LYX_QUIT:
1701                 // quitting is triggered by the gui code
1702                 // (leaving the event loop).
1703                 if (current_view_)
1704                         current_view_->message(from_utf8(N_("Exiting.")));
1705                 if (closeAllViews())
1706                         quit();
1707                 break;
1708
1709         case LFUN_SCREEN_FONT_UPDATE: {
1710                 // handle the screen font changes.
1711                 /* FIXME: this only updates the current document, whereas all
1712                  * documents should see their metrics updated.
1713                  */
1714                 d->font_loader_.update();
1715                 dr.screenUpdate(Update::Force | Update::FitCursor);
1716                 break;
1717         }
1718
1719         case LFUN_BUFFER_NEW:
1720                 validateCurrentView();
1721                 if (!current_view_
1722                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1723                         createView(QString(), false); // keep hidden
1724                         current_view_->newDocument(to_utf8(cmd.argument()));
1725                         current_view_->show();
1726                         setActiveWindow(current_view_);
1727                 } else {
1728                         current_view_->newDocument(to_utf8(cmd.argument()));
1729                 }
1730                 break;
1731
1732         case LFUN_BUFFER_NEW_TEMPLATE: {
1733                 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1734                 string const temp = cmd.getArg(1);
1735                 validateCurrentView();
1736                 if (!current_view_
1737                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1738                         createView();
1739                         current_view_->newDocument(file, temp, true);
1740                         if (!current_view_->documentBufferView())
1741                                 current_view_->close();
1742                 } else {
1743                         current_view_->newDocument(file, temp, true);
1744                 }
1745                 break;
1746         }
1747
1748         case LFUN_FILE_OPEN: {
1749                 // FIXME: normally the code below is not needed, since getStatus makes sure that
1750                 //   current_view_ is not null.
1751                 validateCurrentView();
1752                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1753                 string const fname = to_utf8(cmd.argument());
1754                 bool const is_open = FileName::isAbsolute(fname)
1755                         && theBufferList().getBuffer(FileName(fname));
1756                 if (!current_view_
1757                     || (!lyxrc.open_buffers_in_tabs
1758                         && current_view_->documentBufferView() != nullptr
1759                         && !is_open)) {
1760                         // We want the ui session to be saved per document and not per
1761                         // window number. The filename crc is a good enough identifier.
1762                         createView(support::checksum(fname));
1763                         current_view_->openDocument(fname);
1764                         if (!current_view_->documentBufferView())
1765                                 current_view_->close();
1766                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1767                                 current_view_->raise();
1768                                 current_view_->activateWindow();
1769                                 current_view_->showNormal();
1770                         }
1771                 } else {
1772                         current_view_->openDocument(fname);
1773                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1774                                 current_view_->raise();
1775                                 current_view_->activateWindow();
1776                                 current_view_->showNormal();
1777                         }
1778                 }
1779                 break;
1780         }
1781
1782         case LFUN_HELP_OPEN: {
1783                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1784                 if (current_view_ == nullptr)
1785                         createView();
1786                 string const arg = to_utf8(cmd.argument());
1787                 if (arg.empty()) {
1788                         current_view_->message(_("Missing argument"));
1789                         break;
1790                 }
1791                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1792                 if (fname.empty())
1793                         fname = i18nLibFileSearch("examples", arg, "lyx");
1794
1795                 if (fname.empty()) {
1796                         lyxerr << "LyX: unable to find documentation file `"
1797                                << arg << "'. Bad installation?" << endl;
1798                         break;
1799                 }
1800                 current_view_->message(bformat(_("Opening help file %1$s..."),
1801                                                makeDisplayPath(fname.absFileName())));
1802                 Buffer * buf = current_view_->loadDocument(fname, false);
1803                 if (buf)
1804                         buf->setReadonly(!current_view_->develMode());
1805                 break;
1806         }
1807
1808         case LFUN_SET_COLOR: {
1809                 string const lyx_name = cmd.getArg(0);
1810                 string x11_name = cmd.getArg(1);
1811                 string x11_darkname = cmd.getArg(2);
1812                 if (lyx_name.empty() || x11_name.empty()) {
1813                         if (current_view_)
1814                                 current_view_->message(
1815                                         _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1816                         break;
1817                 }
1818
1819 #if 0
1820                 // FIXME: The graphics cache no longer has a changeDisplay method.
1821                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1822                 bool const graphicsbg_changed =
1823                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1824                 if (graphicsbg_changed)
1825                         graphics::GCache::get().changeDisplay(true);
1826 #endif
1827
1828                 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1829                         x11_darkname = x11_name;
1830                         x11_name.clear();
1831                 }
1832                 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1833                         if (current_view_)
1834                                 current_view_->message(
1835                                         bformat(_("Set-color \"%1$s\" failed "
1836                                         "- color is undefined or "
1837                                         "may not be redefined"),
1838                                         from_utf8(lyx_name)));
1839                         break;
1840                 }
1841                 // Make sure we don't keep old colors in cache.
1842                 d->color_cache_.clear();
1843                 // Update the current view
1844                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1845                 break;
1846         }
1847
1848         case LFUN_LYXRC_APPLY: {
1849                 // reset active key sequences, since the bindings
1850                 // are updated (bug 6064)
1851                 d->keyseq.reset();
1852                 LyXRC const lyxrc_orig = lyxrc;
1853
1854                 istringstream ss(to_utf8(cmd.argument()));
1855                 bool const success = lyxrc.read(ss);
1856
1857                 if (!success) {
1858                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1859                                         << "Unable to read lyxrc data"
1860                                         << endl;
1861                         break;
1862                 }
1863
1864                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1865
1866                 // If the request comes from the minibuffer, then we can't reset
1867                 // the GUI, since that would destroy the minibuffer itself and
1868                 // cause a crash, since we are currently in one of the methods of
1869                 // GuiCommandBuffer. See bug #8540.
1870                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1871                         resetGui();
1872                 // else
1873                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1874                 //   reset the GUI in this case. If the changes to lyxrc affected the
1875                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1876                 //   it definitely is a bug.
1877
1878                 dr.forceBufferUpdate();
1879                 break;
1880         }
1881
1882         case LFUN_COMMAND_PREFIX:
1883                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1884                 break;
1885
1886         case LFUN_CANCEL: {
1887                 d->keyseq.reset();
1888                 d->meta_fake_bit = NoModifier;
1889                 GuiView * gv = currentView();
1890                 if (gv && gv->currentBufferView())
1891                         // cancel any selection
1892                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1893                 dr.setMessage(from_ascii(N_("Cancel")));
1894                 break;
1895         }
1896         case LFUN_META_PREFIX:
1897                 d->meta_fake_bit = AltModifier;
1898                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1899                 break;
1900
1901         // --- Menus -----------------------------------------------
1902         case LFUN_RECONFIGURE:
1903                 // argument is any additional parameter to the configure.py command
1904                 reconfigure(to_utf8(cmd.argument()));
1905                 break;
1906
1907         // --- lyxserver commands ----------------------------
1908         case LFUN_SERVER_GET_FILENAME: {
1909                 if (current_view_ && current_view_->documentBufferView()) {
1910                         docstring const fname = from_utf8(
1911                                 current_view_->documentBufferView()->buffer().absFileName());
1912                         dr.setMessage(fname);
1913                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1914                 } else {
1915                         dr.setMessage(docstring());
1916                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1917                 }
1918                 break;
1919         }
1920
1921         case LFUN_SERVER_NOTIFY: {
1922                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1923                 dr.setMessage(dispatch_buffer);
1924                 theServer().notifyClient(to_utf8(dispatch_buffer));
1925                 break;
1926         }
1927
1928         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1929                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1930                 break;
1931
1932         case LFUN_REPEAT: {
1933                 // repeat command
1934                 string countstr;
1935                 string rest = split(argument, countstr, ' ');
1936                 int const count = convert<int>(countstr);
1937                 // an arbitrary number to limit number of iterations
1938                 int const max_iter = 10000;
1939                 if (count > max_iter) {
1940                         dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1941                         dr.setError(true);
1942                 } else {
1943                         for (int i = 0; i < count; ++i) {
1944                                 FuncRequest lfun = lyxaction.lookupFunc(rest);
1945                                 lfun.allowAsync(false);
1946                                 dispatch(lfun);
1947                         }
1948                 }
1949                 break;
1950         }
1951
1952         case LFUN_COMMAND_SEQUENCE: {
1953                 // argument contains ';'-terminated commands
1954                 string arg = argument;
1955                 // FIXME: this LFUN should also work without any view.
1956                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1957                                   ? &(current_view_->documentBufferView()->buffer()) : nullptr;
1958                 // This handles undo groups automagically
1959                 UndoGroupHelper ugh(buffer);
1960                 while (!arg.empty()) {
1961                         string first;
1962                         arg = split(arg, first, ';');
1963                         FuncRequest func(lyxaction.lookupFunc(first));
1964                         func.allowAsync(false);
1965                         func.setOrigin(cmd.origin());
1966                         dispatch(func);
1967                 }
1968                 break;
1969         }
1970
1971         case LFUN_BUFFER_FORALL: {
1972                 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1973                 funcToRun.allowAsync(false);
1974
1975                 map<Buffer *, GuiView *> views_lVisible;
1976                 map<GuiView *, Buffer *> activeBuffers;
1977
1978                 QList<GuiView *> allViews = d->views_.values();
1979
1980                 // this for does not modify any buffer. It just collects info on local
1981                 // visibility of buffers and on which buffer is active in each view.
1982                 Buffer * const last = theBufferList().last();
1983                 for(GuiView * view : allViews) {
1984                         // all of the buffers might be locally hidden. That is, there is no
1985                         // active buffer.
1986                         if (!view || !view->currentBufferView())
1987                                 activeBuffers[view] = nullptr;
1988                         else
1989                                 activeBuffers[view] = &view->currentBufferView()->buffer();
1990
1991                         // find out if each is locally visible or locally hidden.
1992                         // we don't use a for loop as the buffer list cycles.
1993                         Buffer * b = theBufferList().first();
1994                         while (true) {
1995                                 bool const locallyVisible = view && view->workArea(*b);
1996                                 if (locallyVisible) {
1997                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1998                                         // only need to overwrite/add if we don't already know a buffer is globally
1999                                         // visible or we do know but we would prefer to dispatch LFUN from the
2000                                         // current view because of cursor position issues.
2001                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2002                                                 views_lVisible[b] = view;
2003                                 }
2004                                 if (b == last)
2005                                         break;
2006                                 b = theBufferList().next(b);
2007                         }
2008                 }
2009
2010                 GuiView * const homeView = currentView();
2011                 Buffer * b = theBufferList().first();
2012                 Buffer * nextBuf = nullptr;
2013                 int numProcessed = 0;
2014                 while (true) {
2015                         if (b != last)
2016                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2017
2018                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2019                         if (visible) {
2020                                 // first change to a view where b is locally visible, preferably current_view_.
2021                                 GuiView * const vLv = views_lVisible[b];
2022                                 vLv->setBuffer(b);
2023                                 lyx::dispatch(funcToRun);
2024                                 numProcessed++;
2025                         }
2026                         if (b == last)
2027                                 break;
2028                         b = nextBuf;
2029                 }
2030
2031                 // put things back to how they were (if possible).
2032                 for (GuiView * view : allViews) {
2033                         Buffer * originalBuf = activeBuffers[view];
2034                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2035                         if (theBufferList().isLoaded(originalBuf))
2036                                 view->setBuffer(originalBuf);
2037                 }
2038                 homeView->setFocus();
2039
2040                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2041                 break;
2042         }
2043
2044         case LFUN_COMMAND_ALTERNATIVES: {
2045                 // argument contains ';'-terminated commands
2046                 string arg = argument;
2047                 while (!arg.empty()) {
2048                         string first;
2049                         arg = split(arg, first, ';');
2050                         FuncRequest func(lyxaction.lookupFunc(first));
2051                         func.setOrigin(cmd.origin());
2052                         FuncStatus const stat = getStatus(func);
2053                         if (stat.enabled()) {
2054                                 dispatch(func);
2055                                 break;
2056                         }
2057                 }
2058                 break;
2059         }
2060
2061         case LFUN_CALL: {
2062                 FuncRequest func;
2063                 if (theTopLevelCmdDef().lock(argument, func)) {
2064                         func.setOrigin(cmd.origin());
2065                         dispatch(func);
2066                         theTopLevelCmdDef().release(argument);
2067                 } else {
2068                         if (func.action() == LFUN_UNKNOWN_ACTION) {
2069                                 // unknown command definition
2070                                 lyxerr << "Warning: unknown command definition `"
2071                                                 << argument << "'"
2072                                                 << endl;
2073                         } else {
2074                                 // recursion detected
2075                                 lyxerr << "Warning: Recursion in the command definition `"
2076                                                 << argument << "' detected"
2077                                                 << endl;
2078                         }
2079                 }
2080                 break;
2081         }
2082
2083         case LFUN_IF_RELATIVES: {
2084                 string const lfun = to_utf8(cmd.argument());
2085                 FuncRequest func(lyxaction.lookupFunc(lfun));
2086                 func.setOrigin(cmd.origin());
2087                 FuncStatus const stat = getStatus(func);
2088                 if (stat.enabled()) {
2089                         dispatch(func);
2090                         break;
2091                 }
2092                 break;
2093         }
2094
2095         case LFUN_PREFERENCES_SAVE:
2096                 lyxrc.write(support::makeAbsPath("preferences",
2097                         package().user_support().absFileName()), false);
2098                 break;
2099
2100         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2101                 string const fname = addName(addPath(package().user_support().absFileName(),
2102                         "templates/"), "defaults.lyx");
2103                 Buffer defaults(fname);
2104
2105                 istringstream ss(argument);
2106                 Lexer lex;
2107                 lex.setStream(ss);
2108
2109                 // See #9236
2110                 // We need to make sure that, after we recreat the DocumentClass,
2111                 // which we do in readHeader, we apply it to the document itself.
2112                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2113                 int const unknown_tokens = defaults.readHeader(lex);
2114                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2115                 ErrorList el;
2116                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2117                 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2118
2119                 if (unknown_tokens != 0) {
2120                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2121                                << unknown_tokens << " unknown token"
2122                                << (unknown_tokens == 1 ? "" : "s")
2123                                << endl;
2124                 }
2125
2126                 if (defaults.writeFile(FileName(defaults.absFileName())))
2127                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2128                                               makeDisplayPath(fname)));
2129                 else {
2130                         dr.setError(true);
2131                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2132                 }
2133                 break;
2134         }
2135
2136         case LFUN_BOOKMARK_GOTO:
2137                 // go to bookmark, open unopened file and switch to buffer if necessary
2138                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2139                 dr.screenUpdate(Update::Force | Update::FitCursor);
2140                 break;
2141
2142         case LFUN_BOOKMARK_CLEAR:
2143                 theSession().bookmarks().clear();
2144                 dr.screenUpdate(Update::Force);
2145                 break;
2146
2147         case LFUN_DEBUG_LEVEL_SET:
2148                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2149                 break;
2150
2151         case LFUN_DIALOG_SHOW: {
2152                 string const name = cmd.getArg(0);
2153
2154                 if ( name == "aboutlyx"
2155                         || name == "prefs"
2156                         || name == "texinfo"
2157                         || name == "progress"
2158                         || name == "compare")
2159                 {
2160                         // work around: on Mac OS the application
2161                         // is not terminated when closing the last view.
2162                         // Create a new one to be able to dispatch the
2163                         // LFUN_DIALOG_SHOW to this view.
2164                         if (current_view_ == nullptr)
2165                                 createView();
2166                 }
2167         }
2168         // fall through
2169         default:
2170                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2171                 // let's try that:
2172                 if (current_view_)
2173                         current_view_->dispatch(cmd, dr);
2174                 break;
2175         }
2176
2177         if (cmd.origin() == FuncRequest::LYXSERVER)
2178                 updateCurrentView(cmd, dr);
2179 }
2180
2181
2182 docstring GuiApplication::viewStatusMessage()
2183 {
2184         // When meta-fake key is pressed, show the key sequence so far + "M-".
2185         if (d->meta_fake_bit != NoModifier)
2186                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2187
2188         // Else, when a non-complete key sequence is pressed,
2189         // show the available options.
2190         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2191                 return d->keyseq.printOptions(true);
2192
2193         return docstring();
2194 }
2195
2196
2197 string GuiApplication::inputLanguageCode() const
2198 {
2199 #if (QT_VERSION < 0x050000)
2200         QLocale loc = keyboardInputLocale();
2201 #else
2202         QLocale loc = inputMethod()->locale();
2203 #endif
2204         //LYXERR0("input lang = " << fromqstr(loc.name()));
2205         return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2206 }
2207
2208
2209 void GuiApplication::onLocaleChanged()
2210 {
2211         //LYXERR0("Change language to " << inputLanguage()->lang());
2212         if (currentView() && currentView()->currentBufferView())
2213                 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2214 }
2215
2216
2217 void GuiApplication::handleKeyFunc(FuncCode action)
2218 {
2219         char_type c = 0;
2220
2221         if (d->keyseq.length())
2222                 c = 0;
2223         GuiView * gv = currentView();
2224         LASSERT(gv && gv->currentBufferView(), return);
2225         BufferView * bv = gv->currentBufferView();
2226         bv->getIntl().getTransManager().deadkey(
2227                 c, get_accent(action).accent, bv->cursor().innerText(),
2228                 bv->cursor());
2229         // Need to clear, in case the minibuffer calls these
2230         // actions
2231         d->keyseq.clear();
2232         // copied verbatim from do_accent_char
2233         bv->cursor().resetAnchor();
2234 }
2235
2236
2237 //Keep this in sync with GuiApplication::processKeySym below
2238 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2239                                  KeyModifier state) const
2240 {
2241         // Do nothing if we have nothing
2242         if (!keysym.isOK() || keysym.isModifier())
2243                 return false;
2244         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2245         KeySequence seq;
2246         FuncRequest func = seq.addkey(keysym, state);
2247         // When not cancel or meta-fake, do the normal lookup.
2248         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2249                 seq = d->keyseq;
2250                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2251         }
2252         // Maybe user can only reach the key via holding down shift.
2253         // Let's see. But only if shift is the only modifier
2254         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2255                 // If addkey looked up a command and did not find further commands then
2256                 // seq has been reset at this point
2257                 func = seq.addkey(keysym, NoModifier);
2258
2259         LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2260                << seq.print(KeySequence::Portable) << ']');
2261         return func.action() != LFUN_UNKNOWN_ACTION;
2262 }
2263
2264
2265 //Keep this in sync with GuiApplication::queryKeySym above
2266 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2267 {
2268         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2269
2270         // Do nothing if we have nothing (JMarc)
2271         if (!keysym.isOK() || keysym.isModifier()) {
2272                 if (!keysym.isOK())
2273                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2274                 if (current_view_)
2275                         current_view_->restartCaret();
2276                 return;
2277         }
2278
2279         char_type encoded_last_key = keysym.getUCSEncoded();
2280
2281         // Do a one-deep top-level lookup for
2282         // cancel and meta-fake keys. RVDK_PATCH_5
2283         d->cancel_meta_seq.reset();
2284
2285         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2286         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2287
2288         // When not cancel or meta-fake, do the normal lookup.
2289         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2290         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2291         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2292                 // remove Caps Lock and Mod2 as a modifiers
2293                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2294                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2295         }
2296
2297         // Don't remove this unless you know what you are doing.
2298         d->meta_fake_bit = NoModifier;
2299
2300         // Can this happen now ?
2301         if (func.action() == LFUN_NOACTION)
2302                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2303
2304         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2305                 << d->keyseq.print(KeySequence::Portable) << ']');
2306
2307         // already here we know if it any point in going further
2308         // why not return already here if action == -1 and
2309         // num_bytes == 0? (Lgb)
2310
2311         if (d->keyseq.length() > 1 && current_view_)
2312                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2313
2314
2315         // Maybe user can only reach the key via holding down shift.
2316         // Let's see. But only if shift is the only modifier
2317         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2318                 LYXERR(Debug::KEY, "Trying without shift");
2319                 // If addkey looked up a command and did not find further commands then
2320                 // seq has been reset at this point
2321                 func = d->keyseq.addkey(keysym, NoModifier);
2322                 LYXERR(Debug::KEY, "Action now " << func.action());
2323         }
2324
2325         if (func.action() == LFUN_UNKNOWN_ACTION) {
2326                 // We didn't match any of the key sequences.
2327                 // See if it's normal insertable text not already
2328                 // covered by a binding
2329                 if (keysym.isText() && d->keyseq.length() == 1) {
2330                         // Non-printable characters (such as ASCII control characters)
2331                         // must not be inserted (#5704)
2332                         if (!isPrintable(encoded_last_key)) {
2333                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2334                                 if (current_view_)
2335                                         current_view_->restartCaret();
2336                                 return;
2337                         }
2338                         // The following modifier check is not needed on Mac.
2339                         // The keysym is either not text or it is different
2340                         // from the non-modifier keysym. See #9875 for the
2341                         // broken alt-modifier effect of having this code active.
2342 #if !defined(Q_OS_MAC)
2343                         // If a non-Shift Modifier is used we have a non-bound key sequence
2344                         // (such as Alt+j = j). This should be omitted (#5575).
2345                         // On Windows, AltModifier and ControlModifier are both
2346                         // set when AltGr is pressed. Therefore, in order to not
2347                         // break AltGr-bound symbols (see #5575 for details),
2348                         // unbound Ctrl+Alt key sequences are allowed.
2349                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2350 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2351                             && !(state & AltModifier && state & ControlModifier)
2352 #endif
2353                             )
2354                         {
2355                                 if (current_view_) {
2356                                         current_view_->message(_("Unknown function."));
2357                                         current_view_->restartCaret();
2358                                 }
2359                                 return;
2360                         }
2361 #endif
2362                         // Since all checks above were passed, we now really have text that
2363                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2364                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2365                         // below.
2366                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2367                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2368                 } else {
2369                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2370                         if (current_view_) {
2371                                 current_view_->message(_("Unknown function."));
2372                                 current_view_->restartCaret();
2373                         }
2374                         return;
2375                 }
2376         }
2377
2378         if (func.action() == LFUN_SELF_INSERT) {
2379                 if (encoded_last_key != 0) {
2380                         docstring const arg(1, encoded_last_key);
2381                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2382                                              FuncRequest::KEYBOARD));
2383                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2384                 }
2385         } else
2386                 processFuncRequest(func);
2387 }
2388
2389
2390 void GuiApplication::processFuncRequest(FuncRequest const & func)
2391 {
2392         lyx::dispatch(func);
2393 }
2394
2395
2396 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2397 {
2398         addToFuncRequestQueue(func);
2399         processFuncRequestQueueAsync();
2400 }
2401
2402
2403 void GuiApplication::processFuncRequestQueue()
2404 {
2405         while (!d->func_request_queue_.empty()) {
2406                 // take the item from the stack _before_ processing the
2407                 // request in order to avoid race conditions from nested
2408                 // or parallel requests (see #10406)
2409                 FuncRequest const fr(d->func_request_queue_.front());
2410                 d->func_request_queue_.pop();
2411                 processFuncRequest(fr);
2412         }
2413 }
2414
2415
2416 void GuiApplication::processFuncRequestQueueAsync()
2417 {
2418         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2419 }
2420
2421
2422 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2423 {
2424         d->func_request_queue_.push(func);
2425 }
2426
2427
2428 void GuiApplication::resetGui()
2429 {
2430         // Set the language defined by the user.
2431         setGuiLanguage();
2432
2433         // Read menus
2434         if (!readUIFile(toqstr(lyxrc.ui_file)))
2435                 // Gives some error box here.
2436                 return;
2437
2438         if (d->global_menubar_)
2439                 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2440
2441         QHash<int, GuiView *>::iterator it;
2442         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2443                 GuiView * gv = *it;
2444                 setCurrentView(gv);
2445                 gv->setLayoutDirection(layoutDirection());
2446                 gv->resetDialogs();
2447         }
2448
2449         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2450 }
2451
2452
2453 bool GuiApplication::rtlContext() const
2454 {
2455         if (current_view_ && current_view_->currentBufferView()) {
2456                 BufferView const * bv = current_view_->currentBufferView();
2457                 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2458         } else
2459                 return layoutDirection() == Qt::RightToLeft;
2460 }
2461
2462
2463 void GuiApplication::createView(int view_id)
2464 {
2465         createView(QString(), true, view_id);
2466 }
2467
2468
2469 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2470         int view_id)
2471 {
2472         // release the keyboard which might have been grabbed by the global
2473         // menubar on Mac to catch shortcuts even without any GuiView.
2474         if (d->global_menubar_)
2475                 d->global_menubar_->releaseKeyboard();
2476
2477         // create new view
2478         int id = view_id;
2479         while (d->views_.find(id) != d->views_.end())
2480                 id++;
2481
2482         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2483         GuiView * view = new GuiView(id);
2484         // `view' is the new current_view_. Tell coverity that is is not 0.
2485         LATTEST(current_view_);
2486         // register view
2487         d->views_[id] = view;
2488
2489         if (autoShow) {
2490                 view->show();
2491                 setActiveWindow(view);
2492         }
2493
2494         if (!geometry_arg.isEmpty()) {
2495 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2496                 int x, y;
2497                 int w, h;
2498                 QChar sx, sy;
2499                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2500                 re.indexIn(geometry_arg);
2501                 w = re.cap(1).toInt();
2502                 h = re.cap(2).toInt();
2503                 x = re.cap(3).toInt();
2504                 y = re.cap(4).toInt();
2505                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2506                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2507                 // Set initial geometry such that we can get the frame size.
2508                 view->setGeometry(x, y, w, h);
2509                 int framewidth = view->geometry().x() - view->x();
2510                 int titleheight = view->geometry().y() - view->y();
2511                 // Negative displacements must be interpreted as distances
2512                 // from the right or bottom screen borders.
2513                 if (sx == '-' || sy == '-') {
2514                         QRect rec = QApplication::desktop()->screenGeometry();
2515                         if (sx == '-')
2516                                 x += rec.width() - w - framewidth;
2517                         if (sy == '-')
2518                                 y += rec.height() - h - titleheight;
2519                         view->setGeometry(x, y, w, h);
2520                 }
2521                 // Make sure that the left and top frame borders are visible.
2522                 if (view->x() < 0 || view->y() < 0) {
2523                         if (view->x() < 0)
2524                                 x = framewidth;
2525                         if (view->y() < 0)
2526                                 y = titleheight;
2527                         view->setGeometry(x, y, w, h);
2528                 }
2529 #endif
2530         }
2531         view->setFocus();
2532 }
2533
2534
2535 bool GuiApplication::unhide(Buffer * buf)
2536 {
2537         if (!currentView())
2538                 return false;
2539         currentView()->setBuffer(buf, false);
2540         return true;
2541 }
2542
2543
2544 Clipboard & GuiApplication::clipboard()
2545 {
2546         return d->clipboard_;
2547 }
2548
2549
2550 Selection & GuiApplication::selection()
2551 {
2552         return d->selection_;
2553 }
2554
2555
2556 FontLoader & GuiApplication::fontLoader()
2557 {
2558         return d->font_loader_;
2559 }
2560
2561
2562 Toolbars const & GuiApplication::toolbars() const
2563 {
2564         return d->toolbars_;
2565 }
2566
2567
2568 Toolbars & GuiApplication::toolbars()
2569 {
2570         return d->toolbars_;
2571 }
2572
2573
2574 Menus const & GuiApplication::menus() const
2575 {
2576         return d->menus_;
2577 }
2578
2579
2580 Menus & GuiApplication::menus()
2581 {
2582         return d->menus_;
2583 }
2584
2585
2586 QList<int> GuiApplication::viewIds() const
2587 {
2588         return d->views_.keys();
2589 }
2590
2591
2592 ColorCache & GuiApplication::colorCache()
2593 {
2594         return d->color_cache_;
2595 }
2596
2597
2598 int GuiApplication::exec()
2599 {
2600         // asynchronously handle batch commands. This event will be in
2601         // the event queue in front of other asynchronous events. Hence,
2602         // we can assume in the latter that the gui is setup already.
2603         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2604
2605         return QApplication::exec();
2606 }
2607
2608
2609 void GuiApplication::exit(int status)
2610 {
2611         QApplication::exit(status);
2612 }
2613
2614
2615 void GuiApplication::setGuiLanguage()
2616 {
2617         setLocale();
2618         QLocale theLocale;
2619         // install translation file for Qt built-in dialogs
2620         QString const language_name = QString("qt_") + theLocale.name();
2621         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2622         // Short-named translator can be loaded from a long name, but not the
2623         // opposite. Therefore, long name should be used without truncation.
2624         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2625         if (!d->qt_trans_.load(language_name,
2626                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2627                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2628                         << language_name);
2629         } else {
2630                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2631                         << language_name);
2632         }
2633
2634         switch (theLocale.language()) {
2635         case QLocale::Arabic :
2636         case QLocale::Hebrew :
2637         case QLocale::Persian :
2638         case QLocale::Urdu :
2639                 setLayoutDirection(Qt::RightToLeft);
2640                 break;
2641         default:
2642                 setLayoutDirection(Qt::LeftToRight);
2643         }
2644 }
2645
2646
2647 void GuiApplication::execBatchCommands()
2648 {
2649         setGuiLanguage();
2650
2651         // Read menus
2652         if (!readUIFile(toqstr(lyxrc.ui_file)))
2653                 // Gives some error box here.
2654                 return;
2655
2656 #ifdef Q_OS_MAC
2657 #if QT_VERSION > 0x040600
2658         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2659 #endif
2660 #if QT_VERSION > 0x050100
2661         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2662 #endif
2663         // Create the global default menubar which is shown for the dialogs
2664         // and if no GuiView is visible.
2665         // This must be done after the session was recovered to know the "last files".
2666         d->global_menubar_ = new QMenuBar(0);
2667         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2668 #endif
2669
2670         lyx::execBatchCommands();
2671 }
2672
2673
2674 QAbstractItemModel * GuiApplication::languageModel()
2675 {
2676         if (d->language_model_)
2677                 return d->language_model_;
2678
2679         QStandardItemModel * lang_model = new QStandardItemModel(this);
2680         lang_model->insertColumns(0, 3);
2681         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2682         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2683         Languages::const_iterator it = lyx::languages.begin();
2684         Languages::const_iterator end = lyx::languages.end();
2685         for (; it != end; ++it) {
2686                 int current_row = lang_model->rowCount();
2687                 lang_model->insertRows(current_row, 1);
2688                 QModelIndex pl_item = lang_model->index(current_row, 0);
2689                 QModelIndex sp_item = lang_model->index(current_row, 1);
2690                 QModelIndex th_item = lang_model->index(current_row, 2);
2691                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2692                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2693                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2694                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2695                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2696                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2697                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2698                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2699                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2700                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2701         }
2702         d->language_model_ = new QSortFilterProxyModel(this);
2703         d->language_model_->setSourceModel(lang_model);
2704         d->language_model_->setSortLocaleAware(true);
2705         return d->language_model_;
2706 }
2707
2708
2709 void GuiApplication::restoreGuiSession()
2710 {
2711         if (!lyxrc.load_session)
2712                 return;
2713
2714         Session & session = theSession();
2715         LastOpenedSection::LastOpened const & lastopened =
2716                 session.lastOpened().getfiles();
2717
2718         validateCurrentView();
2719
2720         FileName active_file;
2721         // do not add to the lastfile list since these files are restored from
2722         // last session, and should be already there (regular files), or should
2723         // not be added at all (help files).
2724         for (auto const & last : lastopened) {
2725                 FileName const & file_name = last.file_name;
2726                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2727                           && current_view_->documentBufferView() != nullptr)) {
2728                         string const & fname = file_name.absFileName();
2729                         createView(support::checksum(fname));
2730                 }
2731                 current_view_->loadDocument(file_name, false);
2732
2733                 if (last.active)
2734                         active_file = file_name;
2735         }
2736
2737         // Restore last active buffer
2738         Buffer * buffer = theBufferList().getBuffer(active_file);
2739         if (buffer && current_view_)
2740                 current_view_->setBuffer(buffer);
2741
2742         // clear this list to save a few bytes of RAM
2743         session.lastOpened().clear();
2744 }
2745
2746
2747 QString const GuiApplication::romanFontName()
2748 {
2749         QFont font;
2750         font.setStyleHint(QFont::Serif);
2751         font.setFamily("serif");
2752
2753         return QFontInfo(font).family();
2754 }
2755
2756
2757 QString const GuiApplication::sansFontName()
2758 {
2759         QFont font;
2760         font.setStyleHint(QFont::SansSerif);
2761         font.setFamily("sans");
2762
2763         return QFontInfo(font).family();
2764 }
2765
2766
2767 QString const GuiApplication::typewriterFontName()
2768 {
2769         return QFontInfo(typewriterSystemFont()).family();
2770 }
2771
2772
2773 namespace {
2774         // We cannot use QFont::fixedPitch() because it doesn't
2775         // return the fact but only if it is requested.
2776         static bool isFixedPitch(const QFont & font) {
2777                 const QFontInfo fi(font);
2778                 return fi.fixedPitch();
2779         }
2780 } // namespace
2781
2782
2783 QFont const GuiApplication::typewriterSystemFont()
2784 {
2785 #if QT_VERSION >= 0x050200
2786         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2787 #else
2788         QFont font("monospace");
2789 #endif
2790         if (!isFixedPitch(font)) {
2791                 // try to enforce a real monospaced font
2792                 font.setStyleHint(QFont::Monospace);
2793                 if (!isFixedPitch(font)) {
2794                         font.setStyleHint(QFont::TypeWriter);
2795                         if (!isFixedPitch(font)) font.setFamily("courier");
2796                 }
2797         }
2798 #ifdef Q_OS_MAC
2799         // On a Mac the result is too small and it's not practical to
2800         // rely on Qtconfig utility to change the system settings of Qt.
2801         font.setPointSize(12);
2802 #endif
2803         return font;
2804 }
2805
2806
2807 void GuiApplication::handleRegularEvents()
2808 {
2809         ForkedCallsController::handleCompletedProcesses();
2810 }
2811
2812
2813 bool GuiApplication::event(QEvent * e)
2814 {
2815         switch(e->type()) {
2816         case QEvent::FileOpen: {
2817                 // Open a file; this happens only on Mac OS X for now.
2818                 //
2819                 // We do this asynchronously because on startup the batch
2820                 // commands are not executed here yet and the gui is not ready
2821                 // therefore.
2822                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2823                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2824                 processFuncRequestAsync(fr);
2825                 e->accept();
2826                 return true;
2827         }
2828 #if (QT_VERSION < 0x050000)
2829         // Qt5 uses a signal for that, see above.
2830         case QEvent::KeyboardLayoutChange:
2831                 //LYXERR0("keyboard change");
2832                 if (currentView() && currentView()->currentBufferView())
2833                         currentView()->currentBufferView()->cursor().setLanguageFromInput();
2834                 e->accept();
2835                 return true;
2836 #endif
2837         default:
2838                 return QApplication::event(e);
2839         }
2840 }
2841
2842
2843 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2844 {
2845         try {
2846                 return QApplication::notify(receiver, event);
2847         }
2848         catch (ExceptionMessage const & e) {
2849                 switch(e.type_) {
2850                 case ErrorException:
2851                         emergencyCleanup();
2852                         setQuitOnLastWindowClosed(false);
2853                         closeAllViews();
2854                         Alert::error(e.title_, e.details_);
2855 #ifndef NDEBUG
2856                         // Properly crash in debug mode in order to get a useful backtrace.
2857                         abort();
2858 #endif
2859                         // In release mode, try to exit gracefully.
2860                         this->exit(1);
2861                         // FIXME: GCC 7 thinks we can fall through here. Can we?
2862                         // fall through
2863                 case BufferException: {
2864                         if (!current_view_ || !current_view_->documentBufferView())
2865                                 return false;
2866                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2867                         docstring details = e.details_ + '\n';
2868                         details += buf->emergencyWrite();
2869                         theBufferList().release(buf);
2870                         details += "\n" + _("The current document was closed.");
2871                         Alert::error(e.title_, details);
2872                         return false;
2873                 }
2874                 case WarningException:
2875                         Alert::warning(e.title_, e.details_);
2876                         return false;
2877                 }
2878         }
2879         catch (exception const & e) {
2880                 docstring s = _("LyX has caught an exception, it will now "
2881                         "attempt to save all unsaved documents and exit."
2882                         "\n\nException: ");
2883                 s += from_ascii(e.what());
2884                 Alert::error(_("Software exception Detected"), s);
2885                 lyx_exit(1);
2886         }
2887         catch (...) {
2888                 docstring s = _("LyX has caught some really weird exception, it will "
2889                         "now attempt to save all unsaved documents and exit.");
2890                 Alert::error(_("Software exception Detected"), s);
2891                 lyx_exit(1);
2892         }
2893
2894         return false;
2895 }
2896
2897
2898 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2899 {
2900         QColor const & qcol = d->color_cache_.get(col);
2901         if (!qcol.isValid()) {
2902                 rgbcol.r = 0;
2903                 rgbcol.g = 0;
2904                 rgbcol.b = 0;
2905                 return false;
2906         }
2907         rgbcol.r = qcol.red();
2908         rgbcol.g = qcol.green();
2909         rgbcol.b = qcol.blue();
2910         return true;
2911 }
2912
2913
2914 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2915 {
2916         QColor const qcol(lcolor.getX11HexName(col).c_str());
2917         if (!qcol.isValid()) {
2918                 rgbcol.r = 0;
2919                 rgbcol.g = 0;
2920                 rgbcol.b = 0;
2921                 return false;
2922         }
2923         rgbcol.r = qcol.red();
2924         rgbcol.g = qcol.green();
2925         rgbcol.b = qcol.blue();
2926         return true;
2927 }
2928
2929
2930 string const GuiApplication::hexName(ColorCode col)
2931 {
2932         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2933 }
2934
2935
2936 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2937 {
2938         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2939         d->socket_notifiers_[fd] = sn;
2940         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2941 }
2942
2943
2944 void GuiApplication::socketDataReceived(int fd)
2945 {
2946         d->socket_notifiers_[fd]->func_();
2947 }
2948
2949
2950 void GuiApplication::unregisterSocketCallback(int fd)
2951 {
2952         d->socket_notifiers_.take(fd)->setEnabled(false);
2953 }
2954
2955
2956 void GuiApplication::commitData(QSessionManager & sm)
2957 {
2958         /** The implementation is required to avoid an application exit
2959          ** when session state save is triggered by session manager.
2960          ** The default implementation sends a close event to all
2961          ** visible top level widgets when session management allows
2962          ** interaction.
2963          ** We are changing that to check the state of each buffer in all
2964          ** views and ask the users what to do if buffers are dirty.
2965          ** Furthermore, we save the session state.
2966          ** We do NOT close the views here since the user still can cancel
2967          ** the logout process (see #9277); also, this would hide LyX from
2968          ** an OSes own session handling (application restoration).
2969          **/
2970         #ifdef QT_NO_SESSIONMANAGER
2971                 #ifndef _MSC_VER
2972                         #warning Qt is compiled without session manager
2973                 #else
2974                         #pragma message("warning: Qt is compiled without session manager")
2975                 #endif
2976                 (void) sm;
2977         #else
2978                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2979                         sm.cancel();
2980                 else
2981                         sm.release();
2982         #endif
2983 }
2984
2985
2986 void GuiApplication::unregisterView(GuiView * gv)
2987 {
2988         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2989                 d->views_.remove(gv->id());
2990                 if (current_view_ == gv)
2991                         current_view_ = nullptr;
2992         }
2993 }
2994
2995
2996 bool GuiApplication::closeAllViews()
2997 {
2998         if (d->views_.empty())
2999                 return true;
3000
3001         // When a view/window was closed before without quitting LyX, there
3002         // are already entries in the lastOpened list.
3003         theSession().lastOpened().clear();
3004
3005         QList<GuiView *> const views = d->views_.values();
3006         for (GuiView * view : views) {
3007                 if (!view->closeScheduled())
3008                         return false;
3009         }
3010
3011         d->views_.clear();
3012         return true;
3013 }
3014
3015
3016 bool GuiApplication::prepareAllViewsForLogout()
3017 {
3018         if (d->views_.empty())
3019                 return true;
3020
3021         QList<GuiView *> const views = d->views_.values();
3022         for (GuiView * view : views) {
3023                 if (!view->prepareAllBuffersForLogout())
3024                         return false;
3025         }
3026
3027         return true;
3028 }
3029
3030
3031 GuiView & GuiApplication::view(int id) const
3032 {
3033         LAPPERR(d->views_.contains(id));
3034         return *d->views_.value(id);
3035 }
3036
3037
3038 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3039 {
3040         QList<GuiView *> const views = d->views_.values();
3041         for (GuiView * view : views)
3042                 view->hideDialog(name, inset);
3043 }
3044
3045
3046 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3047 {
3048         Buffer const * buf = nullptr;
3049         QHash<int, GuiView *>::const_iterator end = d->views_.end();
3050         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3051                 if (Buffer const * ptr = (*it)->updateInset(inset))
3052                         buf = ptr;
3053         }
3054         return buf;
3055 }
3056
3057
3058 bool GuiApplication::searchMenu(FuncRequest const & func,
3059         docstring_list & names) const
3060 {
3061         BufferView * bv = nullptr;
3062         if (current_view_)
3063                 bv = current_view_->currentBufferView();
3064         return d->menus_.searchMenu(func, names, bv);
3065 }
3066
3067
3068 bool GuiApplication::hasBufferView() const
3069 {
3070         return (current_view_ && current_view_->currentBufferView());
3071 }
3072
3073
3074 // Ensure that a file is read only once (prevents include loops)
3075 static QStringList uifiles;
3076 // store which ui files define Toolbars
3077 static QStringList toolbar_uifiles;
3078
3079
3080 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3081 {
3082         enum {
3083                 ui_menuset = 1,
3084                 ui_toolbars,
3085                 ui_toolbarset,
3086                 ui_include,
3087                 ui_format,
3088                 ui_last
3089         };
3090
3091         LexerKeyword uitags[] = {
3092                 { "format", ui_format },
3093                 { "include", ui_include },
3094                 { "menuset", ui_menuset },
3095                 { "toolbars", ui_toolbars },
3096                 { "toolbarset", ui_toolbarset }
3097         };
3098
3099         Lexer lex(uitags);
3100         lex.setFile(ui_path);
3101         if (!lex.isOK()) {
3102                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3103                                          << endl;
3104         }
3105
3106         if (lyxerr.debugging(Debug::PARSER))
3107                 lex.printTable(lyxerr);
3108
3109         bool error = false;
3110         // format before introduction of format tag
3111         unsigned int format = 0;
3112         while (lex.isOK()) {
3113                 int const status = lex.lex();
3114
3115                 // we have to do this check here, outside the switch,
3116                 // because otherwise we would start reading include files,
3117                 // e.g., if the first tag we hit was an include tag.
3118                 if (status == ui_format)
3119                         if (lex.next()) {
3120                                 format = lex.getInteger();
3121                                 continue;
3122                         }
3123
3124                 // this will trigger unless the first tag we hit is a format
3125                 // tag, with the right format.
3126                 if (format != LFUN_FORMAT)
3127                         return FormatMismatch;
3128
3129                 switch (status) {
3130                 case Lexer::LEX_FEOF:
3131                         continue;
3132
3133                 case ui_include: {
3134                         lex.next(true);
3135                         QString const file = toqstr(lex.getString());
3136                         bool const success = readUIFile(file, true);
3137                         if (!success) {
3138                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3139                                 return ReadError;
3140                         }
3141                         break;
3142                 }
3143
3144                 case ui_menuset:
3145                         d->menus_.read(lex);
3146                         break;
3147
3148                 case ui_toolbarset:
3149                         d->toolbars_.readToolbars(lex);
3150                         break;
3151
3152                 case ui_toolbars:
3153                         d->toolbars_.readToolbarSettings(lex);
3154                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3155                         break;
3156
3157                 default:
3158                         if (!rtrim(lex.getString()).empty())
3159                                 lex.printError("LyX::ReadUIFile: "
3160                                                "Unknown menu tag: `$$Token'");
3161                         else
3162                                 LYXERR0("Error with status: " << status);
3163                         error = true;
3164                         break;
3165                 }
3166
3167         }
3168         return (error ? ReadError : ReadOK);
3169 }
3170
3171
3172 bool GuiApplication::readUIFile(QString const & name, bool include)
3173 {
3174         LYXERR(Debug::INIT, "About to read " << name << "...");
3175
3176         FileName ui_path;
3177         if (include) {
3178                 ui_path = libFileSearch("ui", name, "inc");
3179                 if (ui_path.empty())
3180                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3181         } else {
3182                 ui_path = libFileSearch("ui", name, "ui");
3183         }
3184
3185         if (ui_path.empty()) {
3186                 static const QString defaultUIFile = "default";
3187                 LYXERR(Debug::INIT, "Could not find " << name);
3188                 if (include) {
3189                         Alert::warning(_("Could not find UI definition file"),
3190                                 bformat(_("Error while reading the included file\n%1$s\n"
3191                                         "Please check your installation."), qstring_to_ucs4(name)));
3192                         return false;
3193                 }
3194                 if (name == defaultUIFile) {
3195                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3196                         Alert::warning(_("Could not find default UI file"),
3197                                 _("LyX could not find the default UI file!\n"
3198                                   "Please check your installation."));
3199                         return false;
3200                 }
3201                 Alert::warning(_("Could not find UI definition file"),
3202                 bformat(_("Error while reading the configuration file\n%1$s\n"
3203                         "Falling back to default.\n"
3204                         "Please look under Tools>Preferences>User Interface and\n"
3205                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3206                 return readUIFile(defaultUIFile, false);
3207         }
3208
3209         QString const uifile = toqstr(ui_path.absFileName());
3210         if (uifiles.contains(uifile)) {
3211                 if (!include) {
3212                         // We are reading again the top uifile so reset the safeguard:
3213                         uifiles.clear();
3214                         d->menus_.reset();
3215                         d->toolbars_.reset();
3216                 } else {
3217                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3218                                 << "Is this an include loop?");
3219                         return false;
3220                 }
3221         }
3222         uifiles.push_back(uifile);
3223
3224         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3225
3226         ReturnValues retval = readUIFile(ui_path);
3227
3228         if (retval == FormatMismatch) {
3229                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3230                 TempFile tmp("convertXXXXXX.ui");
3231                 FileName const tempfile = tmp.name();
3232                 bool const success = prefs2prefs(ui_path, tempfile, true);
3233                 if (!success) {
3234                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3235                                 " to format " << LFUN_FORMAT << ".");
3236                 } else {
3237                         retval = readUIFile(tempfile);
3238                 }
3239         }
3240
3241         if (retval != ReadOK) {
3242                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3243                 return false;
3244         }
3245
3246         if (include)
3247                 return true;
3248
3249         QSettings settings;
3250         settings.beginGroup("ui_files");
3251         bool touched = false;
3252         for (int i = 0; i != uifiles.size(); ++i) {
3253                 QFileInfo fi(uifiles[i]);
3254                 QDateTime const date_value = fi.lastModified();
3255                 QString const name_key = QString::number(i);
3256                 // if an ui file which defines Toolbars has changed,
3257                 // we have to reset the settings
3258                 if (toolbar_uifiles.contains(uifiles[i])
3259                  && (!settings.contains(name_key)
3260                  || settings.value(name_key).toString() != uifiles[i]
3261                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3262                         touched = true;
3263                         settings.setValue(name_key, uifiles[i]);
3264                         settings.setValue(name_key + "/date", date_value);
3265                 }
3266         }
3267         settings.endGroup();
3268         if (touched)
3269                 settings.remove("views");
3270
3271         return true;
3272 }
3273
3274
3275 void GuiApplication::onLastWindowClosed()
3276 {
3277         if (d->global_menubar_)
3278                 d->global_menubar_->grabKeyboard();
3279 }
3280
3281
3282 void GuiApplication::startLongOperation() {
3283         d->key_checker_.start();
3284 }
3285
3286
3287 bool GuiApplication::longOperationCancelled() {
3288         return d->key_checker_.pressed();
3289 }
3290
3291
3292 void GuiApplication::stopLongOperation() {
3293         d->key_checker_.stop();
3294 }
3295
3296
3297 bool GuiApplication::longOperationStarted() {
3298         return d->key_checker_.started();
3299 }
3300
3301
3302 ////////////////////////////////////////////////////////////////////////
3303 //
3304 // X11 specific stuff goes here...
3305
3306 #ifdef Q_WS_X11
3307 bool GuiApplication::x11EventFilter(XEvent * xev)
3308 {
3309         if (!current_view_)
3310                 return false;
3311
3312         switch (xev->type) {
3313         case SelectionRequest: {
3314                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3315                         break;
3316                 LYXERR(Debug::SELECTION, "X requested selection.");
3317                 BufferView * bv = current_view_->currentBufferView();
3318                 if (bv) {
3319                         docstring const sel = bv->requestSelection();
3320                         if (!sel.empty()) {
3321                                 d->selection_.put(sel);
3322                                 // Refresh the selection request timestamp.
3323                                 // We have to do this by ourselves as Qt seems
3324                                 // not doing that, maybe because of our
3325                                 // "persistent selection" implementation
3326                                 // (see comments in GuiSelection.cpp).
3327                                 XSelectionEvent nev;
3328                                 nev.type = SelectionNotify;
3329                                 nev.display = xev->xselectionrequest.display;
3330                                 nev.requestor = xev->xselectionrequest.requestor;
3331                                 nev.selection = xev->xselectionrequest.selection;
3332                                 nev.target = xev->xselectionrequest.target;
3333                                 nev.property = 0L; // None
3334                                 nev.time = CurrentTime;
3335                                 XSendEvent(QX11Info::display(),
3336                                         nev.requestor, False, 0,
3337                                         reinterpret_cast<XEvent *>(&nev));
3338                                 return true;
3339                         }
3340                 }
3341                 break;
3342         }
3343         case SelectionClear: {
3344                 if (xev->xselectionclear.selection != XA_PRIMARY)
3345                         break;
3346                 LYXERR(Debug::SELECTION, "Lost selection.");
3347                 BufferView * bv = current_view_->currentBufferView();
3348                 if (bv)
3349                         bv->clearSelection();
3350                 break;
3351         }
3352         }
3353         return false;
3354 }
3355 #elif defined(QPA_XCB)
3356 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3357                                        void * message, long *)
3358 {
3359         if (!current_view_ || eventType != "xcb_generic_event_t")
3360                 return false;
3361
3362         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3363
3364         switch (ev->response_type) {
3365         case XCB_SELECTION_REQUEST: {
3366                 xcb_selection_request_event_t * srev =
3367                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3368                 if (srev->selection != XCB_ATOM_PRIMARY)
3369                         break;
3370                 LYXERR(Debug::SELECTION, "X requested selection.");
3371                 BufferView * bv = current_view_->currentBufferView();
3372                 if (bv) {
3373                         docstring const sel = bv->requestSelection();
3374                         if (!sel.empty()) {
3375                                 d->selection_.put(sel);
3376 #ifdef HAVE_QT5_X11_EXTRAS
3377                                 // Refresh the selection request timestamp.
3378                                 // We have to do this by ourselves as Qt seems
3379                                 // not doing that, maybe because of our
3380                                 // "persistent selection" implementation
3381                                 // (see comments in GuiSelection.cpp).
3382                                 // It is expected that every X11 event is
3383                                 // 32 bytes long, even if not all 32 bytes are
3384                                 // needed. See:
3385                                 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3386                                 struct alignas(32) padded_event
3387                                         : xcb_selection_notify_event_t {};
3388                                 padded_event nev = {};
3389                                 nev.response_type = XCB_SELECTION_NOTIFY;
3390                                 nev.requestor = srev->requestor;
3391                                 nev.selection = srev->selection;
3392                                 nev.target = srev->target;
3393                                 nev.property = XCB_NONE;
3394                                 nev.time = XCB_CURRENT_TIME;
3395                                 xcb_connection_t * con = QX11Info::connection();
3396                                 xcb_send_event(con, 0, srev->requestor,
3397                                         XCB_EVENT_MASK_NO_EVENT,
3398                                         reinterpret_cast<char const *>(&nev));
3399                                 xcb_flush(con);
3400 #endif
3401                                 return true;
3402                         }
3403                 }
3404                 break;
3405         }
3406         case XCB_SELECTION_CLEAR: {
3407                 xcb_selection_clear_event_t * scev =
3408                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3409                 if (scev->selection != XCB_ATOM_PRIMARY)
3410                         break;
3411                 LYXERR(Debug::SELECTION, "Lost selection.");
3412                 BufferView * bv = current_view_->currentBufferView();
3413                 if (bv)
3414                         bv->clearSelection();
3415                 break;
3416         }
3417         }
3418         return false;
3419 }
3420 #endif
3421
3422 } // namespace frontend
3423
3424
3425 void hideDialogs(std::string const & name, Inset * inset)
3426 {
3427         if (theApp())
3428                 frontend::guiApp->hideDialogs(name, inset);
3429 }
3430
3431
3432 ////////////////////////////////////////////////////////////////////
3433 //
3434 // Font stuff
3435 //
3436 ////////////////////////////////////////////////////////////////////
3437
3438 frontend::FontLoader & theFontLoader()
3439 {
3440         LAPPERR(frontend::guiApp);
3441         return frontend::guiApp->fontLoader();
3442 }
3443
3444
3445 frontend::FontMetrics const & theFontMetrics(Font const & f)
3446 {
3447         return theFontMetrics(f.fontInfo());
3448 }
3449
3450
3451 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3452 {
3453         LAPPERR(frontend::guiApp);
3454         return frontend::guiApp->fontLoader().metrics(f);
3455 }
3456
3457
3458 ////////////////////////////////////////////////////////////////////
3459 //
3460 // Misc stuff
3461 //
3462 ////////////////////////////////////////////////////////////////////
3463
3464 frontend::Clipboard & theClipboard()
3465 {
3466         LAPPERR(frontend::guiApp);
3467         return frontend::guiApp->clipboard();
3468 }
3469
3470
3471 frontend::Selection & theSelection()
3472 {
3473         LAPPERR(frontend::guiApp);
3474         return frontend::guiApp->selection();
3475 }
3476
3477
3478 } // namespace lyx
3479
3480 #include "moc_GuiApplication.cpp"