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