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