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