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