]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
FindAdv: Comments
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "ColorSet.h"
20 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
23 #include "GuiView.h"
24 #include "Menus.h"
25 #include "qt_helpers.h"
26 #include "Toolbars.h"
27
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
32
33 #include "Buffer.h"
34 #include "BufferList.h"
35 #include "BufferParams.h"
36 #include "BufferView.h"
37 #include "CmdDef.h"
38 #include "Color.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
42 #include "Font.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
46 #include "Intl.h"
47 #include "KeyMap.h"
48 #include "Language.h"
49 #include "LaTeXPackages.h"
50 #include "Lexer.h"
51 #include "LyX.h"
52 #include "LyXAction.h"
53 #include "LyXRC.h"
54 #include "Paragraph.h"
55 #include "Server.h"
56 #include "Session.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
59 #include "version.h"
60
61 #include "insets/InsetText.h"
62
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
78
79 #ifdef Q_OS_MAC
80 #include "support/AppleScript.h"
81 #include "support/linkback/LinkBackProxy.h"
82 #endif
83
84 #include <queue>
85
86 #include <QByteArray>
87 #include <QDateTime>
88 #include <QDesktopWidget>
89 #include <QDir>
90 #include <QEvent>
91 #include <QFileOpenEvent>
92 #include <QFileInfo>
93 #include <QFontDatabase>
94 #include <QHash>
95 #include <QIcon>
96 #include <QImageReader>
97 #include <QKeyEvent>
98 #include <QLocale>
99 #include <QLibraryInfo>
100 #include <QList>
101 #include <QMenuBar>
102 #include <QMimeData>
103 #include <QObject>
104 #include <QPixmap>
105 #include <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                 // redraw the screen at the end (first of the two drawing steps).
1416                 // This is done unless explicitly requested otherwise.
1417                 // This code is kept inside the undo group because updateBuffer
1418                 // can create undo actions (see #11292)
1419                 updateCurrentView(cmd, dr);
1420         }
1421
1422         d->dispatch_result_ = dr;
1423         return d->dispatch_result_;
1424 }
1425
1426
1427 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1428 {
1429         if (!current_view_)
1430                 return;
1431
1432         BufferView * bv = current_view_->currentBufferView();
1433         if (bv) {
1434                 if (dr.needBufferUpdate()) {
1435                         bv->cursor().clearBufferUpdate();
1436                         bv->buffer().updateBuffer();
1437                 } else if (dr.needChangesUpdate()) {
1438                         // updateBuffer() already updates the change-tracking presence flag
1439                         bv->buffer().updateChangesPresent();
1440                 }
1441                 // BufferView::update() updates the ViewMetricsInfo and
1442                 // also initializes the position cache for all insets in
1443                 // (at least partially) visible top-level paragraphs.
1444                 // We will redraw the screen only if needed.
1445                 bv->processUpdateFlags(dr.screenUpdate());
1446
1447                 // Do we have a selection?
1448                 theSelection().haveSelection(bv->cursor().selection());
1449
1450                 // update gui
1451                 current_view_->restartCaret();
1452         }
1453         if (dr.needMessageUpdate()) {
1454                 // Some messages may already be translated, so we cannot use _()
1455                 current_view_->message(makeDispatchMessage(
1456                                 translateIfPossible(dr.message()), cmd));
1457         }
1458 }
1459
1460
1461 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1462         bool switchToBuffer)
1463 {
1464         if (!theSession().bookmarks().isValid(idx))
1465                 return;
1466         BookmarksSection::Bookmark const & bm =
1467                 theSession().bookmarks().bookmark(idx);
1468         LASSERT(!bm.filename.empty(), return);
1469         string const file = bm.filename.absFileName();
1470         // if the file is not opened, open it.
1471         if (!theBufferList().exists(bm.filename)) {
1472                 if (openFile)
1473                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1474                 else
1475                         return;
1476         }
1477         // open may fail, so we need to test it again
1478         if (!theBufferList().exists(bm.filename))
1479                 return;
1480
1481         // bm can be changed when saving
1482         BookmarksSection::Bookmark tmp = bm;
1483
1484         // Special case idx == 0 used for back-from-back jump navigation
1485         if (idx == 0)
1486                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1487
1488         // if the current buffer is not that one, switch to it.
1489         BufferView * doc_bv = current_view_ ?
1490                 current_view_->documentBufferView() : 0;
1491         Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1492         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1493                 if (switchToBuffer) {
1494                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1495                         if (!current_view_)
1496                                 return;
1497                         doc_bv = current_view_->documentBufferView();
1498                 } else
1499                         return;
1500         }
1501
1502         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1503         if (!doc_bv || !doc_bv->moveToPosition(
1504                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1505                 return;
1506
1507         Cursor & cur = doc_bv->cursor();
1508         if (old && cur != *old)
1509                 notifyCursorLeavesOrEnters(*old, cur);
1510
1511         // bm changed
1512         if (idx == 0)
1513                 return;
1514
1515         // Cursor jump succeeded!
1516         pit_type new_pit = cur.pit();
1517         pos_type new_pos = cur.pos();
1518         int new_id = cur.paragraph().id();
1519
1520         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1521         // see http://www.lyx.org/trac/ticket/3092
1522         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1523                 || bm.top_id != new_id) {
1524                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1525                         new_pit, new_pos, new_id);
1526         }
1527 }
1528
1529 // This function runs "configure" and then rereads lyx.defaults to
1530 // reconfigure the automatic settings.
1531 void GuiApplication::reconfigure(string const & option)
1532 {
1533         // emit message signal.
1534         if (current_view_)
1535                 current_view_->message(_("Running configure..."));
1536
1537         // Run configure in user lyx directory
1538         string const lock_file = package().getConfigureLockName();
1539         int fd = fileLock(lock_file.c_str());
1540         int const ret = package().reconfigureUserLyXDir(option);
1541         // emit message signal.
1542         if (current_view_)
1543                 current_view_->message(_("Reloading configuration..."));
1544         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1545         // Re-read packages.lst
1546         LaTeXPackages::getAvailable();
1547         fileUnlock(fd, lock_file.c_str());
1548
1549         if (ret)
1550                 Alert::information(_("System reconfiguration failed"),
1551                            _("The system reconfiguration has failed.\n"
1552                                   "Default textclass is used but LyX may\n"
1553                                   "not be able to work properly.\n"
1554                                   "Please reconfigure again if needed."));
1555         else
1556                 Alert::information(_("System reconfigured"),
1557                            _("The system has been reconfigured.\n"
1558                              "You need to restart LyX to make use of any\n"
1559                              "updated document class specifications."));
1560 }
1561
1562 void GuiApplication::validateCurrentView()
1563 {
1564         if (!d->views_.empty() && !current_view_) {
1565                 // currently at least one view exists but no view has the focus.
1566                 // choose the last view to make it current.
1567                 // a view without any open document is preferred.
1568                 GuiView * candidate = 0;
1569                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1570                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1571                 for (; it != end; ++it) {
1572                         candidate = *it;
1573                         if (!candidate->documentBufferView())
1574                                 break;
1575                 }
1576                 setCurrentView(candidate);
1577         }
1578 }
1579
1580 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1581 {
1582         string const argument = to_utf8(cmd.argument());
1583         FuncCode const action = cmd.action();
1584
1585         LYXERR(Debug::ACTION, "cmd: " << cmd);
1586
1587         // we have not done anything wrong yet.
1588         dr.setError(false);
1589
1590         FuncStatus const flag = getStatus(cmd);
1591         if (!flag.enabled()) {
1592                 // We cannot use this function here
1593                 LYXERR(Debug::ACTION, "action "
1594                        << lyxaction.getActionName(action)
1595                        << " [" << action << "] is disabled at this location");
1596                 dr.setMessage(flag.message());
1597                 dr.setError(true);
1598                 dr.dispatched(false);
1599                 dr.screenUpdate(Update::None);
1600                 dr.clearBufferUpdate();
1601                 return;
1602         };
1603
1604         if (cmd.origin() == FuncRequest::LYXSERVER) {
1605                 if (current_view_ && current_view_->currentBufferView())
1606                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1607                 // we will also need to redraw the screen at the end
1608                 dr.screenUpdate(Update::FitCursor);
1609         }
1610
1611         // Assumes that the action will be dispatched.
1612         dr.dispatched(true);
1613
1614         switch (cmd.action()) {
1615
1616         case LFUN_WINDOW_NEW:
1617                 createView(toqstr(cmd.argument()));
1618                 break;
1619
1620         case LFUN_WINDOW_CLOSE:
1621                 // update bookmark pit of the current buffer before window close
1622                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1623                         gotoBookmark(i+1, false, false);
1624                 // clear the last opened list, because
1625                 // maybe this will end the session
1626                 theSession().lastOpened().clear();
1627                 // check for valid current_view_
1628                 validateCurrentView();
1629                 if (current_view_)
1630                         current_view_->closeScheduled();
1631                 break;
1632
1633         case LFUN_LYX_QUIT:
1634                 // quitting is triggered by the gui code
1635                 // (leaving the event loop).
1636                 if (current_view_)
1637                         current_view_->message(from_utf8(N_("Exiting.")));
1638                 if (closeAllViews())
1639                         quit();
1640                 break;
1641
1642         case LFUN_SCREEN_FONT_UPDATE: {
1643                 // handle the screen font changes.
1644                 d->font_loader_.update();
1645                 dr.screenUpdate(Update::Force | Update::FitCursor);
1646                 break;
1647         }
1648
1649         case LFUN_BUFFER_NEW:
1650                 validateCurrentView();
1651                 if (!current_view_
1652                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1653                         createView(QString(), false); // keep hidden
1654                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1655                         current_view_->show();
1656                         setActiveWindow(current_view_);
1657                 } else {
1658                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1659                 }
1660                 break;
1661
1662         case LFUN_BUFFER_NEW_TEMPLATE:
1663                 validateCurrentView();
1664                 if (!current_view_
1665                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1666                         createView();
1667                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1668                         if (!current_view_->documentBufferView())
1669                                 current_view_->close();
1670                 } else {
1671                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1672                 }
1673                 break;
1674
1675         case LFUN_FILE_OPEN: {
1676                 // FIXME: normally the code below is not needed, since getStatus makes sure that
1677                 //   current_view_ is not null.
1678                 validateCurrentView();
1679                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1680                 string const fname = to_utf8(cmd.argument());
1681                 bool const is_open = FileName::isAbsolute(fname)
1682                         && theBufferList().getBuffer(FileName(fname));
1683                 if (!current_view_
1684                     || (!lyxrc.open_buffers_in_tabs
1685                         && current_view_->documentBufferView() != 0
1686                         && !is_open)) {
1687                         // We want the ui session to be saved per document and not per
1688                         // window number. The filename crc is a good enough identifier.
1689                         boost::crc_32_type crc;
1690                         crc = for_each(fname.begin(), fname.end(), crc);
1691                         createView(crc.checksum());
1692                         current_view_->openDocument(fname);
1693                         if (!current_view_->documentBufferView())
1694                                 current_view_->close();
1695                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1696                                 current_view_->raise();
1697                                 current_view_->activateWindow();
1698                                 current_view_->showNormal();
1699                         }
1700                 } else {
1701                         current_view_->openDocument(fname);
1702                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1703                                 current_view_->raise();
1704                                 current_view_->activateWindow();
1705                                 current_view_->showNormal();
1706                         }
1707                 }
1708                 break;
1709         }
1710
1711         case LFUN_HELP_OPEN: {
1712                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1713                 if (current_view_ == 0)
1714                         createView();
1715                 string const arg = to_utf8(cmd.argument());
1716                 if (arg.empty()) {
1717                         current_view_->message(_("Missing argument"));
1718                         break;
1719                 }
1720                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1721                 if (fname.empty())
1722                         fname = i18nLibFileSearch("examples", arg, "lyx");
1723
1724                 if (fname.empty()) {
1725                         lyxerr << "LyX: unable to find documentation file `"
1726                                << arg << "'. Bad installation?" << endl;
1727                         break;
1728                 }
1729                 current_view_->message(bformat(_("Opening help file %1$s..."),
1730                                                makeDisplayPath(fname.absFileName())));
1731                 Buffer * buf = current_view_->loadDocument(fname, false);
1732                 if (buf)
1733                         buf->setReadonly(!current_view_->develMode());
1734                 break;
1735         }
1736
1737         case LFUN_SET_COLOR: {
1738                 string const lyx_name = cmd.getArg(0);
1739                 string const x11_name = cmd.getArg(1);
1740                 if (lyx_name.empty() || x11_name.empty()) {
1741                         if (current_view_)
1742                                 current_view_->message(
1743                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1744                         break;
1745                 }
1746
1747 #if 0
1748                 // FIXME: The graphics cache no longer has a changeDisplay method.
1749                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1750                 bool const graphicsbg_changed =
1751                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1752                 if (graphicsbg_changed)
1753                         graphics::GCache::get().changeDisplay(true);
1754 #endif
1755
1756                 if (!lcolor.setColor(lyx_name, x11_name)) {
1757                         if (current_view_)
1758                                 current_view_->message(
1759                                         bformat(_("Set-color \"%1$s\" failed "
1760                                         "- color is undefined or "
1761                                         "may not be redefined"),
1762                                         from_utf8(lyx_name)));
1763                         break;
1764                 }
1765                 // Make sure we don't keep old colors in cache.
1766                 d->color_cache_.clear();
1767                 // Update the current view
1768                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1769                 break;
1770         }
1771
1772         case LFUN_LYXRC_APPLY: {
1773                 // reset active key sequences, since the bindings
1774                 // are updated (bug 6064)
1775                 d->keyseq.reset();
1776                 LyXRC const lyxrc_orig = lyxrc;
1777
1778                 istringstream ss(to_utf8(cmd.argument()));
1779                 bool const success = lyxrc.read(ss);
1780
1781                 if (!success) {
1782                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1783                                         << "Unable to read lyxrc data"
1784                                         << endl;
1785                         break;
1786                 }
1787
1788                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1789
1790                 // If the request comes from the minibuffer, then we can't reset
1791                 // the GUI, since that would destory the minibuffer itself and
1792                 // cause a crash, since we are currently in one of the methods of
1793                 // GuiCommandBuffer. See bug #8540.
1794                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1795                         resetGui();
1796                 // else
1797                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1798                 //   reset the GUI in this case. If the changes to lyxrc affected the
1799                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1800                 //   it definitely is a bug.
1801
1802                 dr.forceBufferUpdate();
1803                 break;
1804         }
1805
1806         case LFUN_COMMAND_PREFIX:
1807                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1808                 break;
1809
1810         case LFUN_CANCEL: {
1811                 d->keyseq.reset();
1812                 d->meta_fake_bit = NoModifier;
1813                 GuiView * gv = currentView();
1814                 if (gv && gv->currentBufferView())
1815                         // cancel any selection
1816                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1817                 dr.setMessage(from_ascii(N_("Cancel")));
1818                 break;
1819         }
1820         case LFUN_META_PREFIX:
1821                 d->meta_fake_bit = AltModifier;
1822                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1823                 break;
1824
1825         // --- Menus -----------------------------------------------
1826         case LFUN_RECONFIGURE:
1827                 // argument is any additional parameter to the configure.py command
1828                 reconfigure(to_utf8(cmd.argument()));
1829                 break;
1830
1831         // --- lyxserver commands ----------------------------
1832         case LFUN_SERVER_GET_FILENAME: {
1833                 if (current_view_ && current_view_->documentBufferView()) {
1834                         docstring const fname = from_utf8(
1835                                 current_view_->documentBufferView()->buffer().absFileName());
1836                         dr.setMessage(fname);
1837                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1838                 } else {
1839                         dr.setMessage(docstring());
1840                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1841                 }
1842                 break;
1843         }
1844
1845         case LFUN_SERVER_NOTIFY: {
1846                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1847                 dr.setMessage(dispatch_buffer);
1848                 theServer().notifyClient(to_utf8(dispatch_buffer));
1849                 break;
1850         }
1851
1852         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1853                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1854                 break;
1855
1856         case LFUN_REPEAT: {
1857                 // repeat command
1858                 string countstr;
1859                 string rest = split(argument, countstr, ' ');
1860                 int const count = convert<int>(countstr);
1861                 // an arbitrary number to limit number of iterations
1862                 int const max_iter = 10000;
1863                 if (count > max_iter) {
1864                         dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1865                         dr.setError(true);
1866                 } else {
1867                         for (int i = 0; i < count; ++i) {
1868                                 FuncRequest lfun = lyxaction.lookupFunc(rest);
1869                                 lfun.allowAsync(false);
1870                                 dispatch(lfun);
1871                         }
1872                 }
1873                 break;
1874         }
1875
1876         case LFUN_COMMAND_SEQUENCE: {
1877                 // argument contains ';'-terminated commands
1878                 string arg = argument;
1879                 // FIXME: this LFUN should also work without any view.
1880                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1881                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1882                 // This handles undo groups automagically
1883                 UndoGroupHelper ugh(buffer);
1884                 while (!arg.empty()) {
1885                         string first;
1886                         arg = split(arg, first, ';');
1887                         FuncRequest func(lyxaction.lookupFunc(first));
1888                         func.allowAsync(false);
1889                         func.setOrigin(cmd.origin());
1890                         dispatch(func);
1891                 }
1892                 break;
1893         }
1894
1895         case LFUN_BUFFER_FORALL: {
1896                 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1897                 funcToRun.allowAsync(false);
1898
1899                 map<Buffer *, GuiView *> views_lVisible;
1900                 map<GuiView *, Buffer *> activeBuffers;
1901
1902                 QList<GuiView *> allViews = d->views_.values();
1903
1904                 // this for does not modify any buffer. It just collects info on local
1905                 // visibility of buffers and on which buffer is active in each view.
1906                 Buffer * const last = theBufferList().last();
1907                 for(GuiView * view : allViews) {
1908                         // all of the buffers might be locally hidden. That is, there is no
1909                         // active buffer.
1910                         if (!view || !view->currentBufferView())
1911                                 activeBuffers[view] = 0;
1912                         else
1913                                 activeBuffers[view] = &view->currentBufferView()->buffer();
1914
1915                         // find out if each is locally visible or locally hidden.
1916                         // we don't use a for loop as the buffer list cycles.
1917                         Buffer * b = theBufferList().first();
1918                         while (true) {
1919                                 bool const locallyVisible = view && view->workArea(*b);
1920                                 if (locallyVisible) {
1921                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1922                                         // only need to overwrite/add if we don't already know a buffer is globally
1923                                         // visible or we do know but we would prefer to dispatch LFUN from the
1924                                         // current view because of cursor position issues.
1925                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1926                                                 views_lVisible[b] = view;
1927                                 }
1928                                 if (b == last)
1929                                         break;
1930                                 b = theBufferList().next(b);
1931                         }
1932                 }
1933
1934                 GuiView * const homeView = currentView();
1935                 Buffer * b = theBufferList().first();
1936                 Buffer * nextBuf = 0;
1937                 int numProcessed = 0;
1938                 while (true) {
1939                         if (b != last)
1940                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1941
1942                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1943                         if (visible) {
1944                                 // first change to a view where b is locally visible, preferably current_view_.
1945                                 GuiView * const vLv = views_lVisible[b];
1946                                 vLv->setBuffer(b);
1947                                 lyx::dispatch(funcToRun);
1948                                 numProcessed++;
1949                         }
1950                         if (b == last)
1951                                 break;
1952                         b = nextBuf;
1953                 }
1954
1955                 // put things back to how they were (if possible).
1956                 for (GuiView * view : allViews) {
1957                         Buffer * originalBuf = activeBuffers[view];
1958                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1959                         if (theBufferList().isLoaded(originalBuf))
1960                                 view->setBuffer(originalBuf);
1961                 }
1962                 homeView->setFocus();
1963
1964                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1965                 break;
1966         }
1967
1968         case LFUN_COMMAND_ALTERNATIVES: {
1969                 // argument contains ';'-terminated commands
1970                 string arg = argument;
1971                 while (!arg.empty()) {
1972                         string first;
1973                         arg = split(arg, first, ';');
1974                         FuncRequest func(lyxaction.lookupFunc(first));
1975                         func.setOrigin(cmd.origin());
1976                         FuncStatus const stat = getStatus(func);
1977                         if (stat.enabled()) {
1978                                 dispatch(func);
1979                                 break;
1980                         }
1981                 }
1982                 break;
1983         }
1984
1985         case LFUN_CALL: {
1986                 FuncRequest func;
1987                 if (theTopLevelCmdDef().lock(argument, func)) {
1988                         func.setOrigin(cmd.origin());
1989                         dispatch(func);
1990                         theTopLevelCmdDef().release(argument);
1991                 } else {
1992                         if (func.action() == LFUN_UNKNOWN_ACTION) {
1993                                 // unknown command definition
1994                                 lyxerr << "Warning: unknown command definition `"
1995                                                 << argument << "'"
1996                                                 << endl;
1997                         } else {
1998                                 // recursion detected
1999                                 lyxerr << "Warning: Recursion in the command definition `"
2000                                                 << argument << "' detected"
2001                                                 << endl;
2002                         }
2003                 }
2004                 break;
2005         }
2006
2007         case LFUN_PREFERENCES_SAVE:
2008                 lyxrc.write(support::makeAbsPath("preferences",
2009                         package().user_support().absFileName()), false);
2010                 break;
2011
2012         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2013                 string const fname = addName(addPath(package().user_support().absFileName(),
2014                         "templates/"), "defaults.lyx");
2015                 Buffer defaults(fname);
2016
2017                 istringstream ss(argument);
2018                 Lexer lex;
2019                 lex.setStream(ss);
2020
2021                 // See #9236
2022                 // We need to make sure that, after we recreat the DocumentClass,
2023                 // which we do in readHeader, we apply it to the document itself.
2024                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2025                 int const unknown_tokens = defaults.readHeader(lex);
2026                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2027                 ErrorList el;
2028                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2029                 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2030
2031                 if (unknown_tokens != 0) {
2032                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2033                                << unknown_tokens << " unknown token"
2034                                << (unknown_tokens == 1 ? "" : "s")
2035                                << endl;
2036                 }
2037
2038                 if (defaults.writeFile(FileName(defaults.absFileName())))
2039                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2040                                               makeDisplayPath(fname)));
2041                 else {
2042                         dr.setError(true);
2043                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2044                 }
2045                 break;
2046         }
2047
2048         case LFUN_BOOKMARK_GOTO:
2049                 // go to bookmark, open unopened file and switch to buffer if necessary
2050                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2051                 dr.screenUpdate(Update::Force | Update::FitCursor);
2052                 break;
2053
2054         case LFUN_BOOKMARK_CLEAR:
2055                 theSession().bookmarks().clear();
2056                 break;
2057
2058         case LFUN_DEBUG_LEVEL_SET:
2059                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2060                 break;
2061
2062         case LFUN_DIALOG_SHOW: {
2063                 string const name = cmd.getArg(0);
2064
2065                 if ( name == "aboutlyx"
2066                         || name == "prefs"
2067                         || name == "texinfo"
2068                         || name == "progress"
2069                         || name == "compare")
2070                 {
2071                         // work around: on Mac OS the application
2072                         // is not terminated when closing the last view.
2073                         // Create a new one to be able to dispatch the
2074                         // LFUN_DIALOG_SHOW to this view.
2075                         if (current_view_ == 0)
2076                                 createView();
2077                 }
2078         }
2079         // fall through
2080         default:
2081                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2082                 // let's try that:
2083                 if (current_view_)
2084                         current_view_->dispatch(cmd, dr);
2085                 break;
2086         }
2087
2088         if (cmd.origin() == FuncRequest::LYXSERVER)
2089                 updateCurrentView(cmd, dr);
2090 }
2091
2092
2093 docstring GuiApplication::viewStatusMessage()
2094 {
2095         // When meta-fake key is pressed, show the key sequence so far + "M-".
2096         if (d->meta_fake_bit != NoModifier)
2097                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2098
2099         // Else, when a non-complete key sequence is pressed,
2100         // show the available options.
2101         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2102                 return d->keyseq.printOptions(true);
2103
2104         return docstring();
2105 }
2106
2107
2108 void GuiApplication::handleKeyFunc(FuncCode action)
2109 {
2110         char_type c = 0;
2111
2112         if (d->keyseq.length())
2113                 c = 0;
2114         GuiView * gv = currentView();
2115         LASSERT(gv && gv->currentBufferView(), return);
2116         BufferView * bv = gv->currentBufferView();
2117         bv->getIntl().getTransManager().deadkey(
2118                 c, get_accent(action).accent, bv->cursor().innerText(),
2119                 bv->cursor());
2120         // Need to clear, in case the minibuffer calls these
2121         // actions
2122         d->keyseq.clear();
2123         // copied verbatim from do_accent_char
2124         bv->cursor().resetAnchor();
2125 }
2126
2127
2128 //Keep this in sync with GuiApplication::processKeySym below
2129 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2130                                  KeyModifier state) const
2131 {
2132         // Do nothing if we have nothing
2133         if (!keysym.isOK() || keysym.isModifier())
2134                 return false;
2135         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2136         KeySequence seq;
2137         FuncRequest func = seq.addkey(keysym, state);
2138         // When not cancel or meta-fake, do the normal lookup.
2139         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2140                 seq = d->keyseq;
2141                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2142         }
2143         // Maybe user can only reach the key via holding down shift.
2144         // Let's see. But only if shift is the only modifier
2145         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2146                 // If addkey looked up a command and did not find further commands then
2147                 // seq has been reset at this point
2148                 func = seq.addkey(keysym, NoModifier);
2149
2150         LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2151                << seq.print(KeySequence::Portable) << ']');
2152         return func.action() != LFUN_UNKNOWN_ACTION;
2153 }
2154
2155
2156 //Keep this in sync with GuiApplication::queryKeySym above
2157 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2158 {
2159         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2160
2161         // Do nothing if we have nothing (JMarc)
2162         if (!keysym.isOK() || keysym.isModifier()) {
2163                 if (!keysym.isOK())
2164                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2165                 if (current_view_)
2166                         current_view_->restartCaret();
2167                 return;
2168         }
2169
2170         char_type encoded_last_key = keysym.getUCSEncoded();
2171
2172         // Do a one-deep top-level lookup for
2173         // cancel and meta-fake keys. RVDK_PATCH_5
2174         d->cancel_meta_seq.reset();
2175
2176         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2177         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2178
2179         // When not cancel or meta-fake, do the normal lookup.
2180         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2181         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2182         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2183                 // remove Caps Lock and Mod2 as a modifiers
2184                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2185                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2186         }
2187
2188         // Dont remove this unless you know what you are doing.
2189         d->meta_fake_bit = NoModifier;
2190
2191         // Can this happen now ?
2192         if (func.action() == LFUN_NOACTION)
2193                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2194
2195         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2196                 << d->keyseq.print(KeySequence::Portable) << ']');
2197
2198         // already here we know if it any point in going further
2199         // why not return already here if action == -1 and
2200         // num_bytes == 0? (Lgb)
2201
2202         if (d->keyseq.length() > 1 && current_view_)
2203                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2204
2205
2206         // Maybe user can only reach the key via holding down shift.
2207         // Let's see. But only if shift is the only modifier
2208         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2209                 LYXERR(Debug::KEY, "Trying without shift");
2210                 // If addkey looked up a command and did not find further commands then
2211                 // seq has been reset at this point
2212                 func = d->keyseq.addkey(keysym, NoModifier);
2213                 LYXERR(Debug::KEY, "Action now " << func.action());
2214         }
2215
2216         if (func.action() == LFUN_UNKNOWN_ACTION) {
2217                 // We didn't match any of the key sequences.
2218                 // See if it's normal insertable text not already
2219                 // covered by a binding
2220                 if (keysym.isText() && d->keyseq.length() == 1) {
2221                         // Non-printable characters (such as ASCII control characters)
2222                         // must not be inserted (#5704)
2223                         if (!isPrintable(encoded_last_key)) {
2224                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2225                                 if (current_view_)
2226                                         current_view_->restartCaret();
2227                                 return;
2228                         }
2229                         // The following modifier check is not needed on Mac.
2230                         // The keysym is either not text or it is different
2231                         // from the non-modifier keysym. See #9875 for the
2232                         // broken alt-modifier effect of having this code active.
2233 #if !defined(Q_OS_MAC)
2234                         // If a non-Shift Modifier is used we have a non-bound key sequence
2235                         // (such as Alt+j = j). This should be omitted (#5575).
2236                         // On Windows, AltModifier and ControlModifier are both
2237                         // set when AltGr is pressed. Therefore, in order to not
2238                         // break AltGr-bound symbols (see #5575 for details),
2239                         // unbound Ctrl+Alt key sequences are allowed.
2240                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2241 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2242                             && !(state & AltModifier && state & ControlModifier)
2243 #endif
2244                             )
2245                         {
2246                                 if (current_view_) {
2247                                         current_view_->message(_("Unknown function."));
2248                                         current_view_->restartCaret();
2249                                 }
2250                                 return;
2251                         }
2252 #endif
2253                         // Since all checks above were passed, we now really have text that
2254                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2255                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2256                         // below.
2257                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2258                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2259                 } else {
2260                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2261                         if (current_view_) {
2262                                 current_view_->message(_("Unknown function."));
2263                                 current_view_->restartCaret();
2264                         }
2265                         return;
2266                 }
2267         }
2268
2269         if (func.action() == LFUN_SELF_INSERT) {
2270                 if (encoded_last_key != 0) {
2271                         docstring const arg(1, encoded_last_key);
2272                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2273                                              FuncRequest::KEYBOARD));
2274                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2275                 }
2276         } else
2277                 processFuncRequest(func);
2278 }
2279
2280
2281 void GuiApplication::processFuncRequest(FuncRequest const & func)
2282 {
2283         lyx::dispatch(func);
2284 }
2285
2286
2287 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2288 {
2289         addToFuncRequestQueue(func);
2290         processFuncRequestQueueAsync();
2291 }
2292
2293
2294 void GuiApplication::processFuncRequestQueue()
2295 {
2296         while (!d->func_request_queue_.empty()) {
2297                 // take the item from the stack _before_ processing the
2298                 // request in order to avoid race conditions from nested
2299                 // or parallel requests (see #10406)
2300                 FuncRequest const fr(d->func_request_queue_.front());
2301                 d->func_request_queue_.pop();
2302                 processFuncRequest(fr);
2303         }
2304 }
2305
2306
2307 void GuiApplication::processFuncRequestQueueAsync()
2308 {
2309         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2310 }
2311
2312
2313 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2314 {
2315         d->func_request_queue_.push(func);
2316 }
2317
2318
2319 void GuiApplication::resetGui()
2320 {
2321         // Set the language defined by the user.
2322         setGuiLanguage();
2323
2324         // Read menus
2325         if (!readUIFile(toqstr(lyxrc.ui_file)))
2326                 // Gives some error box here.
2327                 return;
2328
2329         if (d->global_menubar_)
2330                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2331
2332         QHash<int, GuiView *>::iterator it;
2333         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2334                 GuiView * gv = *it;
2335                 setCurrentView(gv);
2336                 gv->setLayoutDirection(layoutDirection());
2337                 gv->resetDialogs();
2338         }
2339
2340         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2341 }
2342
2343
2344 void GuiApplication::createView(int view_id)
2345 {
2346         createView(QString(), true, view_id);
2347 }
2348
2349
2350 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2351         int view_id)
2352 {
2353         // release the keyboard which might have been grabed by the global
2354         // menubar on Mac to catch shortcuts even without any GuiView.
2355         if (d->global_menubar_)
2356                 d->global_menubar_->releaseKeyboard();
2357
2358         // create new view
2359         int id = view_id;
2360         while (d->views_.find(id) != d->views_.end())
2361                 id++;
2362
2363         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2364         GuiView * view = new GuiView(id);
2365         // `view' is the new current_view_. Tell coverity that is is not 0.
2366         LATTEST(current_view_);
2367         // register view
2368         d->views_[id] = view;
2369
2370         if (autoShow) {
2371                 view->show();
2372                 setActiveWindow(view);
2373         }
2374
2375         if (!geometry_arg.isEmpty()) {
2376 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2377                 int x, y;
2378                 int w, h;
2379                 QChar sx, sy;
2380                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2381                 re.indexIn(geometry_arg);
2382                 w = re.cap(1).toInt();
2383                 h = re.cap(2).toInt();
2384                 x = re.cap(3).toInt();
2385                 y = re.cap(4).toInt();
2386                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2387                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2388                 // Set initial geometry such that we can get the frame size.
2389                 view->setGeometry(x, y, w, h);
2390                 int framewidth = view->geometry().x() - view->x();
2391                 int titleheight = view->geometry().y() - view->y();
2392                 // Negative displacements must be interpreted as distances
2393                 // from the right or bottom screen borders.
2394                 if (sx == '-' || sy == '-') {
2395                         QRect rec = QApplication::desktop()->screenGeometry();
2396                         if (sx == '-')
2397                                 x += rec.width() - w - framewidth;
2398                         if (sy == '-')
2399                                 y += rec.height() - h - titleheight;
2400                         view->setGeometry(x, y, w, h);
2401                 }
2402                 // Make sure that the left and top frame borders are visible.
2403                 if (view->x() < 0 || view->y() < 0) {
2404                         if (view->x() < 0)
2405                                 x = framewidth;
2406                         if (view->y() < 0)
2407                                 y = titleheight;
2408                         view->setGeometry(x, y, w, h);
2409                 }
2410 #endif
2411         }
2412         view->setFocus();
2413 }
2414
2415
2416 bool GuiApplication::unhide(Buffer * buf)
2417 {
2418         if (!currentView())
2419                 return false;
2420         currentView()->setBuffer(buf, false);
2421         return true;
2422 }
2423
2424
2425 Clipboard & GuiApplication::clipboard()
2426 {
2427         return d->clipboard_;
2428 }
2429
2430
2431 Selection & GuiApplication::selection()
2432 {
2433         return d->selection_;
2434 }
2435
2436
2437 FontLoader & GuiApplication::fontLoader()
2438 {
2439         return d->font_loader_;
2440 }
2441
2442
2443 Toolbars const & GuiApplication::toolbars() const
2444 {
2445         return d->toolbars_;
2446 }
2447
2448
2449 Toolbars & GuiApplication::toolbars()
2450 {
2451         return d->toolbars_;
2452 }
2453
2454
2455 Menus const & GuiApplication::menus() const
2456 {
2457         return d->menus_;
2458 }
2459
2460
2461 Menus & GuiApplication::menus()
2462 {
2463         return d->menus_;
2464 }
2465
2466
2467 QList<int> GuiApplication::viewIds() const
2468 {
2469         return d->views_.keys();
2470 }
2471
2472
2473 ColorCache & GuiApplication::colorCache()
2474 {
2475         return d->color_cache_;
2476 }
2477
2478
2479 int GuiApplication::exec()
2480 {
2481         // asynchronously handle batch commands. This event will be in
2482         // the event queue in front of other asynchronous events. Hence,
2483         // we can assume in the latter that the gui is setup already.
2484         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2485
2486         return QApplication::exec();
2487 }
2488
2489
2490 void GuiApplication::exit(int status)
2491 {
2492         QApplication::exit(status);
2493 }
2494
2495
2496 void GuiApplication::setGuiLanguage()
2497 {
2498         setLocale();
2499         QLocale theLocale;
2500         // install translation file for Qt built-in dialogs
2501         QString const language_name = QString("qt_") + theLocale.name();
2502         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2503         // Short-named translator can be loaded from a long name, but not the
2504         // opposite. Therefore, long name should be used without truncation.
2505         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2506         if (!d->qt_trans_.load(language_name,
2507                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2508                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2509                         << language_name);
2510         } else {
2511                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2512                         << language_name);
2513         }
2514
2515         switch (theLocale.language()) {
2516         case QLocale::Arabic :
2517         case QLocale::Hebrew :
2518         case QLocale::Persian :
2519         case QLocale::Urdu :
2520                 setLayoutDirection(Qt::RightToLeft);
2521                 break;
2522         default:
2523                 setLayoutDirection(Qt::LeftToRight);
2524         }
2525 }
2526
2527
2528 void GuiApplication::execBatchCommands()
2529 {
2530         setGuiLanguage();
2531
2532         // Read menus
2533         if (!readUIFile(toqstr(lyxrc.ui_file)))
2534                 // Gives some error box here.
2535                 return;
2536
2537 #ifdef Q_OS_MAC
2538 #if QT_VERSION > 0x040600
2539         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2540 #endif
2541 #if QT_VERSION > 0x050100
2542         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2543 #endif
2544         // Create the global default menubar which is shown for the dialogs
2545         // and if no GuiView is visible.
2546         // This must be done after the session was recovered to know the "last files".
2547         d->global_menubar_ = new QMenuBar(0);
2548         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2549 #endif
2550
2551         lyx::execBatchCommands();
2552 }
2553
2554
2555 QAbstractItemModel * GuiApplication::languageModel()
2556 {
2557         if (d->language_model_)
2558                 return d->language_model_;
2559
2560         QStandardItemModel * lang_model = new QStandardItemModel(this);
2561         lang_model->insertColumns(0, 3);
2562         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2563         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2564         Languages::const_iterator it = lyx::languages.begin();
2565         Languages::const_iterator end = lyx::languages.end();
2566         for (; it != end; ++it) {
2567                 int current_row = lang_model->rowCount();
2568                 lang_model->insertRows(current_row, 1);
2569                 QModelIndex pl_item = lang_model->index(current_row, 0);
2570                 QModelIndex sp_item = lang_model->index(current_row, 1);
2571                 QModelIndex th_item = lang_model->index(current_row, 2);
2572                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2573                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2574                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2575                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2576                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2577                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2578                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2579                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2580                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2581                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2582         }
2583         d->language_model_ = new QSortFilterProxyModel(this);
2584         d->language_model_->setSourceModel(lang_model);
2585         d->language_model_->setSortLocaleAware(true);
2586         return d->language_model_;
2587 }
2588
2589
2590 void GuiApplication::restoreGuiSession()
2591 {
2592         if (!lyxrc.load_session)
2593                 return;
2594
2595         Session & session = theSession();
2596         LastOpenedSection::LastOpened const & lastopened =
2597                 session.lastOpened().getfiles();
2598
2599         validateCurrentView();
2600
2601         FileName active_file;
2602         // do not add to the lastfile list since these files are restored from
2603         // last session, and should be already there (regular files), or should
2604         // not be added at all (help files).
2605         for (size_t i = 0; i < lastopened.size(); ++i) {
2606                 FileName const & file_name = lastopened[i].file_name;
2607                 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2608                           && current_view_->documentBufferView() != 0)) {
2609                         boost::crc_32_type crc;
2610                         string const & fname = file_name.absFileName();
2611                         crc = for_each(fname.begin(), fname.end(), crc);
2612                         createView(crc.checksum());
2613                 }
2614                 current_view_->loadDocument(file_name, false);
2615
2616                 if (lastopened[i].active)
2617                         active_file = file_name;
2618         }
2619
2620         // Restore last active buffer
2621         Buffer * buffer = theBufferList().getBuffer(active_file);
2622         if (buffer && current_view_)
2623                 current_view_->setBuffer(buffer);
2624
2625         // clear this list to save a few bytes of RAM
2626         session.lastOpened().clear();
2627 }
2628
2629
2630 QString const GuiApplication::romanFontName()
2631 {
2632         QFont font;
2633         font.setStyleHint(QFont::Serif);
2634         font.setFamily("serif");
2635
2636         return QFontInfo(font).family();
2637 }
2638
2639
2640 QString const GuiApplication::sansFontName()
2641 {
2642         QFont font;
2643         font.setStyleHint(QFont::SansSerif);
2644         font.setFamily("sans");
2645
2646         return QFontInfo(font).family();
2647 }
2648
2649
2650 QString const GuiApplication::typewriterFontName()
2651 {
2652         return QFontInfo(typewriterSystemFont()).family();
2653 }
2654
2655
2656 namespace {
2657         // We cannot use QFont::fixedPitch() because it doesn't
2658         // return the fact but only if it is requested.
2659         static bool isFixedPitch(const QFont & font) {
2660                 const QFontInfo fi(font);
2661                 return fi.fixedPitch();
2662         }
2663 } // namespace
2664
2665
2666 QFont const GuiApplication::typewriterSystemFont()
2667 {
2668 #if QT_VERSION >= 0x050200
2669         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2670 #else
2671         QFont font("monospace");
2672 #endif
2673         if (!isFixedPitch(font)) {
2674                 // try to enforce a real monospaced font
2675                 font.setStyleHint(QFont::Monospace);
2676                 if (!isFixedPitch(font)) {
2677                         font.setStyleHint(QFont::TypeWriter);
2678                         if (!isFixedPitch(font)) font.setFamily("courier");
2679                 }
2680         }
2681 #ifdef Q_OS_MAC
2682         // On a Mac the result is too small and it's not practical to
2683         // rely on Qtconfig utility to change the system settings of Qt.
2684         font.setPointSize(12);
2685 #endif
2686         return font;
2687 }
2688
2689
2690 void GuiApplication::handleRegularEvents()
2691 {
2692         ForkedCallsController::handleCompletedProcesses();
2693 }
2694
2695
2696 bool GuiApplication::event(QEvent * e)
2697 {
2698         switch(e->type()) {
2699         case QEvent::FileOpen: {
2700                 // Open a file; this happens only on Mac OS X for now.
2701                 //
2702                 // We do this asynchronously because on startup the batch
2703                 // commands are not executed here yet and the gui is not ready
2704                 // therefore.
2705                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2706                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2707                 processFuncRequestAsync(fr);
2708                 e->accept();
2709                 return true;
2710         }
2711         default:
2712                 return QApplication::event(e);
2713         }
2714 }
2715
2716
2717 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2718 {
2719         try {
2720                 return QApplication::notify(receiver, event);
2721         }
2722         catch (ExceptionMessage const & e) {
2723                 switch(e.type_) {
2724                 case ErrorException:
2725                         emergencyCleanup();
2726                         setQuitOnLastWindowClosed(false);
2727                         closeAllViews();
2728                         Alert::error(e.title_, e.details_);
2729 #ifndef NDEBUG
2730                         // Properly crash in debug mode in order to get a useful backtrace.
2731                         abort();
2732 #endif
2733                         // In release mode, try to exit gracefully.
2734                         this->exit(1);
2735                         // FIXME: GCC 7 thinks we can fall through here. Can we?
2736                         // fall through
2737                 case BufferException: {
2738                         if (!current_view_ || !current_view_->documentBufferView())
2739                                 return false;
2740                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2741                         docstring details = e.details_ + '\n';
2742                         details += buf->emergencyWrite();
2743                         theBufferList().release(buf);
2744                         details += "\n" + _("The current document was closed.");
2745                         Alert::error(e.title_, details);
2746                         return false;
2747                 }
2748                 case WarningException:
2749                         Alert::warning(e.title_, e.details_);
2750                         return false;
2751                 }
2752         }
2753         catch (exception const & e) {
2754                 docstring s = _("LyX has caught an exception, it will now "
2755                         "attempt to save all unsaved documents and exit."
2756                         "\n\nException: ");
2757                 s += from_ascii(e.what());
2758                 Alert::error(_("Software exception Detected"), s);
2759                 lyx_exit(1);
2760         }
2761         catch (...) {
2762                 docstring s = _("LyX has caught some really weird exception, it will "
2763                         "now attempt to save all unsaved documents and exit.");
2764                 Alert::error(_("Software exception Detected"), s);
2765                 lyx_exit(1);
2766         }
2767
2768         return false;
2769 }
2770
2771
2772 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2773 {
2774         QColor const & qcol = d->color_cache_.get(col);
2775         if (!qcol.isValid()) {
2776                 rgbcol.r = 0;
2777                 rgbcol.g = 0;
2778                 rgbcol.b = 0;
2779                 return false;
2780         }
2781         rgbcol.r = qcol.red();
2782         rgbcol.g = qcol.green();
2783         rgbcol.b = qcol.blue();
2784         return true;
2785 }
2786
2787
2788 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2789 {
2790         QColor const qcol(lcolor.getX11Name(col).c_str());
2791         if (!qcol.isValid()) {
2792                 rgbcol.r = 0;
2793                 rgbcol.g = 0;
2794                 rgbcol.b = 0;
2795                 return false;
2796         }
2797         rgbcol.r = qcol.red();
2798         rgbcol.g = qcol.green();
2799         rgbcol.b = qcol.blue();
2800         return true;
2801 }
2802
2803
2804 string const GuiApplication::hexName(ColorCode col)
2805 {
2806         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2807 }
2808
2809
2810 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2811 {
2812         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2813         d->socket_notifiers_[fd] = sn;
2814         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2815 }
2816
2817
2818 void GuiApplication::socketDataReceived(int fd)
2819 {
2820         d->socket_notifiers_[fd]->func_();
2821 }
2822
2823
2824 void GuiApplication::unregisterSocketCallback(int fd)
2825 {
2826         d->socket_notifiers_.take(fd)->setEnabled(false);
2827 }
2828
2829
2830 void GuiApplication::commitData(QSessionManager & sm)
2831 {
2832         /** The implementation is required to avoid an application exit
2833          ** when session state save is triggered by session manager.
2834          ** The default implementation sends a close event to all
2835          ** visible top level widgets when session managment allows
2836          ** interaction.
2837          ** We are changing that to check the state of each buffer in all
2838          ** views and ask the users what to do if buffers are dirty.
2839          ** Furthermore, we save the session state.
2840          ** We do NOT close the views here since the user still can cancel
2841          ** the logout process (see #9277); also, this would hide LyX from
2842          ** an OSes own session handling (application restoration).
2843          **/
2844         #ifdef QT_NO_SESSIONMANAGER
2845                 #ifndef _MSC_VER
2846                         #warning Qt is compiled without session manager
2847                 #else
2848                         #pragma message("warning: Qt is compiled without session manager")
2849                 #endif
2850                 (void) sm;
2851         #else
2852                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2853                         sm.cancel();
2854                 else
2855                         sm.release();
2856         #endif
2857 }
2858
2859
2860 void GuiApplication::unregisterView(GuiView * gv)
2861 {
2862         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2863                 d->views_.remove(gv->id());
2864                 if (current_view_ == gv)
2865                         current_view_ = 0;
2866         }
2867 }
2868
2869
2870 bool GuiApplication::closeAllViews()
2871 {
2872         if (d->views_.empty())
2873                 return true;
2874
2875         // When a view/window was closed before without quitting LyX, there
2876         // are already entries in the lastOpened list.
2877         theSession().lastOpened().clear();
2878
2879         QList<GuiView *> const views = d->views_.values();
2880         for (GuiView * view : views) {
2881                 if (!view->closeScheduled())
2882                         return false;
2883         }
2884
2885         d->views_.clear();
2886         return true;
2887 }
2888
2889
2890 bool GuiApplication::prepareAllViewsForLogout()
2891 {
2892         if (d->views_.empty())
2893                 return true;
2894
2895         QList<GuiView *> const views = d->views_.values();
2896         for (GuiView * view : views) {
2897                 if (!view->prepareAllBuffersForLogout())
2898                         return false;
2899         }
2900
2901         return true;
2902 }
2903
2904
2905 GuiView & GuiApplication::view(int id) const
2906 {
2907         LAPPERR(d->views_.contains(id));
2908         return *d->views_.value(id);
2909 }
2910
2911
2912 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2913 {
2914         QList<GuiView *> const views = d->views_.values();
2915         for (GuiView * view : views)
2916                 view->hideDialog(name, inset);
2917 }
2918
2919
2920 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2921 {
2922         Buffer const * buffer_ = 0;
2923         QHash<int, GuiView *>::const_iterator end = d->views_.end();
2924         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2925                 if (Buffer const * ptr = (*it)->updateInset(inset))
2926                         buffer_ = ptr;
2927         }
2928         return buffer_;
2929 }
2930
2931
2932 bool GuiApplication::searchMenu(FuncRequest const & func,
2933         docstring_list & names) const
2934 {
2935         BufferView * bv = 0;
2936         if (current_view_)
2937                 bv = current_view_->currentBufferView();
2938         return d->menus_.searchMenu(func, names, bv);
2939 }
2940
2941
2942 bool GuiApplication::hasBufferView() const
2943 {
2944         return (current_view_ && current_view_->currentBufferView());
2945 }
2946
2947
2948 // Ensure that a file is read only once (prevents include loops)
2949 static QStringList uifiles;
2950 // store which ui files define Toolbars
2951 static QStringList toolbar_uifiles;
2952
2953
2954 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2955 {
2956         enum {
2957                 ui_menuset = 1,
2958                 ui_toolbars,
2959                 ui_toolbarset,
2960                 ui_include,
2961                 ui_format,
2962                 ui_last
2963         };
2964
2965         LexerKeyword uitags[] = {
2966                 { "format", ui_format },
2967                 { "include", ui_include },
2968                 { "menuset", ui_menuset },
2969                 { "toolbars", ui_toolbars },
2970                 { "toolbarset", ui_toolbarset }
2971         };
2972
2973         Lexer lex(uitags);
2974         lex.setFile(ui_path);
2975         if (!lex.isOK()) {
2976                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2977                                          << endl;
2978         }
2979
2980         if (lyxerr.debugging(Debug::PARSER))
2981                 lex.printTable(lyxerr);
2982
2983         bool error = false;
2984         // format before introduction of format tag
2985         unsigned int format = 0;
2986         while (lex.isOK()) {
2987                 int const status = lex.lex();
2988
2989                 // we have to do this check here, outside the switch,
2990                 // because otherwise we would start reading include files,
2991                 // e.g., if the first tag we hit was an include tag.
2992                 if (status == ui_format)
2993                         if (lex.next()) {
2994                                 format = lex.getInteger();
2995                                 continue;
2996                         }
2997
2998                 // this will trigger unless the first tag we hit is a format
2999                 // tag, with the right format.
3000                 if (format != LFUN_FORMAT)
3001                         return FormatMismatch;
3002
3003                 switch (status) {
3004                 case Lexer::LEX_FEOF:
3005                         continue;
3006
3007                 case ui_include: {
3008                         lex.next(true);
3009                         QString const file = toqstr(lex.getString());
3010                         bool const success = readUIFile(file, true);
3011                         if (!success) {
3012                                 LYXERR0("Failed to read included file: " << fromqstr(file));
3013                                 return ReadError;
3014                         }
3015                         break;
3016                 }
3017
3018                 case ui_menuset:
3019                         d->menus_.read(lex);
3020                         break;
3021
3022                 case ui_toolbarset:
3023                         d->toolbars_.readToolbars(lex);
3024                         break;
3025
3026                 case ui_toolbars:
3027                         d->toolbars_.readToolbarSettings(lex);
3028                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3029                         break;
3030
3031                 default:
3032                         if (!rtrim(lex.getString()).empty())
3033                                 lex.printError("LyX::ReadUIFile: "
3034                                                "Unknown menu tag: `$$Token'");
3035                         else
3036                                 LYXERR0("Error with status: " << status);
3037                         error = true;
3038                         break;
3039                 }
3040
3041         }
3042         return (error ? ReadError : ReadOK);
3043 }
3044
3045
3046 bool GuiApplication::readUIFile(QString const & name, bool include)
3047 {
3048         LYXERR(Debug::INIT, "About to read " << name << "...");
3049
3050         FileName ui_path;
3051         if (include) {
3052                 ui_path = libFileSearch("ui", name, "inc");
3053                 if (ui_path.empty())
3054                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3055         } else {
3056                 ui_path = libFileSearch("ui", name, "ui");
3057         }
3058
3059         if (ui_path.empty()) {
3060                 static const QString defaultUIFile = "default";
3061                 LYXERR(Debug::INIT, "Could not find " << name);
3062                 if (include) {
3063                         Alert::warning(_("Could not find UI definition file"),
3064                                 bformat(_("Error while reading the included file\n%1$s\n"
3065                                         "Please check your installation."), qstring_to_ucs4(name)));
3066                         return false;
3067                 }
3068                 if (name == defaultUIFile) {
3069                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3070                         Alert::warning(_("Could not find default UI file"),
3071                                 _("LyX could not find the default UI file!\n"
3072                                   "Please check your installation."));
3073                         return false;
3074                 }
3075                 Alert::warning(_("Could not find UI definition file"),
3076                 bformat(_("Error while reading the configuration file\n%1$s\n"
3077                         "Falling back to default.\n"
3078                         "Please look under Tools>Preferences>User Interface and\n"
3079                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3080                 return readUIFile(defaultUIFile, false);
3081         }
3082
3083         QString const uifile = toqstr(ui_path.absFileName());
3084         if (uifiles.contains(uifile)) {
3085                 if (!include) {
3086                         // We are reading again the top uifile so reset the safeguard:
3087                         uifiles.clear();
3088                         d->menus_.reset();
3089                         d->toolbars_.reset();
3090                 } else {
3091                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3092                                 << "Is this an include loop?");
3093                         return false;
3094                 }
3095         }
3096         uifiles.push_back(uifile);
3097
3098         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3099
3100         ReturnValues retval = readUIFile(ui_path);
3101
3102         if (retval == FormatMismatch) {
3103                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3104                 TempFile tmp("convertXXXXXX.ui");
3105                 FileName const tempfile = tmp.name();
3106                 bool const success = prefs2prefs(ui_path, tempfile, true);
3107                 if (!success) {
3108                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3109                                 " to format " << LFUN_FORMAT << ".");
3110                 } else {
3111                         retval = readUIFile(tempfile);
3112                 }
3113         }
3114
3115         if (retval != ReadOK) {
3116                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3117                 return false;
3118         }
3119
3120         if (include)
3121                 return true;
3122
3123         QSettings settings;
3124         settings.beginGroup("ui_files");
3125         bool touched = false;
3126         for (int i = 0; i != uifiles.size(); ++i) {
3127                 QFileInfo fi(uifiles[i]);
3128                 QDateTime const date_value = fi.lastModified();
3129                 QString const name_key = QString::number(i);
3130                 // if an ui file which defines Toolbars has changed,
3131                 // we have to reset the settings
3132                 if (toolbar_uifiles.contains(uifiles[i])
3133                  && (!settings.contains(name_key)
3134                  || settings.value(name_key).toString() != uifiles[i]
3135                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3136                         touched = true;
3137                         settings.setValue(name_key, uifiles[i]);
3138                         settings.setValue(name_key + "/date", date_value);
3139                 }
3140         }
3141         settings.endGroup();
3142         if (touched)
3143                 settings.remove("views");
3144
3145         return true;
3146 }
3147
3148
3149 void GuiApplication::onLastWindowClosed()
3150 {
3151         if (d->global_menubar_)
3152                 d->global_menubar_->grabKeyboard();
3153 }
3154
3155
3156 void GuiApplication::startLongOperation() {
3157         d->key_checker_.start();
3158 }
3159
3160
3161 bool GuiApplication::longOperationCancelled() {
3162         return d->key_checker_.pressed();
3163 }
3164
3165
3166 void GuiApplication::stopLongOperation() {
3167         d->key_checker_.stop();
3168 }
3169
3170
3171 bool GuiApplication::longOperationStarted() {
3172         return d->key_checker_.started();
3173 }
3174
3175
3176 ////////////////////////////////////////////////////////////////////////
3177 //
3178 // X11 specific stuff goes here...
3179
3180 #ifdef Q_WS_X11
3181 bool GuiApplication::x11EventFilter(XEvent * xev)
3182 {
3183         if (!current_view_)
3184                 return false;
3185
3186         switch (xev->type) {
3187         case SelectionRequest: {
3188                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3189                         break;
3190                 LYXERR(Debug::SELECTION, "X requested selection.");
3191                 BufferView * bv = current_view_->currentBufferView();
3192                 if (bv) {
3193                         docstring const sel = bv->requestSelection();
3194                         if (!sel.empty()) {
3195                                 d->selection_.put(sel);
3196                                 // Refresh the selection request timestamp.
3197                                 // We have to do this by ourselves as Qt seems
3198                                 // not doing that, maybe because of our
3199                                 // "persistent selection" implementation
3200                                 // (see comments in GuiSelection.cpp).
3201                                 XSelectionEvent nev;
3202                                 nev.type = SelectionNotify;
3203                                 nev.display = xev->xselectionrequest.display;
3204                                 nev.requestor = xev->xselectionrequest.requestor;
3205                                 nev.selection = xev->xselectionrequest.selection;
3206                                 nev.target = xev->xselectionrequest.target;
3207                                 nev.property = 0L; // None
3208                                 nev.time = CurrentTime;
3209                                 XSendEvent(QX11Info::display(),
3210                                         nev.requestor, False, 0,
3211                                         reinterpret_cast<XEvent *>(&nev));
3212                                 return true;
3213                         }
3214                 }
3215                 break;
3216         }
3217         case SelectionClear: {
3218                 if (xev->xselectionclear.selection != XA_PRIMARY)
3219                         break;
3220                 LYXERR(Debug::SELECTION, "Lost selection.");
3221                 BufferView * bv = current_view_->currentBufferView();
3222                 if (bv)
3223                         bv->clearSelection();
3224                 break;
3225         }
3226         }
3227         return false;
3228 }
3229 #elif defined(QPA_XCB)
3230 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3231                                        void * message, long *)
3232 {
3233         if (!current_view_ || eventType != "xcb_generic_event_t")
3234                 return false;
3235
3236         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3237
3238         switch (ev->response_type) {
3239         case XCB_SELECTION_REQUEST: {
3240                 xcb_selection_request_event_t * srev =
3241                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3242                 if (srev->selection != XCB_ATOM_PRIMARY)
3243                         break;
3244                 LYXERR(Debug::SELECTION, "X requested selection.");
3245                 BufferView * bv = current_view_->currentBufferView();
3246                 if (bv) {
3247                         docstring const sel = bv->requestSelection();
3248                         if (!sel.empty()) {
3249                                 d->selection_.put(sel);
3250 #ifdef HAVE_QT5_X11_EXTRAS
3251                                 // Refresh the selection request timestamp.
3252                                 // We have to do this by ourselves as Qt seems
3253                                 // not doing that, maybe because of our
3254                                 // "persistent selection" implementation
3255                                 // (see comments in GuiSelection.cpp).
3256                                 xcb_selection_notify_event_t nev;
3257                                 nev.response_type = XCB_SELECTION_NOTIFY;
3258                                 nev.requestor = srev->requestor;
3259                                 nev.selection = srev->selection;
3260                                 nev.target = srev->target;
3261                                 nev.property = XCB_NONE;
3262                                 nev.time = XCB_CURRENT_TIME;
3263                                 xcb_connection_t * con = QX11Info::connection();
3264                                 xcb_send_event(con, 0, srev->requestor,
3265                                         XCB_EVENT_MASK_NO_EVENT,
3266                                         reinterpret_cast<char const *>(&nev));
3267                                 xcb_flush(con);
3268 #endif
3269                                 return true;
3270                         }
3271                 }
3272                 break;
3273         }
3274         case XCB_SELECTION_CLEAR: {
3275                 xcb_selection_clear_event_t * scev =
3276                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3277                 if (scev->selection != XCB_ATOM_PRIMARY)
3278                         break;
3279                 LYXERR(Debug::SELECTION, "Lost selection.");
3280                 BufferView * bv = current_view_->currentBufferView();
3281                 if (bv)
3282                         bv->clearSelection();
3283                 break;
3284         }
3285         }
3286         return false;
3287 }
3288 #endif
3289
3290 } // namespace frontend
3291
3292
3293 void hideDialogs(std::string const & name, Inset * inset)
3294 {
3295         if (theApp())
3296                 frontend::guiApp->hideDialogs(name, inset);
3297 }
3298
3299
3300 ////////////////////////////////////////////////////////////////////
3301 //
3302 // Font stuff
3303 //
3304 ////////////////////////////////////////////////////////////////////
3305
3306 frontend::FontLoader & theFontLoader()
3307 {
3308         LAPPERR(frontend::guiApp);
3309         return frontend::guiApp->fontLoader();
3310 }
3311
3312
3313 frontend::FontMetrics const & theFontMetrics(Font const & f)
3314 {
3315         return theFontMetrics(f.fontInfo());
3316 }
3317
3318
3319 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3320 {
3321         LAPPERR(frontend::guiApp);
3322         return frontend::guiApp->fontLoader().metrics(f);
3323 }
3324
3325
3326 ////////////////////////////////////////////////////////////////////
3327 //
3328 // Misc stuff
3329 //
3330 ////////////////////////////////////////////////////////////////////
3331
3332 frontend::Clipboard & theClipboard()
3333 {
3334         LAPPERR(frontend::guiApp);
3335         return frontend::guiApp->clipboard();
3336 }
3337
3338
3339 frontend::Selection & theSelection()
3340 {
3341         LAPPERR(frontend::guiApp);
3342         return frontend::guiApp->selection();
3343 }
3344
3345
3346 } // namespace lyx
3347
3348 #include "moc_GuiApplication.cpp"