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