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