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