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