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