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