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