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