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