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