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