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