]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Get rid of Application::initGlobalMenu().
[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
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
30
31 #include "Buffer.h"
32 #include "BufferList.h"
33 #include "BufferView.h"
34 #include "Font.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "Language.h"
38 #include "LyX.h"
39 #include "LyXFunc.h"
40 #include "LyXRC.h"
41 #include "Session.h"
42 #include "version.h"
43
44 #include "support/lassert.h"
45 #include "support/debug.h"
46 #include "support/ExceptionMessage.h"
47 #include "support/FileName.h"
48 #include "support/ForkedCalls.h"
49 #include "support/gettext.h"
50 #include "support/lstrings.h"
51 #include "support/os.h"
52 #include "support/Package.h"
53
54 #ifdef Q_WS_MACX
55 #include "support/linkback/LinkBackProxy.h"
56 #endif
57
58 #include <QClipboard>
59 #include <QEventLoop>
60 #include <QFileOpenEvent>
61 #include <QLocale>
62 #include <QLibraryInfo>
63 #include <QMacPasteboardMime>
64 #include <QMenuBar>
65 #include <QMimeData>
66 #include <QPixmapCache>
67 #include <QRegExp>
68 #include <QSessionManager>
69 #include <QSocketNotifier>
70 #include <QSortFilterProxyModel>
71 #include <QStandardItemModel>
72 #include <QTextCodec>
73 #include <QTimer>
74 #include <QTranslator>
75 #include <QWidget>
76
77 #ifdef Q_WS_X11
78 #include <X11/Xatom.h>
79 #include <X11/Xlib.h>
80 #undef CursorShape
81 #undef None
82 #endif
83
84 #ifdef Q_WS_WIN
85 #include <QVector>
86 #include <QWindowsMime>
87 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
88 #include <wtypes.h>
89 #endif
90 #include <objidl.h>
91 #endif // Q_WS_WIN
92
93 #include <boost/bind.hpp>
94
95 #include <exception>
96 #include <map>
97
98 using namespace std;
99 using namespace lyx::support;
100
101 // FIXME: These strings are also used in GuiClipboard.cpp.
102 static char const * const lyx_mime_type = "application/x-lyx";
103 static char const * const pdf_mime_type = "application/pdf";
104 static char const * const emf_mime_type = "image/x-emf";
105 static char const * const wmf_mime_type = "image/x-wmf";
106
107 namespace lyx {
108
109 frontend::Application * createApplication(int & argc, char * argv[])
110 {
111         return new frontend::GuiApplication(argc, argv);
112 }
113
114
115 namespace frontend {
116
117 class SocketNotifier : public QSocketNotifier
118 {
119 public:
120         /// connect a connection notification from the LyXServerSocket
121         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
122                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
123         {}
124
125 public:
126         /// The callback function
127         Application::SocketCallback func_;
128 };
129
130
131 ////////////////////////////////////////////////////////////////////////
132 // Mac specific stuff goes here...
133
134 class MenuTranslator : public QTranslator
135 {
136 public:
137         MenuTranslator(QObject * parent)
138                 : QTranslator(parent)
139         {}
140
141         QString translate(const char * /*context*/, 
142           const char * sourceText, 
143           const char * /*comment*/ = 0) 
144         {
145                 string const s = sourceText;
146                 if (s == N_("About %1") || s == N_("Preferences") 
147                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
148                         return qt_(s);
149                 else 
150                         return QString();
151         }
152 };
153
154 class GlobalMenuBar : public QMenuBar
155 {
156 public:
157         ///
158         GlobalMenuBar() : QMenuBar(0) {}
159         
160         ///
161         bool event(QEvent * e)
162         {
163                 if (e->type() == QEvent::ShortcutOverride) {
164                         //          && activeWindow() == 0) {
165                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
166                         KeySymbol sym;
167                         setKeySymbol(&sym, ke);
168                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
169                         e->accept();
170                         return true;
171                 }
172                 return false;
173         }
174 };
175
176 #ifdef Q_WS_MACX
177 // QMacPasteboardMimeGraphics can only be compiled on Mac.
178
179 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
180 {
181 public:
182         QMacPasteboardMimeGraphics()
183                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
184         {}
185
186         QString convertorName() { return "Graphics"; }
187
188         QString flavorFor(QString const & mime)
189         {
190                 LYXERR(Debug::ACTION, "flavorFor " << mime);
191                 if (mime == QLatin1String(pdf_mime_type))
192                         return QLatin1String("com.adobe.pdf");
193                 return QString();
194         }
195
196         QString mimeFor(QString flav)
197         {
198                 LYXERR(Debug::ACTION, "mimeFor " << flav);
199                 if (flav == QLatin1String("com.adobe.pdf"))
200                         return QLatin1String(pdf_mime_type);
201                 return QString();
202         }
203
204         bool canConvert(QString const & mime, QString flav)
205         { return mimeFor(flav) == mime; }
206
207         QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav)
208         {
209                 if(data.count() > 1)
210                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
211                 return data.first();
212         }
213
214         QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav)
215         {
216                 QList<QByteArray> ret;
217                 ret.append(data.toByteArray());
218                 return ret;
219         }
220 };
221 #endif
222
223 ///////////////////////////////////////////////////////////////
224 // You can find more platform specific stuff
225 // at the end of this file...
226 ///////////////////////////////////////////////////////////////
227
228 ////////////////////////////////////////////////////////////////////////
229 // Windows specific stuff goes here...
230
231 #ifdef Q_WS_WIN
232 // QWindowsMimeMetafile can only be compiled on Windows.
233
234 static FORMATETC cfFromMime(QString const & mimetype)
235 {
236         FORMATETC formatetc;
237         if (mimetype == emf_mime_type) {
238                 formatetc.cfFormat = CF_ENHMETAFILE;
239                 formatetc.tymed = TYMED_ENHMF;
240         } else if (mimetype == wmf_mime_type) {
241                 formatetc.cfFormat = CF_METAFILEPICT;
242                 formatetc.tymed = TYMED_MFPICT;
243         }
244         formatetc.ptd = 0;
245         formatetc.dwAspect = DVASPECT_CONTENT;
246         formatetc.lindex = -1;
247         return formatetc;
248 }
249
250
251 class QWindowsMimeMetafile : public QWindowsMime {
252 public:
253         QWindowsMimeMetafile() {}
254
255         bool canConvertFromMime(FORMATETC const & formatetc,
256                 QMimeData const * mimedata) const
257         {
258                 return false;
259         }
260
261         bool canConvertToMime(QString const & mimetype,
262                 IDataObject * pDataObj) const
263         {
264                 if (mimetype != emf_mime_type && mimetype != wmf_mime_type)
265                         return false;
266                 FORMATETC formatetc = cfFromMime(mimetype);
267                 return pDataObj->QueryGetData(&formatetc) == S_OK;
268         }
269
270         bool convertFromMime(FORMATETC const & formatetc,
271                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
272         {
273                 return false;
274         }
275
276         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
277                 QVariant::Type preferredType) const
278         {
279                 QByteArray data;
280                 if (!canConvertToMime(mimetype, pDataObj))
281                         return data;
282
283                 FORMATETC formatetc = cfFromMime(mimetype);
284                 STGMEDIUM s;
285                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
286                         return data;
287
288                 int dataSize;
289                 if (s.tymed == TYMED_ENHMF) {
290                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
291                         data.resize(dataSize);
292                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
293                                 (LPBYTE)data.data());
294                 } else if (s.tymed == TYMED_MFPICT) {
295                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
296                         data.resize(dataSize);
297                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
298                                 (LPBYTE)data.data());
299                 }
300                 data.detach();
301                 ReleaseStgMedium(&s);
302
303                 return data;
304         }
305
306
307         QVector<FORMATETC> formatsForMime(QString const & mimeType,
308                 QMimeData const * mimeData) const
309         {
310                 QVector<FORMATETC> formats;
311                 formats += cfFromMime(mimeType);
312                 return formats;
313         }
314
315         QString mimeForFormat(FORMATETC const & formatetc) const
316         {
317                 switch (formatetc.cfFormat) {
318                 case CF_ENHMETAFILE:
319                         return emf_mime_type; 
320                 case CF_METAFILEPICT:
321                         return wmf_mime_type;
322                 }
323                 return QString();
324         }
325 };
326
327 #endif // Q_WS_WIN
328
329 ////////////////////////////////////////////////////////////////////////
330 // GuiApplication::Private definition and implementation.
331 ////////////////////////////////////////////////////////////////////////
332
333 struct GuiApplication::Private
334 {
335         Private(): language_model_(0), global_menubar_(0)
336         {
337 #ifdef Q_WS_MACX
338                 // Create the global default menubar which is shown for the dialogs
339                 // and if no GuiView is visible.
340                 global_menubar_ = new GlobalMenuBar();
341 #endif
342         }
343
344         ///
345         QSortFilterProxyModel * language_model_;
346         ///
347         GuiClipboard clipboard_;
348         ///
349         GuiSelection selection_;
350         ///
351         FontLoader font_loader_;
352         ///
353         ColorCache color_cache_;
354         ///
355         QTranslator qt_trans_;
356         ///
357         std::map<int, SocketNotifier *> socket_notifiers_;
358         ///
359         Menus menus_;
360         /// this timer is used for any regular events one wants to
361         /// perform. at present it is used to check if forked processes
362         /// are done.
363         QTimer general_timer_;
364
365         /// Multiple views container.
366         /**
367         * Warning: This must not be a smart pointer as the destruction of the
368         * object is handled by Qt when the view is closed
369         * \sa Qt::WA_DeleteOnClose attribute.
370         */
371         std::map<int, GuiView *> views_;
372         ///
373         std::vector<int> view_ids_;
374
375         /// Only used on mac.
376         GlobalMenuBar * global_menubar_;
377
378 #ifdef Q_WS_MACX
379         /// Linkback mime handler for MacOSX.
380         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
381 #endif
382
383 #ifdef Q_WS_WIN
384         /// WMF Mime handler for Windows clipboard.
385         // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
386         // But this makes LyX crash on exit when LyX is compiled in release mode and if there
387         // is something in the clipboard.
388         QWindowsMimeMetafile wmf_mime_;
389 #endif
390 };
391
392
393 GuiApplication * guiApp;
394
395 GuiApplication::~GuiApplication()
396 {
397 #ifdef Q_WS_MACX
398         closeAllLinkBackLinks();
399 #endif
400         delete d;
401 }
402
403
404 GuiApplication::GuiApplication(int & argc, char ** argv)
405         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
406 {
407         QString app_name = "LyX";
408         QCoreApplication::setOrganizationName(app_name);
409         QCoreApplication::setOrganizationDomain("lyx.org");
410         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
411
412         // FIXME: quitOnLastWindowClosed is true by default. We should have a
413         // lyxrc setting for this in order to let the application stay resident.
414         // But then we need some kind of dock icon, at least on Windows.
415         /*
416         if (lyxrc.quit_on_last_window_closed)
417                 setQuitOnLastWindowClosed(false);
418         */
419 #ifdef Q_WS_MACX
420         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
421         // seems to be the default case for applications like LyX.
422         setQuitOnLastWindowClosed(false);
423 #endif
424         
425 #ifdef Q_WS_X11
426         // doubleClickInterval() is 400 ms on X11 which is just too long.
427         // On Windows and Mac OS X, the operating system's value is used.
428         // On Microsoft Windows, calling this function sets the double
429         // click interval for all applications. So we don't!
430         QApplication::setDoubleClickInterval(300);
431 #endif
432
433         // install translation file for Qt built-in dialogs
434         QString language_name = QString("qt_") + QLocale::system().name();
435         
436         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
437         // Short-named translator can be loaded from a long name, but not the
438         // opposite. Therefore, long name should be used without truncation.
439         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
440         if (d->qt_trans_.load(language_name,
441                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
442         {
443                 installTranslator(&d->qt_trans_);
444                 // even if the language calls for RtL, don't do that
445                 setLayoutDirection(Qt::LeftToRight);
446                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
447                         << language_name);
448         } else
449                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
450                         << language_name);
451
452 #ifdef Q_WS_MACX
453         // This allows to translate the strings that appear in the LyX menu.
454         /// A translator suitable for the entries in the LyX menu.
455         /// Only needed with Qt/Mac.
456         installTranslator(new MenuTranslator(this));
457 #endif
458         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
459
460         using namespace lyx::graphics;
461
462         Image::newImage = boost::bind(&GuiImage::newImage);
463         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
464
465         // needs to be done before reading lyxrc
466         QWidget w;
467         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
468
469         guiApp = this;
470
471         // Set the cache to 5120 kilobytes which corresponds to screen size of
472         // 1280 by 1024 pixels with a color depth of 32 bits.
473         QPixmapCache::setCacheLimit(5120);
474
475         // Initialize RC Fonts
476         if (lyxrc.roman_font_name.empty())
477                 lyxrc.roman_font_name = fromqstr(romanFontName());
478
479         if (lyxrc.sans_font_name.empty())
480                 lyxrc.sans_font_name = fromqstr(sansFontName());
481
482         if (lyxrc.typewriter_font_name.empty())
483                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
484
485         d->general_timer_.setInterval(500);
486         connect(&d->general_timer_, SIGNAL(timeout()),
487                 this, SLOT(handleRegularEvents()));
488         d->general_timer_.start();
489 }
490
491
492 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd)
493 {
494         FuncStatus flag;
495         bool enable = true;
496
497         switch(cmd.action) {
498
499         case LFUN_WINDOW_CLOSE:
500                 enable = d->view_ids_.size() > 0;
501                 break;
502
503         default:
504                 if (!current_view_) {
505                         enable = false;
506                         break;
507                 }
508         }
509
510         if (!enable)
511                 flag.enabled(false);
512
513         return flag;
514 }
515
516         
517 bool GuiApplication::dispatch(FuncRequest const & cmd)
518 {
519         switch(cmd.action) {
520
521         case LFUN_WINDOW_NEW:
522                 createView(toqstr(cmd.argument()));
523                 break;
524
525         case LFUN_WINDOW_CLOSE:
526                 // update bookmark pit of the current buffer before window close
527                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
528                         theLyXFunc().gotoBookmark(i+1, false, false);
529                 current_view_->close();
530                 break;
531
532         case LFUN_LYX_QUIT:
533                 // quitting is triggered by the gui code
534                 // (leaving the event loop).
535                 if (current_view_)
536                         current_view_->message(from_utf8(N_("Exiting.")));
537                 if (closeAllViews())
538                         quit();
539                 break;
540
541         case LFUN_SCREEN_FONT_UPDATE: {
542                 // handle the screen font changes.
543                 d->font_loader_.update();
544                 // Backup current_view_
545                 GuiView * view = current_view_;
546                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
547                 // to skip the refresh.
548                 current_view_ = 0;
549                 BufferList::iterator it = theBufferList().begin();
550                 BufferList::iterator const end = theBufferList().end();
551                 for (; it != end; ++it)
552                         (*it)->changed();
553                 // Restore current_view_
554                 current_view_ = view;
555                 break;
556         }
557
558         case LFUN_BUFFER_NEW:
559                 if (viewCount() == 0
560                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
561                         createView(QString(), false); // keep hidden
562                         current_view_->newDocument(to_utf8(cmd.argument()), false);
563                         current_view_->show();
564                         setActiveWindow(current_view_);
565                 } else
566                         current_view_->newDocument(to_utf8(cmd.argument()), false);
567                 break;
568
569         case LFUN_BUFFER_NEW_TEMPLATE:
570                 if (viewCount() == 0 
571                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
572                         createView();
573                         current_view_->newDocument(to_utf8(cmd.argument()), true);
574                         if (!current_view_->buffer())
575                                 current_view_->close();
576                 } else
577                         current_view_->newDocument(to_utf8(cmd.argument()), true);
578                 break;
579
580         case LFUN_FILE_OPEN:
581                 if (viewCount() == 0
582                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
583                         createView();
584                         current_view_->openDocument(to_utf8(cmd.argument()));
585                         if (!current_view_->buffer())
586                                 current_view_->close();
587                 } else
588                         current_view_->openDocument(to_utf8(cmd.argument()));
589                 break;
590
591         default:
592                 // Notify the caller that the action has not been dispatched.
593                 return false;
594         }
595
596         // The action has been dispatched.
597         return true;
598 }
599
600
601 void GuiApplication::resetGui()
602 {
603         map<int, GuiView *>::iterator it;
604         for (it = d->views_.begin(); it != d->views_.end(); ++it)
605                 it->second->resetDialogs();
606
607         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
608 }
609
610
611 static void updateIds(map<int, GuiView *> const & stdmap, vector<int> & ids)
612 {
613         ids.clear();
614         map<int, GuiView *>::const_iterator it;
615         for (it = stdmap.begin(); it != stdmap.end(); ++it)
616                 ids.push_back(it->first);
617 }
618
619
620 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
621 {
622         // release the keyboard which might have been grabed by the global
623         // menubar on Mac to catch shortcuts even without any GuiView.
624         if (d->global_menubar_)
625                 d->global_menubar_->releaseKeyboard();
626
627         // create new view
628         updateIds(d->views_, d->view_ids_);
629         int id = 0;
630         while (d->views_.find(id) != d->views_.end())
631                 id++;
632         GuiView * view = new GuiView(id);
633         
634         // copy the icon size from old view
635         if (viewCount() > 0)
636                 view->setIconSize(current_view_->iconSize());
637
638         // register view
639         d->views_[id] = view;
640         updateIds(d->views_, d->view_ids_);
641
642         if (autoShow) {
643                 view->show();
644                 setActiveWindow(view);
645         }
646
647         if (!geometry_arg.isEmpty()) {
648 #ifdef Q_WS_WIN
649                 int x, y;
650                 int w, h;
651                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
652                 re.indexIn(geometry_arg);
653                 w = re.cap(1).toInt();
654                 h = re.cap(2).toInt();
655                 x = re.cap(3).toInt();
656                 y = re.cap(4).toInt();
657                 view->setGeometry(x, y, w, h);
658 #endif
659         }
660         view->setFocus();
661         setCurrentView(view);
662 }
663
664
665 Clipboard & GuiApplication::clipboard()
666 {
667         return d->clipboard_;
668 }
669
670
671 Selection & GuiApplication::selection()
672 {
673         return d->selection_;
674 }
675
676
677 FontLoader & GuiApplication::fontLoader() 
678 {
679         return d->font_loader_;
680 }
681
682
683 Menus const & GuiApplication::menus() const 
684 {
685         return d->menus_;
686 }
687
688
689 Menus & GuiApplication::menus()
690 {
691         return d->menus_; 
692 }
693
694
695 size_t GuiApplication::viewCount() const
696 {
697         return d->view_ids_.size();
698 }
699
700
701 vector<int> const & GuiApplication::viewIds()
702 {
703         return d->view_ids_;
704 }
705
706 ColorCache & GuiApplication::colorCache()
707 {
708         return d->color_cache_;
709 }
710
711
712 int GuiApplication::exec()
713 {
714         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
715         return QApplication::exec();
716 }
717
718
719 void GuiApplication::exit(int status)
720 {
721         QApplication::exit(status);
722 }
723
724
725 void GuiApplication::execBatchCommands()
726 {
727         // init the global menubar on Mac. This must be done after the session
728         // was recovered to know the "last files".
729         if (d->global_menubar_)
730                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
731
732         LyX::ref().execBatchCommands();
733 }
734
735 QAbstractItemModel * GuiApplication::languageModel()
736 {
737         if (d->language_model_)
738                 return d->language_model_;
739
740         QStandardItemModel * lang_model = new QStandardItemModel(this);
741         lang_model->insertColumns(0, 1);
742         int current_row;
743         Languages::const_iterator it = languages.begin();
744         Languages::const_iterator end = languages.end();
745         for (; it != end; ++it) {
746                 current_row = lang_model->rowCount();
747                 lang_model->insertRows(current_row, 1);
748                 QModelIndex item = lang_model->index(current_row, 0);
749                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
750                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
751         }
752         d->language_model_ = new QSortFilterProxyModel(this);
753         d->language_model_->setSourceModel(lang_model);
754 #if QT_VERSION >= 0x040300
755         d->language_model_->setSortLocaleAware(true);
756 #endif
757         return d->language_model_;
758 }
759
760
761 void GuiApplication::restoreGuiSession()
762 {
763         if (!lyxrc.load_session)
764                 return;
765
766         Session & session = LyX::ref().session();
767         vector<FileName> const & lastopened = session.lastOpened().getfiles();
768         // do not add to the lastfile list since these files are restored from
769         // last session, and should be already there (regular files), or should
770         // not be added at all (help files).
771         for_each(lastopened.begin(), lastopened.end(),
772                 bind(&GuiView::loadDocument, current_view_, _1, false));
773
774         // clear this list to save a few bytes of RAM
775         session.lastOpened().clear();
776 }
777
778
779 QString const GuiApplication::romanFontName()
780 {
781         QFont font;
782         font.setKerning(false);
783         font.setStyleHint(QFont::Serif);
784         font.setFamily("serif");
785
786         return QFontInfo(font).family();
787 }
788
789
790 QString const GuiApplication::sansFontName()
791 {
792         QFont font;
793         font.setKerning(false);
794         font.setStyleHint(QFont::SansSerif);
795         font.setFamily("sans");
796
797         return QFontInfo(font).family();
798 }
799
800
801 QString const GuiApplication::typewriterFontName()
802 {
803         QFont font;
804         font.setKerning(false);
805         font.setStyleHint(QFont::TypeWriter);
806         font.setFamily("monospace");
807
808         return QFontInfo(font).family();
809 }
810
811
812 void GuiApplication::handleRegularEvents()
813 {
814         ForkedCallsController::handleCompletedProcesses();
815 }
816
817
818 bool GuiApplication::event(QEvent * e)
819 {
820         switch(e->type()) {
821         case QEvent::FileOpen: {
822                 // Open a file; this happens only on Mac OS X for now
823                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
824
825                 if (!current_view_ || !current_view_->view())
826                         // The application is not properly initialized yet.
827                         // So we acknowledge the event and delay the file opening
828                         // until LyX is ready.
829                         // FIXME UNICODE: FileName accept an utf8 encoded string.
830                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
831                 else
832                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
833                                 qstring_to_ucs4(foe->file())));
834
835                 e->accept();
836                 return true;
837         }
838         default:
839                 return QApplication::event(e);
840         }
841 }
842
843
844 bool GuiApplication::notify(QObject * receiver, QEvent * event)
845 {
846         try {
847                 return QApplication::notify(receiver, event);
848         }
849         catch (ExceptionMessage const & e) {
850                 switch(e.type_) { 
851                 case ErrorException:
852                         LyX::cref().emergencyCleanup();
853                         setQuitOnLastWindowClosed(false);
854                         closeAllViews();
855                         Alert::error(e.title_, e.details_);
856 #ifndef NDEBUG
857                         // Properly crash in debug mode in order to get a useful backtrace.
858                         abort();
859 #endif
860                         // In release mode, try to exit gracefully.
861                         this->exit(1);
862
863                 case BufferException: {
864                         Buffer * buf = current_view_->buffer();
865                         docstring details = e.details_ + '\n';
866                         details += theBufferList().emergencyWrite(buf);
867                         theBufferList().release(buf);
868                         details += "\n" + _("The current document was closed.");
869                         Alert::error(e.title_, details);
870                         return false;
871                 }
872                 case WarningException:
873                         Alert::warning(e.title_, e.details_);
874                         return false;
875                 }
876         }
877         catch (exception const & e) {
878                 docstring s = _("LyX has caught an exception, it will now "
879                         "attempt to save all unsaved documents and exit."
880                         "\n\nException: ");
881                 s += from_ascii(e.what());
882                 Alert::error(_("Software exception Detected"), s);
883                 LyX::cref().exit(1);
884         }
885         catch (...) {
886                 docstring s = _("LyX has caught some really weird exception, it will "
887                         "now attempt to save all unsaved documents and exit.");
888                 Alert::error(_("Software exception Detected"), s);
889                 LyX::cref().exit(1);
890         }
891
892         return false;
893 }
894
895
896 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
897 {
898         QColor const & qcol = d->color_cache_.get(col);
899         if (!qcol.isValid()) {
900                 rgbcol.r = 0;
901                 rgbcol.g = 0;
902                 rgbcol.b = 0;
903                 return false;
904         }
905         rgbcol.r = qcol.red();
906         rgbcol.g = qcol.green();
907         rgbcol.b = qcol.blue();
908         return true;
909 }
910
911
912 string const GuiApplication::hexName(ColorCode col)
913 {
914         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
915 }
916
917
918 void GuiApplication::updateColor(ColorCode)
919 {
920         // FIXME: Bleh, can't we just clear them all at once ?
921         d->color_cache_.clear();
922 }
923
924
925 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
926 {
927         SocketNotifier * sn = new SocketNotifier(this, fd, func);
928         d->socket_notifiers_[fd] = sn;
929         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
930 }
931
932
933 void GuiApplication::socketDataReceived(int fd)
934 {
935         d->socket_notifiers_[fd]->func_();
936 }
937
938
939 void GuiApplication::unregisterSocketCallback(int fd)
940 {
941         d->socket_notifiers_[fd]->setEnabled(false);
942         d->socket_notifiers_.erase(fd);
943 }
944
945
946 void GuiApplication::commitData(QSessionManager & sm)
947 {
948         /// The implementation is required to avoid an application exit
949         /// when session state save is triggered by session manager.
950         /// The default implementation sends a close event to all
951         /// visible top level widgets when session managment allows
952         /// interaction.
953         /// We are changing that to close all wiew one by one.
954         /// FIXME: verify if the default implementation is enough now.
955         if (sm.allowsInteraction() && !closeAllViews())
956                 sm.cancel();
957 }
958
959
960 bool GuiApplication::unregisterView(int id)
961 {
962         updateIds(d->views_, d->view_ids_);
963         LASSERT(d->views_.find(id) != d->views_.end(), /**/);
964         LASSERT(d->views_[id], /**/);
965
966         map<int, GuiView *>::iterator it;
967         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
968                 if (it->first == id) {
969                         d->views_.erase(id);
970                         break;
971                 }
972         }
973         updateIds(d->views_, d->view_ids_);
974         return true;
975 }
976
977
978 bool GuiApplication::closeAllViews()
979 {
980         updateIds(d->views_, d->view_ids_);
981         if (d->views_.empty())
982                 return true;
983
984         map<int, GuiView*> const cmap = d->views_;
985         map<int, GuiView*>::const_iterator it;
986         for (it = cmap.begin(); it != cmap.end(); ++it) {
987                 if (!it->second->close())
988                         return false;
989         }
990
991         d->views_.clear();
992         d->view_ids_.clear();
993         return true;
994 }
995
996
997 GuiView & GuiApplication::view(int id) const
998 {
999         LASSERT(d->views_.find(id) != d->views_.end(), /**/);
1000         return *d->views_.find(id)->second;
1001 }
1002
1003
1004 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1005 {
1006         vector<int>::const_iterator it = d->view_ids_.begin();
1007         vector<int>::const_iterator const end = d->view_ids_.end();
1008         for (; it != end; ++it)
1009                 view(*it).hideDialog(name, inset);
1010 }
1011
1012
1013 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1014 {
1015         Buffer const * buffer_ = 0;
1016         vector<int>::const_iterator it = d->view_ids_.begin();
1017         vector<int>::const_iterator const end = d->view_ids_.end();
1018         for (; it != end; ++it) {
1019                 Buffer const * ptr = view(*it).updateInset(inset);
1020                 if (ptr)
1021                         buffer_ = ptr;
1022         }
1023         return buffer_;
1024 }
1025
1026
1027 void GuiApplication::readMenus(Lexer & lex)
1028 {
1029         menus().read(lex);
1030 }
1031
1032
1033 bool GuiApplication::searchMenu(FuncRequest const & func,
1034         vector<docstring> & names) const
1035 {
1036         return menus().searchMenu(func, names);
1037 }
1038
1039
1040 void GuiApplication::onLastWindowClosed()
1041 {
1042         if (d->global_menubar_)
1043                 d->global_menubar_->grabKeyboard();
1044 }
1045
1046
1047 ////////////////////////////////////////////////////////////////////////
1048 //
1049 // X11 specific stuff goes here...
1050
1051 #ifdef Q_WS_X11
1052 bool GuiApplication::x11EventFilter(XEvent * xev)
1053 {
1054         if (!current_view_)
1055                 return false;
1056
1057         switch (xev->type) {
1058         case SelectionRequest: {
1059                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1060                         break;
1061                 LYXERR(Debug::GUI, "X requested selection.");
1062                 BufferView * bv = current_view_->view();
1063                 if (bv) {
1064                         docstring const sel = bv->requestSelection();
1065                         if (!sel.empty())
1066                                 selection_.put(sel);
1067                 }
1068                 break;
1069         }
1070         case SelectionClear: {
1071                 if (xev->xselectionclear.selection != XA_PRIMARY)
1072                         break;
1073                 LYXERR(Debug::GUI, "Lost selection.");
1074                 BufferView * bv = current_view_->view();
1075                 if (bv)
1076                         bv->clearSelection();
1077                 break;
1078         }
1079         }
1080         return false;
1081 }
1082 #endif
1083
1084 } // namespace frontend
1085
1086
1087 void hideDialogs(std::string const & name, Inset * inset)
1088 {
1089         if (theApp())
1090                 theApp()->hideDialogs(name, inset);
1091 }
1092
1093
1094 ////////////////////////////////////////////////////////////////////
1095 //
1096 // Font stuff
1097 //
1098 ////////////////////////////////////////////////////////////////////
1099
1100 frontend::FontLoader & theFontLoader()
1101 {
1102         LASSERT(frontend::guiApp, /**/);
1103         return frontend::guiApp->fontLoader();
1104 }
1105
1106
1107 frontend::FontMetrics const & theFontMetrics(Font const & f)
1108 {
1109         return theFontMetrics(f.fontInfo());
1110 }
1111
1112
1113 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1114 {
1115         LASSERT(frontend::guiApp, /**/);
1116         return frontend::guiApp->fontLoader().metrics(f);
1117 }
1118
1119
1120 ////////////////////////////////////////////////////////////////////
1121 //
1122 // Misc stuff
1123 //
1124 ////////////////////////////////////////////////////////////////////
1125
1126 frontend::Clipboard & theClipboard()
1127 {
1128         LASSERT(frontend::guiApp, /**/);
1129         return frontend::guiApp->clipboard();
1130 }
1131
1132
1133 frontend::Selection & theSelection()
1134 {
1135         LASSERT(frontend::guiApp, /**/);
1136         return frontend::guiApp->selection();
1137 }
1138
1139 } // namespace lyx
1140
1141 #include "GuiApplication_moc.cpp"