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