]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
172ac0bce479fd1ca07dee58dfd48eb2cdb15e94
[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                 return QString(":/images/unknown.png");
367
368         return QString();
369 }
370
371
372 QIcon getIcon(FuncRequest const & f, bool unknown)
373 {
374         QString icon = iconName(f, unknown);
375         if (icon.isEmpty())
376                 return QIcon();
377
378         //LYXERR(Debug::GUI, "Found icon: " << icon);
379         QPixmap pm;
380         if (!pm.load(icon)) {
381                 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
382                 return QIcon();
383         }
384
385         return QIcon(pm);
386 }
387
388
389 ////////////////////////////////////////////////////////////////////////
390 //
391 // LyX server support code.
392 //
393 ////////////////////////////////////////////////////////////////////////
394
395 class SocketNotifier : public QSocketNotifier
396 {
397 public:
398         /// connect a connection notification from the LyXServerSocket
399         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
400                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
401         {}
402
403 public:
404         /// The callback function
405         Application::SocketCallback func_;
406 };
407
408
409 ////////////////////////////////////////////////////////////////////////
410 //
411 // Mac specific stuff goes here...
412 //
413 ////////////////////////////////////////////////////////////////////////
414
415 class MenuTranslator : public QTranslator
416 {
417 public:
418         MenuTranslator(QObject * parent)
419                 : QTranslator(parent)
420         {}
421
422         QString translate(const char * /*context*/, 
423           const char * sourceText, 
424           const char * /*comment*/ = 0) 
425         {
426                 string const s = sourceText;
427                 if (s == N_("About %1") || s == N_("Preferences") 
428                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
429                         return qt_(s);
430                 else 
431                         return QString();
432         }
433 };
434
435 class GlobalMenuBar : public QMenuBar
436 {
437 public:
438         ///
439         GlobalMenuBar() : QMenuBar(0) {}
440         
441         ///
442         bool event(QEvent * e)
443         {
444                 if (e->type() == QEvent::ShortcutOverride) {
445                         //          && activeWindow() == 0) {
446                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
447                         KeySymbol sym;
448                         setKeySymbol(&sym, ke);
449                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
450                         e->accept();
451                         return true;
452                 }
453                 return false;
454         }
455 };
456
457 #ifdef Q_WS_MACX
458 // QMacPasteboardMimeGraphics can only be compiled on Mac.
459
460 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
461 {
462 public:
463         QMacPasteboardMimeGraphics()
464                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
465         {}
466
467         QString convertorName() { return "Graphics"; }
468
469         QString flavorFor(QString const & mime)
470         {
471                 LYXERR(Debug::ACTION, "flavorFor " << mime);
472                 if (mime == pdfMimeType())
473                         return QLatin1String("com.adobe.pdf");
474                 return QString();
475         }
476
477         QString mimeFor(QString flav)
478         {
479                 LYXERR(Debug::ACTION, "mimeFor " << flav);
480                 if (flav == QLatin1String("com.adobe.pdf"))
481                         return pdfMimeType();
482                 return QString();
483         }
484
485         bool canConvert(QString const & mime, QString flav)
486         {
487                 return mimeFor(flav) == mime;
488         }
489
490         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
491                 QString /*flav*/)
492         {
493                 if(data.count() > 1)
494                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
495                 return data.first();
496         }
497
498         QList<QByteArray> convertFromMime(QString const & /*mime*/,
499                 QVariant data, QString /*flav*/)
500         {
501                 QList<QByteArray> ret;
502                 ret.append(data.toByteArray());
503                 return ret;
504         }
505 };
506 #endif
507
508 ///////////////////////////////////////////////////////////////
509 //
510 // You can find more platform specific stuff at the end of this file...
511 //
512 ///////////////////////////////////////////////////////////////
513
514 ////////////////////////////////////////////////////////////////////////
515 // Windows specific stuff goes here...
516
517 #ifdef Q_WS_WIN
518 // QWindowsMimeMetafile can only be compiled on Windows.
519
520 static FORMATETC cfFromMime(QString const & mimetype)
521 {
522         FORMATETC formatetc;
523         if (mimetype == emfMimeType()) {
524                 formatetc.cfFormat = CF_ENHMETAFILE;
525                 formatetc.tymed = TYMED_ENHMF;
526         } else if (mimetype == wmfMimeType()) {
527                 formatetc.cfFormat = CF_METAFILEPICT;
528                 formatetc.tymed = TYMED_MFPICT;
529         }
530         formatetc.ptd = 0;
531         formatetc.dwAspect = DVASPECT_CONTENT;
532         formatetc.lindex = -1;
533         return formatetc;
534 }
535
536
537 class QWindowsMimeMetafile : public QWindowsMime {
538 public:
539         QWindowsMimeMetafile() {}
540
541         bool canConvertFromMime(FORMATETC const & formatetc,
542                 QMimeData const * mimedata) const
543         {
544                 return false;
545         }
546
547         bool canConvertToMime(QString const & mimetype,
548                 IDataObject * pDataObj) const
549         {
550                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
551                         return false;
552                 FORMATETC formatetc = cfFromMime(mimetype);
553                 return pDataObj->QueryGetData(&formatetc) == S_OK;
554         }
555
556         bool convertFromMime(FORMATETC const & formatetc,
557                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
558         {
559                 return false;
560         }
561
562         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
563                 QVariant::Type preferredType) const
564         {
565                 QByteArray data;
566                 if (!canConvertToMime(mimetype, pDataObj))
567                         return data;
568
569                 FORMATETC formatetc = cfFromMime(mimetype);
570                 STGMEDIUM s;
571                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
572                         return data;
573
574                 int dataSize;
575                 if (s.tymed == TYMED_ENHMF) {
576                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
577                         data.resize(dataSize);
578                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
579                                 (LPBYTE)data.data());
580                 } else if (s.tymed == TYMED_MFPICT) {
581                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
582                         data.resize(dataSize);
583                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
584                                 (LPBYTE)data.data());
585                 }
586                 data.detach();
587                 ReleaseStgMedium(&s);
588
589                 return data;
590         }
591
592
593         QVector<FORMATETC> formatsForMime(QString const & mimetype,
594                 QMimeData const * mimedata) const
595         {
596                 QVector<FORMATETC> formats;
597                 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
598                         formats += cfFromMime(mimetype);
599                 return formats;
600         }
601
602         QString mimeForFormat(FORMATETC const & formatetc) const
603         {
604                 switch (formatetc.cfFormat) {
605                 case CF_ENHMETAFILE:
606                         return emfMimeType(); 
607                 case CF_METAFILEPICT:
608                         return wmfMimeType();
609                 }
610                 return QString();
611         }
612 };
613
614 #endif // Q_WS_WIN
615
616 ////////////////////////////////////////////////////////////////////////
617 // GuiApplication::Private definition and implementation.
618 ////////////////////////////////////////////////////////////////////////
619
620 struct GuiApplication::Private
621 {
622         Private(): language_model_(0), global_menubar_(0) {}
623
624         ///
625         QSortFilterProxyModel * language_model_;
626         ///
627         GuiClipboard clipboard_;
628         ///
629         GuiSelection selection_;
630         ///
631         FontLoader font_loader_;
632         ///
633         ColorCache color_cache_;
634         ///
635         QTranslator qt_trans_;
636         ///
637         QHash<int, SocketNotifier *> socket_notifiers_;
638         ///
639         Menus menus_;
640         ///
641         /// The global instance
642         Toolbars toolbars_;
643
644         /// this timer is used for any regular events one wants to
645         /// perform. at present it is used to check if forked processes
646         /// are done.
647         QTimer general_timer_;
648
649         /// delayed FuncRequests
650         std::queue<FuncRequest> func_request_queue_;
651
652         /// Multiple views container.
653         /**
654         * Warning: This must not be a smart pointer as the destruction of the
655         * object is handled by Qt when the view is closed
656         * \sa Qt::WA_DeleteOnClose attribute.
657         */
658         QHash<int, GuiView *> views_;
659
660         /// Only used on mac.
661         GlobalMenuBar * global_menubar_;
662
663 #ifdef Q_WS_MACX
664         /// Linkback mime handler for MacOSX.
665         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
666 #endif
667
668 #ifdef Q_WS_WIN
669         /// WMF Mime handler for Windows clipboard.
670         /// \warning: see comment in ~GuiApplication and in bug 4846.
671         QWindowsMimeMetafile wmf_mime_;
672 #endif
673 };
674
675
676 GuiApplication * guiApp;
677
678 GuiApplication::~GuiApplication()
679 {
680 #ifdef Q_WS_MACX
681         closeAllLinkBackLinks();
682 #endif
683         // FIXME: Work around bug 4846 for Windows Vista and Qt4
684         // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
685         // If the clipboard is not cleared, LyX crashes on exit when it is
686         // compiled in release mode and if there is something in the clipboard.
687         // This is related to QWindowsMimeMetafile which is apparently not 
688         // properly destroyed.
689         qApp->clipboard()->clear(QClipboard::Clipboard);
690         delete d;
691 }
692
693
694 GuiApplication::GuiApplication(int & argc, char ** argv)
695         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
696 {
697         QString app_name = "LyX";
698         QCoreApplication::setOrganizationName(app_name);
699         QCoreApplication::setOrganizationDomain("lyx.org");
700         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
701
702         // Install translator for GUI elements.
703         installTranslator(&d->qt_trans_);
704
705         // FIXME: quitOnLastWindowClosed is true by default. We should have a
706         // lyxrc setting for this in order to let the application stay resident.
707         // But then we need some kind of dock icon, at least on Windows.
708         /*
709         if (lyxrc.quit_on_last_window_closed)
710                 setQuitOnLastWindowClosed(false);
711         */
712 #ifdef Q_WS_MACX
713         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
714         // seems to be the default case for applications like LyX.
715         setQuitOnLastWindowClosed(false);
716
717         // This allows to translate the strings that appear in the LyX menu.
718         /// A translator suitable for the entries in the LyX menu.
719         /// Only needed with Qt/Mac.
720         installTranslator(new MenuTranslator(this));
721 #endif
722         
723 #ifdef Q_WS_X11
724         // doubleClickInterval() is 400 ms on X11 which is just too long.
725         // On Windows and Mac OS X, the operating system's value is used.
726         // On Microsoft Windows, calling this function sets the double
727         // click interval for all applications. So we don't!
728         QApplication::setDoubleClickInterval(300);
729 #endif
730
731         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
732
733         // needs to be done before reading lyxrc
734         QWidget w;
735         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
736
737         guiApp = this;
738
739         // Set the cache to 5120 kilobytes which corresponds to screen size of
740         // 1280 by 1024 pixels with a color depth of 32 bits.
741         QPixmapCache::setCacheLimit(5120);
742
743         // Initialize RC Fonts
744         if (lyxrc.roman_font_name.empty())
745                 lyxrc.roman_font_name = fromqstr(romanFontName());
746
747         if (lyxrc.sans_font_name.empty())
748                 lyxrc.sans_font_name = fromqstr(sansFontName());
749
750         if (lyxrc.typewriter_font_name.empty())
751                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
752
753         d->general_timer_.setInterval(500);
754         connect(&d->general_timer_, SIGNAL(timeout()),
755                 this, SLOT(handleRegularEvents()));
756         d->general_timer_.start();
757 }
758
759
760 GuiApplication * theGuiApp()
761 {
762         return dynamic_cast<GuiApplication *>(theApp());
763 }
764
765
766 void GuiApplication::clearSession()
767 {
768         QSettings settings;
769         settings.clear();
770 }
771
772
773 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
774 {
775         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
776 }
777
778
779
780 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
781 {
782         bool enable = true;
783
784         switch(cmd.action) {
785
786         case LFUN_WINDOW_CLOSE:
787                 enable = d->views_.size() > 0;
788                 break;
789
790         case LFUN_BUFFER_NEW:
791         case LFUN_BUFFER_NEW_TEMPLATE:
792         case LFUN_FILE_OPEN:
793         case LFUN_SCREEN_FONT_UPDATE:
794         case LFUN_SET_COLOR:
795         case LFUN_WINDOW_NEW:
796         case LFUN_LYX_QUIT:
797                 enable = true;
798                 break;
799
800         default:
801                 return false;
802         }
803
804         if (!enable)
805                 flag.setEnabled(false);
806
807         return true;
808 }
809
810         
811 bool GuiApplication::dispatch(FuncRequest const & cmd)
812 {
813         switch (cmd.action) {
814
815         case LFUN_WINDOW_NEW:
816                 createView(toqstr(cmd.argument()));
817                 break;
818
819         case LFUN_WINDOW_CLOSE:
820                 // update bookmark pit of the current buffer before window close
821                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
822                         theLyXFunc().gotoBookmark(i+1, false, false);
823                 current_view_->close();
824                 break;
825
826         case LFUN_LYX_QUIT:
827                 // quitting is triggered by the gui code
828                 // (leaving the event loop).
829                 if (current_view_)
830                         current_view_->message(from_utf8(N_("Exiting.")));
831                 if (closeAllViews())
832                         quit();
833                 break;
834
835         case LFUN_SCREEN_FONT_UPDATE: {
836                 // handle the screen font changes.
837                 d->font_loader_.update();
838                 // Backup current_view_
839                 GuiView * view = current_view_;
840                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
841                 // to skip the refresh.
842                 current_view_ = 0;
843                 BufferList::iterator it = theBufferList().begin();
844                 BufferList::iterator const end = theBufferList().end();
845                 for (; it != end; ++it)
846                         (*it)->changed();
847                 // Restore current_view_
848                 current_view_ = view;
849                 break;
850         }
851
852         case LFUN_BUFFER_NEW:
853                 if (d->views_.empty()
854                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
855                         createView(QString(), false); // keep hidden
856                         current_view_->newDocument(to_utf8(cmd.argument()), false);
857                         current_view_->show();
858                         setActiveWindow(current_view_);
859                 } else {
860                         current_view_->newDocument(to_utf8(cmd.argument()), false);
861                 }
862                 break;
863
864         case LFUN_BUFFER_NEW_TEMPLATE:
865                 if (d->views_.empty()
866                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
867                         createView();
868                         current_view_->newDocument(to_utf8(cmd.argument()), true);
869                         if (!current_view_->buffer())
870                                 current_view_->close();
871                 } else {
872                         current_view_->newDocument(to_utf8(cmd.argument()), true);
873                 }
874                 break;
875
876         case LFUN_FILE_OPEN:
877                 if (d->views_.empty()
878                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
879                         string const fname = to_utf8(cmd.argument());
880                         // We want the ui session to be saved per document and not per
881                         // window number. The filename crc is a good enough identifier.
882                         boost::crc_32_type crc;
883                         crc = for_each(fname.begin(), fname.end(), crc);
884                         createView(crc.checksum());
885                         current_view_->openDocument(fname);
886                         if (current_view_ && !current_view_->buffer())
887                                 current_view_->close();
888                 } else
889                         current_view_->openDocument(to_utf8(cmd.argument()));
890                 break;
891
892         case LFUN_SET_COLOR: {
893                 string lyx_name;
894                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
895                 if (lyx_name.empty() || x11_name.empty()) {
896                         current_view_->message(
897                                 _("Syntax: set-color <lyx_name> <x11_name>"));
898                         break;
899                 }
900
901                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
902                 bool const graphicsbg_changed = lyx_name == graphicsbg
903                         && x11_name != graphicsbg;
904                 if (graphicsbg_changed) {
905                         // FIXME: The graphics cache no longer has a changeDisplay method.
906 #if 0
907                         graphics::GCache::get().changeDisplay(true);
908 #endif
909                 }
910
911                 if (!lcolor.setColor(lyx_name, x11_name)) {
912                         current_view_->message(
913                                         bformat(_("Set-color \"%1$s\" failed "
914                                                                "- color is undefined or "
915                                                                "may not be redefined"),
916                                                                    from_utf8(lyx_name)));
917                         break;
918                 }
919                 // Make sure we don't keep old colors in cache.
920                 d->color_cache_.clear();
921                 break;
922         }
923
924         default:
925                 // Notify the caller that the action has not been dispatched.
926                 return false;
927         }
928
929         // The action has been dispatched.
930         return true;
931 }
932
933
934 void GuiApplication::dispatchDelayed(FuncRequest const & func)
935 {
936         d->func_request_queue_.push(func);
937         QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
938 }
939
940
941 void GuiApplication::resetGui()
942 {
943         // Set the language defined by the user.
944         setGuiLanguage();
945
946         // Read menus
947         if (!readUIFile(toqstr(lyxrc.ui_file)))
948                 // Gives some error box here.
949                 return;
950
951         if (d->global_menubar_)
952                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
953
954         QHash<int, GuiView *>::iterator it;
955         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
956                 GuiView * gv = *it;
957                 gv->setLayoutDirection(layoutDirection());
958                 gv->resetDialogs();
959         }
960
961         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
962 }
963
964
965 void GuiApplication::createView(int view_id)
966 {
967         createView(QString(), true, view_id);
968 }
969
970
971 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
972         int view_id)
973 {
974         // release the keyboard which might have been grabed by the global
975         // menubar on Mac to catch shortcuts even without any GuiView.
976         if (d->global_menubar_)
977                 d->global_menubar_->releaseKeyboard();
978
979         // create new view
980         int id = view_id;
981         if (id == 0) {
982                 while (d->views_.find(id) != d->views_.end())
983                         id++;
984         }
985         LYXERR(Debug::GUI, "About to create new window with ID " << id);
986         GuiView * view = new GuiView(id);
987         // register view
988         d->views_[id] = view;
989
990         if (autoShow) {
991                 view->show();
992                 setActiveWindow(view);
993         }
994
995         if (!geometry_arg.isEmpty()) {
996 #ifdef Q_WS_WIN
997                 int x, y;
998                 int w, h;
999                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1000                 re.indexIn(geometry_arg);
1001                 w = re.cap(1).toInt();
1002                 h = re.cap(2).toInt();
1003                 x = re.cap(3).toInt();
1004                 y = re.cap(4).toInt();
1005                 view->setGeometry(x, y, w, h);
1006 #endif
1007         }
1008         view->setFocus();
1009 }
1010
1011
1012 Clipboard & GuiApplication::clipboard()
1013 {
1014         return d->clipboard_;
1015 }
1016
1017
1018 Selection & GuiApplication::selection()
1019 {
1020         return d->selection_;
1021 }
1022
1023
1024 FontLoader & GuiApplication::fontLoader() 
1025 {
1026         return d->font_loader_;
1027 }
1028
1029
1030 Toolbars const & GuiApplication::toolbars() const 
1031 {
1032         return d->toolbars_;
1033 }
1034
1035
1036 Toolbars & GuiApplication::toolbars()
1037 {
1038         return d->toolbars_; 
1039 }
1040
1041
1042 Menus const & GuiApplication::menus() const 
1043 {
1044         return d->menus_;
1045 }
1046
1047
1048 Menus & GuiApplication::menus()
1049 {
1050         return d->menus_; 
1051 }
1052
1053
1054 QList<int> GuiApplication::viewIds() const
1055 {
1056         return d->views_.keys();
1057 }
1058
1059
1060 ColorCache & GuiApplication::colorCache()
1061 {
1062         return d->color_cache_;
1063 }
1064
1065
1066 int GuiApplication::exec()
1067 {
1068         // asynchronously handle batch commands. This event will be in
1069         // the event queue in front of other asynchronous events. Hence,
1070         // we can assume in the latter that the gui is setup already.
1071         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1072
1073         return QApplication::exec();
1074 }
1075
1076
1077 void GuiApplication::exit(int status)
1078 {
1079         QApplication::exit(status);
1080 }
1081
1082
1083 void GuiApplication::setGuiLanguage()
1084 {
1085         // Set the language defined by the user.
1086         setRcGuiLanguage();
1087
1088         QString const default_language = toqstr(Messages::defaultLanguage());
1089         LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1090         QLocale const default_locale(default_language);
1091         QLocale::setDefault(default_locale);
1092
1093         // install translation file for Qt built-in dialogs
1094         QString const language_name = QString("qt_") + default_locale.name();
1095
1096         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1097         // Short-named translator can be loaded from a long name, but not the
1098         // opposite. Therefore, long name should be used without truncation.
1099         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1100         if (!d->qt_trans_.load(language_name,
1101                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1102                 LYXERR(Debug::LOCALE, "Could not find  Qt translations for locale "
1103                         << language_name);
1104         } else {
1105                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1106                         << language_name);
1107         }
1108
1109         switch (default_locale.language()) {
1110         case QLocale::Arabic :
1111         case QLocale::Hebrew :
1112         case QLocale::Persian :
1113         case QLocale::Urdu :
1114         setLayoutDirection(Qt::RightToLeft);
1115                 break;
1116         default:
1117         setLayoutDirection(Qt::LeftToRight);
1118         }
1119 }
1120
1121
1122 void GuiApplication::processFuncRequestQueue()
1123 {
1124         while (!d->func_request_queue_.empty()) {
1125                 lyx::dispatch(d->func_request_queue_.back());
1126                 d->func_request_queue_.pop();
1127         }
1128 }
1129
1130
1131 void GuiApplication::execBatchCommands()
1132 {
1133         setGuiLanguage();
1134
1135         // Read menus
1136         if (!readUIFile(toqstr(lyxrc.ui_file)))
1137                 // Gives some error box here.
1138                 return;
1139
1140 #ifdef Q_WS_MACX
1141         // Create the global default menubar which is shown for the dialogs
1142         // and if no GuiView is visible.
1143         // This must be done after the session was recovered to know the "last files".
1144         d->global_menubar_ = new GlobalMenuBar();
1145         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1146 #endif
1147
1148         lyx::execBatchCommands();
1149 }
1150
1151
1152 QAbstractItemModel * GuiApplication::languageModel()
1153 {
1154         if (d->language_model_)
1155                 return d->language_model_;
1156
1157         QStandardItemModel * lang_model = new QStandardItemModel(this);
1158         lang_model->insertColumns(0, 1);
1159         int current_row;
1160         Languages::const_iterator it = languages.begin();
1161         Languages::const_iterator end = languages.end();
1162         for (; it != end; ++it) {
1163                 current_row = lang_model->rowCount();
1164                 lang_model->insertRows(current_row, 1);
1165                 QModelIndex item = lang_model->index(current_row, 0);
1166                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1167                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1168         }
1169         d->language_model_ = new QSortFilterProxyModel(this);
1170         d->language_model_->setSourceModel(lang_model);
1171 #if QT_VERSION >= 0x040300
1172         d->language_model_->setSortLocaleAware(true);
1173 #endif
1174         return d->language_model_;
1175 }
1176
1177
1178 void GuiApplication::restoreGuiSession()
1179 {
1180         if (!lyxrc.load_session)
1181                 return;
1182
1183         Session & session = theSession();
1184         vector<FileName> const & lastopened = session.lastOpened().getfiles();
1185         // do not add to the lastfile list since these files are restored from
1186         // last session, and should be already there (regular files), or should
1187         // not be added at all (help files).
1188         for_each(lastopened.begin(), lastopened.end(),
1189                 bind(&GuiView::loadDocument, current_view_, _1, false));
1190
1191         // clear this list to save a few bytes of RAM
1192         session.lastOpened().clear();
1193 }
1194
1195
1196 QString const GuiApplication::romanFontName()
1197 {
1198         QFont font;
1199         font.setKerning(false);
1200         font.setStyleHint(QFont::Serif);
1201         font.setFamily("serif");
1202
1203         return QFontInfo(font).family();
1204 }
1205
1206
1207 QString const GuiApplication::sansFontName()
1208 {
1209         QFont font;
1210         font.setKerning(false);
1211         font.setStyleHint(QFont::SansSerif);
1212         font.setFamily("sans");
1213
1214         return QFontInfo(font).family();
1215 }
1216
1217
1218 QString const GuiApplication::typewriterFontName()
1219 {
1220         QFont font;
1221         font.setKerning(false);
1222         font.setStyleHint(QFont::TypeWriter);
1223         font.setFamily("monospace");
1224
1225         return QFontInfo(font).family();
1226 }
1227
1228
1229 void GuiApplication::handleRegularEvents()
1230 {
1231         ForkedCallsController::handleCompletedProcesses();
1232 }
1233
1234
1235 bool GuiApplication::event(QEvent * e)
1236 {
1237         switch(e->type()) {
1238         case QEvent::FileOpen: {
1239                 // Open a file; this happens only on Mac OS X for now.
1240                 //
1241                 // We do this asynchronously because on startup the batch
1242                 // commands are not executed here yet and the gui is not ready
1243                 // therefore.
1244                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1245                 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1246                 e->accept();
1247                 return true;
1248         }
1249         default:
1250                 return QApplication::event(e);
1251         }
1252 }
1253
1254
1255 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1256 {
1257         try {
1258                 return QApplication::notify(receiver, event);
1259         }
1260         catch (ExceptionMessage const & e) {
1261                 switch(e.type_) { 
1262                 case ErrorException:
1263                         emergencyCleanup();
1264                         setQuitOnLastWindowClosed(false);
1265                         closeAllViews();
1266                         Alert::error(e.title_, e.details_);
1267 #ifndef NDEBUG
1268                         // Properly crash in debug mode in order to get a useful backtrace.
1269                         abort();
1270 #endif
1271                         // In release mode, try to exit gracefully.
1272                         this->exit(1);
1273
1274                 case BufferException: {
1275                         Buffer * buf = current_view_->buffer();
1276                         docstring details = e.details_ + '\n';
1277                         details += theBufferList().emergencyWrite(buf);
1278                         theBufferList().release(buf);
1279                         details += "\n" + _("The current document was closed.");
1280                         Alert::error(e.title_, details);
1281                         return false;
1282                 }
1283                 case WarningException:
1284                         Alert::warning(e.title_, e.details_);
1285                         return false;
1286                 }
1287         }
1288         catch (exception const & e) {
1289                 docstring s = _("LyX has caught an exception, it will now "
1290                         "attempt to save all unsaved documents and exit."
1291                         "\n\nException: ");
1292                 s += from_ascii(e.what());
1293                 Alert::error(_("Software exception Detected"), s);
1294                 lyx_exit(1);
1295         }
1296         catch (...) {
1297                 docstring s = _("LyX has caught some really weird exception, it will "
1298                         "now attempt to save all unsaved documents and exit.");
1299                 Alert::error(_("Software exception Detected"), s);
1300                 lyx_exit(1);
1301         }
1302
1303         return false;
1304 }
1305
1306
1307 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1308 {
1309         QColor const & qcol = d->color_cache_.get(col);
1310         if (!qcol.isValid()) {
1311                 rgbcol.r = 0;
1312                 rgbcol.g = 0;
1313                 rgbcol.b = 0;
1314                 return false;
1315         }
1316         rgbcol.r = qcol.red();
1317         rgbcol.g = qcol.green();
1318         rgbcol.b = qcol.blue();
1319         return true;
1320 }
1321
1322
1323 string const GuiApplication::hexName(ColorCode col)
1324 {
1325         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1326 }
1327
1328
1329 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1330 {
1331         SocketNotifier * sn = new SocketNotifier(this, fd, func);
1332         d->socket_notifiers_[fd] = sn;
1333         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1334 }
1335
1336
1337 void GuiApplication::socketDataReceived(int fd)
1338 {
1339         d->socket_notifiers_[fd]->func_();
1340 }
1341
1342
1343 void GuiApplication::unregisterSocketCallback(int fd)
1344 {
1345         d->socket_notifiers_.take(fd)->setEnabled(false);
1346 }
1347
1348
1349 void GuiApplication::commitData(QSessionManager & sm)
1350 {
1351         /// The implementation is required to avoid an application exit
1352         /// when session state save is triggered by session manager.
1353         /// The default implementation sends a close event to all
1354         /// visible top level widgets when session managment allows
1355         /// interaction.
1356         /// We are changing that to close all wiew one by one.
1357         /// FIXME: verify if the default implementation is enough now.
1358         if (sm.allowsInteraction() && !closeAllViews())
1359                 sm.cancel();
1360 }
1361
1362
1363 void GuiApplication::unregisterView(GuiView * gv)
1364 {
1365         LASSERT(d->views_[gv->id()] == gv, /**/);
1366         d->views_.remove(gv->id());
1367         if (current_view_ == gv) {
1368                 current_view_ = 0;
1369                 theLyXFunc().setLyXView(0);
1370         }
1371 }
1372
1373
1374 bool GuiApplication::closeAllViews()
1375 {
1376         if (d->views_.empty())
1377                 return true;
1378
1379         QList<GuiView *> views = d->views_.values();
1380         foreach (GuiView * view, views) {
1381                 if (!view->close())
1382                         return false;
1383         }
1384
1385         d->views_.clear();
1386         return true;
1387 }
1388
1389
1390 GuiView & GuiApplication::view(int id) const
1391 {
1392         LASSERT(d->views_.contains(id), /**/);
1393         return *d->views_.value(id);
1394 }
1395
1396
1397 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1398 {
1399         QList<GuiView *> views = d->views_.values();
1400         foreach (GuiView * view, views)
1401                 view->hideDialog(name, inset);
1402 }
1403
1404
1405 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1406 {
1407         Buffer const * buffer_ = 0;
1408         QHash<int, GuiView *>::iterator end = d->views_.end();
1409         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1410                 if (Buffer const * ptr = (*it)->updateInset(inset))
1411                         buffer_ = ptr;
1412         }
1413         return buffer_;
1414 }
1415
1416
1417 bool GuiApplication::searchMenu(FuncRequest const & func,
1418         docstring_list & names) const
1419 {
1420         return d->menus_.searchMenu(func, names);
1421 }
1422
1423
1424 bool GuiApplication::readUIFile(QString const & name, bool include)
1425 {
1426         enum {
1427                 ui_menuset = 1,
1428                 ui_toolbars,
1429                 ui_toolbarset,
1430                 ui_include,
1431                 ui_last
1432         };
1433
1434         LexerKeyword uitags[] = {
1435                 { "include", ui_include },
1436                 { "menuset", ui_menuset },
1437                 { "toolbars", ui_toolbars },
1438                 { "toolbarset", ui_toolbarset }
1439         };
1440
1441         LYXERR(Debug::INIT, "About to read " << name << "...");
1442
1443         FileName ui_path;
1444         if (include) {
1445                 ui_path = libFileSearch("ui", name, "inc");
1446                 if (ui_path.empty())
1447                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1448         } else {
1449                 ui_path = libFileSearch("ui", name, "ui");
1450         }
1451
1452         if (ui_path.empty()) {
1453                 LYXERR(Debug::INIT, "Could not find " << name);
1454                 Alert::warning(_("Could not find UI definition file"),
1455                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1456                                    "Please check your installation."), qstring_to_ucs4(name)));
1457                 return false;
1458         }
1459
1460
1461         // Ensure that a file is read only once (prevents include loops)
1462         static QStringList uifiles;
1463         QString const uifile = toqstr(ui_path.absFilename());
1464         if (uifiles.contains(uifile)) {
1465                 if (!include) {
1466                         // We are reading again the top uifile so reset the safeguard:
1467                         uifiles.clear();
1468                         d->menus_.reset();
1469                         d->toolbars_.reset();
1470                 } else {
1471                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1472                                 << "Is this an include loop?");
1473                         return false;
1474                 }
1475         }
1476         uifiles.push_back(uifile);
1477
1478         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1479
1480         Lexer lex(uitags);
1481         lex.setFile(ui_path);
1482         if (!lex.isOK()) {
1483                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1484                        << endl;
1485         }
1486
1487         if (lyxerr.debugging(Debug::PARSER))
1488                 lex.printTable(lyxerr);
1489
1490         while (lex.isOK()) {
1491                 switch (lex.lex()) {
1492                 case ui_include: {
1493                         lex.next(true);
1494                         QString const file = toqstr(lex.getString());
1495                         if (!readUIFile(file, true))
1496                                 return false;
1497                         break;
1498                 }
1499                 case ui_menuset:
1500                         d->menus_.read(lex);
1501                         break;
1502
1503                 case ui_toolbarset:
1504                         d->toolbars_.readToolbars(lex);
1505                         break;
1506
1507                 case ui_toolbars:
1508                         d->toolbars_.readToolbarSettings(lex);
1509                         break;
1510
1511                 default:
1512                         if (!rtrim(lex.getString()).empty())
1513                                 lex.printError("LyX::ReadUIFile: "
1514                                                "Unknown menu tag: `$$Token'");
1515                         break;
1516                 }
1517         }
1518
1519         if (include)
1520                 return true;
1521
1522         QSettings settings;
1523         settings.beginGroup("ui_files");
1524         bool touched = false;
1525         for (int i = 0; i != uifiles.size(); ++i) {
1526                 QFileInfo fi(uifiles[i]);
1527                 QDateTime const date_value = fi.lastModified();
1528                 QString const name_key = QString::number(i);
1529                 if (!settings.contains(name_key)
1530                  || settings.value(name_key).toString() != uifiles[i]
1531                  || settings.value(name_key + "/date").toDateTime() != date_value) {
1532                         touched = true;
1533                         settings.setValue(name_key, uifiles[i]);
1534                         settings.setValue(name_key + "/date", date_value);
1535                 }
1536         }
1537         settings.endGroup();
1538         if (touched)
1539                 settings.remove("views");
1540
1541         return true;
1542 }
1543
1544
1545 void GuiApplication::onLastWindowClosed()
1546 {
1547         if (d->global_menubar_)
1548                 d->global_menubar_->grabKeyboard();
1549 }
1550
1551
1552 ////////////////////////////////////////////////////////////////////////
1553 //
1554 // X11 specific stuff goes here...
1555
1556 #ifdef Q_WS_X11
1557 bool GuiApplication::x11EventFilter(XEvent * xev)
1558 {
1559         if (!current_view_)
1560                 return false;
1561
1562         switch (xev->type) {
1563         case SelectionRequest: {
1564                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1565                         break;
1566                 LYXERR(Debug::SELECTION, "X requested selection.");
1567                 BufferView * bv = current_view_->view();
1568                 if (bv) {
1569                         docstring const sel = bv->requestSelection();
1570                         if (!sel.empty())
1571                                 d->selection_.put(sel);
1572                 }
1573                 break;
1574         }
1575         case SelectionClear: {
1576                 if (xev->xselectionclear.selection != XA_PRIMARY)
1577                         break;
1578                 LYXERR(Debug::SELECTION, "Lost selection.");
1579                 BufferView * bv = current_view_->view();
1580                 if (bv)
1581                         bv->clearSelection();
1582                 break;
1583         }
1584         }
1585         return false;
1586 }
1587 #endif
1588
1589 } // namespace frontend
1590
1591
1592 void hideDialogs(std::string const & name, Inset * inset)
1593 {
1594         if (theApp())
1595                 theApp()->hideDialogs(name, inset);
1596 }
1597
1598
1599 ////////////////////////////////////////////////////////////////////
1600 //
1601 // Font stuff
1602 //
1603 ////////////////////////////////////////////////////////////////////
1604
1605 frontend::FontLoader & theFontLoader()
1606 {
1607         LASSERT(frontend::guiApp, /**/);
1608         return frontend::guiApp->fontLoader();
1609 }
1610
1611
1612 frontend::FontMetrics const & theFontMetrics(Font const & f)
1613 {
1614         return theFontMetrics(f.fontInfo());
1615 }
1616
1617
1618 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1619 {
1620         LASSERT(frontend::guiApp, /**/);
1621         return frontend::guiApp->fontLoader().metrics(f);
1622 }
1623
1624
1625 ////////////////////////////////////////////////////////////////////
1626 //
1627 // Misc stuff
1628 //
1629 ////////////////////////////////////////////////////////////////////
1630
1631 frontend::Clipboard & theClipboard()
1632 {
1633         LASSERT(frontend::guiApp, /**/);
1634         return frontend::guiApp->clipboard();
1635 }
1636
1637
1638 frontend::Selection & theSelection()
1639 {
1640         LASSERT(frontend::guiApp, /**/);
1641         return frontend::guiApp->selection();
1642 }
1643
1644
1645 } // namespace lyx
1646
1647 #include "moc_GuiApplication.cpp"