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