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