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