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