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