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