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