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