]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
TocWidget::updateView(): only set the tree depth if there's a model reset. This is...
[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         setCurrentView(view);
972 }
973
974
975 Clipboard & GuiApplication::clipboard()
976 {
977         return d->clipboard_;
978 }
979
980
981 Selection & GuiApplication::selection()
982 {
983         return d->selection_;
984 }
985
986
987 FontLoader & GuiApplication::fontLoader() 
988 {
989         return d->font_loader_;
990 }
991
992
993 Toolbars const & GuiApplication::toolbars() const 
994 {
995         return d->toolbars_;
996 }
997
998
999 Toolbars & GuiApplication::toolbars()
1000 {
1001         return d->toolbars_; 
1002 }
1003
1004
1005 Menus const & GuiApplication::menus() const 
1006 {
1007         return d->menus_;
1008 }
1009
1010
1011 Menus & GuiApplication::menus()
1012 {
1013         return d->menus_; 
1014 }
1015
1016
1017 QList<int> GuiApplication::viewIds() const
1018 {
1019         return d->views_.keys();
1020 }
1021
1022
1023 ColorCache & GuiApplication::colorCache()
1024 {
1025         return d->color_cache_;
1026 }
1027
1028
1029 int GuiApplication::exec()
1030 {
1031         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1032         return QApplication::exec();
1033 }
1034
1035
1036 void GuiApplication::exit(int status)
1037 {
1038         QApplication::exit(status);
1039 }
1040
1041
1042 void GuiApplication::setGuiLanguage()
1043 {
1044         // Set the language defined by the user.
1045         setRcGuiLanguage();
1046
1047         QString const default_language = toqstr(Messages::defaultLanguage());
1048         LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1049         QLocale const default_locale(default_language);
1050         QLocale::setDefault(default_locale);
1051
1052         // install translation file for Qt built-in dialogs
1053         QString const language_name = QString("qt_") + default_locale.name();
1054
1055         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1056         // Short-named translator can be loaded from a long name, but not the
1057         // opposite. Therefore, long name should be used without truncation.
1058         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1059         if (!d->qt_trans_.load(language_name,
1060                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1061                 LYXERR(Debug::LOCALE, "Could not find  Qt translations for locale "
1062                         << language_name);
1063         } else {
1064                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1065                         << language_name);
1066         }
1067
1068         switch (default_locale.language()) {
1069         case QLocale::Arabic :
1070         case QLocale::Hebrew :
1071         case QLocale::Persian :
1072         case QLocale::Urdu :
1073         setLayoutDirection(Qt::RightToLeft);
1074                 break;
1075         default:
1076         setLayoutDirection(Qt::LeftToRight);
1077         }
1078 }
1079
1080
1081 void GuiApplication::execBatchCommands()
1082 {
1083         setGuiLanguage();
1084
1085         // Read menus
1086         if (!readUIFile(toqstr(lyxrc.ui_file)))
1087                 // Gives some error box here.
1088                 return;
1089
1090         // init the global menubar on Mac. This must be done after the session
1091         // was recovered to know the "last files".
1092         if (d->global_menubar_)
1093                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1094
1095         lyx::execBatchCommands();
1096 }
1097
1098
1099 QAbstractItemModel * GuiApplication::languageModel()
1100 {
1101         if (d->language_model_)
1102                 return d->language_model_;
1103
1104         QStandardItemModel * lang_model = new QStandardItemModel(this);
1105         lang_model->insertColumns(0, 1);
1106         int current_row;
1107         Languages::const_iterator it = languages.begin();
1108         Languages::const_iterator end = languages.end();
1109         for (; it != end; ++it) {
1110                 current_row = lang_model->rowCount();
1111                 lang_model->insertRows(current_row, 1);
1112                 QModelIndex item = lang_model->index(current_row, 0);
1113                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1114                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1115         }
1116         d->language_model_ = new QSortFilterProxyModel(this);
1117         d->language_model_->setSourceModel(lang_model);
1118 #if QT_VERSION >= 0x040300
1119         d->language_model_->setSortLocaleAware(true);
1120 #endif
1121         return d->language_model_;
1122 }
1123
1124
1125 void GuiApplication::restoreGuiSession()
1126 {
1127         if (!lyxrc.load_session)
1128                 return;
1129
1130         Session & session = theSession();
1131         vector<FileName> const & lastopened = session.lastOpened().getfiles();
1132         // do not add to the lastfile list since these files are restored from
1133         // last session, and should be already there (regular files), or should
1134         // not be added at all (help files).
1135         for_each(lastopened.begin(), lastopened.end(),
1136                 bind(&GuiView::loadDocument, current_view_, _1, false));
1137
1138         // clear this list to save a few bytes of RAM
1139         session.lastOpened().clear();
1140 }
1141
1142
1143 QString const GuiApplication::romanFontName()
1144 {
1145         QFont font;
1146         font.setKerning(false);
1147         font.setStyleHint(QFont::Serif);
1148         font.setFamily("serif");
1149
1150         return QFontInfo(font).family();
1151 }
1152
1153
1154 QString const GuiApplication::sansFontName()
1155 {
1156         QFont font;
1157         font.setKerning(false);
1158         font.setStyleHint(QFont::SansSerif);
1159         font.setFamily("sans");
1160
1161         return QFontInfo(font).family();
1162 }
1163
1164
1165 QString const GuiApplication::typewriterFontName()
1166 {
1167         QFont font;
1168         font.setKerning(false);
1169         font.setStyleHint(QFont::TypeWriter);
1170         font.setFamily("monospace");
1171
1172         return QFontInfo(font).family();
1173 }
1174
1175
1176 void GuiApplication::handleRegularEvents()
1177 {
1178         ForkedCallsController::handleCompletedProcesses();
1179 }
1180
1181
1182 bool GuiApplication::event(QEvent * e)
1183 {
1184         switch(e->type()) {
1185         case QEvent::FileOpen: {
1186                 // Open a file; this happens only on Mac OS X for now
1187                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1188                 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1189                         qstring_to_ucs4(foe->file())));
1190                 e->accept();
1191                 return true;
1192         }
1193         default:
1194                 return QApplication::event(e);
1195         }
1196 }
1197
1198
1199 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1200 {
1201         try {
1202                 return QApplication::notify(receiver, event);
1203         }
1204         catch (ExceptionMessage const & e) {
1205                 switch(e.type_) { 
1206                 case ErrorException:
1207                         emergencyCleanup();
1208                         setQuitOnLastWindowClosed(false);
1209                         closeAllViews();
1210                         Alert::error(e.title_, e.details_);
1211 #ifndef NDEBUG
1212                         // Properly crash in debug mode in order to get a useful backtrace.
1213                         abort();
1214 #endif
1215                         // In release mode, try to exit gracefully.
1216                         this->exit(1);
1217
1218                 case BufferException: {
1219                         Buffer * buf = current_view_->buffer();
1220                         docstring details = e.details_ + '\n';
1221                         details += theBufferList().emergencyWrite(buf);
1222                         theBufferList().release(buf);
1223                         details += "\n" + _("The current document was closed.");
1224                         Alert::error(e.title_, details);
1225                         return false;
1226                 }
1227                 case WarningException:
1228                         Alert::warning(e.title_, e.details_);
1229                         return false;
1230                 }
1231         }
1232         catch (exception const & e) {
1233                 docstring s = _("LyX has caught an exception, it will now "
1234                         "attempt to save all unsaved documents and exit."
1235                         "\n\nException: ");
1236                 s += from_ascii(e.what());
1237                 Alert::error(_("Software exception Detected"), s);
1238                 lyx_exit(1);
1239         }
1240         catch (...) {
1241                 docstring s = _("LyX has caught some really weird exception, it will "
1242                         "now attempt to save all unsaved documents and exit.");
1243                 Alert::error(_("Software exception Detected"), s);
1244                 lyx_exit(1);
1245         }
1246
1247         return false;
1248 }
1249
1250
1251 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1252 {
1253         QColor const & qcol = d->color_cache_.get(col);
1254         if (!qcol.isValid()) {
1255                 rgbcol.r = 0;
1256                 rgbcol.g = 0;
1257                 rgbcol.b = 0;
1258                 return false;
1259         }
1260         rgbcol.r = qcol.red();
1261         rgbcol.g = qcol.green();
1262         rgbcol.b = qcol.blue();
1263         return true;
1264 }
1265
1266
1267 string const GuiApplication::hexName(ColorCode col)
1268 {
1269         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1270 }
1271
1272
1273 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1274 {
1275         SocketNotifier * sn = new SocketNotifier(this, fd, func);
1276         d->socket_notifiers_[fd] = sn;
1277         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1278 }
1279
1280
1281 void GuiApplication::socketDataReceived(int fd)
1282 {
1283         d->socket_notifiers_[fd]->func_();
1284 }
1285
1286
1287 void GuiApplication::unregisterSocketCallback(int fd)
1288 {
1289         d->socket_notifiers_.take(fd)->setEnabled(false);
1290 }
1291
1292
1293 void GuiApplication::commitData(QSessionManager & sm)
1294 {
1295         /// The implementation is required to avoid an application exit
1296         /// when session state save is triggered by session manager.
1297         /// The default implementation sends a close event to all
1298         /// visible top level widgets when session managment allows
1299         /// interaction.
1300         /// We are changing that to close all wiew one by one.
1301         /// FIXME: verify if the default implementation is enough now.
1302         if (sm.allowsInteraction() && !closeAllViews())
1303                 sm.cancel();
1304 }
1305
1306
1307 void GuiApplication::unregisterView(GuiView * gv)
1308 {
1309         LASSERT(d->views_[gv->id()] == gv, /**/);
1310         d->views_.remove(gv->id());
1311         if (current_view_ == gv) {
1312                 current_view_ = 0;
1313                 theLyXFunc().setLyXView(0);
1314         }
1315 }
1316
1317
1318 bool GuiApplication::closeAllViews()
1319 {
1320         if (d->views_.empty())
1321                 return true;
1322
1323         QList<GuiView *> views = d->views_.values();
1324         foreach (GuiView * view, views) {
1325                 if (!view->close())
1326                         return false;
1327         }
1328
1329         d->views_.clear();
1330         return true;
1331 }
1332
1333
1334 GuiView & GuiApplication::view(int id) const
1335 {
1336         LASSERT(d->views_.contains(id), /**/);
1337         return *d->views_.value(id);
1338 }
1339
1340
1341 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1342 {
1343         QList<GuiView *> views = d->views_.values();
1344         foreach (GuiView * view, views)
1345                 view->hideDialog(name, inset);
1346 }
1347
1348
1349 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1350 {
1351         Buffer const * buffer_ = 0;
1352         QHash<int, GuiView *>::iterator end = d->views_.end();
1353         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1354                 if (Buffer const * ptr = (*it)->updateInset(inset))
1355                         buffer_ = ptr;
1356         }
1357         return buffer_;
1358 }
1359
1360
1361 bool GuiApplication::searchMenu(FuncRequest const & func,
1362         docstring_list & names) const
1363 {
1364         return d->menus_.searchMenu(func, names);
1365 }
1366
1367
1368 bool GuiApplication::readUIFile(QString const & name, bool include)
1369 {
1370         enum {
1371                 ui_menuset = 1,
1372                 ui_toolbars,
1373                 ui_toolbarset,
1374                 ui_include,
1375                 ui_last
1376         };
1377
1378         LexerKeyword uitags[] = {
1379                 { "include", ui_include },
1380                 { "menuset", ui_menuset },
1381                 { "toolbars", ui_toolbars },
1382                 { "toolbarset", ui_toolbarset }
1383         };
1384
1385         LYXERR(Debug::INIT, "About to read " << name << "...");
1386
1387         FileName ui_path;
1388         if (include) {
1389                 ui_path = libFileSearch("ui", name, "inc");
1390                 if (ui_path.empty())
1391                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1392         } else {
1393                 ui_path = libFileSearch("ui", name, "ui");
1394         }
1395
1396         if (ui_path.empty()) {
1397                 LYXERR(Debug::INIT, "Could not find " << name);
1398                 Alert::warning(_("Could not find UI definition file"),
1399                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1400                                    "Please check your installation."), qstring_to_ucs4(name)));
1401                 return false;
1402         }
1403
1404
1405         // Ensure that a file is read only once (prevents include loops)
1406         static QStringList uifiles;
1407         QString const uifile = toqstr(ui_path.absFilename());
1408         if (uifiles.contains(uifile)) {
1409                 if (!include) {
1410                         // We are reading again the top uifile so reset the safeguard:
1411                         uifiles.clear();
1412                         d->menus_.reset();
1413                         d->toolbars_.reset();
1414                 } else {
1415                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1416                                 << "Is this an include loop?");
1417                         return false;
1418                 }
1419         }
1420         uifiles.push_back(uifile);
1421
1422         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1423
1424         Lexer lex(uitags);
1425         lex.setFile(ui_path);
1426         if (!lex.isOK()) {
1427                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1428                        << endl;
1429         }
1430
1431         if (lyxerr.debugging(Debug::PARSER))
1432                 lex.printTable(lyxerr);
1433
1434         while (lex.isOK()) {
1435                 switch (lex.lex()) {
1436                 case ui_include: {
1437                         lex.next(true);
1438                         QString const file = toqstr(lex.getString());
1439                         if (!readUIFile(file, true))
1440                                 return false;
1441                         break;
1442                 }
1443                 case ui_menuset:
1444                         d->menus_.read(lex);
1445                         break;
1446
1447                 case ui_toolbarset:
1448                         d->toolbars_.readToolbars(lex);
1449                         break;
1450
1451                 case ui_toolbars:
1452                         d->toolbars_.readToolbarSettings(lex);
1453                         break;
1454
1455                 default:
1456                         if (!rtrim(lex.getString()).empty())
1457                                 lex.printError("LyX::ReadUIFile: "
1458                                                "Unknown menu tag: `$$Token'");
1459                         break;
1460                 }
1461         }
1462
1463         if (include)
1464                 return true;
1465
1466         QSettings settings;
1467         settings.beginGroup("ui_files");
1468         bool touched = false;
1469         for (int i = 0; i != uifiles.size(); ++i) {
1470                 QFileInfo fi(uifiles[i]);
1471                 QDateTime const date_value = fi.lastModified();
1472                 QString const name_key = QString::number(i);
1473                 if (!settings.contains(name_key)
1474                  || settings.value(name_key).toString() != uifiles[i]
1475                  || settings.value(name_key + "/date").toDateTime() != date_value) {
1476                         touched = true;
1477                         settings.setValue(name_key, uifiles[i]);
1478                         settings.setValue(name_key + "/date", date_value);
1479                 }
1480         }
1481         settings.endGroup();
1482         if (touched)
1483                 settings.remove("views");
1484
1485         return true;
1486 }
1487
1488
1489 void GuiApplication::onLastWindowClosed()
1490 {
1491         if (d->global_menubar_)
1492                 d->global_menubar_->grabKeyboard();
1493 }
1494
1495
1496 ////////////////////////////////////////////////////////////////////////
1497 //
1498 // X11 specific stuff goes here...
1499
1500 #ifdef Q_WS_X11
1501 bool GuiApplication::x11EventFilter(XEvent * xev)
1502 {
1503         if (!current_view_)
1504                 return false;
1505
1506         switch (xev->type) {
1507         case SelectionRequest: {
1508                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1509                         break;
1510                 LYXERR(Debug::SELECTION, "X requested selection.");
1511                 BufferView * bv = current_view_->view();
1512                 if (bv) {
1513                         docstring const sel = bv->requestSelection();
1514                         if (!sel.empty())
1515                                 d->selection_.put(sel);
1516                 }
1517                 break;
1518         }
1519         case SelectionClear: {
1520                 if (xev->xselectionclear.selection != XA_PRIMARY)
1521                         break;
1522                 LYXERR(Debug::SELECTION, "Lost selection.");
1523                 BufferView * bv = current_view_->view();
1524                 if (bv)
1525                         bv->clearSelection();
1526                 break;
1527         }
1528         }
1529         return false;
1530 }
1531 #endif
1532
1533 } // namespace frontend
1534
1535
1536 void hideDialogs(std::string const & name, Inset * inset)
1537 {
1538         if (theApp())
1539                 theApp()->hideDialogs(name, inset);
1540 }
1541
1542
1543 ////////////////////////////////////////////////////////////////////
1544 //
1545 // Font stuff
1546 //
1547 ////////////////////////////////////////////////////////////////////
1548
1549 frontend::FontLoader & theFontLoader()
1550 {
1551         LASSERT(frontend::guiApp, /**/);
1552         return frontend::guiApp->fontLoader();
1553 }
1554
1555
1556 frontend::FontMetrics const & theFontMetrics(Font const & f)
1557 {
1558         return theFontMetrics(f.fontInfo());
1559 }
1560
1561
1562 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1563 {
1564         LASSERT(frontend::guiApp, /**/);
1565         return frontend::guiApp->fontLoader().metrics(f);
1566 }
1567
1568
1569 ////////////////////////////////////////////////////////////////////
1570 //
1571 // Misc stuff
1572 //
1573 ////////////////////////////////////////////////////////////////////
1574
1575 frontend::Clipboard & theClipboard()
1576 {
1577         LASSERT(frontend::guiApp, /**/);
1578         return frontend::guiApp->clipboard();
1579 }
1580
1581
1582 frontend::Selection & theSelection()
1583 {
1584         LASSERT(frontend::guiApp, /**/);
1585         return frontend::guiApp->selection();
1586 }
1587
1588 } // namespace lyx
1589
1590 #include "GuiApplication_moc.cpp"