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