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