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