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