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