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