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