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