]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Typos.
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
19 #include "GuiImage.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
22 #include "GuiView.h"
23 #include "Menus.h"
24 #include "qt_helpers.h"
25 #include "Toolbars.h"
26
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
31
32 #include "Buffer.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
35 #include "Color.h"
36 #include "Font.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
39 #include "Language.h"
40 #include "Lexer.h"
41 #include "LyX.h"
42 #include "LyXAction.h"
43 #include "LyXFunc.h"
44 #include "LyXRC.h"
45 #include "Session.h"
46 #include "version.h"
47
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/ExceptionMessage.h"
51 #include "support/FileName.h"
52 #include "support/foreach.h"
53 #include "support/ForkedCalls.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // sorted
57 #include "support/Messages.h"
58 #include "support/os.h"
59 #include "support/Package.h"
60
61 #ifdef Q_WS_MACX
62 #include "support/linkback/LinkBackProxy.h"
63 #endif
64
65 #include <QByteArray>
66 #include <QClipboard>
67 #include <QDateTime>
68 #include <QDir>
69 #include <QEventLoop>
70 #include <QFileOpenEvent>
71 #include <QFileInfo>
72 #include <QHash>
73 #include <QIcon>
74 #include <QImageReader>
75 #include <QLocale>
76 #include <QLibraryInfo>
77 #include <QList>
78 #include <QMacPasteboardMime>
79 #include <QMenuBar>
80 #include <QMimeData>
81 #include <QObject>
82 #include <QPixmap>
83 #include <QPixmapCache>
84 #include <QRegExp>
85 #include <QSessionManager>
86 #include <QSettings>
87 #include <QSocketNotifier>
88 #include <QSortFilterProxyModel>
89 #include <QStandardItemModel>
90 #include <QTextCodec>
91 #include <QTimer>
92 #include <QTranslator>
93 #include <QWidget>
94
95 #ifdef Q_WS_X11
96 #include <X11/Xatom.h>
97 #include <X11/Xlib.h>
98 #undef CursorShape
99 #undef None
100 #endif
101
102 #ifdef Q_WS_WIN
103 #include <QWindowsMime>
104 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
105 #include <wtypes.h>
106 #endif
107 #include <objidl.h>
108 #endif // Q_WS_WIN
109
110 #include <boost/bind.hpp>
111 #include <boost/crc.hpp>
112
113 #include <exception>
114 #include <vector>
115
116 using namespace std;
117 using namespace lyx::support;
118
119
120 static void initializeResources()
121 {
122         static bool initialized = false;
123         if (!initialized) {
124                 Q_INIT_RESOURCE(Resources); 
125                 initialized = true;
126         }
127 }
128
129
130 namespace lyx {
131
132 frontend::Application * createApplication(int & argc, char * argv[])
133 {
134 #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()
597                 : language_model_(0), global_menubar_(0)
598         {
599 #ifdef Q_WS_MACX
600                 // Create the global default menubar which is shown for the dialogs
601                 // and if no GuiView is visible.
602                 global_menubar_ = new GlobalMenuBar();
603 #endif
604         }
605
606         ///
607         QSortFilterProxyModel * language_model_;
608         ///
609         GuiClipboard clipboard_;
610         ///
611         GuiSelection selection_;
612         ///
613         FontLoader font_loader_;
614         ///
615         ColorCache color_cache_;
616         ///
617         QTranslator qt_trans_;
618         ///
619         QHash<int, SocketNotifier *> socket_notifiers_;
620         ///
621         Menus menus_;
622         ///
623         /// The global instance
624         Toolbars toolbars_;
625
626         /// this timer is used for any regular events one wants to
627         /// perform. at present it is used to check if forked processes
628         /// are done.
629         QTimer general_timer_;
630
631         /// Multiple views container.
632         /**
633         * Warning: This must not be a smart pointer as the destruction of the
634         * object is handled by Qt when the view is closed
635         * \sa Qt::WA_DeleteOnClose attribute.
636         */
637         QHash<int, GuiView *> views_;
638
639         /// Only used on mac.
640         GlobalMenuBar * global_menubar_;
641
642 #ifdef Q_WS_MACX
643         /// Linkback mime handler for MacOSX.
644         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
645 #endif
646
647 #ifdef Q_WS_WIN
648         /// WMF Mime handler for Windows clipboard.
649         /// \warning: see comment in ~GuiApplication and in bug 4846.
650         QWindowsMimeMetafile wmf_mime_;
651 #endif
652 };
653
654
655 GuiApplication * guiApp;
656
657 GuiApplication::~GuiApplication()
658 {
659 #ifdef Q_WS_MACX
660         closeAllLinkBackLinks();
661 #endif
662         // FIXME: Work around bug 4846 for Windows Vista and Qt4
663         // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
664         // If the clipboard is not cleared, LyX crashes on exit when it is
665         // compiled in release mode and if there is something in the clipboard.
666         // This is related to QWindowsMimeMetafile which is apparently not 
667         // properly destroyed.
668         qApp->clipboard()->clear(QClipboard::Clipboard);
669         delete d;
670 }
671
672
673 GuiApplication::GuiApplication(int & argc, char ** argv)
674         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
675 {
676         QString app_name = "LyX";
677         QCoreApplication::setOrganizationName(app_name);
678         QCoreApplication::setOrganizationDomain("lyx.org");
679         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
680
681         // Install translator for GUI elements.
682         installTranslator(&d->qt_trans_);
683
684         // FIXME: quitOnLastWindowClosed is true by default. We should have a
685         // lyxrc setting for this in order to let the application stay resident.
686         // But then we need some kind of dock icon, at least on Windows.
687         /*
688         if (lyxrc.quit_on_last_window_closed)
689                 setQuitOnLastWindowClosed(false);
690         */
691 #ifdef Q_WS_MACX
692         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
693         // seems to be the default case for applications like LyX.
694         setQuitOnLastWindowClosed(false);
695
696         // This allows to translate the strings that appear in the LyX menu.
697         /// A translator suitable for the entries in the LyX menu.
698         /// Only needed with Qt/Mac.
699         installTranslator(new MenuTranslator(this));
700 #endif
701         
702 #ifdef Q_WS_X11
703         // doubleClickInterval() is 400 ms on X11 which is just too long.
704         // On Windows and Mac OS X, the operating system's value is used.
705         // On Microsoft Windows, calling this function sets the double
706         // click interval for all applications. So we don't!
707         QApplication::setDoubleClickInterval(300);
708 #endif
709
710         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
711
712         // needs to be done before reading lyxrc
713         QWidget w;
714         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
715
716         guiApp = this;
717
718         // Set the cache to 5120 kilobytes which corresponds to screen size of
719         // 1280 by 1024 pixels with a color depth of 32 bits.
720         QPixmapCache::setCacheLimit(5120);
721
722         // Initialize RC Fonts
723         if (lyxrc.roman_font_name.empty())
724                 lyxrc.roman_font_name = fromqstr(romanFontName());
725
726         if (lyxrc.sans_font_name.empty())
727                 lyxrc.sans_font_name = fromqstr(sansFontName());
728
729         if (lyxrc.typewriter_font_name.empty())
730                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
731
732         d->general_timer_.setInterval(500);
733         connect(&d->general_timer_, SIGNAL(timeout()),
734                 this, SLOT(handleRegularEvents()));
735         d->general_timer_.start();
736 }
737
738
739 void GuiApplication::clearSession()
740 {
741         QSettings settings;
742         settings.clear();
743 }
744
745
746 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
747 {
748         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
749 }
750
751
752
753 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
754 {
755         bool enable = true;
756
757         switch(cmd.action) {
758
759         case LFUN_WINDOW_CLOSE:
760                 enable = d->views_.size() > 0;
761                 break;
762
763         case LFUN_BUFFER_NEW:
764         case LFUN_BUFFER_NEW_TEMPLATE:
765         case LFUN_FILE_OPEN:
766         case LFUN_SCREEN_FONT_UPDATE:
767         case LFUN_SET_COLOR:
768         case LFUN_WINDOW_NEW:
769         case LFUN_LYX_QUIT:
770                 enable = true;
771                 break;
772
773         default:
774                 return false;
775         }
776
777         if (!enable)
778                 flag.setEnabled(false);
779
780         return true;
781 }
782
783         
784 bool GuiApplication::dispatch(FuncRequest const & cmd)
785 {
786         switch (cmd.action) {
787
788         case LFUN_WINDOW_NEW:
789                 createView(toqstr(cmd.argument()));
790                 break;
791
792         case LFUN_WINDOW_CLOSE:
793                 // update bookmark pit of the current buffer before window close
794                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
795                         theLyXFunc().gotoBookmark(i+1, false, false);
796                 current_view_->close();
797                 break;
798
799         case LFUN_LYX_QUIT:
800                 // quitting is triggered by the gui code
801                 // (leaving the event loop).
802                 if (current_view_)
803                         current_view_->message(from_utf8(N_("Exiting.")));
804                 if (closeAllViews())
805                         quit();
806                 break;
807
808         case LFUN_SCREEN_FONT_UPDATE: {
809                 // handle the screen font changes.
810                 d->font_loader_.update();
811                 // Backup current_view_
812                 GuiView * view = current_view_;
813                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
814                 // to skip the refresh.
815                 current_view_ = 0;
816                 BufferList::iterator it = theBufferList().begin();
817                 BufferList::iterator const end = theBufferList().end();
818                 for (; it != end; ++it)
819                         (*it)->changed();
820                 // Restore current_view_
821                 current_view_ = view;
822                 break;
823         }
824
825         case LFUN_BUFFER_NEW:
826                 if (d->views_.empty()
827                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
828                         createView(QString(), false); // keep hidden
829                         current_view_->newDocument(to_utf8(cmd.argument()), false);
830                         current_view_->show();
831                         setActiveWindow(current_view_);
832                 } else {
833                         current_view_->newDocument(to_utf8(cmd.argument()), false);
834                 }
835                 break;
836
837         case LFUN_BUFFER_NEW_TEMPLATE:
838                 if (d->views_.empty()
839                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
840                         createView();
841                         current_view_->newDocument(to_utf8(cmd.argument()), true);
842                         if (!current_view_->buffer())
843                                 current_view_->close();
844                 } else {
845                         current_view_->newDocument(to_utf8(cmd.argument()), true);
846                 }
847                 break;
848
849         case LFUN_FILE_OPEN:
850                 if (d->views_.empty()
851                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
852                         string const fname = to_utf8(cmd.argument());
853                         // We want the ui session to be saved per document and not per
854                         // window number. The filename crc is a good enough identifier.
855                         boost::crc_32_type crc;
856                         crc = for_each(fname.begin(), fname.end(), crc);
857                         createView(crc.checksum());
858                         current_view_->openDocument(fname);
859                         if (!current_view_->buffer())
860                                 current_view_->close();
861                 } else
862                         current_view_->openDocument(to_utf8(cmd.argument()));
863                 break;
864
865         case LFUN_SET_COLOR: {
866                 string lyx_name;
867                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
868                 if (lyx_name.empty() || x11_name.empty()) {
869                         current_view_->message(
870                                 _("Syntax: set-color <lyx_name> <x11_name>"));
871                         break;
872                 }
873
874                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
875                 bool const graphicsbg_changed = lyx_name == graphicsbg
876                         && x11_name != graphicsbg;
877                 if (graphicsbg_changed) {
878                         // FIXME: The graphics cache no longer has a changeDisplay method.
879 #if 0
880                         graphics::GCache::get().changeDisplay(true);
881 #endif
882                 }
883
884                 if (!lcolor.setColor(lyx_name, x11_name)) {
885                         current_view_->message(
886                                         bformat(_("Set-color \"%1$s\" failed "
887                                                                "- color is undefined or "
888                                                                "may not be redefined"),
889                                                                    from_utf8(lyx_name)));
890                         break;
891                 }
892                 // Make sure we don't keep old colors in cache.
893                 d->color_cache_.clear();
894                 break;
895         }
896
897         default:
898                 // Notify the caller that the action has not been dispatched.
899                 return false;
900         }
901
902         // The action has been dispatched.
903         return true;
904 }
905
906
907 void GuiApplication::resetGui()
908 {
909         // Set the language defined by the user.
910         setGuiLanguage();
911
912         // Read menus
913         if (!readUIFile(toqstr(lyxrc.ui_file)))
914                 // Gives some error box here.
915                 return;
916
917 #ifdef Q_WS_MACX
918         d->global_menubar_->clear();
919         delete d->global_menubar_;
920         // Create the global default menubar which is shown for the dialogs
921         // and if no GuiView is visible.
922         d->global_menubar_ = new GlobalMenuBar();
923
924         // init the global menubar on Mac. This must be done after the session
925         // was recovered to know the "last files".
926         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
927 #endif
928
929         QHash<int, GuiView *>::iterator it;
930         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
931                 GuiView * gv = *it;
932                 gv->setLayoutDirection(layoutDirection());
933                 gv->resetDialogs();
934         }
935
936         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
937 }
938
939
940 void GuiApplication::createView(int view_id)
941 {
942         createView(QString(), true, view_id);
943 }
944
945
946 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
947         int view_id)
948 {
949         // release the keyboard which might have been grabed by the global
950         // menubar on Mac to catch shortcuts even without any GuiView.
951         if (d->global_menubar_)
952                 d->global_menubar_->releaseKeyboard();
953
954         // create new view
955         int id = view_id;
956         if (id == 0) {
957                 while (d->views_.find(id) != d->views_.end())
958                         id++;
959         }
960         LYXERR(Debug::GUI, "About to create new window with ID " << id);
961         GuiView * view = new GuiView(id);
962         // register view
963         d->views_[id] = view;
964
965         if (autoShow) {
966                 view->show();
967                 setActiveWindow(view);
968         }
969
970         if (!geometry_arg.isEmpty()) {
971 #ifdef Q_WS_WIN
972                 int x, y;
973                 int w, h;
974                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
975                 re.indexIn(geometry_arg);
976                 w = re.cap(1).toInt();
977                 h = re.cap(2).toInt();
978                 x = re.cap(3).toInt();
979                 y = re.cap(4).toInt();
980                 view->setGeometry(x, y, w, h);
981 #endif
982         }
983         view->setFocus();
984 }
985
986
987 Clipboard & GuiApplication::clipboard()
988 {
989         return d->clipboard_;
990 }
991
992
993 Selection & GuiApplication::selection()
994 {
995         return d->selection_;
996 }
997
998
999 FontLoader & GuiApplication::fontLoader() 
1000 {
1001         return d->font_loader_;
1002 }
1003
1004
1005 Toolbars const & GuiApplication::toolbars() const 
1006 {
1007         return d->toolbars_;
1008 }
1009
1010
1011 Toolbars & GuiApplication::toolbars()
1012 {
1013         return d->toolbars_; 
1014 }
1015
1016
1017 Menus const & GuiApplication::menus() const 
1018 {
1019         return d->menus_;
1020 }
1021
1022
1023 Menus & GuiApplication::menus()
1024 {
1025         return d->menus_; 
1026 }
1027
1028
1029 QList<int> GuiApplication::viewIds() const
1030 {
1031         return d->views_.keys();
1032 }
1033
1034
1035 ColorCache & GuiApplication::colorCache()
1036 {
1037         return d->color_cache_;
1038 }
1039
1040
1041 int GuiApplication::exec()
1042 {
1043         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1044         return QApplication::exec();
1045 }
1046
1047
1048 void GuiApplication::exit(int status)
1049 {
1050         QApplication::exit(status);
1051 }
1052
1053
1054 void GuiApplication::setGuiLanguage()
1055 {
1056         // Set the language defined by the user.
1057         setRcGuiLanguage();
1058
1059         QString const default_language = toqstr(Messages::defaultLanguage());
1060         LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1061         QLocale const default_locale(default_language);
1062         QLocale::setDefault(default_locale);
1063
1064         // install translation file for Qt built-in dialogs
1065         QString const language_name = QString("qt_") + default_locale.name();
1066
1067         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1068         // Short-named translator can be loaded from a long name, but not the
1069         // opposite. Therefore, long name should be used without truncation.
1070         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1071         if (!d->qt_trans_.load(language_name,
1072                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1073                 LYXERR(Debug::LOCALE, "Could not find  Qt translations for locale "
1074                         << language_name);
1075         } else {
1076                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1077                         << language_name);
1078         }
1079
1080         switch (default_locale.language()) {
1081         case QLocale::Arabic :
1082         case QLocale::Hebrew :
1083         case QLocale::Persian :
1084         case QLocale::Urdu :
1085         setLayoutDirection(Qt::RightToLeft);
1086                 break;
1087         default:
1088         setLayoutDirection(Qt::LeftToRight);
1089         }
1090 }
1091
1092
1093 void GuiApplication::execBatchCommands()
1094 {
1095         setGuiLanguage();
1096
1097         // Read menus
1098         if (!readUIFile(toqstr(lyxrc.ui_file)))
1099                 // Gives some error box here.
1100                 return;
1101
1102         // init the global menubar on Mac. This must be done after the session
1103         // was recovered to know the "last files".
1104         if (d->global_menubar_)
1105                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1106
1107         lyx::execBatchCommands();
1108 }
1109
1110
1111 QAbstractItemModel * GuiApplication::languageModel()
1112 {
1113         if (d->language_model_)
1114                 return d->language_model_;
1115
1116         QStandardItemModel * lang_model = new QStandardItemModel(this);
1117         lang_model->insertColumns(0, 1);
1118         int current_row;
1119         Languages::const_iterator it = languages.begin();
1120         Languages::const_iterator end = languages.end();
1121         for (; it != end; ++it) {
1122                 current_row = lang_model->rowCount();
1123                 lang_model->insertRows(current_row, 1);
1124                 QModelIndex item = lang_model->index(current_row, 0);
1125                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1126                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1127         }
1128         d->language_model_ = new QSortFilterProxyModel(this);
1129         d->language_model_->setSourceModel(lang_model);
1130 #if QT_VERSION >= 0x040300
1131         d->language_model_->setSortLocaleAware(true);
1132 #endif
1133         return d->language_model_;
1134 }
1135
1136
1137 void GuiApplication::restoreGuiSession()
1138 {
1139         if (!lyxrc.load_session)
1140                 return;
1141
1142         Session & session = theSession();
1143         vector<FileName> const & lastopened = session.lastOpened().getfiles();
1144         // do not add to the lastfile list since these files are restored from
1145         // last session, and should be already there (regular files), or should
1146         // not be added at all (help files).
1147         for_each(lastopened.begin(), lastopened.end(),
1148                 bind(&GuiView::loadDocument, current_view_, _1, false));
1149
1150         // clear this list to save a few bytes of RAM
1151         session.lastOpened().clear();
1152 }
1153
1154
1155 QString const GuiApplication::romanFontName()
1156 {
1157         QFont font;
1158         font.setKerning(false);
1159         font.setStyleHint(QFont::Serif);
1160         font.setFamily("serif");
1161
1162         return QFontInfo(font).family();
1163 }
1164
1165
1166 QString const GuiApplication::sansFontName()
1167 {
1168         QFont font;
1169         font.setKerning(false);
1170         font.setStyleHint(QFont::SansSerif);
1171         font.setFamily("sans");
1172
1173         return QFontInfo(font).family();
1174 }
1175
1176
1177 QString const GuiApplication::typewriterFontName()
1178 {
1179         QFont font;
1180         font.setKerning(false);
1181         font.setStyleHint(QFont::TypeWriter);
1182         font.setFamily("monospace");
1183
1184         return QFontInfo(font).family();
1185 }
1186
1187
1188 void GuiApplication::handleRegularEvents()
1189 {
1190         ForkedCallsController::handleCompletedProcesses();
1191 }
1192
1193
1194 bool GuiApplication::event(QEvent * e)
1195 {
1196         switch(e->type()) {
1197         case QEvent::FileOpen: {
1198                 // Open a file; this happens only on Mac OS X for now
1199                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1200                 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1201                         qstring_to_ucs4(foe->file())));
1202                 e->accept();
1203                 return true;
1204         }
1205         default:
1206                 return QApplication::event(e);
1207         }
1208 }
1209
1210
1211 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1212 {
1213         try {
1214                 return QApplication::notify(receiver, event);
1215         }
1216         catch (ExceptionMessage const & e) {
1217                 switch(e.type_) { 
1218                 case ErrorException:
1219                         emergencyCleanup();
1220                         setQuitOnLastWindowClosed(false);
1221                         closeAllViews();
1222                         Alert::error(e.title_, e.details_);
1223 #ifndef NDEBUG
1224                         // Properly crash in debug mode in order to get a useful backtrace.
1225                         abort();
1226 #endif
1227                         // In release mode, try to exit gracefully.
1228                         this->exit(1);
1229
1230                 case BufferException: {
1231                         Buffer * buf = current_view_->buffer();
1232                         docstring details = e.details_ + '\n';
1233                         details += theBufferList().emergencyWrite(buf);
1234                         theBufferList().release(buf);
1235                         details += "\n" + _("The current document was closed.");
1236                         Alert::error(e.title_, details);
1237                         return false;
1238                 }
1239                 case WarningException:
1240                         Alert::warning(e.title_, e.details_);
1241                         return false;
1242                 }
1243         }
1244         catch (exception const & e) {
1245                 docstring s = _("LyX has caught an exception, it will now "
1246                         "attempt to save all unsaved documents and exit."
1247                         "\n\nException: ");
1248                 s += from_ascii(e.what());
1249                 Alert::error(_("Software exception Detected"), s);
1250                 lyx_exit(1);
1251         }
1252         catch (...) {
1253                 docstring s = _("LyX has caught some really weird exception, it will "
1254                         "now attempt to save all unsaved documents and exit.");
1255                 Alert::error(_("Software exception Detected"), s);
1256                 lyx_exit(1);
1257         }
1258
1259         return false;
1260 }
1261
1262
1263 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1264 {
1265         QColor const & qcol = d->color_cache_.get(col);
1266         if (!qcol.isValid()) {
1267                 rgbcol.r = 0;
1268                 rgbcol.g = 0;
1269                 rgbcol.b = 0;
1270                 return false;
1271         }
1272         rgbcol.r = qcol.red();
1273         rgbcol.g = qcol.green();
1274         rgbcol.b = qcol.blue();
1275         return true;
1276 }
1277
1278
1279 string const GuiApplication::hexName(ColorCode col)
1280 {
1281         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1282 }
1283
1284
1285 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1286 {
1287         SocketNotifier * sn = new SocketNotifier(this, fd, func);
1288         d->socket_notifiers_[fd] = sn;
1289         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1290 }
1291
1292
1293 void GuiApplication::socketDataReceived(int fd)
1294 {
1295         d->socket_notifiers_[fd]->func_();
1296 }
1297
1298
1299 void GuiApplication::unregisterSocketCallback(int fd)
1300 {
1301         d->socket_notifiers_.take(fd)->setEnabled(false);
1302 }
1303
1304
1305 void GuiApplication::commitData(QSessionManager & sm)
1306 {
1307         /// The implementation is required to avoid an application exit
1308         /// when session state save is triggered by session manager.
1309         /// The default implementation sends a close event to all
1310         /// visible top level widgets when session managment allows
1311         /// interaction.
1312         /// We are changing that to close all wiew one by one.
1313         /// FIXME: verify if the default implementation is enough now.
1314         if (sm.allowsInteraction() && !closeAllViews())
1315                 sm.cancel();
1316 }
1317
1318
1319 void GuiApplication::unregisterView(GuiView * gv)
1320 {
1321         LASSERT(d->views_[gv->id()] == gv, /**/);
1322         d->views_.remove(gv->id());
1323         if (current_view_ == gv) {
1324                 current_view_ = 0;
1325                 theLyXFunc().setLyXView(0);
1326         }
1327 }
1328
1329
1330 bool GuiApplication::closeAllViews()
1331 {
1332         if (d->views_.empty())
1333                 return true;
1334
1335         QList<GuiView *> views = d->views_.values();
1336         foreach (GuiView * view, views) {
1337                 if (!view->close())
1338                         return false;
1339         }
1340
1341         d->views_.clear();
1342         return true;
1343 }
1344
1345
1346 GuiView & GuiApplication::view(int id) const
1347 {
1348         LASSERT(d->views_.contains(id), /**/);
1349         return *d->views_.value(id);
1350 }
1351
1352
1353 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1354 {
1355         QList<GuiView *> views = d->views_.values();
1356         foreach (GuiView * view, views)
1357                 view->hideDialog(name, inset);
1358 }
1359
1360
1361 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1362 {
1363         Buffer const * buffer_ = 0;
1364         QHash<int, GuiView *>::iterator end = d->views_.end();
1365         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1366                 if (Buffer const * ptr = (*it)->updateInset(inset))
1367                         buffer_ = ptr;
1368         }
1369         return buffer_;
1370 }
1371
1372
1373 bool GuiApplication::searchMenu(FuncRequest const & func,
1374         docstring_list & names) const
1375 {
1376         return d->menus_.searchMenu(func, names);
1377 }
1378
1379
1380 bool GuiApplication::readUIFile(QString const & name, bool include)
1381 {
1382         enum {
1383                 ui_menuset = 1,
1384                 ui_toolbars,
1385                 ui_toolbarset,
1386                 ui_include,
1387                 ui_last
1388         };
1389
1390         LexerKeyword uitags[] = {
1391                 { "include", ui_include },
1392                 { "menuset", ui_menuset },
1393                 { "toolbars", ui_toolbars },
1394                 { "toolbarset", ui_toolbarset }
1395         };
1396
1397         LYXERR(Debug::INIT, "About to read " << name << "...");
1398
1399         FileName ui_path;
1400         if (include) {
1401                 ui_path = libFileSearch("ui", name, "inc");
1402                 if (ui_path.empty())
1403                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1404         } else {
1405                 ui_path = libFileSearch("ui", name, "ui");
1406         }
1407
1408         if (ui_path.empty()) {
1409                 LYXERR(Debug::INIT, "Could not find " << name);
1410                 Alert::warning(_("Could not find UI definition file"),
1411                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1412                                    "Please check your installation."), qstring_to_ucs4(name)));
1413                 return false;
1414         }
1415
1416
1417         // Ensure that a file is read only once (prevents include loops)
1418         static QStringList uifiles;
1419         QString const uifile = toqstr(ui_path.absFilename());
1420         if (uifiles.contains(uifile)) {
1421                 if (!include) {
1422                         // We are reading again the top uifile so reset the safeguard:
1423                         uifiles.clear();
1424                         d->menus_.reset();
1425                         d->toolbars_.reset();
1426                 } else {
1427                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1428                                 << "Is this an include loop?");
1429                         return false;
1430                 }
1431         }
1432         uifiles.push_back(uifile);
1433
1434         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1435
1436         Lexer lex(uitags);
1437         lex.setFile(ui_path);
1438         if (!lex.isOK()) {
1439                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1440                        << endl;
1441         }
1442
1443         if (lyxerr.debugging(Debug::PARSER))
1444                 lex.printTable(lyxerr);
1445
1446         while (lex.isOK()) {
1447                 switch (lex.lex()) {
1448                 case ui_include: {
1449                         lex.next(true);
1450                         QString const file = toqstr(lex.getString());
1451                         if (!readUIFile(file, true))
1452                                 return false;
1453                         break;
1454                 }
1455                 case ui_menuset:
1456                         d->menus_.read(lex);
1457                         break;
1458
1459                 case ui_toolbarset:
1460                         d->toolbars_.readToolbars(lex);
1461                         break;
1462
1463                 case ui_toolbars:
1464                         d->toolbars_.readToolbarSettings(lex);
1465                         break;
1466
1467                 default:
1468                         if (!rtrim(lex.getString()).empty())
1469                                 lex.printError("LyX::ReadUIFile: "
1470                                                "Unknown menu tag: `$$Token'");
1471                         break;
1472                 }
1473         }
1474
1475         if (include)
1476                 return true;
1477
1478         QSettings settings;
1479         settings.beginGroup("ui_files");
1480         bool touched = false;
1481         for (int i = 0; i != uifiles.size(); ++i) {
1482                 QFileInfo fi(uifiles[i]);
1483                 QDateTime const date_value = fi.lastModified();
1484                 QString const name_key = QString::number(i);
1485                 if (!settings.contains(name_key)
1486                  || settings.value(name_key).toString() != uifiles[i]
1487                  || settings.value(name_key + "/date").toDateTime() != date_value) {
1488                         touched = true;
1489                         settings.setValue(name_key, uifiles[i]);
1490                         settings.setValue(name_key + "/date", date_value);
1491                 }
1492         }
1493         settings.endGroup();
1494         if (touched)
1495                 settings.remove("views");
1496
1497         return true;
1498 }
1499
1500
1501 void GuiApplication::onLastWindowClosed()
1502 {
1503         if (d->global_menubar_)
1504                 d->global_menubar_->grabKeyboard();
1505 }
1506
1507
1508 ////////////////////////////////////////////////////////////////////////
1509 //
1510 // X11 specific stuff goes here...
1511
1512 #ifdef Q_WS_X11
1513 bool GuiApplication::x11EventFilter(XEvent * xev)
1514 {
1515         if (!current_view_)
1516                 return false;
1517
1518         switch (xev->type) {
1519         case SelectionRequest: {
1520                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1521                         break;
1522                 LYXERR(Debug::SELECTION, "X requested selection.");
1523                 BufferView * bv = current_view_->view();
1524                 if (bv) {
1525                         docstring const sel = bv->requestSelection();
1526                         if (!sel.empty())
1527                                 d->selection_.put(sel);
1528                 }
1529                 break;
1530         }
1531         case SelectionClear: {
1532                 if (xev->xselectionclear.selection != XA_PRIMARY)
1533                         break;
1534                 LYXERR(Debug::SELECTION, "Lost selection.");
1535                 BufferView * bv = current_view_->view();
1536                 if (bv)
1537                         bv->clearSelection();
1538                 break;
1539         }
1540         }
1541         return false;
1542 }
1543 #endif
1544
1545 } // namespace frontend
1546
1547
1548 void hideDialogs(std::string const & name, Inset * inset)
1549 {
1550         if (theApp())
1551                 theApp()->hideDialogs(name, inset);
1552 }
1553
1554
1555 ////////////////////////////////////////////////////////////////////
1556 //
1557 // Font stuff
1558 //
1559 ////////////////////////////////////////////////////////////////////
1560
1561 frontend::FontLoader & theFontLoader()
1562 {
1563         LASSERT(frontend::guiApp, /**/);
1564         return frontend::guiApp->fontLoader();
1565 }
1566
1567
1568 frontend::FontMetrics const & theFontMetrics(Font const & f)
1569 {
1570         return theFontMetrics(f.fontInfo());
1571 }
1572
1573
1574 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1575 {
1576         LASSERT(frontend::guiApp, /**/);
1577         return frontend::guiApp->fontLoader().metrics(f);
1578 }
1579
1580
1581 ////////////////////////////////////////////////////////////////////
1582 //
1583 // Misc stuff
1584 //
1585 ////////////////////////////////////////////////////////////////////
1586
1587 frontend::Clipboard & theClipboard()
1588 {
1589         LASSERT(frontend::guiApp, /**/);
1590         return frontend::guiApp->clipboard();
1591 }
1592
1593
1594 frontend::Selection & theSelection()
1595 {
1596         LASSERT(frontend::guiApp, /**/);
1597         return frontend::guiApp->selection();
1598 }
1599
1600 } // namespace lyx
1601
1602 #include "GuiApplication_moc.cpp"