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