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