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