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