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