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