]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiApplication.cpp
e67a47621817ad1fb1f5c35339dd0db110cfbfde
[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/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/TempFile.h"
77 #include "support/textutils.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
86 #include <QByteArray>
87 #include <QDateTime>
88 #include <QDesktopWidget>
89 #include <QDir>
90 #include <QEvent>
91 #include <QFileOpenEvent>
92 #include <QFileInfo>
93 #include <QFontDatabase>
94 #include <QHash>
95 #include <QIcon>
96 #include <QImageReader>
97 #include <QKeyEvent>
98 #include <QLocale>
99 #include <QLibraryInfo>
100 #include <QList>
101 #include <QMenuBar>
102 #include <QMimeData>
103 #include <QObject>
104 #include <QPixmap>
105 #include <QRegExp>
106 #include <QSessionManager>
107 #include <QSettings>
108 #include <QSocketNotifier>
109 #include <QSortFilterProxyModel>
110 #include <QStandardItemModel>
111 #include <QTimer>
112 #include <QTranslator>
113 #include <QThreadPool>
114 #include <QWidget>
115
116 #ifdef Q_WS_X11
117 #include <X11/Xatom.h>
118 #include <X11/Xlib.h>
119 #include <QX11Info>
120 #undef CursorShape
121 #undef None
122 #elif defined(QPA_XCB)
123 #include <xcb/xcb.h>
124 #ifdef HAVE_QT5_X11_EXTRAS
125 #include <QtX11Extras/QX11Info>
126 #endif
127 #endif
128
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
134 #else
135 #include <QWinMime>
136 #define QWINDOWSMIME QWinMime
137 #endif
138 #ifdef Q_CC_GNU
139 #include <wtypes.h>
140 #endif
141 #include <objidl.h>
142 #endif
143 #endif
144
145 #ifdef Q_OS_MAC
146 #include <QMacPasteboardMime>
147 #endif // Q_OS_MAC
148
149 #include <boost/crc.hpp>
150
151 #include <exception>
152 #include <sstream>
153 #include <vector>
154
155 using namespace std;
156 using namespace lyx::support;
157
158
159 static void initializeResources()
160 {
161         static bool initialized = false;
162         if (!initialized) {
163                 Q_INIT_RESOURCE(Resources);
164                 initialized = true;
165         }
166 }
167
168
169 namespace lyx {
170
171 frontend::Application * createApplication(int & argc, char * argv[])
172 {
173 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
174         // prune -geometry argument(s) by shifting
175         // the following ones 2 places down.
176         for (int i = 0 ; i < argc ; ++i) {
177                 if (strcmp(argv[i], "-geometry") == 0) {
178                         int const remove = (i+1) < argc ? 2 : 1;
179                         argc -= remove;
180                         for (int j = i; j < argc; ++j)
181                                 argv[j] = argv[j + remove];
182                         --i;
183                 }
184         }
185 #endif
186
187 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
188         // On Windows, allow bringing the LyX window to top
189         AllowSetForegroundWindow(ASFW_ANY);
190 #endif
191
192         frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
193         // I'd rather do that in the constructor, but I do not think that
194         // the palette is accessible there.
195         guiApp->colorCache().setPalette(guiApp->palette());
196         return guiApp;
197 }
198
199
200 void setLocale()
201 {
202         QLocale theLocale;
203         string code;
204         if (lyxrc.gui_language == "auto") {
205                 theLocale = QLocale::system();
206                 code = fromqstr(theLocale.name());
207         } else {
208                 Language const * l = languages.getLanguage(lyxrc.gui_language);
209                 code = l ? l->code() : "C";
210                 theLocale = QLocale(toqstr(code));
211         }
212         // Qt tries to outsmart us and transforms en_US to C.
213         Messages::guiLanguage((code == "C") ? "en_US" : code);
214         QLocale::setDefault(theLocale);
215         setlocale(LC_NUMERIC, "C");
216 }
217
218
219 namespace frontend {
220
221
222 /// Return the list of loadable formats.
223 vector<string> loadableImageFormats()
224 {
225         vector<string> fmts;
226
227         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
228
229         LYXERR(Debug::GRAPHICS,
230                 "\nThe image loader can load the following directly:\n");
231
232         if (qt_formats.empty())
233                 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
234
235         bool jpeg_found = false;
236         bool jpg_found = false;
237         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
238
239                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
240
241                 string ext = ascii_lowercase((const char *) *it);
242                 // special case
243                 if (ext == "jpeg") {
244                         jpeg_found = true;
245                         if (jpg_found)
246                                 continue;
247                         ext = "jpg";
248                 }
249                 else if (ext == "jpg") {
250                         jpg_found = true;
251                         if (jpeg_found)
252                                 continue;
253                 }
254                 else if (lyxrc.use_converter_cache &&
255                          (ext == "svg" || ext == "svgz") &&
256                           theConverters().isReachable("svg", "png"))
257                         // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
258                         // the SVG as in the output. However we require that the converter
259                         // cache is enabled since this is expensive. We also require that
260                         // an explicit svg->png converter is defined, since the default
261                         // converter could produce bad quality as well. This assumes that
262                         // png can always be loaded.
263                         continue;
264                 fmts.push_back(ext);
265         }
266
267         return fmts;
268 }
269
270
271 ////////////////////////////////////////////////////////////////////////
272 //
273 // Icon loading support code
274 //
275 ////////////////////////////////////////////////////////////////////////
276
277 namespace {
278
279 struct ImgMap {
280         QString key;
281         QString value;
282 };
283
284
285 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
286 {
287         return lhs.key < rhs.key;
288 }
289
290
291 class CompareKey {
292 public:
293         CompareKey(QString const & name) : name_(name) {}
294         bool operator()(ImgMap const & other) const { return other.key == name_; }
295 private:
296         QString const name_;
297 };
298
299
300 // this must be sorted alphabetically
301 // Upper case comes before lower case
302 // Please don't change the formatting, this list is parsed by
303 // development/tools/generate_symbols_images.py.
304 ImgMap sorted_img_map[] = {
305         { "Arrownot", "arrownot2"},
306         { "Arrowvert", "arrowvert2"},
307         { "Bowtie", "bowtie2" },
308         { "Box", "box2" },
309         { "Bumpeq", "bumpeq2" },
310         { "CIRCLE", "circle3" },
311         { "Cap", "cap2" },
312         { "CheckedBox", "checkedbox2" },
313         { "Circle", "circle2" },
314         { "Colonapprox", "colonapprox2" },
315         { "Coloneq", "coloneq2" },
316         { "Coloneqq", "coloneqq2" },
317         { "Colonsim", "colonsim2" },
318         { "Cup", "cup2" },
319         { "DOWNarrow", "downarrow3" },
320         { "Delta", "delta2" },
321         { "Diamond", "diamond2" },
322         { "Doteq", "doteq2" },
323         { "Downarrow", "downarrow2" },
324         { "Eqcolon", "eqcolon2" },
325         { "Eqqcolon", "eqqcolon2" },
326         { "Gamma", "gamma2" },
327         { "Join", "join2" },
328         { "LEFTCIRCLE", "leftcircle3" },
329         { "LEFTarrow", "leftarrow3" },
330         { "LEFTcircle", "leftcircle4" },
331         { "LHD", "lhd2" },
332         { "Lambda", "lambda2" },
333         { "Lbag", "lbag2"},
334         { "Leftarrow", "leftarrow2" },
335         { "Leftcircle", "leftcircle2" },
336         { "Leftrightarrow", "leftrightarrow2" },
337         { "Longarrownot", "longarrownot2"},
338         { "Longleftarrow", "longleftarrow2" },
339         { "Longleftrightarrow", "longleftrightarrow2" },
340         { "Longmapsfrom", "longmapsfrom2"},
341         { "Longmapsto", "longmapsto2"},
342         { "Longrightarrow", "longrightarrow2" },
343         { "Mapsfrom", "mapsfrom2"},
344         { "Mapsfromchar", "mapsfromchar2"},
345         { "Mapsto", "mapsto2"},
346         { "Mapstochar", "mapstochar2"},
347         { "Omega", "omega2" },
348         { "Phi", "phi2" },
349         { "Pi", "pi2" },
350         { "Psi", "psi2" },
351         { "RHD", "rhd2" },
352         { "RIGHTCIRCLE", "rightcircle3" },
353         { "RIGHTarrow", "rightarrow3" },
354         { "RIGHTcircle", "rightcircle4" },
355         { "Rbag", "rbag2"},
356         { "Rightarrow", "rightarrow2" },
357         { "Rightcircle", "rightcircle2" },
358         { "Sigma", "sigma2" },
359         { "Square", "square2" },
360         { "Subset", "subset2" },
361         { "Supset", "supset2" },
362         { "Theta", "theta2" },
363         { "Thorn", "thorn2" },
364         { "UParrow", "uparrow3" },
365         { "Uparrow", "uparrow2" },
366         { "Updownarrow", "updownarrow2" },
367         { "Upsilon", "upsilon2" },
368         { "Vdash", "vdash3" },
369         { "Vert", "vert2" },
370         { "XBox", "xbox3" },
371         { "Xbox", "xbox2" },
372         { "Xi", "xi2" },
373         { "lVert", "vert2" },
374         { "lvert", "vert" },
375         { "nLeftarrow", "nleftarrow2" },
376         { "nLeftrightarrow", "nleftrightarrow2" },
377         { "nRightarrow", "nrightarrow2" },
378         { "nVDash", "nvdash3" },
379         { "nVdash", "nvdash4" },
380         { "nvDash", "nvdash2" },
381         { "rVert", "vert2" },
382         { "rvert", "vert" },
383         { "textrm \\AA", "textrm_AA"},
384         { "textrm \\O", "textrm_O"},
385         { "vDash", "vdash2" },
386         { "varDelta", "vardelta2" },
387         { "varGamma", "vargamma2" },
388         { "varLambda", "varlambda2" },
389         { "varOmega", "varomega2" },
390         { "varPhi", "varphi2" },
391         { "varPi", "varpi2" },
392         { "varPsi", "varpsi2" },
393         { "varSigma", "varsigma2" },
394         { "varTheta", "vartheta2" },
395         { "varUpsilon", "varupsilon2" },
396         { "varXi", "varxi2" }
397 };
398
399
400 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
401
402 // This list specifies which system's theme icon is related to which lyx
403 // command. It was based on:
404 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
405 // this must be sorted alphabetically
406 // Upper case comes before lower case
407 ImgMap sorted_theme_icon_map[] = {
408         { "bookmark-goto 0", "go-jump" },
409         { "buffer-new", "document-new" },
410         { "buffer-write", "document-save" },
411         { "buffer-write-as", "document-save-as" },
412         { "buffer-zoom-in", "zoom-in" },
413         { "buffer-zoom-out", "zoom-out" },
414         { "copy", "edit-copy" },
415         { "cut", "edit-cut" },
416         { "depth-decrement", "format-indent-less" },
417         { "depth-increment", "format-indent-more" },
418         { "dialog-show spellchecker", "tools-check-spelling" },
419         { "dialog-show-new-inset graphics", "insert-image" },
420         { "dialog-toggle findreplaceadv", "edit-find-replace" },
421         { "file-open", "document-open" },
422         { "font-bold", "format-text-bold" },
423         { "font-ital", "format-text-italic" },
424         { "font-strikeout", "format-text-strikethrough" },
425         { "font-underline", "format-text-underline" },
426         { "lyx-quit", "application-exit" },
427         { "paste", "edit-paste" },
428         { "redo", "edit-redo" },
429         { "undo", "edit-undo" },
430         { "window-close", "window-close" },
431         { "window-new", "window-new" }
432 };
433
434 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
435
436
437 QString findImg(QString const & name)
438 {
439         ImgMap const * const begin = sorted_img_map;
440         ImgMap const * const end = begin + nr_sorted_img_map;
441         LATTEST(sorted(begin, end));
442
443         ImgMap const * const it = find_if(begin, end, CompareKey(name));
444
445         QString img_name;
446         if (it != end) {
447                 img_name = it->value;
448         } else {
449                 img_name = name;
450                 img_name.replace('_', "underscore");
451                 img_name.replace(' ', '_');
452
453                 // This way we can have "math-delim { }" on the toolbar.
454                 img_name.replace('(', "lparen");
455                 img_name.replace(')', "rparen");
456                 img_name.replace('[', "lbracket");
457                 img_name.replace(']', "rbracket");
458                 img_name.replace('{', "lbrace");
459                 img_name.replace('}', "rbrace");
460                 img_name.replace('|', "bars");
461                 img_name.replace(',', "thinspace");
462                 img_name.replace(':', "mediumspace");
463                 img_name.replace(';', "thickspace");
464                 img_name.replace('!', "negthinspace");
465         }
466
467         LYXERR(Debug::GUI, "findImg(" << name << ")\n"
468                 << "Looking for math icon called \"" << img_name << '"');
469         return img_name;
470 }
471
472 } // namespace
473
474
475 QString themeIconName(QString const & action)
476 {
477         ImgMap const * const begin = sorted_theme_icon_map;
478         ImgMap const * const end = begin + nr_sorted_theme_icon_map;
479         LASSERT(sorted(begin, end), /**/);
480
481         ImgMap const * const it = find_if(begin, end, CompareKey(action));
482
483         if (it != end)
484                 return it->value;
485         return QString();
486 }
487
488
489 QString iconName(FuncRequest const & f, bool unknown)
490 {
491         initializeResources();
492         QString name1;
493         QString name2;
494         QString path;
495         switch (f.action()) {
496         case LFUN_MATH_INSERT:
497                 if (!f.argument().empty()) {
498                         path = "math/";
499                         name1 = findImg(toqstr(f.argument()).mid(1));
500                 }
501                 break;
502         case LFUN_MATH_DELIM:
503         case LFUN_MATH_BIGDELIM:
504                 path = "math/";
505                 name1 = findImg(toqstr(f.argument()));
506                 break;
507         case LFUN_CALL:
508                 path = "commands/";
509                 name1 = toqstr(f.argument());
510                 break;
511         case LFUN_COMMAND_ALTERNATIVES: {
512                 // use the first of the alternative commands
513                 docstring firstcom;
514                 docstring dummy = split(f.argument(), firstcom, ';');
515                 name1 = toqstr(firstcom);
516                 name1.replace(' ', '_');
517                 break;
518         }
519         default:
520                 name2 = toqstr(lyxaction.getActionName(f.action()));
521                 name1 = name2;
522
523                 if (!f.argument().empty()) {
524                         name1 = name2 + ' ' + toqstr(f.argument());
525                         name1.replace(' ', '_');
526                         name1.replace('\\', "backslash");
527                 }
528         }
529
530         QStringList imagedirs;
531         imagedirs << "images/" << "images/ipa/";
532         search_mode mode = theGuiApp()->imageSearchMode();
533         for (int i = 0; i < imagedirs.size(); ++i) {
534                 QString imagedir = imagedirs.at(i) + path;
535                 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
536                 if (fname.exists())
537                         return toqstr(fname.absFileName());
538
539                 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
540                 if (fname.exists())
541                         return toqstr(fname.absFileName());
542         }
543
544         path = ":/images/" + path;
545         QDir res(path);
546         if (!res.exists()) {
547                 LYXERR0("Directory " << path << " not found in resource!");
548                 return QString();
549         }
550         if (res.exists(name1 + ".svgz"))
551                 return path + name1 + ".svgz";
552         else if (res.exists(name1 + ".png"))
553                 return path + name1 + ".png";
554
555         if (res.exists(name2 + ".svgz"))
556                 return path + name2 + ".svgz";
557         else if (res.exists(name2 + ".png"))
558                 return path + name2 + ".png";
559
560         LYXERR(Debug::GUI, "Cannot find icon with filename "
561                            << "\"" << name1 << ".{svgz,png}\""
562                            << " or filename "
563                            << "\"" << name2 << ".{svgz,png}\""
564                            << " for command \""
565                            << lyxaction.getActionName(f.action())
566                            << '(' << to_utf8(f.argument()) << ")\"");
567
568         if (unknown) {
569                 QString imagedir = "images/";
570                 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
571                 if (fname.exists())
572                         return toqstr(fname.absFileName());
573                 return QString(":/images/unknown.svgz");
574         }
575
576         return QString();
577 }
578
579
580 bool getPixmap(QPixmap & pixmap, QString const & path)
581 {
582         return pixmap.load(path);
583 }
584
585
586 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
587 {
588         QString imagedir = path;
589         FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
590         QString fpath = toqstr(fname.absFileName());
591         QPixmap pixmap = QPixmap();
592
593         if (getPixmap(pixmap, fpath)) {
594                 return pixmap;
595         }
596
597         QStringList exts = ext.split(",");
598         fpath = ":/" + path + name + ".";
599         for (int i = 0; i < exts.size(); ++i) {
600                 if (getPixmap(pixmap, fpath + exts.at(i))) {
601                         return pixmap;
602                 }
603         }
604
605         bool const list = ext.contains(",");
606         LYXERR0("Cannot load pixmap \""
607                 << path << name << "." << (list ? "{" : "") << ext
608                 << (list ? "}" : "") << "\", please verify resource system!");
609
610         return QPixmap();
611 }
612
613
614 QIcon getIcon(FuncRequest const & f, bool unknown)
615 {
616 #if (QT_VERSION >= 0x040600)
617         if (lyxrc.use_system_theme_icons) {
618                 // use the icons from system theme that are available
619                 QString action = toqstr(lyxaction.getActionName(f.action()));
620                 if (!f.argument().empty())
621                         action += " " + toqstr(f.argument());
622                 QString const theme_icon = themeIconName(action);
623                 if (QIcon::hasThemeIcon(theme_icon)) {
624                         QIcon const thmicn = QIcon::fromTheme(theme_icon);
625                         if (!thmicn.isNull())
626                                 return thmicn;
627                 }
628         }
629 #endif
630
631         QString icon = iconName(f, unknown);
632         if (icon.isEmpty())
633                 return QIcon();
634
635         //LYXERR(Debug::GUI, "Found icon: " << icon);
636         QPixmap pixmap = QPixmap();
637         if (!getPixmap(pixmap,icon)) {
638                 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
639                 return QIcon();
640         }
641
642         return QIcon(pixmap);
643 }
644
645
646 ////////////////////////////////////////////////////////////////////////
647 //
648 // LyX server support code.
649 //
650 ////////////////////////////////////////////////////////////////////////
651
652 class SocketNotifier : public QSocketNotifier
653 {
654 public:
655         /// connect a connection notification from the LyXServerSocket
656         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
657                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
658         {}
659
660 public:
661         /// The callback function
662         Application::SocketCallback func_;
663 };
664
665
666 class GuiTranslator : public QTranslator
667 {
668 public:
669         GuiTranslator(QObject * parent = nullptr)
670                 : QTranslator(parent)
671         {}
672
673         virtual QString translate(const char * /* context */,
674                 const char *sourceText,
675 #if QT_VERSION >= 0x050000
676                 const char * /* disambiguation */ = 0, int /* n */ = -1) const
677 #else
678                 const char * /*comment*/ = 0) const
679 #endif
680         {
681                 // Here we declare the strings that need to be translated from Qt own GUI
682                 // This is needed to include these strings to po files
683                 _("About %1");
684                 _("Preferences");
685                 _("Reconfigure");
686                 _("Restore Defaults");
687                 _("Quit %1");
688                 _("&OK");
689                 // Already in po: "Cancel", "&Cancel"
690                 _("Apply"); // Already in po: "&Apply"
691                 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
692                 _("Open");
693
694                 docstring s = getGuiMessages().getIfFound(sourceText);
695                 // This test should eventually be removed when translations are updated
696                 if (s.empty())
697                         LYXERR(Debug::LOCALE, "Missing translation for `"
698                                << string(sourceText) << "'");
699                 return toqstr(s);
700         }
701 };
702
703
704 ////////////////////////////////////////////////////////////////////////
705 //
706 // Mac specific stuff goes here...
707 //
708 ////////////////////////////////////////////////////////////////////////
709
710 #ifdef Q_OS_MAC
711 // QMacPasteboardMimeGraphics can only be compiled on Mac.
712
713 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
714 {
715 public:
716         QMacPasteboardMimeGraphics()
717                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
718         {}
719
720         QString convertorName() { return "Graphics"; }
721
722         QString flavorFor(QString const & mime)
723         {
724                 LYXERR(Debug::ACTION, "flavorFor " << mime);
725                 if (mime == pdfMimeType())
726                         return QLatin1String("com.adobe.pdf");
727                 return QString();
728         }
729
730         QString mimeFor(QString flav)
731         {
732                 LYXERR(Debug::ACTION, "mimeFor " << flav);
733                 if (flav == QLatin1String("com.adobe.pdf"))
734                         return pdfMimeType();
735                 return QString();
736         }
737
738         bool canConvert(QString const & mime, QString flav)
739         {
740                 return mimeFor(flav) == mime;
741         }
742
743         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
744                 QString /*flav*/)
745         {
746                 if(data.count() > 1)
747                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
748                 return data.first();
749         }
750
751         QList<QByteArray> convertFromMime(QString const & /*mime*/,
752                 QVariant data, QString /*flav*/)
753         {
754                 QList<QByteArray> ret;
755                 ret.append(data.toByteArray());
756                 return ret;
757         }
758 };
759 #endif
760
761 ///////////////////////////////////////////////////////////////
762 //
763 // You can find more platform specific stuff at the end of this file...
764 //
765 ///////////////////////////////////////////////////////////////
766
767 ////////////////////////////////////////////////////////////////////////
768 // Windows specific stuff goes here...
769
770 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
771 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
772 // QWindowsMimeMetafile can only be compiled on Windows.
773
774 static FORMATETC cfFromMime(QString const & mimetype)
775 {
776         FORMATETC formatetc;
777         if (mimetype == emfMimeType()) {
778                 formatetc.cfFormat = CF_ENHMETAFILE;
779                 formatetc.tymed = TYMED_ENHMF;
780         } else if (mimetype == wmfMimeType()) {
781                 formatetc.cfFormat = CF_METAFILEPICT;
782                 formatetc.tymed = TYMED_MFPICT;
783         }
784         formatetc.ptd = 0;
785         formatetc.dwAspect = DVASPECT_CONTENT;
786         formatetc.lindex = -1;
787         return formatetc;
788 }
789
790
791 class QWindowsMimeMetafile : public QWINDOWSMIME {
792 public:
793         QWindowsMimeMetafile() {}
794
795         bool canConvertFromMime(FORMATETC const & /*formatetc*/,
796                 QMimeData const * /*mimedata*/) const
797         {
798                 return false;
799         }
800
801         bool canConvertToMime(QString const & mimetype,
802                 IDataObject * pDataObj) const
803         {
804                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
805                         return false;
806                 FORMATETC formatetc = cfFromMime(mimetype);
807                 return pDataObj->QueryGetData(&formatetc) == S_OK;
808         }
809
810         bool convertFromMime(FORMATETC const & /*formatetc*/,
811                 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
812         {
813                 return false;
814         }
815
816         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
817                 QVariant::Type /*preferredType*/) const
818         {
819                 QByteArray data;
820                 if (!canConvertToMime(mimetype, pDataObj))
821                         return data;
822
823                 FORMATETC formatetc = cfFromMime(mimetype);
824                 STGMEDIUM s;
825                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
826                         return data;
827
828                 int dataSize;
829                 if (s.tymed == TYMED_ENHMF) {
830                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
831                         data.resize(dataSize);
832                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
833                                 (LPBYTE)data.data());
834                 } else if (s.tymed == TYMED_MFPICT) {
835                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
836                         data.resize(dataSize);
837                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
838                                 (LPBYTE)data.data());
839                 }
840                 data.detach();
841                 ReleaseStgMedium(&s);
842
843                 return data;
844         }
845
846
847         QVector<FORMATETC> formatsForMime(QString const & mimetype,
848                 QMimeData const * /*mimedata*/) const
849         {
850                 QVector<FORMATETC> formats;
851                 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
852                         formats += cfFromMime(mimetype);
853                 return formats;
854         }
855
856         QString mimeForFormat(FORMATETC const & formatetc) const
857         {
858                 switch (formatetc.cfFormat) {
859                 case CF_ENHMETAFILE:
860                         return emfMimeType();
861                 case CF_METAFILEPICT:
862                         return wmfMimeType();
863                 }
864                 return QString();
865         }
866 };
867
868 #endif
869 #endif
870
871
872 /// Allows to check whether ESC was pressed during a long operation
873 class KeyChecker : public QObject {
874 private:
875         bool pressed_;
876         bool started_;
877 public:
878         KeyChecker() : pressed_(false), started_(false) {}
879
880         void start() {
881                 QCoreApplication::instance()->installEventFilter(this);
882                 pressed_ = false;
883                 started_ = true;
884         }
885         void stop() {
886                 QCoreApplication::instance()->removeEventFilter(this);
887                 started_ = false;
888         }
889         bool pressed() {
890                 QCoreApplication::processEvents();
891                 return pressed_;
892         }
893         bool started() const {
894                 return started_;
895         }
896         bool eventFilter(QObject *obj, QEvent *event) {
897                 LYXERR(Debug::ACTION, "Event Type: " << event->type());
898                 switch (event->type()) {
899                 case QEvent::Show:
900                 case QEvent::Hide:
901                 case QEvent::Resize:
902                 case QEvent::UpdateRequest:
903                 case QEvent::CursorChange:
904                 case QEvent::ActionChanged:
905                 case QEvent::EnabledChange:
906                 case QEvent::SockAct:
907                 case QEvent::Timer:
908                 case QEvent::Paint:
909                 case QEvent::ToolTipChange:
910                 case QEvent::LayoutRequest:
911                 case QEvent::MetaCall:
912                         return QObject::eventFilter(obj, event);
913                 default:
914                         // FIXME Blocking all these events is a bad idea.
915                         QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
916                         if (keyEvent && keyEvent->key() == Qt::Key_Escape)
917                                 pressed_ = true;
918                         return true;
919                 }
920         }
921 };
922
923
924 ////////////////////////////////////////////////////////////////////////
925 // GuiApplication::Private definition and implementation.
926 ////////////////////////////////////////////////////////////////////////
927
928 struct GuiApplication::Private
929 {
930         Private(): language_model_(0), meta_fake_bit(NoModifier),
931                    global_menubar_(0)
932         {
933         #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
934         #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
935                 /// WMF Mime handler for Windows clipboard.
936                 wmf_mime_ = new QWindowsMimeMetafile;
937         #endif
938         #endif
939                 initKeySequences(&theTopLevelKeymap());
940         }
941
942         void initKeySequences(KeyMap * kb)
943         {
944                 keyseq = KeySequence(kb, kb);
945                 cancel_meta_seq = KeySequence(kb, kb);
946         }
947
948         ///
949         QSortFilterProxyModel * language_model_;
950         ///
951         GuiClipboard clipboard_;
952         ///
953         GuiSelection selection_;
954         ///
955         FontLoader font_loader_;
956         ///
957         ColorCache color_cache_;
958         /// the built-in Qt translation mechanism
959         QTranslator qt_trans_;
960         /// LyX gettext-based translation for Qt elements
961         GuiTranslator gui_trans_;
962         ///
963         QHash<int, SocketNotifier *> socket_notifiers_;
964         ///
965         Menus menus_;
966         ///
967         /// The global instance
968         Toolbars toolbars_;
969
970         /// this timer is used for any regular events one wants to
971         /// perform. at present it is used to check if forked processes
972         /// are done.
973         QTimer general_timer_;
974
975         /// delayed FuncRequests
976         std::queue<FuncRequest> func_request_queue_;
977
978         ///
979         KeySequence keyseq;
980         ///
981         KeySequence cancel_meta_seq;
982         ///
983         KeyModifier meta_fake_bit;
984
985         /// The result of last dispatch action
986         DispatchResult dispatch_result_;
987
988         /// Multiple views container.
989         /**
990         * Warning: This must not be a smart pointer as the destruction of the
991         * object is handled by Qt when the view is closed
992         * \sa Qt::WA_DeleteOnClose attribute.
993         */
994         QHash<int, GuiView *> views_;
995
996         /// Only used on mac.
997         QMenuBar * global_menubar_;
998
999 #ifdef Q_OS_MAC
1000         /// Linkback mime handler for MacOSX.
1001         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1002 #endif
1003
1004 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1005 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1006         /// WMF Mime handler for Windows clipboard.
1007         QWindowsMimeMetafile * wmf_mime_;
1008 #endif
1009 #endif
1010
1011         /// Allows to check whether ESC was pressed during a long operation
1012         KeyChecker key_checker_;
1013 };
1014
1015
1016 GuiApplication * guiApp;
1017
1018 GuiApplication::~GuiApplication()
1019 {
1020 #ifdef Q_OS_MAC
1021         closeAllLinkBackLinks();
1022 #endif
1023         delete d;
1024 }
1025
1026
1027 GuiApplication::GuiApplication(int & argc, char ** argv)
1028         : QApplication(argc, argv), current_view_(0),
1029           d(new GuiApplication::Private)
1030 {
1031         QString app_name = "LyX";
1032         QCoreApplication::setOrganizationName(app_name);
1033         QCoreApplication::setOrganizationDomain("lyx.org");
1034         QCoreApplication::setApplicationName(lyx_package);
1035 #if QT_VERSION >= 0x050000
1036         QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1037 #endif
1038
1039         qsrand(QDateTime::currentDateTime().toTime_t());
1040
1041         // Install LyX translator for missing Qt translations
1042         installTranslator(&d->gui_trans_);
1043         // Install Qt native translator for GUI elements.
1044         installTranslator(&d->qt_trans_);
1045
1046 #ifdef QPA_XCB
1047         // Enable reception of XCB events.
1048         installNativeEventFilter(this);
1049 #endif
1050
1051         // FIXME: quitOnLastWindowClosed is true by default. We should have a
1052         // lyxrc setting for this in order to let the application stay resident.
1053         // But then we need some kind of dock icon, at least on Windows.
1054         /*
1055         if (lyxrc.quit_on_last_window_closed)
1056                 setQuitOnLastWindowClosed(false);
1057         */
1058 #ifdef Q_OS_MAC
1059         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1060         // seems to be the default case for applications like LyX.
1061         setQuitOnLastWindowClosed(false);
1062         ///
1063         setupApplescript();
1064 #endif
1065
1066 #if defined(Q_WS_X11) || defined(QPA_XCB)
1067         // doubleClickInterval() is 400 ms on X11 which is just too long.
1068         // On Windows and Mac OS X, the operating system's value is used.
1069         // On Microsoft Windows, calling this function sets the double
1070         // click interval for all applications. So we don't!
1071         QApplication::setDoubleClickInterval(300);
1072 #endif
1073
1074         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1075
1076         // needs to be done before reading lyxrc
1077         QWidget w;
1078         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1079
1080         guiApp = this;
1081
1082         // Initialize RC Fonts
1083         if (lyxrc.roman_font_name.empty())
1084                 lyxrc.roman_font_name = fromqstr(romanFontName());
1085
1086         if (lyxrc.sans_font_name.empty())
1087                 lyxrc.sans_font_name = fromqstr(sansFontName());
1088
1089         if (lyxrc.typewriter_font_name.empty())
1090                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1091
1092 #if (QT_VERSION >= 0x050000)
1093         // Qt4 does this in event(), see below.
1094         // Track change of keyboard
1095         connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1096 #endif
1097
1098         d->general_timer_.setInterval(500);
1099         connect(&d->general_timer_, SIGNAL(timeout()),
1100                 this, SLOT(handleRegularEvents()));
1101         d->general_timer_.start();
1102
1103         // maxThreadCount() defaults in general to 2 on single or dual-processor.
1104         // This is clearly not enough in a time where we use threads for
1105         // document preview and/or export. 20 should be OK.
1106         QThreadPool::globalInstance()->setMaxThreadCount(20);
1107
1108         // make sure tooltips are formatted
1109         installEventFilter(new ToolTipFormatter(this));
1110 }
1111
1112
1113 GuiApplication * theGuiApp()
1114 {
1115         return dynamic_cast<GuiApplication *>(theApp());
1116 }
1117
1118
1119 double GuiApplication::pixelRatio() const
1120 {
1121 #if QT_VERSION >= 0x050000
1122         return qt_scale_factor * devicePixelRatio();
1123 #else
1124         return 1.0;
1125 #endif
1126 }
1127
1128
1129 void GuiApplication::clearSession()
1130 {
1131         QSettings settings;
1132         settings.clear();
1133 }
1134
1135
1136 docstring Application::iconName(FuncRequest const & f, bool unknown)
1137 {
1138         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1139 }
1140
1141
1142 docstring Application::mathIcon(docstring const & c)
1143 {
1144         return qstring_to_ucs4(findImg(toqstr(c)));
1145 }
1146
1147
1148 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1149 {
1150         FuncStatus status;
1151
1152         BufferView * bv = 0;
1153         BufferView * doc_bv = 0;
1154
1155         if (cmd.action() == LFUN_NOACTION) {
1156                 status.message(from_utf8(N_("Nothing to do")));
1157                 status.setEnabled(false);
1158         }
1159
1160         else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1161                 status.setUnknown(true);
1162                 status.message(from_utf8(N_("Unknown action")));
1163                 status.setEnabled(false);
1164         }
1165
1166         // Does the GuiApplication know something?
1167         else if (getStatus(cmd, status)) { }
1168
1169         // If we do not have a GuiView, then other functions are disabled
1170         else if (!current_view_)
1171                 status.setEnabled(false);
1172
1173         // Does the GuiView know something?
1174         else if (current_view_->getStatus(cmd, status)) { }
1175
1176         // In LyX/Mac, when a dialog is open, the menus of the
1177         // application can still be accessed without giving focus to
1178         // the main window. In this case, we want to disable the menu
1179         // entries that are buffer or view-related.
1180         //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1181         /*
1182         else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1183                 status.setEnabled(false);
1184         */
1185
1186         // If we do not have a BufferView, then other functions are disabled
1187         else if (!(bv = current_view_->currentBufferView()))
1188                 status.setEnabled(false);
1189
1190         // Does the current BufferView know something?
1191         else if (bv->getStatus(cmd, status)) { }
1192
1193         // Does the current Buffer know something?
1194         else if (bv->buffer().getStatus(cmd, status)) { }
1195
1196         // If we do not have a document BufferView, different from the
1197         // current BufferView, then other functions are disabled
1198         else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1199                 status.setEnabled(false);
1200
1201         // Does the document Buffer know something?
1202         else if (doc_bv->buffer().getStatus(cmd, status)) { }
1203
1204         else {
1205                 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1206                 status.message(from_utf8(N_("Command not handled")));
1207                 status.setEnabled(false);
1208         }
1209
1210         // the default error message if we disable the command
1211         if (!status.enabled() && status.message().empty())
1212                 status.message(from_utf8(N_("Command disabled")));
1213
1214         return status;
1215 }
1216
1217
1218 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1219 {
1220         // I would really like to avoid having this switch and rather try to
1221         // encode this in the function itself.
1222         // -- And I'd rather let an inset decide which LFUNs it is willing
1223         // to handle (Andre')
1224         bool enable = true;
1225         switch (cmd.action()) {
1226
1227         // This could be used for the no-GUI version. The GUI version is handled in
1228         // GuiView::getStatus(). See above.
1229         /*
1230         case LFUN_BUFFER_WRITE:
1231         case LFUN_BUFFER_WRITE_AS:
1232         case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1233                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1234                 enable = b && (b->isUnnamed() || !b->isClean());
1235                 break;
1236         }
1237         */
1238
1239         case LFUN_BOOKMARK_GOTO: {
1240                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1241                 enable = theSession().bookmarks().isValid(num);
1242                 break;
1243         }
1244
1245         case LFUN_BOOKMARK_CLEAR:
1246                 enable = theSession().bookmarks().hasValid();
1247                 break;
1248
1249         // this one is difficult to get right. As a half-baked
1250         // solution, we consider only the first action of the sequence
1251         case LFUN_COMMAND_SEQUENCE: {
1252                 // argument contains ';'-terminated commands
1253                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1254                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1255                 func.setOrigin(cmd.origin());
1256                 flag = getStatus(func);
1257                 break;
1258         }
1259
1260         // we want to check if at least one of these is enabled
1261         case LFUN_COMMAND_ALTERNATIVES: {
1262                 // argument contains ';'-terminated commands
1263                 string arg = to_utf8(cmd.argument());
1264                 while (!arg.empty()) {
1265                         string first;
1266                         arg = split(arg, first, ';');
1267                         FuncRequest func(lyxaction.lookupFunc(first));
1268                         func.setOrigin(cmd.origin());
1269                         flag = getStatus(func);
1270                         // if this one is enabled, the whole thing is
1271                         if (flag.enabled())
1272                                 break;
1273                 }
1274                 break;
1275         }
1276
1277         case LFUN_CALL: {
1278                 FuncRequest func;
1279                 string name = to_utf8(cmd.argument());
1280                 if (theTopLevelCmdDef().lock(name, func)) {
1281                         func.setOrigin(cmd.origin());
1282                         flag = getStatus(func);
1283                         theTopLevelCmdDef().release(name);
1284                 } else {
1285                         // catch recursion or unknown command
1286                         // definition. all operations until the
1287                         // recursion or unknown command definition
1288                         // occurs are performed, so set the state to
1289                         // enabled
1290                         enable = true;
1291                 }
1292                 break;
1293         }
1294
1295         case LFUN_BIDI: {
1296                 string const dir = cmd.getArg(0);
1297                 string const lfun = cmd.getLongArg(1);
1298                 BufferView const * bv =
1299                         current_view_ ? current_view_->currentBufferView() : nullptr;
1300                 bool rtl = bv ? bv->cursor().innerParagraph().isRTL(bv->buffer().params())
1301                               : layoutDirection() == Qt::RightToLeft;
1302                 if (((rtl && dir != "rtl") || (!rtl && dir != "ltr"))) {
1303                         flag.setUnknown(true);
1304                         flag.setEnabled(false);
1305                 } else {
1306                         FuncRequest func(lyxaction.lookupFunc(lfun));
1307                         func.setOrigin(cmd.origin());
1308                         flag = getStatus(func);
1309                 }
1310                 break;
1311         }
1312
1313         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1314         case LFUN_REPEAT:
1315         case LFUN_PREFERENCES_SAVE:
1316         case LFUN_BUFFER_SAVE_AS_DEFAULT:
1317         case LFUN_DEBUG_LEVEL_SET:
1318                 // these are handled in our dispatch()
1319                 break;
1320
1321         case LFUN_WINDOW_CLOSE:
1322                 enable = d->views_.size() > 0;
1323                 break;
1324
1325         case LFUN_BUFFER_NEW:
1326         case LFUN_BUFFER_NEW_TEMPLATE:
1327         case LFUN_FILE_OPEN:
1328         case LFUN_HELP_OPEN:
1329         case LFUN_SCREEN_FONT_UPDATE:
1330         case LFUN_SET_COLOR:
1331         case LFUN_WINDOW_NEW:
1332         case LFUN_LYX_QUIT:
1333         case LFUN_LYXRC_APPLY:
1334         case LFUN_COMMAND_PREFIX:
1335         case LFUN_CANCEL:
1336         case LFUN_META_PREFIX:
1337         case LFUN_RECONFIGURE:
1338         case LFUN_SERVER_GET_FILENAME:
1339         case LFUN_SERVER_NOTIFY:
1340                 enable = true;
1341                 break;
1342
1343         case LFUN_BUFFER_FORALL: {
1344                 if (theBufferList().empty()) {
1345                         flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1346                         flag.setEnabled(false);
1347                         break;
1348                 }
1349
1350                 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1351                 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1352                         flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1353                         flag.setEnabled(false);
1354                 }
1355                 break;
1356         }
1357
1358         case LFUN_DIALOG_SHOW: {
1359                 string const name = cmd.getArg(0);
1360                 return name == "aboutlyx"
1361                         || name == "lyxfiles"
1362                         || name == "prefs"
1363                         || name == "texinfo"
1364                         || name == "progress"
1365                         || name == "compare";
1366         }
1367
1368         default:
1369                 return false;
1370         }
1371
1372         if (!enable)
1373                 flag.setEnabled(false);
1374         return true;
1375 }
1376
1377 /// make a post-dispatch status message
1378 static docstring makeDispatchMessage(docstring const & msg,
1379                                      FuncRequest const & cmd)
1380 {
1381         const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1382                               || cmd.origin() == FuncRequest::TOOLBAR
1383                               || cmd.origin() == FuncRequest::COMMANDBUFFER);
1384
1385         if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1386                 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1387                 return msg;
1388         }
1389
1390         docstring dispatch_msg = msg;
1391         if (!dispatch_msg.empty())
1392                 dispatch_msg += ' ';
1393
1394         docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1395
1396         bool argsadded = false;
1397
1398         if (!cmd.argument().empty()) {
1399                 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1400                         comname += ' ' + cmd.argument();
1401                         argsadded = true;
1402                 }
1403         }
1404         docstring const shortcuts = theTopLevelKeymap().
1405                 printBindings(cmd, KeySequence::ForGui);
1406
1407         if (!shortcuts.empty())
1408                 comname += ": " + shortcuts;
1409         else if (!argsadded && !cmd.argument().empty())
1410                 comname += ' ' + cmd.argument();
1411
1412         if (!comname.empty()) {
1413                 comname = rtrim(comname);
1414                 dispatch_msg += '(' + rtrim(comname) + ')';
1415         }
1416         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1417         return dispatch_msg;
1418 }
1419
1420
1421 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1422 {
1423         DispatchResult dr;
1424
1425         Buffer * buffer = 0;
1426         if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1427                 //setCurrentView(cmd.view_origin); //does not work
1428                 dr.setError(true);
1429                 dr.setMessage(_("Wrong focus!"));
1430                 d->dispatch_result_ = dr;
1431                 return d->dispatch_result_;
1432         }
1433         if (current_view_ && current_view_->currentBufferView()) {
1434                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1435                 buffer = &current_view_->currentBufferView()->buffer();
1436         }
1437
1438         dr.screenUpdate(Update::FitCursor);
1439         {
1440                 // This handles undo groups automagically
1441                 UndoGroupHelper ugh(buffer);
1442                 dispatch(cmd, dr);
1443                 // redraw the screen at the end (first of the two drawing steps).
1444                 // This is done unless explicitly requested otherwise.
1445                 // This code is kept inside the undo group because updateBuffer
1446                 // can create undo actions (see #11292)
1447                 updateCurrentView(cmd, dr);
1448         }
1449
1450         d->dispatch_result_ = dr;
1451         return d->dispatch_result_;
1452 }
1453
1454
1455 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1456 {
1457         if (!current_view_)
1458                 return;
1459
1460         BufferView * bv = current_view_->currentBufferView();
1461         if (bv) {
1462                 if (dr.needBufferUpdate()) {
1463                         bv->cursor().clearBufferUpdate();
1464                         bv->buffer().updateBuffer();
1465                 } else if (dr.needChangesUpdate()) {
1466                         // updateBuffer() already updates the change-tracking presence flag
1467                         bv->buffer().updateChangesPresent();
1468                 }
1469                 // BufferView::update() updates the ViewMetricsInfo and
1470                 // also initializes the position cache for all insets in
1471                 // (at least partially) visible top-level paragraphs.
1472                 // We will redraw the screen only if needed.
1473                 bv->processUpdateFlags(dr.screenUpdate());
1474
1475                 // Do we have a selection?
1476                 theSelection().haveSelection(bv->cursor().selection());
1477
1478                 // update gui
1479                 current_view_->restartCaret();
1480         }
1481         if (dr.needMessageUpdate()) {
1482                 // Some messages may already be translated, so we cannot use _()
1483                 current_view_->message(makeDispatchMessage(
1484                                 translateIfPossible(dr.message()), cmd));
1485         }
1486 }
1487
1488
1489 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1490         bool switchToBuffer)
1491 {
1492         if (!theSession().bookmarks().isValid(idx))
1493                 return;
1494         BookmarksSection::Bookmark const & bm =
1495                 theSession().bookmarks().bookmark(idx);
1496         LASSERT(!bm.filename.empty(), return);
1497         string const file = bm.filename.absFileName();
1498         // if the file is not opened, open it.
1499         if (!theBufferList().exists(bm.filename)) {
1500                 if (openFile)
1501                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1502                 else
1503                         return;
1504         }
1505         // open may fail, so we need to test it again
1506         if (!theBufferList().exists(bm.filename))
1507                 return;
1508
1509         // bm can be changed when saving
1510         BookmarksSection::Bookmark tmp = bm;
1511
1512         // Special case idx == 0 used for back-from-back jump navigation
1513         if (idx == 0)
1514                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1515
1516         // if the current buffer is not that one, switch to it.
1517         BufferView * doc_bv = current_view_ ?
1518                 current_view_->documentBufferView() : 0;
1519         Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1520         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1521                 if (switchToBuffer) {
1522                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1523                         if (!current_view_)
1524                                 return;
1525                         doc_bv = current_view_->documentBufferView();
1526                 } else
1527                         return;
1528         }
1529
1530         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1531         if (!doc_bv || !doc_bv->moveToPosition(
1532                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1533                 return;
1534
1535         Cursor & cur = doc_bv->cursor();
1536         if (old && cur != *old)
1537                 notifyCursorLeavesOrEnters(*old, cur);
1538
1539         // bm changed
1540         if (idx == 0)
1541                 return;
1542
1543         // Cursor jump succeeded!
1544         pit_type new_pit = cur.pit();
1545         pos_type new_pos = cur.pos();
1546         int new_id = cur.paragraph().id();
1547
1548         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1549         // see http://www.lyx.org/trac/ticket/3092
1550         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1551                 || bm.top_id != new_id) {
1552                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1553                         new_pit, new_pos, new_id);
1554         }
1555 }
1556
1557 // This function runs "configure" and then rereads lyx.defaults to
1558 // reconfigure the automatic settings.
1559 void GuiApplication::reconfigure(string const & option)
1560 {
1561         // emit message signal.
1562         if (current_view_)
1563                 current_view_->message(_("Running configure..."));
1564
1565         // Run configure in user lyx directory
1566         string const lock_file = package().getConfigureLockName();
1567         int fd = fileLock(lock_file.c_str());
1568         int const ret = package().reconfigureUserLyXDir(option);
1569         // emit message signal.
1570         if (current_view_)
1571                 current_view_->message(_("Reloading configuration..."));
1572         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1573         // Re-read packages.lst
1574         LaTeXPackages::getAvailable();
1575         fileUnlock(fd, lock_file.c_str());
1576
1577         if (ret)
1578                 Alert::information(_("System reconfiguration failed"),
1579                            _("The system reconfiguration has failed.\n"
1580                                   "Default textclass is used but LyX may\n"
1581                                   "not be able to work properly.\n"
1582                                   "Please reconfigure again if needed."));
1583         else
1584                 Alert::information(_("System reconfigured"),
1585                            _("The system has been reconfigured.\n"
1586                              "You need to restart LyX to make use of any\n"
1587                              "updated document class specifications."));
1588 }
1589
1590 void GuiApplication::validateCurrentView()
1591 {
1592         if (!d->views_.empty() && !current_view_) {
1593                 // currently at least one view exists but no view has the focus.
1594                 // choose the last view to make it current.
1595                 // a view without any open document is preferred.
1596                 GuiView * candidate = 0;
1597                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1598                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1599                 for (; it != end; ++it) {
1600                         candidate = *it;
1601                         if (!candidate->documentBufferView())
1602                                 break;
1603                 }
1604                 setCurrentView(candidate);
1605         }
1606 }
1607
1608 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1609 {
1610         string const argument = to_utf8(cmd.argument());
1611         FuncCode const action = cmd.action();
1612
1613         LYXERR(Debug::ACTION, "cmd: " << cmd);
1614
1615         // we have not done anything wrong yet.
1616         dr.setError(false);
1617
1618         FuncStatus const flag = getStatus(cmd);
1619         if (!flag.enabled()) {
1620                 // We cannot use this function here
1621                 LYXERR(Debug::ACTION, "action "
1622                        << lyxaction.getActionName(action)
1623                        << " [" << action << "] is disabled at this location");
1624                 dr.setMessage(flag.message());
1625                 dr.setError(true);
1626                 dr.dispatched(false);
1627                 dr.screenUpdate(Update::None);
1628                 dr.clearBufferUpdate();
1629                 return;
1630         };
1631
1632         if (cmd.origin() == FuncRequest::LYXSERVER) {
1633                 if (current_view_ && current_view_->currentBufferView())
1634                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1635                 // we will also need to redraw the screen at the end
1636                 dr.screenUpdate(Update::FitCursor);
1637         }
1638
1639         // Assumes that the action will be dispatched.
1640         dr.dispatched(true);
1641
1642         switch (cmd.action()) {
1643
1644         case LFUN_WINDOW_NEW:
1645                 createView(toqstr(cmd.argument()));
1646                 break;
1647
1648         case LFUN_WINDOW_CLOSE:
1649                 // update bookmark pit of the current buffer before window close
1650                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1651                         gotoBookmark(i+1, false, false);
1652                 // clear the last opened list, because
1653                 // maybe this will end the session
1654                 theSession().lastOpened().clear();
1655                 // check for valid current_view_
1656                 validateCurrentView();
1657                 if (current_view_)
1658                         current_view_->closeScheduled();
1659                 break;
1660
1661         case LFUN_LYX_QUIT:
1662                 // quitting is triggered by the gui code
1663                 // (leaving the event loop).
1664                 if (current_view_)
1665                         current_view_->message(from_utf8(N_("Exiting.")));
1666                 if (closeAllViews())
1667                         quit();
1668                 break;
1669
1670         case LFUN_SCREEN_FONT_UPDATE: {
1671                 // handle the screen font changes.
1672                 /* FIXME: this only updates the current document, whereas all
1673                  * documents should see their metrics updated.
1674                  */
1675                 d->font_loader_.update();
1676                 dr.screenUpdate(Update::Force | Update::FitCursor);
1677                 break;
1678         }
1679
1680         case LFUN_BUFFER_NEW:
1681                 validateCurrentView();
1682                 if (!current_view_
1683                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1684                         createView(QString(), false); // keep hidden
1685                         current_view_->newDocument(to_utf8(cmd.argument()));
1686                         current_view_->show();
1687                         setActiveWindow(current_view_);
1688                 } else {
1689                         current_view_->newDocument(to_utf8(cmd.argument()));
1690                 }
1691                 break;
1692
1693         case LFUN_BUFFER_NEW_TEMPLATE: {
1694                 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1695                 string const temp = cmd.getArg(1);
1696                 validateCurrentView();
1697                 if (!current_view_
1698                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1699                         createView();
1700                         current_view_->newDocument(file, temp, true);
1701                         if (!current_view_->documentBufferView())
1702                                 current_view_->close();
1703                 } else {
1704                         current_view_->newDocument(file, temp, true);
1705                 }
1706                 break;
1707         }
1708
1709         case LFUN_FILE_OPEN: {
1710                 // FIXME: normally the code below is not needed, since getStatus makes sure that
1711                 //   current_view_ is not null.
1712                 validateCurrentView();
1713                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1714                 string const fname = to_utf8(cmd.argument());
1715                 bool const is_open = FileName::isAbsolute(fname)
1716                         && theBufferList().getBuffer(FileName(fname));
1717                 if (!current_view_
1718                     || (!lyxrc.open_buffers_in_tabs
1719                         && current_view_->documentBufferView() != 0
1720                         && !is_open)) {
1721                         // We want the ui session to be saved per document and not per
1722                         // window number. The filename crc is a good enough identifier.
1723                         boost::crc_32_type crc;
1724                         crc = for_each(fname.begin(), fname.end(), crc);
1725                         createView(crc.checksum());
1726                         current_view_->openDocument(fname);
1727                         if (!current_view_->documentBufferView())
1728                                 current_view_->close();
1729                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1730                                 current_view_->raise();
1731                                 current_view_->activateWindow();
1732                                 current_view_->showNormal();
1733                         }
1734                 } else {
1735                         current_view_->openDocument(fname);
1736                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1737                                 current_view_->raise();
1738                                 current_view_->activateWindow();
1739                                 current_view_->showNormal();
1740                         }
1741                 }
1742                 break;
1743         }
1744
1745         case LFUN_HELP_OPEN: {
1746                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1747                 if (current_view_ == 0)
1748                         createView();
1749                 string const arg = to_utf8(cmd.argument());
1750                 if (arg.empty()) {
1751                         current_view_->message(_("Missing argument"));
1752                         break;
1753                 }
1754                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1755                 if (fname.empty())
1756                         fname = i18nLibFileSearch("examples", arg, "lyx");
1757
1758                 if (fname.empty()) {
1759                         lyxerr << "LyX: unable to find documentation file `"
1760                                << arg << "'. Bad installation?" << endl;
1761                         break;
1762                 }
1763                 current_view_->message(bformat(_("Opening help file %1$s..."),
1764                                                makeDisplayPath(fname.absFileName())));
1765                 Buffer * buf = current_view_->loadDocument(fname, false);
1766                 if (buf)
1767                         buf->setReadonly(!current_view_->develMode());
1768                 break;
1769         }
1770
1771         case LFUN_SET_COLOR: {
1772                 string const lyx_name = cmd.getArg(0);
1773                 string const x11_name = cmd.getArg(1);
1774                 if (lyx_name.empty() || x11_name.empty()) {
1775                         if (current_view_)
1776                                 current_view_->message(
1777                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1778                         break;
1779                 }
1780
1781 #if 0
1782                 // FIXME: The graphics cache no longer has a changeDisplay method.
1783                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1784                 bool const graphicsbg_changed =
1785                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1786                 if (graphicsbg_changed)
1787                         graphics::GCache::get().changeDisplay(true);
1788 #endif
1789
1790                 if (!lcolor.setColor(lyx_name, x11_name)) {
1791                         if (current_view_)
1792                                 current_view_->message(
1793                                         bformat(_("Set-color \"%1$s\" failed "
1794                                         "- color is undefined or "
1795                                         "may not be redefined"),
1796                                         from_utf8(lyx_name)));
1797                         break;
1798                 }
1799                 // Make sure we don't keep old colors in cache.
1800                 d->color_cache_.clear();
1801                 // Update the current view
1802                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1803                 break;
1804         }
1805
1806         case LFUN_LYXRC_APPLY: {
1807                 // reset active key sequences, since the bindings
1808                 // are updated (bug 6064)
1809                 d->keyseq.reset();
1810                 LyXRC const lyxrc_orig = lyxrc;
1811
1812                 istringstream ss(to_utf8(cmd.argument()));
1813                 bool const success = lyxrc.read(ss);
1814
1815                 if (!success) {
1816                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1817                                         << "Unable to read lyxrc data"
1818                                         << endl;
1819                         break;
1820                 }
1821
1822                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1823
1824                 // If the request comes from the minibuffer, then we can't reset
1825                 // the GUI, since that would destory the minibuffer itself and
1826                 // cause a crash, since we are currently in one of the methods of
1827                 // GuiCommandBuffer. See bug #8540.
1828                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1829                         resetGui();
1830                 // else
1831                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1832                 //   reset the GUI in this case. If the changes to lyxrc affected the
1833                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1834                 //   it definitely is a bug.
1835
1836                 dr.forceBufferUpdate();
1837                 break;
1838         }
1839
1840         case LFUN_COMMAND_PREFIX:
1841                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1842                 break;
1843
1844         case LFUN_CANCEL: {
1845                 d->keyseq.reset();
1846                 d->meta_fake_bit = NoModifier;
1847                 GuiView * gv = currentView();
1848                 if (gv && gv->currentBufferView())
1849                         // cancel any selection
1850                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1851                 dr.setMessage(from_ascii(N_("Cancel")));
1852                 break;
1853         }
1854         case LFUN_META_PREFIX:
1855                 d->meta_fake_bit = AltModifier;
1856                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1857                 break;
1858
1859         // --- Menus -----------------------------------------------
1860         case LFUN_RECONFIGURE:
1861                 // argument is any additional parameter to the configure.py command
1862                 reconfigure(to_utf8(cmd.argument()));
1863                 break;
1864
1865         // --- lyxserver commands ----------------------------
1866         case LFUN_SERVER_GET_FILENAME: {
1867                 if (current_view_ && current_view_->documentBufferView()) {
1868                         docstring const fname = from_utf8(
1869                                 current_view_->documentBufferView()->buffer().absFileName());
1870                         dr.setMessage(fname);
1871                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1872                 } else {
1873                         dr.setMessage(docstring());
1874                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1875                 }
1876                 break;
1877         }
1878
1879         case LFUN_SERVER_NOTIFY: {
1880                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1881                 dr.setMessage(dispatch_buffer);
1882                 theServer().notifyClient(to_utf8(dispatch_buffer));
1883                 break;
1884         }
1885
1886         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1887                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1888                 break;
1889
1890         // --- syntax commands ----------------------------
1891         case LFUN_REPEAT: {
1892                 // repeat command
1893                 string countstr;
1894                 string rest = split(argument, countstr, ' ');
1895                 int const count = convert<int>(countstr);
1896                 // an arbitrary number to limit number of iterations
1897                 int const max_iter = 10000;
1898                 if (count > max_iter) {
1899                         dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1900                         dr.setError(true);
1901                 } else {
1902                         for (int i = 0; i < count; ++i) {
1903                                 FuncRequest lfun = lyxaction.lookupFunc(rest);
1904                                 lfun.allowAsync(false);
1905                                 dispatch(lfun);
1906                         }
1907                 }
1908                 break;
1909         }
1910
1911         case LFUN_COMMAND_SEQUENCE: {
1912                 // argument contains ';'-terminated commands
1913                 string arg = argument;
1914                 // FIXME: this LFUN should also work without any view.
1915                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1916                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1917                 // This handles undo groups automagically
1918                 UndoGroupHelper ugh(buffer);
1919                 while (!arg.empty()) {
1920                         string first;
1921                         arg = split(arg, first, ';');
1922                         FuncRequest func(lyxaction.lookupFunc(first));
1923                         func.allowAsync(false);
1924                         func.setOrigin(cmd.origin());
1925                         dispatch(func);
1926                 }
1927                 break;
1928         }
1929
1930         case LFUN_BUFFER_FORALL: {
1931                 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1932                 funcToRun.allowAsync(false);
1933
1934                 map<Buffer *, GuiView *> views_lVisible;
1935                 map<GuiView *, Buffer *> activeBuffers;
1936
1937                 QList<GuiView *> allViews = d->views_.values();
1938
1939                 // this for does not modify any buffer. It just collects info on local
1940                 // visibility of buffers and on which buffer is active in each view.
1941                 Buffer * const last = theBufferList().last();
1942                 for(GuiView * view : allViews) {
1943                         // all of the buffers might be locally hidden. That is, there is no
1944                         // active buffer.
1945                         if (!view || !view->currentBufferView())
1946                                 activeBuffers[view] = 0;
1947                         else
1948                                 activeBuffers[view] = &view->currentBufferView()->buffer();
1949
1950                         // find out if each is locally visible or locally hidden.
1951                         // we don't use a for loop as the buffer list cycles.
1952                         Buffer * b = theBufferList().first();
1953                         while (true) {
1954                                 bool const locallyVisible = view && view->workArea(*b);
1955                                 if (locallyVisible) {
1956                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1957                                         // only need to overwrite/add if we don't already know a buffer is globally
1958                                         // visible or we do know but we would prefer to dispatch LFUN from the
1959                                         // current view because of cursor position issues.
1960                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1961                                                 views_lVisible[b] = view;
1962                                 }
1963                                 if (b == last)
1964                                         break;
1965                                 b = theBufferList().next(b);
1966                         }
1967                 }
1968
1969                 GuiView * const homeView = currentView();
1970                 Buffer * b = theBufferList().first();
1971                 Buffer * nextBuf = 0;
1972                 int numProcessed = 0;
1973                 while (true) {
1974                         if (b != last)
1975                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1976
1977                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1978                         if (visible) {
1979                                 // first change to a view where b is locally visible, preferably current_view_.
1980                                 GuiView * const vLv = views_lVisible[b];
1981                                 vLv->setBuffer(b);
1982                                 lyx::dispatch(funcToRun);
1983                                 numProcessed++;
1984                         }
1985                         if (b == last)
1986                                 break;
1987                         b = nextBuf;
1988                 }
1989
1990                 // put things back to how they were (if possible).
1991                 for (GuiView * view : allViews) {
1992                         Buffer * originalBuf = activeBuffers[view];
1993                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1994                         if (theBufferList().isLoaded(originalBuf))
1995                                 view->setBuffer(originalBuf);
1996                 }
1997                 homeView->setFocus();
1998
1999                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2000                 break;
2001         }
2002
2003         case LFUN_COMMAND_ALTERNATIVES: {
2004                 // argument contains ';'-terminated commands
2005                 string arg = argument;
2006                 while (!arg.empty()) {
2007                         string first;
2008                         arg = split(arg, first, ';');
2009                         FuncRequest func(lyxaction.lookupFunc(first));
2010                         func.setOrigin(cmd.origin());
2011                         FuncStatus const stat = getStatus(func);
2012                         if (stat.enabled()) {
2013                                 dispatch(func);
2014                                 break;
2015                         }
2016                 }
2017                 break;
2018         }
2019
2020         case LFUN_CALL: {
2021                 FuncRequest func;
2022                 if (theTopLevelCmdDef().lock(argument, func)) {
2023                         func.setOrigin(cmd.origin());
2024                         dispatch(func);
2025                         theTopLevelCmdDef().release(argument);
2026                 } else {
2027                         if (func.action() == LFUN_UNKNOWN_ACTION) {
2028                                 // unknown command definition
2029                                 lyxerr << "Warning: unknown command definition `"
2030                                                 << argument << "'"
2031                                                 << endl;
2032                         } else {
2033                                 // recursion detected
2034                                 lyxerr << "Warning: Recursion in the command definition `"
2035                                                 << argument << "' detected"
2036                                                 << endl;
2037                         }
2038                 }
2039                 break;
2040         }
2041
2042         case LFUN_BIDI: {
2043                 string const lfun = cmd.getLongArg(1);
2044                 FuncRequest func(lyxaction.lookupFunc(cmd.getLongArg(1)));
2045                 func.setOrigin(cmd.origin());
2046                 FuncStatus const stat = getStatus(func);
2047                 if (stat.enabled()) {
2048                         dispatch(func);
2049                         break;
2050                 }
2051                 break;
2052         }
2053
2054         case LFUN_PREFERENCES_SAVE:
2055                 lyxrc.write(support::makeAbsPath("preferences",
2056                         package().user_support().absFileName()), false);
2057                 break;
2058
2059         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2060                 string const fname = addName(addPath(package().user_support().absFileName(),
2061                         "templates/"), "defaults.lyx");
2062                 Buffer defaults(fname);
2063
2064                 istringstream ss(argument);
2065                 Lexer lex;
2066                 lex.setStream(ss);
2067
2068                 // See #9236
2069                 // We need to make sure that, after we recreat the DocumentClass,
2070                 // which we do in readHeader, we apply it to the document itself.
2071                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2072                 int const unknown_tokens = defaults.readHeader(lex);
2073                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2074                 ErrorList el;
2075                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2076                 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2077
2078                 if (unknown_tokens != 0) {
2079                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2080                                << unknown_tokens << " unknown token"
2081                                << (unknown_tokens == 1 ? "" : "s")
2082                                << endl;
2083                 }
2084
2085                 if (defaults.writeFile(FileName(defaults.absFileName())))
2086                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2087                                               makeDisplayPath(fname)));
2088                 else {
2089                         dr.setError(true);
2090                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2091                 }
2092                 break;
2093         }
2094
2095         case LFUN_BOOKMARK_GOTO:
2096                 // go to bookmark, open unopened file and switch to buffer if necessary
2097                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2098                 dr.screenUpdate(Update::Force | Update::FitCursor);
2099                 break;
2100
2101         case LFUN_BOOKMARK_CLEAR:
2102                 theSession().bookmarks().clear();
2103                 break;
2104
2105         case LFUN_DEBUG_LEVEL_SET:
2106                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2107                 break;
2108
2109         case LFUN_DIALOG_SHOW: {
2110                 string const name = cmd.getArg(0);
2111
2112                 if ( name == "aboutlyx"
2113                         || name == "prefs"
2114                         || name == "texinfo"
2115                         || name == "progress"
2116                         || name == "compare")
2117                 {
2118                         // work around: on Mac OS the application
2119                         // is not terminated when closing the last view.
2120                         // Create a new one to be able to dispatch the
2121                         // LFUN_DIALOG_SHOW to this view.
2122                         if (current_view_ == 0)
2123                                 createView();
2124                 }
2125         }
2126         // fall through
2127         default:
2128                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2129                 // let's try that:
2130                 if (current_view_)
2131                         current_view_->dispatch(cmd, dr);
2132                 break;
2133         }
2134
2135         if (cmd.origin() == FuncRequest::LYXSERVER)
2136                 updateCurrentView(cmd, dr);
2137 }
2138
2139
2140 docstring GuiApplication::viewStatusMessage()
2141 {
2142         // When meta-fake key is pressed, show the key sequence so far + "M-".
2143         if (d->meta_fake_bit != NoModifier)
2144                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2145
2146         // Else, when a non-complete key sequence is pressed,
2147         // show the available options.
2148         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2149                 return d->keyseq.printOptions(true);
2150
2151         return docstring();
2152 }
2153
2154
2155 string GuiApplication::inputLanguageCode() const
2156 {
2157 #if (QT_VERSION < 0x050000)
2158         QLocale loc = keyboardInputLocale();
2159 #else
2160         QLocale loc = inputMethod()->locale();
2161 #endif
2162         //LYXERR0("input lang = " << fromqstr(loc.name()));
2163         return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2164 }
2165
2166
2167 void GuiApplication::onLocaleChanged()
2168 {
2169         //LYXERR0("Change language to " << inputLanguage()->lang());
2170         if (currentView() && currentView()->currentBufferView())
2171                 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2172 }
2173
2174
2175 void GuiApplication::handleKeyFunc(FuncCode action)
2176 {
2177         char_type c = 0;
2178
2179         if (d->keyseq.length())
2180                 c = 0;
2181         GuiView * gv = currentView();
2182         LASSERT(gv && gv->currentBufferView(), return);
2183         BufferView * bv = gv->currentBufferView();
2184         bv->getIntl().getTransManager().deadkey(
2185                 c, get_accent(action).accent, bv->cursor().innerText(),
2186                 bv->cursor());
2187         // Need to clear, in case the minibuffer calls these
2188         // actions
2189         d->keyseq.clear();
2190         // copied verbatim from do_accent_char
2191         bv->cursor().resetAnchor();
2192 }
2193
2194
2195 //Keep this in sync with GuiApplication::processKeySym below
2196 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2197                                  KeyModifier state) const
2198 {
2199         // Do nothing if we have nothing
2200         if (!keysym.isOK() || keysym.isModifier())
2201                 return false;
2202         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2203         KeySequence seq;
2204         FuncRequest func = seq.addkey(keysym, state);
2205         // When not cancel or meta-fake, do the normal lookup.
2206         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2207                 seq = d->keyseq;
2208                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2209         }
2210         // Maybe user can only reach the key via holding down shift.
2211         // Let's see. But only if shift is the only modifier
2212         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2213                 // If addkey looked up a command and did not find further commands then
2214                 // seq has been reset at this point
2215                 func = seq.addkey(keysym, NoModifier);
2216
2217         LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2218                << seq.print(KeySequence::Portable) << ']');
2219         return func.action() != LFUN_UNKNOWN_ACTION;
2220 }
2221
2222
2223 //Keep this in sync with GuiApplication::queryKeySym above
2224 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2225 {
2226         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2227
2228         // Do nothing if we have nothing (JMarc)
2229         if (!keysym.isOK() || keysym.isModifier()) {
2230                 if (!keysym.isOK())
2231                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2232                 if (current_view_)
2233                         current_view_->restartCaret();
2234                 return;
2235         }
2236
2237         char_type encoded_last_key = keysym.getUCSEncoded();
2238
2239         // Do a one-deep top-level lookup for
2240         // cancel and meta-fake keys. RVDK_PATCH_5
2241         d->cancel_meta_seq.reset();
2242
2243         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2244         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2245
2246         // When not cancel or meta-fake, do the normal lookup.
2247         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2248         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2249         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2250                 // remove Caps Lock and Mod2 as a modifiers
2251                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2252                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2253         }
2254
2255         // Dont remove this unless you know what you are doing.
2256         d->meta_fake_bit = NoModifier;
2257
2258         // Can this happen now ?
2259         if (func.action() == LFUN_NOACTION)
2260                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2261
2262         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2263                 << d->keyseq.print(KeySequence::Portable) << ']');
2264
2265         // already here we know if it any point in going further
2266         // why not return already here if action == -1 and
2267         // num_bytes == 0? (Lgb)
2268
2269         if (d->keyseq.length() > 1 && current_view_)
2270                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2271
2272
2273         // Maybe user can only reach the key via holding down shift.
2274         // Let's see. But only if shift is the only modifier
2275         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2276                 LYXERR(Debug::KEY, "Trying without shift");
2277                 // If addkey looked up a command and did not find further commands then
2278                 // seq has been reset at this point
2279                 func = d->keyseq.addkey(keysym, NoModifier);
2280                 LYXERR(Debug::KEY, "Action now " << func.action());
2281         }
2282
2283         if (func.action() == LFUN_UNKNOWN_ACTION) {
2284                 // We didn't match any of the key sequences.
2285                 // See if it's normal insertable text not already
2286                 // covered by a binding
2287                 if (keysym.isText() && d->keyseq.length() == 1) {
2288                         // Non-printable characters (such as ASCII control characters)
2289                         // must not be inserted (#5704)
2290                         if (!isPrintable(encoded_last_key)) {
2291                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2292                                 if (current_view_)
2293                                         current_view_->restartCaret();
2294                                 return;
2295                         }
2296                         // The following modifier check is not needed on Mac.
2297                         // The keysym is either not text or it is different
2298                         // from the non-modifier keysym. See #9875 for the
2299                         // broken alt-modifier effect of having this code active.
2300 #if !defined(Q_OS_MAC)
2301                         // If a non-Shift Modifier is used we have a non-bound key sequence
2302                         // (such as Alt+j = j). This should be omitted (#5575).
2303                         // On Windows, AltModifier and ControlModifier are both
2304                         // set when AltGr is pressed. Therefore, in order to not
2305                         // break AltGr-bound symbols (see #5575 for details),
2306                         // unbound Ctrl+Alt key sequences are allowed.
2307                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2308 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2309                             && !(state & AltModifier && state & ControlModifier)
2310 #endif
2311                             )
2312                         {
2313                                 if (current_view_) {
2314                                         current_view_->message(_("Unknown function."));
2315                                         current_view_->restartCaret();
2316                                 }
2317                                 return;
2318                         }
2319 #endif
2320                         // Since all checks above were passed, we now really have text that
2321                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2322                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2323                         // below.
2324                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2325                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2326                 } else {
2327                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2328                         if (current_view_) {
2329                                 current_view_->message(_("Unknown function."));
2330                                 current_view_->restartCaret();
2331                         }
2332                         return;
2333                 }
2334         }
2335
2336         if (func.action() == LFUN_SELF_INSERT) {
2337                 if (encoded_last_key != 0) {
2338                         docstring const arg(1, encoded_last_key);
2339                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2340                                              FuncRequest::KEYBOARD));
2341                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2342                 }
2343         } else
2344                 processFuncRequest(func);
2345 }
2346
2347
2348 void GuiApplication::processFuncRequest(FuncRequest const & func)
2349 {
2350         lyx::dispatch(func);
2351 }
2352
2353
2354 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2355 {
2356         addToFuncRequestQueue(func);
2357         processFuncRequestQueueAsync();
2358 }
2359
2360
2361 void GuiApplication::processFuncRequestQueue()
2362 {
2363         while (!d->func_request_queue_.empty()) {
2364                 // take the item from the stack _before_ processing the
2365                 // request in order to avoid race conditions from nested
2366                 // or parallel requests (see #10406)
2367                 FuncRequest const fr(d->func_request_queue_.front());
2368                 d->func_request_queue_.pop();
2369                 processFuncRequest(fr);
2370         }
2371 }
2372
2373
2374 void GuiApplication::processFuncRequestQueueAsync()
2375 {
2376         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2377 }
2378
2379
2380 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2381 {
2382         d->func_request_queue_.push(func);
2383 }
2384
2385
2386 void GuiApplication::resetGui()
2387 {
2388         // Set the language defined by the user.
2389         setGuiLanguage();
2390
2391         // Read menus
2392         if (!readUIFile(toqstr(lyxrc.ui_file)))
2393                 // Gives some error box here.
2394                 return;
2395
2396         if (d->global_menubar_)
2397                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2398
2399         QHash<int, GuiView *>::iterator it;
2400         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2401                 GuiView * gv = *it;
2402                 setCurrentView(gv);
2403                 gv->setLayoutDirection(layoutDirection());
2404                 gv->resetDialogs();
2405         }
2406
2407         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
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                                 xcb_selection_notify_event_t nev;
3333                                 nev.response_type = XCB_SELECTION_NOTIFY;
3334                                 nev.requestor = srev->requestor;
3335                                 nev.selection = srev->selection;
3336                                 nev.target = srev->target;
3337                                 nev.property = XCB_NONE;
3338                                 nev.time = XCB_CURRENT_TIME;
3339                                 xcb_connection_t * con = QX11Info::connection();
3340                                 xcb_send_event(con, 0, srev->requestor,
3341                                         XCB_EVENT_MASK_NO_EVENT,
3342                                         reinterpret_cast<char const *>(&nev));
3343                                 xcb_flush(con);
3344 #endif
3345                                 return true;
3346                         }
3347                 }
3348                 break;
3349         }
3350         case XCB_SELECTION_CLEAR: {
3351                 xcb_selection_clear_event_t * scev =
3352                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3353                 if (scev->selection != XCB_ATOM_PRIMARY)
3354                         break;
3355                 LYXERR(Debug::SELECTION, "Lost selection.");
3356                 BufferView * bv = current_view_->currentBufferView();
3357                 if (bv)
3358                         bv->clearSelection();
3359                 break;
3360         }
3361         }
3362         return false;
3363 }
3364 #endif
3365
3366 } // namespace frontend
3367
3368
3369 void hideDialogs(std::string const & name, Inset * inset)
3370 {
3371         if (theApp())
3372                 frontend::guiApp->hideDialogs(name, inset);
3373 }
3374
3375
3376 ////////////////////////////////////////////////////////////////////
3377 //
3378 // Font stuff
3379 //
3380 ////////////////////////////////////////////////////////////////////
3381
3382 frontend::FontLoader & theFontLoader()
3383 {
3384         LAPPERR(frontend::guiApp);
3385         return frontend::guiApp->fontLoader();
3386 }
3387
3388
3389 frontend::FontMetrics const & theFontMetrics(Font const & f)
3390 {
3391         return theFontMetrics(f.fontInfo());
3392 }
3393
3394
3395 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3396 {
3397         LAPPERR(frontend::guiApp);
3398         return frontend::guiApp->fontLoader().metrics(f);
3399 }
3400
3401
3402 ////////////////////////////////////////////////////////////////////
3403 //
3404 // Misc stuff
3405 //
3406 ////////////////////////////////////////////////////////////////////
3407
3408 frontend::Clipboard & theClipboard()
3409 {
3410         LAPPERR(frontend::guiApp);
3411         return frontend::guiApp->clipboard();
3412 }
3413
3414
3415 frontend::Selection & theSelection()
3416 {
3417         LAPPERR(frontend::guiApp);
3418         return frontend::guiApp->selection();
3419 }
3420
3421
3422 } // namespace lyx
3423
3424 #include "moc_GuiApplication.cpp"