]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Next camel
[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 "Color.h"
37 #include "Font.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
40 #include "Language.h"
41 #include "Lexer.h"
42 #include "LyX.h"
43 #include "LyXAction.h"
44 #include "LyXFunc.h"
45 #include "LyXRC.h"
46 #include "Session.h"
47 #include "version.h"
48
49 #include "support/lassert.h"
50 #include "support/debug.h"
51 #include "support/ExceptionMessage.h"
52 #include "support/FileName.h"
53 #include "support/foreach.h"
54 #include "support/ForkedCalls.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/lyxalgo.h" // sorted
58 #include "support/Messages.h"
59 #include "support/os.h"
60 #include "support/Package.h"
61
62 #ifdef Q_WS_MACX
63 #include "support/linkback/LinkBackProxy.h"
64 #endif
65
66 #include <queue>
67
68 #include <QByteArray>
69 #include <QClipboard>
70 #include <QDateTime>
71 #include <QDir>
72 #include <QEventLoop>
73 #include <QFileOpenEvent>
74 #include <QFileInfo>
75 #include <QHash>
76 #include <QIcon>
77 #include <QImageReader>
78 #include <QLocale>
79 #include <QLibraryInfo>
80 #include <QList>
81 #include <QMacPasteboardMime>
82 #include <QMenuBar>
83 #include <QMimeData>
84 #include <QObject>
85 #include <QPixmap>
86 #include <QPixmapCache>
87 #include <QRegExp>
88 #include <QSessionManager>
89 #include <QSettings>
90 #include <QSocketNotifier>
91 #include <QSortFilterProxyModel>
92 #include <QStandardItemModel>
93 #include <QTextCodec>
94 #include <QTimer>
95 #include <QTranslator>
96 #include <QWidget>
97
98 #ifdef Q_WS_X11
99 #include <X11/Xatom.h>
100 #include <X11/Xlib.h>
101 #undef CursorShape
102 #undef None
103 #endif
104
105 #ifdef Q_WS_WIN
106 #include <QWindowsMime>
107 #ifdef Q_CC_GNU
108 #include <wtypes.h>
109 #endif
110 #include <objidl.h>
111 #endif // Q_WS_WIN
112
113 #include <boost/bind.hpp>
114 #include <boost/crc.hpp>
115
116 #include <exception>
117 #include <vector>
118
119 using namespace std;
120 using namespace lyx::support;
121
122
123 static void initializeResources()
124 {
125         static bool initialized = false;
126         if (!initialized) {
127                 Q_INIT_RESOURCE(Resources); 
128                 initialized = true;
129         }
130 }
131
132
133 namespace lyx {
134
135 frontend::Application * createApplication(int & argc, char * argv[])
136 {
137 #ifndef Q_WS_X11
138         // prune -geometry argument(s) by shifting
139         // the following ones 2 places down.
140         for (int i = 0 ; i < argc ; ++i) {
141                 if (strcmp(argv[i], "-geometry") == 0) {
142                         int const remove = (i+1) < argc ? 2 : 1;
143                         argc -= remove;
144                         for (int j = i; j < argc; ++j)
145                                 argv[j] = argv[j + remove];
146                         --i;
147                 }
148         }
149 #endif
150         return new frontend::GuiApplication(argc, argv);
151 }
152
153 namespace frontend {
154
155
156 /// Return the list of loadable formats.
157 vector<string> loadableImageFormats()
158 {
159         vector<string> fmts;
160
161         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
162
163         LYXERR(Debug::GRAPHICS,
164                 "\nThe image loader can load the following directly:\n");
165
166         if (qt_formats.empty())
167                 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
168
169         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
170
171                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
172
173                 string ext = ascii_lowercase((const char *) *it);
174                 // special case
175                 if (ext == "jpeg")
176                         ext = "jpg";
177                 fmts.push_back(ext);
178         }
179
180         return fmts;
181 }
182
183
184 ////////////////////////////////////////////////////////////////////////
185 //
186 // Icon loading support code
187 //
188 ////////////////////////////////////////////////////////////////////////
189
190 namespace {
191
192 struct PngMap {
193         QString key;
194         QString value;
195 };
196
197
198 bool operator<(PngMap const & lhs, PngMap const & rhs)
199 {
200         return lhs.key < rhs.key;
201 }
202
203
204 class CompareKey {
205 public:
206         CompareKey(QString const & name) : name_(name) {}
207         bool operator()(PngMap const & other) const { return other.key == name_; }
208 private:
209         QString const name_;
210 };
211
212
213 // this must be sorted alphabetically
214 // Upper case comes before lower case
215 PngMap sorted_png_map[] = {
216         { "Bumpeq", "bumpeq2" },
217         { "Cap", "cap2" },
218         { "Cup", "cup2" },
219         { "Delta", "delta2" },
220         { "Downarrow", "downarrow2" },
221         { "Gamma", "gamma2" },
222         { "Lambda", "lambda2" },
223         { "Leftarrow", "leftarrow2" },
224         { "Leftrightarrow", "leftrightarrow2" },
225         { "Longleftarrow", "longleftarrow2" },
226         { "Longleftrightarrow", "longleftrightarrow2" },
227         { "Longrightarrow", "longrightarrow2" },
228         { "Omega", "omega2" },
229         { "Phi", "phi2" },
230         { "Pi", "pi2" },
231         { "Psi", "psi2" },
232         { "Rightarrow", "rightarrow2" },
233         { "Sigma", "sigma2" },
234         { "Subset", "subset2" },
235         { "Supset", "supset2" },
236         { "Theta", "theta2" },
237         { "Uparrow", "uparrow2" },
238         { "Updownarrow", "updownarrow2" },
239         { "Upsilon", "upsilon2" },
240         { "Vdash", "vdash3" },
241         { "Vert", "vert2" },
242         { "Xi", "xi2" },
243         { "nLeftarrow", "nleftarrow2" },
244         { "nLeftrightarrow", "nleftrightarrow2" },
245         { "nRightarrow", "nrightarrow2" },
246         { "nVDash", "nvdash3" },
247         { "nvDash", "nvdash2" },
248         { "textrm \\AA", "textrm_AA"},
249         { "textrm \\O", "textrm_O"},
250         { "vDash", "vdash2" }
251 };
252
253 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
254
255
256 QString findPng(QString const & name)
257 {
258         PngMap const * const begin = sorted_png_map;
259         PngMap const * const end = begin + nr_sorted_png_map;
260         LASSERT(sorted(begin, end), /**/);
261
262         PngMap const * const it = find_if(begin, end, CompareKey(name));
263
264         QString png_name;
265         if (it != end) {
266                 png_name = it->value;
267         } else {
268                 png_name = name;
269                 png_name.replace('_', "underscore");
270                 png_name.replace(' ', '_');
271
272                 // This way we can have "math-delim { }" on the toolbar.
273                 png_name.replace('(', "lparen");
274                 png_name.replace(')', "rparen");
275                 png_name.replace('[', "lbracket");
276                 png_name.replace(']', "rbracket");
277                 png_name.replace('{', "lbrace");
278                 png_name.replace('}', "rbrace");
279                 png_name.replace('|', "bars");
280                 png_name.replace(',', "thinspace");
281                 png_name.replace(':', "mediumspace");
282                 png_name.replace(';', "thickspace");
283                 png_name.replace('!', "negthinspace");
284         }
285
286         LYXERR(Debug::GUI, "findPng(" << name << ")\n"
287                 << "Looking for math PNG called \"" << png_name << '"');
288         return png_name;
289 }
290
291 } // namespace anon
292
293
294 QString iconName(FuncRequest const & f, bool unknown)
295 {
296         initializeResources();
297         QString name1;
298         QString name2;
299         QString path;
300         switch (f.action) {
301         case LFUN_MATH_INSERT:
302                 if (!f.argument().empty()) {
303                         path = "math/";
304                         name1 = findPng(toqstr(f.argument()).mid(1));
305                 }
306                 break;
307         case LFUN_MATH_DELIM:
308         case LFUN_MATH_BIGDELIM:
309                 path = "math/";
310                 name1 = findPng(toqstr(f.argument()));
311                 break;
312         case LFUN_CALL:
313                 path = "commands/";
314                 name1 = toqstr(f.argument());
315                 break;
316         case LFUN_COMMAND_ALTERNATIVES: {
317                 // use the first of the alternative commands
318                 docstring firstcom;
319                 docstring dummy = split(f.argument(), firstcom, ';');
320                 name1 = toqstr(firstcom);
321                 name1.replace(' ', '_');
322                 break;
323         }
324         default:
325                 name2 = toqstr(lyxaction.getActionName(f.action));
326                 name1 = name2;
327
328                 if (!f.argument().empty()) {
329                         name1 = name2 + ' ' + toqstr(f.argument());
330                         name1.replace(' ', '_');
331                         name1.replace('\\', "backslash");
332                 }
333         }
334
335         FileName fname = libFileSearch("images/" + path, name1, "png");
336         if (fname.exists())
337                 return toqstr(fname.absFilename());
338
339         fname = libFileSearch("images/" + path, name2, "png");
340         if (fname.exists())
341                 return toqstr(fname.absFilename());
342
343         path = ":/images/" + path;
344         QDir res(path);
345         if (!res.exists()) {
346                 LYXERR0("Directory " << path << " not found in resource!"); 
347                 return QString();
348         }
349         name1 += ".png";
350         if (res.exists(name1))
351                 return path + name1;
352
353         name2 += ".png";
354         if (res.exists(name2))
355                 return path + name2;
356
357         LYXERR(Debug::GUI, "Cannot find icon with filename "
358                            << "\"" << name1 << "\""
359                            << " or filename "
360                            << "\"" << name2 << "\"" 
361                            << " for command \""
362                            << lyxaction.getActionName(f.action)
363                            << '(' << to_utf8(f.argument()) << ")\"");
364
365         if (unknown) {
366                 fname = libFileSearch(QString("images/"), "unknown", "png");
367                 if (fname.exists())
368                         return toqstr(fname.absFilename());
369                 return QString(":/images/unknown.png");
370         }
371
372         return QString();
373 }
374
375 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
376 {
377         QPixmap pixmap;
378         FileName fname = libFileSearch(path, name, ext);
379         QString path1 = toqstr(fname.absFilename());
380         QString path2 = ":/" + path + name + "." + ext;
381
382         if (pixmap.load(path1)) {
383                 return pixmap;
384         }
385         else if (pixmap.load(path2)) {
386                 return pixmap;
387         }
388
389         LYXERR0("Cannot load pixmap \""
390                 << path << name << '.' << ext
391                 << "\", please verify resource system!");
392
393         return QPixmap();
394 }
395
396 QIcon getIcon(FuncRequest const & f, bool unknown)
397 {
398         QString icon = iconName(f, unknown);
399         if (icon.isEmpty())
400                 return QIcon();
401
402         //LYXERR(Debug::GUI, "Found icon: " << icon);
403         QPixmap pm;
404         if (!pm.load(icon)) {
405                 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
406                 return QIcon();
407         }
408
409         return QIcon(pm);
410 }
411
412
413 ////////////////////////////////////////////////////////////////////////
414 //
415 // LyX server support code.
416 //
417 ////////////////////////////////////////////////////////////////////////
418
419 class SocketNotifier : public QSocketNotifier
420 {
421 public:
422         /// connect a connection notification from the LyXServerSocket
423         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
424                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
425         {}
426
427 public:
428         /// The callback function
429         Application::SocketCallback func_;
430 };
431
432
433 ////////////////////////////////////////////////////////////////////////
434 //
435 // Mac specific stuff goes here...
436 //
437 ////////////////////////////////////////////////////////////////////////
438
439 class MenuTranslator : public QTranslator
440 {
441 public:
442         MenuTranslator(QObject * parent)
443                 : QTranslator(parent)
444         {}
445
446         QString translate(const char * /*context*/, 
447           const char * sourceText, 
448           const char * /*comment*/ = 0) 
449         {
450                 string const s = sourceText;
451                 if (s == N_("About %1") || s == N_("Preferences") 
452                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
453                         return qt_(s);
454                 else 
455                         return QString();
456         }
457 };
458
459 class GlobalMenuBar : public QMenuBar
460 {
461 public:
462         ///
463         GlobalMenuBar() : QMenuBar(0) {}
464         
465         ///
466         bool event(QEvent * e)
467         {
468                 if (e->type() == QEvent::ShortcutOverride) {
469                         //          && activeWindow() == 0) {
470                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
471                         KeySymbol sym;
472                         setKeySymbol(&sym, ke);
473                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
474                         e->accept();
475                         return true;
476                 }
477                 return false;
478         }
479 };
480
481 #ifdef Q_WS_MACX
482 // QMacPasteboardMimeGraphics can only be compiled on Mac.
483
484 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
485 {
486 public:
487         QMacPasteboardMimeGraphics()
488                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
489         {}
490
491         QString convertorName() { return "Graphics"; }
492
493         QString flavorFor(QString const & mime)
494         {
495                 LYXERR(Debug::ACTION, "flavorFor " << mime);
496                 if (mime == pdfMimeType())
497                         return QLatin1String("com.adobe.pdf");
498                 return QString();
499         }
500
501         QString mimeFor(QString flav)
502         {
503                 LYXERR(Debug::ACTION, "mimeFor " << flav);
504                 if (flav == QLatin1String("com.adobe.pdf"))
505                         return pdfMimeType();
506                 return QString();
507         }
508
509         bool canConvert(QString const & mime, QString flav)
510         {
511                 return mimeFor(flav) == mime;
512         }
513
514         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
515                 QString /*flav*/)
516         {
517                 if(data.count() > 1)
518                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
519                 return data.first();
520         }
521
522         QList<QByteArray> convertFromMime(QString const & /*mime*/,
523                 QVariant data, QString /*flav*/)
524         {
525                 QList<QByteArray> ret;
526                 ret.append(data.toByteArray());
527                 return ret;
528         }
529 };
530 #endif
531
532 ///////////////////////////////////////////////////////////////
533 //
534 // You can find more platform specific stuff at the end of this file...
535 //
536 ///////////////////////////////////////////////////////////////
537
538 ////////////////////////////////////////////////////////////////////////
539 // Windows specific stuff goes here...
540
541 #ifdef Q_WS_WIN
542 // QWindowsMimeMetafile can only be compiled on Windows.
543
544 static FORMATETC cfFromMime(QString const & mimetype)
545 {
546         FORMATETC formatetc;
547         if (mimetype == emfMimeType()) {
548                 formatetc.cfFormat = CF_ENHMETAFILE;
549                 formatetc.tymed = TYMED_ENHMF;
550         } else if (mimetype == wmfMimeType()) {
551                 formatetc.cfFormat = CF_METAFILEPICT;
552                 formatetc.tymed = TYMED_MFPICT;
553         }
554         formatetc.ptd = 0;
555         formatetc.dwAspect = DVASPECT_CONTENT;
556         formatetc.lindex = -1;
557         return formatetc;
558 }
559
560
561 class QWindowsMimeMetafile : public QWindowsMime {
562 public:
563         QWindowsMimeMetafile() {}
564
565         bool canConvertFromMime(FORMATETC const & formatetc,
566                 QMimeData const * mimedata) const
567         {
568                 return false;
569         }
570
571         bool canConvertToMime(QString const & mimetype,
572                 IDataObject * pDataObj) const
573         {
574                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
575                         return false;
576                 FORMATETC formatetc = cfFromMime(mimetype);
577                 return pDataObj->QueryGetData(&formatetc) == S_OK;
578         }
579
580         bool convertFromMime(FORMATETC const & formatetc,
581                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
582         {
583                 return false;
584         }
585
586         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
587                 QVariant::Type preferredType) const
588         {
589                 QByteArray data;
590                 if (!canConvertToMime(mimetype, pDataObj))
591                         return data;
592
593                 FORMATETC formatetc = cfFromMime(mimetype);
594                 STGMEDIUM s;
595                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
596                         return data;
597
598                 int dataSize;
599                 if (s.tymed == TYMED_ENHMF) {
600                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
601                         data.resize(dataSize);
602                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
603                                 (LPBYTE)data.data());
604                 } else if (s.tymed == TYMED_MFPICT) {
605                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
606                         data.resize(dataSize);
607                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
608                                 (LPBYTE)data.data());
609                 }
610                 data.detach();
611                 ReleaseStgMedium(&s);
612
613                 return data;
614         }
615
616
617         QVector<FORMATETC> formatsForMime(QString const & mimetype,
618                 QMimeData const * mimedata) const
619         {
620                 QVector<FORMATETC> formats;
621                 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
622                         formats += cfFromMime(mimetype);
623                 return formats;
624         }
625
626         QString mimeForFormat(FORMATETC const & formatetc) const
627         {
628                 switch (formatetc.cfFormat) {
629                 case CF_ENHMETAFILE:
630                         return emfMimeType(); 
631                 case CF_METAFILEPICT:
632                         return wmfMimeType();
633                 }
634                 return QString();
635         }
636 };
637
638 #endif // Q_WS_WIN
639
640 ////////////////////////////////////////////////////////////////////////
641 // GuiApplication::Private definition and implementation.
642 ////////////////////////////////////////////////////////////////////////
643
644 struct GuiApplication::Private
645 {
646         Private(): language_model_(0), global_menubar_(0) 
647         {
648         #ifdef Q_WS_WIN
649                 /// WMF Mime handler for Windows clipboard.
650                 wmf_mime_ = new QWindowsMimeMetafile();
651         #endif
652         }
653
654         ///
655         QSortFilterProxyModel * language_model_;
656         ///
657         GuiClipboard clipboard_;
658         ///
659         GuiSelection selection_;
660         ///
661         FontLoader font_loader_;
662         ///
663         ColorCache color_cache_;
664         ///
665         QTranslator qt_trans_;
666         ///
667         QHash<int, SocketNotifier *> socket_notifiers_;
668         ///
669         Menus menus_;
670         ///
671         /// The global instance
672         Toolbars toolbars_;
673
674         /// this timer is used for any regular events one wants to
675         /// perform. at present it is used to check if forked processes
676         /// are done.
677         QTimer general_timer_;
678
679         /// delayed FuncRequests
680         std::queue<FuncRequest> func_request_queue_;
681
682         /// Multiple views container.
683         /**
684         * Warning: This must not be a smart pointer as the destruction of the
685         * object is handled by Qt when the view is closed
686         * \sa Qt::WA_DeleteOnClose attribute.
687         */
688         QHash<int, GuiView *> views_;
689
690         /// Only used on mac.
691         GlobalMenuBar * global_menubar_;
692
693 #ifdef Q_WS_MACX
694         /// Linkback mime handler for MacOSX.
695         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
696 #endif
697
698 #ifdef Q_WS_WIN
699         /// WMF Mime handler for Windows clipboard.
700         QWindowsMimeMetafile * wmf_mime_;
701 #endif
702 };
703
704
705 GuiApplication * guiApp;
706
707 GuiApplication::~GuiApplication()
708 {
709 #ifdef Q_WS_MACX
710         closeAllLinkBackLinks();
711 #endif
712         delete d;
713 }
714
715
716 GuiApplication::GuiApplication(int & argc, char ** argv)
717         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
718 {
719         QString app_name = "LyX";
720         QCoreApplication::setOrganizationName(app_name);
721         QCoreApplication::setOrganizationDomain("lyx.org");
722         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
723
724         // Install translator for GUI elements.
725         installTranslator(&d->qt_trans_);
726
727         // FIXME: quitOnLastWindowClosed is true by default. We should have a
728         // lyxrc setting for this in order to let the application stay resident.
729         // But then we need some kind of dock icon, at least on Windows.
730         /*
731         if (lyxrc.quit_on_last_window_closed)
732                 setQuitOnLastWindowClosed(false);
733         */
734 #ifdef Q_WS_MACX
735         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
736         // seems to be the default case for applications like LyX.
737         setQuitOnLastWindowClosed(false);
738
739         // This allows to translate the strings that appear in the LyX menu.
740         /// A translator suitable for the entries in the LyX menu.
741         /// Only needed with Qt/Mac.
742         installTranslator(new MenuTranslator(this));
743 #endif
744         
745 #ifdef Q_WS_X11
746         // doubleClickInterval() is 400 ms on X11 which is just too long.
747         // On Windows and Mac OS X, the operating system's value is used.
748         // On Microsoft Windows, calling this function sets the double
749         // click interval for all applications. So we don't!
750         QApplication::setDoubleClickInterval(300);
751 #endif
752
753         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
754
755         // needs to be done before reading lyxrc
756         QWidget w;
757         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
758
759         guiApp = this;
760
761         // Set the cache to 5120 kilobytes which corresponds to screen size of
762         // 1280 by 1024 pixels with a color depth of 32 bits.
763         QPixmapCache::setCacheLimit(5120);
764
765         // Initialize RC Fonts
766         if (lyxrc.roman_font_name.empty())
767                 lyxrc.roman_font_name = fromqstr(romanFontName());
768
769         if (lyxrc.sans_font_name.empty())
770                 lyxrc.sans_font_name = fromqstr(sansFontName());
771
772         if (lyxrc.typewriter_font_name.empty())
773                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
774
775         d->general_timer_.setInterval(500);
776         connect(&d->general_timer_, SIGNAL(timeout()),
777                 this, SLOT(handleRegularEvents()));
778         d->general_timer_.start();
779 }
780
781
782 GuiApplication * theGuiApp()
783 {
784         return dynamic_cast<GuiApplication *>(theApp());
785 }
786
787
788 void GuiApplication::clearSession()
789 {
790         QSettings settings;
791         settings.clear();
792 }
793
794
795 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
796 {
797         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
798 }
799
800
801
802 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
803 {
804         bool enable = true;
805
806         switch(cmd.action) {
807
808         case LFUN_WINDOW_CLOSE:
809                 enable = d->views_.size() > 0;
810                 break;
811
812         case LFUN_BUFFER_NEW:
813         case LFUN_BUFFER_NEW_TEMPLATE:
814         case LFUN_FILE_OPEN:
815         case LFUN_SCREEN_FONT_UPDATE:
816         case LFUN_SET_COLOR:
817         case LFUN_WINDOW_NEW:
818         case LFUN_LYX_QUIT:
819                 enable = true;
820                 break;
821
822         default:
823                 return false;
824         }
825
826         if (!enable)
827                 flag.setEnabled(false);
828
829         return true;
830 }
831
832         
833 bool GuiApplication::dispatch(FuncRequest const & cmd)
834 {
835         switch (cmd.action) {
836
837         case LFUN_WINDOW_NEW:
838                 createView(toqstr(cmd.argument()));
839                 break;
840
841         case LFUN_WINDOW_CLOSE:
842                 // update bookmark pit of the current buffer before window close
843                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
844                         theLyXFunc().gotoBookmark(i+1, false, false);
845                 current_view_->close();
846                 break;
847
848         case LFUN_LYX_QUIT:
849                 // quitting is triggered by the gui code
850                 // (leaving the event loop).
851                 if (current_view_)
852                         current_view_->message(from_utf8(N_("Exiting.")));
853                 if (closeAllViews())
854                         quit();
855                 break;
856
857         case LFUN_SCREEN_FONT_UPDATE: {
858                 // handle the screen font changes.
859                 d->font_loader_.update();
860                 // Backup current_view_
861                 GuiView * view = current_view_;
862                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
863                 // to skip the refresh.
864                 current_view_ = 0;
865                 BufferList::iterator it = theBufferList().begin();
866                 BufferList::iterator const end = theBufferList().end();
867                 for (; it != end; ++it)
868                         (*it)->changed();
869                 // Restore current_view_
870                 current_view_ = view;
871                 break;
872         }
873
874         case LFUN_BUFFER_NEW:
875                 if (d->views_.empty()
876                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
877                         createView(QString(), false); // keep hidden
878                         current_view_->newDocument(to_utf8(cmd.argument()), false);
879                         current_view_->show();
880                         setActiveWindow(current_view_);
881                 } else {
882                         current_view_->newDocument(to_utf8(cmd.argument()), false);
883                 }
884                 break;
885
886         case LFUN_BUFFER_NEW_TEMPLATE:
887                 if (d->views_.empty()
888                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
889                         createView();
890                         current_view_->newDocument(to_utf8(cmd.argument()), true);
891                         if (!current_view_->buffer())
892                                 current_view_->close();
893                 } else {
894                         current_view_->newDocument(to_utf8(cmd.argument()), true);
895                 }
896                 break;
897
898         case LFUN_FILE_OPEN:
899                 if (d->views_.empty()
900                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
901                         string const fname = to_utf8(cmd.argument());
902                         // We want the ui session to be saved per document and not per
903                         // window number. The filename crc is a good enough identifier.
904                         boost::crc_32_type crc;
905                         crc = for_each(fname.begin(), fname.end(), crc);
906                         createView(crc.checksum());
907                         current_view_->openDocument(fname);
908                         if (current_view_ && !current_view_->buffer())
909                                 current_view_->close();
910                 } else
911                         current_view_->openDocument(to_utf8(cmd.argument()));
912                 break;
913
914         case LFUN_SET_COLOR: {
915                 string lyx_name;
916                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
917                 if (lyx_name.empty() || x11_name.empty()) {
918                         current_view_->message(
919                                 _("Syntax: set-color <lyx_name> <x11_name>"));
920                         break;
921                 }
922
923                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
924                 bool const graphicsbg_changed = lyx_name == graphicsbg
925                         && x11_name != graphicsbg;
926                 if (graphicsbg_changed) {
927                         // FIXME: The graphics cache no longer has a changeDisplay method.
928 #if 0
929                         graphics::GCache::get().changeDisplay(true);
930 #endif
931                 }
932
933                 if (!lcolor.setColor(lyx_name, x11_name)) {
934                         current_view_->message(
935                                         bformat(_("Set-color \"%1$s\" failed "
936                                                                "- color is undefined or "
937                                                                "may not be redefined"),
938                                                                    from_utf8(lyx_name)));
939                         break;
940                 }
941                 // Make sure we don't keep old colors in cache.
942                 d->color_cache_.clear();
943                 break;
944         }
945
946         default:
947                 // Notify the caller that the action has not been dispatched.
948                 return false;
949         }
950
951         // The action has been dispatched.
952         return true;
953 }
954
955
956 void GuiApplication::dispatchDelayed(FuncRequest const & func)
957 {
958         d->func_request_queue_.push(func);
959         QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
960 }
961
962
963 void GuiApplication::resetGui()
964 {
965         // Set the language defined by the user.
966         setGuiLanguage();
967
968         // Read menus
969         if (!readUIFile(toqstr(lyxrc.ui_file)))
970                 // Gives some error box here.
971                 return;
972
973         if (d->global_menubar_)
974                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
975
976         QHash<int, GuiView *>::iterator it;
977         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
978                 GuiView * gv = *it;
979                 gv->setLayoutDirection(layoutDirection());
980                 gv->resetDialogs();
981         }
982
983         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
984 }
985
986
987 void GuiApplication::createView(int view_id)
988 {
989         createView(QString(), true, view_id);
990 }
991
992
993 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
994         int view_id)
995 {
996         // release the keyboard which might have been grabed by the global
997         // menubar on Mac to catch shortcuts even without any GuiView.
998         if (d->global_menubar_)
999                 d->global_menubar_->releaseKeyboard();
1000
1001         // create new view
1002         int id = view_id;
1003         if (id == 0) {
1004                 while (d->views_.find(id) != d->views_.end())
1005                         id++;
1006         }
1007         LYXERR(Debug::GUI, "About to create new window with ID " << id);
1008         GuiView * view = new GuiView(id);
1009         // register view
1010         d->views_[id] = view;
1011
1012         if (autoShow) {
1013                 view->show();
1014                 setActiveWindow(view);
1015         }
1016
1017         if (!geometry_arg.isEmpty()) {
1018 #ifdef Q_WS_WIN
1019                 int x, y;
1020                 int w, h;
1021                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1022                 re.indexIn(geometry_arg);
1023                 w = re.cap(1).toInt();
1024                 h = re.cap(2).toInt();
1025                 x = re.cap(3).toInt();
1026                 y = re.cap(4).toInt();
1027                 view->setGeometry(x, y, w, h);
1028 #endif
1029         }
1030         view->setFocus();
1031 }
1032
1033
1034 Clipboard & GuiApplication::clipboard()
1035 {
1036         return d->clipboard_;
1037 }
1038
1039
1040 Selection & GuiApplication::selection()
1041 {
1042         return d->selection_;
1043 }
1044
1045
1046 FontLoader & GuiApplication::fontLoader() 
1047 {
1048         return d->font_loader_;
1049 }
1050
1051
1052 Toolbars const & GuiApplication::toolbars() const 
1053 {
1054         return d->toolbars_;
1055 }
1056
1057
1058 Toolbars & GuiApplication::toolbars()
1059 {
1060         return d->toolbars_; 
1061 }
1062
1063
1064 Menus const & GuiApplication::menus() const 
1065 {
1066         return d->menus_;
1067 }
1068
1069
1070 Menus & GuiApplication::menus()
1071 {
1072         return d->menus_; 
1073 }
1074
1075
1076 QList<int> GuiApplication::viewIds() const
1077 {
1078         return d->views_.keys();
1079 }
1080
1081
1082 ColorCache & GuiApplication::colorCache()
1083 {
1084         return d->color_cache_;
1085 }
1086
1087
1088 int GuiApplication::exec()
1089 {
1090         // asynchronously handle batch commands. This event will be in
1091         // the event queue in front of other asynchronous events. Hence,
1092         // we can assume in the latter that the gui is setup already.
1093         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1094
1095         return QApplication::exec();
1096 }
1097
1098
1099 void GuiApplication::exit(int status)
1100 {
1101         QApplication::exit(status);
1102 }
1103
1104
1105 void GuiApplication::setGuiLanguage()
1106 {
1107         // Set the language defined by the user.
1108         setRcGuiLanguage();
1109
1110         QString const default_language = toqstr(Messages::defaultLanguage());
1111         LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1112         QLocale const default_locale(default_language);
1113         QLocale::setDefault(default_locale);
1114
1115         // install translation file for Qt built-in dialogs
1116         QString const language_name = QString("qt_") + default_locale.name();
1117
1118         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1119         // Short-named translator can be loaded from a long name, but not the
1120         // opposite. Therefore, long name should be used without truncation.
1121         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1122         if (!d->qt_trans_.load(language_name,
1123                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1124                 LYXERR(Debug::LOCALE, "Could not find  Qt translations for locale "
1125                         << language_name);
1126         } else {
1127                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1128                         << language_name);
1129         }
1130
1131         switch (default_locale.language()) {
1132         case QLocale::Arabic :
1133         case QLocale::Hebrew :
1134         case QLocale::Persian :
1135         case QLocale::Urdu :
1136         setLayoutDirection(Qt::RightToLeft);
1137                 break;
1138         default:
1139         setLayoutDirection(Qt::LeftToRight);
1140         }
1141 }
1142
1143
1144 void GuiApplication::processFuncRequestQueue()
1145 {
1146         while (!d->func_request_queue_.empty()) {
1147                 lyx::dispatch(d->func_request_queue_.back());
1148                 d->func_request_queue_.pop();
1149         }
1150 }
1151
1152
1153 void GuiApplication::execBatchCommands()
1154 {
1155         setGuiLanguage();
1156
1157         // Read menus
1158         if (!readUIFile(toqstr(lyxrc.ui_file)))
1159                 // Gives some error box here.
1160                 return;
1161
1162 #ifdef Q_WS_MACX
1163         // Create the global default menubar which is shown for the dialogs
1164         // and if no GuiView is visible.
1165         // This must be done after the session was recovered to know the "last files".
1166         d->global_menubar_ = new GlobalMenuBar();
1167         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1168 #endif
1169
1170         lyx::execBatchCommands();
1171 }
1172
1173
1174 QAbstractItemModel * GuiApplication::languageModel()
1175 {
1176         if (d->language_model_)
1177                 return d->language_model_;
1178
1179         QStandardItemModel * lang_model = new QStandardItemModel(this);
1180         lang_model->insertColumns(0, 1);
1181         int current_row;
1182         Languages::const_iterator it = languages.begin();
1183         Languages::const_iterator end = languages.end();
1184         for (; it != end; ++it) {
1185                 current_row = lang_model->rowCount();
1186                 lang_model->insertRows(current_row, 1);
1187                 QModelIndex item = lang_model->index(current_row, 0);
1188                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1189                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1190         }
1191         d->language_model_ = new QSortFilterProxyModel(this);
1192         d->language_model_->setSourceModel(lang_model);
1193 #if QT_VERSION >= 0x040300
1194         d->language_model_->setSortLocaleAware(true);
1195 #endif
1196         return d->language_model_;
1197 }
1198
1199
1200 void GuiApplication::restoreGuiSession()
1201 {
1202         if (!lyxrc.load_session)
1203                 return;
1204
1205         Session & session = theSession();
1206         LastOpenedSection::LastOpened const & lastopened = 
1207                 session.lastOpened().getfiles();
1208
1209         FileName active_file;
1210         // do not add to the lastfile list since these files are restored from
1211         // last session, and should be already there (regular files), or should
1212         // not be added at all (help files).
1213         // Note that we open them in reverse order. This is because we close
1214         // buffers also in reverse order (aesthetically motivated).
1215         for (size_t i = lastopened.size(); i > 0; --i) {
1216                 current_view_->loadDocument(lastopened[i - 1].file_name, false);
1217                 if (lastopened[i - 1].active)
1218                         active_file = lastopened[i - 1].file_name;
1219         }
1220
1221         // Restore last active buffer
1222         Buffer * buffer = theBufferList().getBuffer(active_file);
1223         if (buffer)
1224                 current_view_->setBuffer(buffer);
1225
1226         // clear this list to save a few bytes of RAM
1227         session.lastOpened().clear();
1228 }
1229
1230
1231 QString const GuiApplication::romanFontName()
1232 {
1233         QFont font;
1234         font.setKerning(false);
1235         font.setStyleHint(QFont::Serif);
1236         font.setFamily("serif");
1237
1238         return QFontInfo(font).family();
1239 }
1240
1241
1242 QString const GuiApplication::sansFontName()
1243 {
1244         QFont font;
1245         font.setKerning(false);
1246         font.setStyleHint(QFont::SansSerif);
1247         font.setFamily("sans");
1248
1249         return QFontInfo(font).family();
1250 }
1251
1252
1253 QString const GuiApplication::typewriterFontName()
1254 {
1255         QFont font;
1256         font.setKerning(false);
1257         font.setStyleHint(QFont::TypeWriter);
1258         font.setFamily("monospace");
1259
1260         return QFontInfo(font).family();
1261 }
1262
1263
1264 void GuiApplication::handleRegularEvents()
1265 {
1266         ForkedCallsController::handleCompletedProcesses();
1267 }
1268
1269
1270 bool GuiApplication::event(QEvent * e)
1271 {
1272         switch(e->type()) {
1273         case QEvent::FileOpen: {
1274                 // Open a file; this happens only on Mac OS X for now.
1275                 //
1276                 // We do this asynchronously because on startup the batch
1277                 // commands are not executed here yet and the gui is not ready
1278                 // therefore.
1279                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1280                 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1281                 e->accept();
1282                 return true;
1283         }
1284         default:
1285                 return QApplication::event(e);
1286         }
1287 }
1288
1289
1290 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1291 {
1292         try {
1293                 return QApplication::notify(receiver, event);
1294         }
1295         catch (ExceptionMessage const & e) {
1296                 switch(e.type_) { 
1297                 case ErrorException:
1298                         emergencyCleanup();
1299                         setQuitOnLastWindowClosed(false);
1300                         closeAllViews();
1301                         Alert::error(e.title_, e.details_);
1302 #ifndef NDEBUG
1303                         // Properly crash in debug mode in order to get a useful backtrace.
1304                         abort();
1305 #endif
1306                         // In release mode, try to exit gracefully.
1307                         this->exit(1);
1308
1309                 case BufferException: {
1310                         Buffer * buf = current_view_->buffer();
1311                         docstring details = e.details_ + '\n';
1312                         details += theBufferList().emergencyWrite(buf);
1313                         theBufferList().release(buf);
1314                         details += "\n" + _("The current document was closed.");
1315                         Alert::error(e.title_, details);
1316                         return false;
1317                 }
1318                 case WarningException:
1319                         Alert::warning(e.title_, e.details_);
1320                         return false;
1321                 }
1322         }
1323         catch (exception const & e) {
1324                 docstring s = _("LyX has caught an exception, it will now "
1325                         "attempt to save all unsaved documents and exit."
1326                         "\n\nException: ");
1327                 s += from_ascii(e.what());
1328                 Alert::error(_("Software exception Detected"), s);
1329                 lyx_exit(1);
1330         }
1331         catch (...) {
1332                 docstring s = _("LyX has caught some really weird exception, it will "
1333                         "now attempt to save all unsaved documents and exit.");
1334                 Alert::error(_("Software exception Detected"), s);
1335                 lyx_exit(1);
1336         }
1337
1338         return false;
1339 }
1340
1341
1342 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1343 {
1344         QColor const & qcol = d->color_cache_.get(col);
1345         if (!qcol.isValid()) {
1346                 rgbcol.r = 0;
1347                 rgbcol.g = 0;
1348                 rgbcol.b = 0;
1349                 return false;
1350         }
1351         rgbcol.r = qcol.red();
1352         rgbcol.g = qcol.green();
1353         rgbcol.b = qcol.blue();
1354         return true;
1355 }
1356
1357
1358 string const GuiApplication::hexName(ColorCode col)
1359 {
1360         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1361 }
1362
1363
1364 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1365 {
1366         SocketNotifier * sn = new SocketNotifier(this, fd, func);
1367         d->socket_notifiers_[fd] = sn;
1368         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1369 }
1370
1371
1372 void GuiApplication::socketDataReceived(int fd)
1373 {
1374         d->socket_notifiers_[fd]->func_();
1375 }
1376
1377
1378 void GuiApplication::unregisterSocketCallback(int fd)
1379 {
1380         d->socket_notifiers_.take(fd)->setEnabled(false);
1381 }
1382
1383
1384 void GuiApplication::commitData(QSessionManager & sm)
1385 {
1386         /// The implementation is required to avoid an application exit
1387         /// when session state save is triggered by session manager.
1388         /// The default implementation sends a close event to all
1389         /// visible top level widgets when session managment allows
1390         /// interaction.
1391         /// We are changing that to close all wiew one by one.
1392         /// FIXME: verify if the default implementation is enough now.
1393         if (sm.allowsInteraction() && !closeAllViews())
1394                 sm.cancel();
1395 }
1396
1397
1398 void GuiApplication::unregisterView(GuiView * gv)
1399 {
1400         LASSERT(d->views_[gv->id()] == gv, /**/);
1401         d->views_.remove(gv->id());
1402         if (current_view_ == gv) {
1403                 current_view_ = 0;
1404                 theLyXFunc().setLyXView(0);
1405         }
1406 }
1407
1408
1409 bool GuiApplication::closeAllViews()
1410 {
1411         if (d->views_.empty())
1412                 return true;
1413
1414         // When a view/window was closed before without quitting LyX, there
1415         // are already entries in the lastOpened list.
1416         theSession().lastOpened().clear();
1417
1418         QList<GuiView *> views = d->views_.values();
1419         foreach (GuiView * view, views) {
1420                 if (!view->close())
1421                         return false;
1422         }
1423
1424         d->views_.clear();
1425         return true;
1426 }
1427
1428
1429 GuiView & GuiApplication::view(int id) const
1430 {
1431         LASSERT(d->views_.contains(id), /**/);
1432         return *d->views_.value(id);
1433 }
1434
1435
1436 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1437 {
1438         QList<GuiView *> views = d->views_.values();
1439         foreach (GuiView * view, views)
1440                 view->hideDialog(name, inset);
1441 }
1442
1443
1444 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1445 {
1446         Buffer const * buffer_ = 0;
1447         QHash<int, GuiView *>::iterator end = d->views_.end();
1448         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1449                 if (Buffer const * ptr = (*it)->updateInset(inset))
1450                         buffer_ = ptr;
1451         }
1452         return buffer_;
1453 }
1454
1455
1456 bool GuiApplication::searchMenu(FuncRequest const & func,
1457         docstring_list & names) const
1458 {
1459         return d->menus_.searchMenu(func, names);
1460 }
1461
1462
1463 bool GuiApplication::readUIFile(QString const & name, bool include)
1464 {
1465         enum {
1466                 ui_menuset = 1,
1467                 ui_toolbars,
1468                 ui_toolbarset,
1469                 ui_include,
1470                 ui_last
1471         };
1472
1473         LexerKeyword uitags[] = {
1474                 { "include", ui_include },
1475                 { "menuset", ui_menuset },
1476                 { "toolbars", ui_toolbars },
1477                 { "toolbarset", ui_toolbarset }
1478         };
1479
1480         LYXERR(Debug::INIT, "About to read " << name << "...");
1481
1482         FileName ui_path;
1483         if (include) {
1484                 ui_path = libFileSearch("ui", name, "inc");
1485                 if (ui_path.empty())
1486                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1487         } else {
1488                 ui_path = libFileSearch("ui", name, "ui");
1489         }
1490
1491         if (ui_path.empty()) {
1492                 LYXERR(Debug::INIT, "Could not find " << name);
1493                 Alert::warning(_("Could not find UI definition file"),
1494                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1495                                    "Please check your installation."), qstring_to_ucs4(name)));
1496                 return false;
1497         }
1498
1499
1500         // Ensure that a file is read only once (prevents include loops)
1501         static QStringList uifiles;
1502         QString const uifile = toqstr(ui_path.absFilename());
1503         if (uifiles.contains(uifile)) {
1504                 if (!include) {
1505                         // We are reading again the top uifile so reset the safeguard:
1506                         uifiles.clear();
1507                         d->menus_.reset();
1508                         d->toolbars_.reset();
1509                 } else {
1510                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1511                                 << "Is this an include loop?");
1512                         return false;
1513                 }
1514         }
1515         uifiles.push_back(uifile);
1516
1517         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1518
1519         Lexer lex(uitags);
1520         lex.setFile(ui_path);
1521         if (!lex.isOK()) {
1522                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1523                        << endl;
1524         }
1525
1526         if (lyxerr.debugging(Debug::PARSER))
1527                 lex.printTable(lyxerr);
1528
1529         while (lex.isOK()) {
1530                 switch (lex.lex()) {
1531                 case ui_include: {
1532                         lex.next(true);
1533                         QString const file = toqstr(lex.getString());
1534                         if (!readUIFile(file, true))
1535                                 return false;
1536                         break;
1537                 }
1538                 case ui_menuset:
1539                         d->menus_.read(lex);
1540                         break;
1541
1542                 case ui_toolbarset:
1543                         d->toolbars_.readToolbars(lex);
1544                         break;
1545
1546                 case ui_toolbars:
1547                         d->toolbars_.readToolbarSettings(lex);
1548                         break;
1549
1550                 default:
1551                         if (!rtrim(lex.getString()).empty())
1552                                 lex.printError("LyX::ReadUIFile: "
1553                                                "Unknown menu tag: `$$Token'");
1554                         break;
1555                 }
1556         }
1557
1558         if (include)
1559                 return true;
1560
1561         QSettings settings;
1562         settings.beginGroup("ui_files");
1563         bool touched = false;
1564         for (int i = 0; i != uifiles.size(); ++i) {
1565                 QFileInfo fi(uifiles[i]);
1566                 QDateTime const date_value = fi.lastModified();
1567                 QString const name_key = QString::number(i);
1568                 if (!settings.contains(name_key)
1569                  || settings.value(name_key).toString() != uifiles[i]
1570                  || settings.value(name_key + "/date").toDateTime() != date_value) {
1571                         touched = true;
1572                         settings.setValue(name_key, uifiles[i]);
1573                         settings.setValue(name_key + "/date", date_value);
1574                 }
1575         }
1576         settings.endGroup();
1577         if (touched)
1578                 settings.remove("views");
1579
1580         return true;
1581 }
1582
1583
1584 void GuiApplication::onLastWindowClosed()
1585 {
1586         if (d->global_menubar_)
1587                 d->global_menubar_->grabKeyboard();
1588 }
1589
1590
1591 ////////////////////////////////////////////////////////////////////////
1592 //
1593 // X11 specific stuff goes here...
1594
1595 #ifdef Q_WS_X11
1596 bool GuiApplication::x11EventFilter(XEvent * xev)
1597 {
1598         if (!current_view_)
1599                 return false;
1600
1601         switch (xev->type) {
1602         case SelectionRequest: {
1603                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1604                         break;
1605                 LYXERR(Debug::SELECTION, "X requested selection.");
1606                 BufferView * bv = current_view_->view();
1607                 if (bv) {
1608                         docstring const sel = bv->requestSelection();
1609                         if (!sel.empty())
1610                                 d->selection_.put(sel);
1611                 }
1612                 break;
1613         }
1614         case SelectionClear: {
1615                 if (xev->xselectionclear.selection != XA_PRIMARY)
1616                         break;
1617                 LYXERR(Debug::SELECTION, "Lost selection.");
1618                 BufferView * bv = current_view_->view();
1619                 if (bv)
1620                         bv->clearSelection();
1621                 break;
1622         }
1623         }
1624         return false;
1625 }
1626 #endif
1627
1628 } // namespace frontend
1629
1630
1631 void hideDialogs(std::string const & name, Inset * inset)
1632 {
1633         if (theApp())
1634                 theApp()->hideDialogs(name, inset);
1635 }
1636
1637
1638 ////////////////////////////////////////////////////////////////////
1639 //
1640 // Font stuff
1641 //
1642 ////////////////////////////////////////////////////////////////////
1643
1644 frontend::FontLoader & theFontLoader()
1645 {
1646         LASSERT(frontend::guiApp, /**/);
1647         return frontend::guiApp->fontLoader();
1648 }
1649
1650
1651 frontend::FontMetrics const & theFontMetrics(Font const & f)
1652 {
1653         return theFontMetrics(f.fontInfo());
1654 }
1655
1656
1657 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1658 {
1659         LASSERT(frontend::guiApp, /**/);
1660         return frontend::guiApp->fontLoader().metrics(f);
1661 }
1662
1663
1664 ////////////////////////////////////////////////////////////////////
1665 //
1666 // Misc stuff
1667 //
1668 ////////////////////////////////////////////////////////////////////
1669
1670 frontend::Clipboard & theClipboard()
1671 {
1672         LASSERT(frontend::guiApp, /**/);
1673         return frontend::guiApp->clipboard();
1674 }
1675
1676
1677 frontend::Selection & theSelection()
1678 {
1679         LASSERT(frontend::guiApp, /**/);
1680         return frontend::guiApp->selection();
1681 }
1682
1683
1684 } // namespace lyx
1685
1686 #include "moc_GuiApplication.cpp"