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