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