]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Pimpl stuff in GuiApplication.
[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         LyX::ref().execBatchCommands();
728 }
729
730 QAbstractItemModel * GuiApplication::languageModel()
731 {
732         if (d->language_model_)
733                 return d->language_model_;
734
735         QStandardItemModel * lang_model = new QStandardItemModel(this);
736         lang_model->insertColumns(0, 1);
737         int current_row;
738         Languages::const_iterator it = languages.begin();
739         Languages::const_iterator end = languages.end();
740         for (; it != end; ++it) {
741                 current_row = lang_model->rowCount();
742                 lang_model->insertRows(current_row, 1);
743                 QModelIndex item = lang_model->index(current_row, 0);
744                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
745                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
746         }
747         d->language_model_ = new QSortFilterProxyModel(this);
748         d->language_model_->setSourceModel(lang_model);
749 #if QT_VERSION >= 0x040300
750         d->language_model_->setSortLocaleAware(true);
751 #endif
752         return d->language_model_;
753 }
754
755
756 void GuiApplication::restoreGuiSession()
757 {
758         if (!lyxrc.load_session)
759                 return;
760
761         Session & session = LyX::ref().session();
762         vector<FileName> const & lastopened = session.lastOpened().getfiles();
763         // do not add to the lastfile list since these files are restored from
764         // last session, and should be already there (regular files), or should
765         // not be added at all (help files).
766         for_each(lastopened.begin(), lastopened.end(),
767                 bind(&GuiView::loadDocument, current_view_, _1, false));
768
769         // clear this list to save a few bytes of RAM
770         session.lastOpened().clear();
771 }
772
773
774 QString const GuiApplication::romanFontName()
775 {
776         QFont font;
777         font.setKerning(false);
778         font.setStyleHint(QFont::Serif);
779         font.setFamily("serif");
780
781         return QFontInfo(font).family();
782 }
783
784
785 QString const GuiApplication::sansFontName()
786 {
787         QFont font;
788         font.setKerning(false);
789         font.setStyleHint(QFont::SansSerif);
790         font.setFamily("sans");
791
792         return QFontInfo(font).family();
793 }
794
795
796 QString const GuiApplication::typewriterFontName()
797 {
798         QFont font;
799         font.setKerning(false);
800         font.setStyleHint(QFont::TypeWriter);
801         font.setFamily("monospace");
802
803         return QFontInfo(font).family();
804 }
805
806
807 void GuiApplication::handleRegularEvents()
808 {
809         ForkedCallsController::handleCompletedProcesses();
810 }
811
812
813 bool GuiApplication::event(QEvent * e)
814 {
815         switch(e->type()) {
816         case QEvent::FileOpen: {
817                 // Open a file; this happens only on Mac OS X for now
818                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
819
820                 if (!current_view_ || !current_view_->view())
821                         // The application is not properly initialized yet.
822                         // So we acknowledge the event and delay the file opening
823                         // until LyX is ready.
824                         // FIXME UNICODE: FileName accept an utf8 encoded string.
825                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
826                 else
827                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
828                                 qstring_to_ucs4(foe->file())));
829
830                 e->accept();
831                 return true;
832         }
833         default:
834                 return QApplication::event(e);
835         }
836 }
837
838
839 bool GuiApplication::notify(QObject * receiver, QEvent * event)
840 {
841         try {
842                 return QApplication::notify(receiver, event);
843         }
844         catch (ExceptionMessage const & e) {
845                 switch(e.type_) { 
846                 case ErrorException:
847                         LyX::cref().emergencyCleanup();
848                         setQuitOnLastWindowClosed(false);
849                         closeAllViews();
850                         Alert::error(e.title_, e.details_);
851 #ifndef NDEBUG
852                         // Properly crash in debug mode in order to get a useful backtrace.
853                         abort();
854 #endif
855                         // In release mode, try to exit gracefully.
856                         this->exit(1);
857
858                 case BufferException: {
859                         Buffer * buf = current_view_->buffer();
860                         docstring details = e.details_ + '\n';
861                         details += theBufferList().emergencyWrite(buf);
862                         theBufferList().release(buf);
863                         details += "\n" + _("The current document was closed.");
864                         Alert::error(e.title_, details);
865                         return false;
866                 }
867                 case WarningException:
868                         Alert::warning(e.title_, e.details_);
869                         return false;
870                 }
871         }
872         catch (exception const & e) {
873                 docstring s = _("LyX has caught an exception, it will now "
874                         "attempt to save all unsaved documents and exit."
875                         "\n\nException: ");
876                 s += from_ascii(e.what());
877                 Alert::error(_("Software exception Detected"), s);
878                 LyX::cref().exit(1);
879         }
880         catch (...) {
881                 docstring s = _("LyX has caught some really weird exception, it will "
882                         "now attempt to save all unsaved documents and exit.");
883                 Alert::error(_("Software exception Detected"), s);
884                 LyX::cref().exit(1);
885         }
886
887         return false;
888 }
889
890
891 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
892 {
893         QColor const & qcol = d->color_cache_.get(col);
894         if (!qcol.isValid()) {
895                 rgbcol.r = 0;
896                 rgbcol.g = 0;
897                 rgbcol.b = 0;
898                 return false;
899         }
900         rgbcol.r = qcol.red();
901         rgbcol.g = qcol.green();
902         rgbcol.b = qcol.blue();
903         return true;
904 }
905
906
907 string const GuiApplication::hexName(ColorCode col)
908 {
909         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
910 }
911
912
913 void GuiApplication::updateColor(ColorCode)
914 {
915         // FIXME: Bleh, can't we just clear them all at once ?
916         d->color_cache_.clear();
917 }
918
919
920 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
921 {
922         SocketNotifier * sn = new SocketNotifier(this, fd, func);
923         d->socket_notifiers_[fd] = sn;
924         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
925 }
926
927
928 void GuiApplication::socketDataReceived(int fd)
929 {
930         d->socket_notifiers_[fd]->func_();
931 }
932
933
934 void GuiApplication::unregisterSocketCallback(int fd)
935 {
936         d->socket_notifiers_[fd]->setEnabled(false);
937         d->socket_notifiers_.erase(fd);
938 }
939
940
941 void GuiApplication::commitData(QSessionManager & sm)
942 {
943         /// The implementation is required to avoid an application exit
944         /// when session state save is triggered by session manager.
945         /// The default implementation sends a close event to all
946         /// visible top level widgets when session managment allows
947         /// interaction.
948         /// We are changing that to close all wiew one by one.
949         /// FIXME: verify if the default implementation is enough now.
950         if (sm.allowsInteraction() && !closeAllViews())
951                 sm.cancel();
952 }
953
954
955 bool GuiApplication::unregisterView(int id)
956 {
957         updateIds(d->views_, d->view_ids_);
958         LASSERT(d->views_.find(id) != d->views_.end(), /**/);
959         LASSERT(d->views_[id], /**/);
960
961         map<int, GuiView *>::iterator it;
962         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
963                 if (it->first == id) {
964                         d->views_.erase(id);
965                         break;
966                 }
967         }
968         updateIds(d->views_, d->view_ids_);
969         return true;
970 }
971
972
973 bool GuiApplication::closeAllViews()
974 {
975         updateIds(d->views_, d->view_ids_);
976         if (d->views_.empty())
977                 return true;
978
979         map<int, GuiView*> const cmap = d->views_;
980         map<int, GuiView*>::const_iterator it;
981         for (it = cmap.begin(); it != cmap.end(); ++it) {
982                 if (!it->second->close())
983                         return false;
984         }
985
986         d->views_.clear();
987         d->view_ids_.clear();
988         return true;
989 }
990
991
992 GuiView & GuiApplication::view(int id) const
993 {
994         LASSERT(d->views_.find(id) != d->views_.end(), /**/);
995         return *d->views_.find(id)->second;
996 }
997
998
999 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1000 {
1001         vector<int>::const_iterator it = d->view_ids_.begin();
1002         vector<int>::const_iterator const end = d->view_ids_.end();
1003         for (; it != end; ++it)
1004                 view(*it).hideDialog(name, inset);
1005 }
1006
1007
1008 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1009 {
1010         Buffer const * buffer_ = 0;
1011         vector<int>::const_iterator it = d->view_ids_.begin();
1012         vector<int>::const_iterator const end = d->view_ids_.end();
1013         for (; it != end; ++it) {
1014                 Buffer const * ptr = view(*it).updateInset(inset);
1015                 if (ptr)
1016                         buffer_ = ptr;
1017         }
1018         return buffer_;
1019 }
1020
1021
1022 void GuiApplication::readMenus(Lexer & lex)
1023 {
1024         menus().read(lex);
1025 }
1026
1027
1028 bool GuiApplication::searchMenu(FuncRequest const & func,
1029         vector<docstring> & names) const
1030 {
1031         return menus().searchMenu(func, names);
1032 }
1033
1034
1035 void GuiApplication::initGlobalMenu()
1036 {
1037         if (d->global_menubar_)
1038                 menus().fillMenuBar(d->global_menubar_, 0, true);
1039 }
1040
1041
1042 void GuiApplication::onLastWindowClosed()
1043 {
1044         if (d->global_menubar_)
1045                 d->global_menubar_->grabKeyboard();
1046 }
1047
1048
1049 ////////////////////////////////////////////////////////////////////////
1050 //
1051 // X11 specific stuff goes here...
1052
1053 #ifdef Q_WS_X11
1054 bool GuiApplication::x11EventFilter(XEvent * xev)
1055 {
1056         if (!current_view_)
1057                 return false;
1058
1059         switch (xev->type) {
1060         case SelectionRequest: {
1061                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1062                         break;
1063                 LYXERR(Debug::GUI, "X requested selection.");
1064                 BufferView * bv = current_view_->view();
1065                 if (bv) {
1066                         docstring const sel = bv->requestSelection();
1067                         if (!sel.empty())
1068                                 selection_.put(sel);
1069                 }
1070                 break;
1071         }
1072         case SelectionClear: {
1073                 if (xev->xselectionclear.selection != XA_PRIMARY)
1074                         break;
1075                 LYXERR(Debug::GUI, "Lost selection.");
1076                 BufferView * bv = current_view_->view();
1077                 if (bv)
1078                         bv->clearSelection();
1079                 break;
1080         }
1081         }
1082         return false;
1083 }
1084 #endif
1085
1086 } // namespace frontend
1087
1088
1089 void hideDialogs(std::string const & name, Inset * inset)
1090 {
1091         if (theApp())
1092                 theApp()->hideDialogs(name, inset);
1093 }
1094
1095
1096 ////////////////////////////////////////////////////////////////////
1097 //
1098 // Font stuff
1099 //
1100 ////////////////////////////////////////////////////////////////////
1101
1102 frontend::FontLoader & theFontLoader()
1103 {
1104         LASSERT(frontend::guiApp, /**/);
1105         return frontend::guiApp->fontLoader();
1106 }
1107
1108
1109 frontend::FontMetrics const & theFontMetrics(Font const & f)
1110 {
1111         return theFontMetrics(f.fontInfo());
1112 }
1113
1114
1115 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1116 {
1117         LASSERT(frontend::guiApp, /**/);
1118         return frontend::guiApp->fontLoader().metrics(f);
1119 }
1120
1121
1122 ////////////////////////////////////////////////////////////////////
1123 //
1124 // Misc stuff
1125 //
1126 ////////////////////////////////////////////////////////////////////
1127
1128 frontend::Clipboard & theClipboard()
1129 {
1130         LASSERT(frontend::guiApp, /**/);
1131         return frontend::guiApp->clipboard();
1132 }
1133
1134
1135 frontend::Selection & theSelection()
1136 {
1137         LASSERT(frontend::guiApp, /**/);
1138         return frontend::guiApp->selection();
1139 }
1140
1141 } // namespace lyx
1142
1143 #include "GuiApplication_moc.cpp"