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