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