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