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