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