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