]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
d57c91075306b1da9b66388133a2f36bfd5250f0
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
19 #include "GuiImage.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
22 #include "GuiView.h"
23 #include "Menus.h"
24 #include "qt_helpers.h"
25 #include "ToolbarBackend.h"
26
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
31
32 #include "Buffer.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
35 #include "Color.h"
36 #include "Font.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
39 #include "Language.h"
40 #include "Lexer.h"
41 #include "LyX.h"
42 #include "LyXFunc.h"
43 #include "LyXRC.h"
44 #include "Session.h"
45 #include "version.h"
46
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/ExceptionMessage.h"
50 #include "support/FileName.h"
51 #include "support/foreach.h"
52 #include "support/ForkedCalls.h"
53 #include "support/gettext.h"
54 #include "support/lstrings.h"
55 #include "support/os.h"
56 #include "support/Package.h"
57
58 #ifdef Q_WS_MACX
59 #include "support/linkback/LinkBackProxy.h"
60 #endif
61
62 #include <QClipboard>
63 #include <QEventLoop>
64 #include <QFileOpenEvent>
65 #include <QHash>
66 #include <QLocale>
67 #include <QLibraryInfo>
68 #include <QMacPasteboardMime>
69 #include <QMenuBar>
70 #include <QMimeData>
71 #include <QPixmapCache>
72 #include <QRegExp>
73 #include <QSessionManager>
74 #include <QSocketNotifier>
75 #include <QSortFilterProxyModel>
76 #include <QStandardItemModel>
77 #include <QTextCodec>
78 #include <QTimer>
79 #include <QTranslator>
80 #include <QWidget>
81
82 #ifdef Q_WS_X11
83 #include <X11/Xatom.h>
84 #include <X11/Xlib.h>
85 #undef CursorShape
86 #undef None
87 #endif
88
89 #ifdef Q_WS_WIN
90 #include <QList>
91 #include <QWindowsMime>
92 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
93 #include <wtypes.h>
94 #endif
95 #include <objidl.h>
96 #endif // Q_WS_WIN
97
98 #include <boost/bind.hpp>
99
100 #include <exception>
101
102 using namespace std;
103 using namespace lyx::support;
104
105
106 namespace lyx {
107
108 frontend::Application * createApplication(int & argc, char * argv[])
109 {
110         return new frontend::GuiApplication(argc, argv);
111 }
112
113 namespace frontend {
114
115 class SocketNotifier : public QSocketNotifier
116 {
117 public:
118         /// connect a connection notification from the LyXServerSocket
119         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
120                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
121         {}
122
123 public:
124         /// The callback function
125         Application::SocketCallback func_;
126 };
127
128
129 ////////////////////////////////////////////////////////////////////////
130 // Mac specific stuff goes here...
131
132 class MenuTranslator : public QTranslator
133 {
134 public:
135         MenuTranslator(QObject * parent)
136                 : QTranslator(parent)
137         {}
138
139         QString translate(const char * /*context*/, 
140           const char * sourceText, 
141           const char * /*comment*/ = 0) 
142         {
143                 string const s = sourceText;
144                 if (s == N_("About %1") || s == N_("Preferences") 
145                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
146                         return qt_(s);
147                 else 
148                         return QString();
149         }
150 };
151
152 class GlobalMenuBar : public QMenuBar
153 {
154 public:
155         ///
156         GlobalMenuBar() : QMenuBar(0) {}
157         
158         ///
159         bool event(QEvent * e)
160         {
161                 if (e->type() == QEvent::ShortcutOverride) {
162                         //          && activeWindow() == 0) {
163                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
164                         KeySymbol sym;
165                         setKeySymbol(&sym, ke);
166                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
167                         e->accept();
168                         return true;
169                 }
170                 return false;
171         }
172 };
173
174 #ifdef Q_WS_MACX
175 // QMacPasteboardMimeGraphics can only be compiled on Mac.
176
177 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
178 {
179 public:
180         QMacPasteboardMimeGraphics()
181                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
182         {}
183
184         QString convertorName() { return "Graphics"; }
185
186         QString flavorFor(QString const & mime)
187         {
188                 LYXERR(Debug::ACTION, "flavorFor " << mime);
189                 if (mime == QLatin1String(pdf_mime_type))
190                         return QLatin1String("com.adobe.pdf");
191                 return QString();
192         }
193
194         QString mimeFor(QString flav)
195         {
196                 LYXERR(Debug::ACTION, "mimeFor " << flav);
197                 if (flav == QLatin1String("com.adobe.pdf"))
198                         return QLatin1String(pdf_mime_type);
199                 return QString();
200         }
201
202         bool canConvert(QString const & mime, QString flav)
203         { return mimeFor(flav) == mime; }
204
205         QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav)
206         {
207                 if(data.count() > 1)
208                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
209                 return data.first();
210         }
211
212         QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav)
213         {
214                 QList<QByteArray> ret;
215                 ret.append(data.toByteArray());
216                 return ret;
217         }
218 };
219 #endif
220
221 ///////////////////////////////////////////////////////////////
222 // You can find more platform specific stuff
223 // at the end of this file...
224 ///////////////////////////////////////////////////////////////
225
226 ////////////////////////////////////////////////////////////////////////
227 // Windows specific stuff goes here...
228
229 #ifdef Q_WS_WIN
230 // QWindowsMimeMetafile can only be compiled on Windows.
231
232 static FORMATETC cfFromMime(QString const & mimetype)
233 {
234         FORMATETC formatetc;
235         if (mimetype == emf_mime_type) {
236                 formatetc.cfFormat = CF_ENHMETAFILE;
237                 formatetc.tymed = TYMED_ENHMF;
238         } else if (mimetype == wmf_mime_type) {
239                 formatetc.cfFormat = CF_METAFILEPICT;
240                 formatetc.tymed = TYMED_MFPICT;
241         }
242         formatetc.ptd = 0;
243         formatetc.dwAspect = DVASPECT_CONTENT;
244         formatetc.lindex = -1;
245         return formatetc;
246 }
247
248
249 class QWindowsMimeMetafile : public QWindowsMime {
250 public:
251         QWindowsMimeMetafile() {}
252
253         bool canConvertFromMime(FORMATETC const & formatetc,
254                 QMimeData const * mimedata) const
255         {
256                 return false;
257         }
258
259         bool canConvertToMime(QString const & mimetype,
260                 IDataObject * pDataObj) const
261         {
262                 if (mimetype != emf_mime_type && mimetype != wmf_mime_type)
263                         return false;
264                 FORMATETC formatetc = cfFromMime(mimetype);
265                 return pDataObj->QueryGetData(&formatetc) == S_OK;
266         }
267
268         bool convertFromMime(FORMATETC const & formatetc,
269                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
270         {
271                 return false;
272         }
273
274         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
275                 QVariant::Type preferredType) const
276         {
277                 QByteArray data;
278                 if (!canConvertToMime(mimetype, pDataObj))
279                         return data;
280
281                 FORMATETC formatetc = cfFromMime(mimetype);
282                 STGMEDIUM s;
283                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
284                         return data;
285
286                 int dataSize;
287                 if (s.tymed == TYMED_ENHMF) {
288                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
289                         data.resize(dataSize);
290                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
291                                 (LPBYTE)data.data());
292                 } else if (s.tymed == TYMED_MFPICT) {
293                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
294                         data.resize(dataSize);
295                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
296                                 (LPBYTE)data.data());
297                 }
298                 data.detach();
299                 ReleaseStgMedium(&s);
300
301                 return data;
302         }
303
304
305         QVector<FORMATETC> formatsForMime(QString const & mimeType,
306                 QMimeData const * mimeData) const
307         {
308                 QVector<FORMATETC> formats;
309                 formats += cfFromMime(mimeType);
310                 return formats;
311         }
312
313         QString mimeForFormat(FORMATETC const & formatetc) const
314         {
315                 switch (formatetc.cfFormat) {
316                 case CF_ENHMETAFILE:
317                         return emf_mime_type; 
318                 case CF_METAFILEPICT:
319                         return wmf_mime_type;
320                 }
321                 return QString();
322         }
323 };
324
325 #endif // Q_WS_WIN
326
327 ////////////////////////////////////////////////////////////////////////
328 // GuiApplication::Private definition and implementation.
329 ////////////////////////////////////////////////////////////////////////
330
331 struct GuiApplication::Private
332 {
333         Private()
334                 : language_model_(0), global_menubar_(0)
335         {
336 #ifdef Q_WS_MACX
337                 // Create the global default menubar which is shown for the dialogs
338                 // and if no GuiView is visible.
339                 global_menubar_ = new GlobalMenuBar();
340 #endif
341         }
342
343         ///
344         QSortFilterProxyModel * language_model_;
345         ///
346         GuiClipboard clipboard_;
347         ///
348         GuiSelection selection_;
349         ///
350         FontLoader font_loader_;
351         ///
352         ColorCache color_cache_;
353         ///
354         QTranslator qt_trans_;
355         ///
356         QHash<int, SocketNotifier *> socket_notifiers_;
357         ///
358         Menus menus_;
359         /// this timer is used for any regular events one wants to
360         /// perform. at present it is used to check if forked processes
361         /// are done.
362         QTimer general_timer_;
363
364         /// Multiple views container.
365         /**
366         * Warning: This must not be a smart pointer as the destruction of the
367         * object is handled by Qt when the view is closed
368         * \sa Qt::WA_DeleteOnClose attribute.
369         */
370         QHash<int, GuiView *> views_;
371
372         /// Only used on mac.
373         GlobalMenuBar * global_menubar_;
374
375 #ifdef Q_WS_MACX
376         /// Linkback mime handler for MacOSX.
377         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
378 #endif
379
380 #ifdef Q_WS_WIN
381         /// WMF Mime handler for Windows clipboard.
382         // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
383         // But this makes LyX crash on exit when LyX is compiled in release mode and if there
384         // is something in the clipboard.
385         QWindowsMimeMetafile wmf_mime_;
386 #endif
387 };
388
389
390 GuiApplication * guiApp;
391
392 GuiApplication::~GuiApplication()
393 {
394 #ifdef Q_WS_MACX
395         closeAllLinkBackLinks();
396 #endif
397         delete d;
398 }
399
400
401 GuiApplication::GuiApplication(int & argc, char ** argv)
402         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
403 {
404         QString app_name = "LyX";
405         QCoreApplication::setOrganizationName(app_name);
406         QCoreApplication::setOrganizationDomain("lyx.org");
407         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
408
409         // FIXME: quitOnLastWindowClosed is true by default. We should have a
410         // lyxrc setting for this in order to let the application stay resident.
411         // But then we need some kind of dock icon, at least on Windows.
412         /*
413         if (lyxrc.quit_on_last_window_closed)
414                 setQuitOnLastWindowClosed(false);
415         */
416 #ifdef Q_WS_MACX
417         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
418         // seems to be the default case for applications like LyX.
419         setQuitOnLastWindowClosed(false);
420 #endif
421         
422 #ifdef Q_WS_X11
423         // doubleClickInterval() is 400 ms on X11 which is just too long.
424         // On Windows and Mac OS X, the operating system's value is used.
425         // On Microsoft Windows, calling this function sets the double
426         // click interval for all applications. So we don't!
427         QApplication::setDoubleClickInterval(300);
428 #endif
429
430         // install translation file for Qt built-in dialogs
431         QString language_name = QString("qt_") + QLocale::system().name();
432         
433         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
434         // Short-named translator can be loaded from a long name, but not the
435         // opposite. Therefore, long name should be used without truncation.
436         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
437         if (d->qt_trans_.load(language_name,
438                 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
439         {
440                 installTranslator(&d->qt_trans_);
441                 // even if the language calls for RtL, don't do that
442                 setLayoutDirection(Qt::LeftToRight);
443                 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
444                         << language_name);
445         } else
446                 LYXERR(Debug::GUI, "Could not find  Qt translations for locale "
447                         << language_name);
448
449 #ifdef Q_WS_MACX
450         // This allows to translate the strings that appear in the LyX menu.
451         /// A translator suitable for the entries in the LyX menu.
452         /// Only needed with Qt/Mac.
453         installTranslator(new MenuTranslator(this));
454 #endif
455         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
456
457         using namespace lyx::graphics;
458
459         Image::newImage = boost::bind(&GuiImage::newImage);
460         Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
461
462         // needs to be done before reading lyxrc
463         QWidget w;
464         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
465
466         guiApp = this;
467
468         // Set the cache to 5120 kilobytes which corresponds to screen size of
469         // 1280 by 1024 pixels with a color depth of 32 bits.
470         QPixmapCache::setCacheLimit(5120);
471
472         // Initialize RC Fonts
473         if (lyxrc.roman_font_name.empty())
474                 lyxrc.roman_font_name = fromqstr(romanFontName());
475
476         if (lyxrc.sans_font_name.empty())
477                 lyxrc.sans_font_name = fromqstr(sansFontName());
478
479         if (lyxrc.typewriter_font_name.empty())
480                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
481
482         d->general_timer_.setInterval(500);
483         connect(&d->general_timer_, SIGNAL(timeout()),
484                 this, SLOT(handleRegularEvents()));
485         d->general_timer_.start();
486 }
487
488
489 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
490 {
491         bool enable = true;
492
493         switch(cmd.action) {
494
495         case LFUN_WINDOW_CLOSE:
496                 enable = d->views_.size() > 0;
497                 break;
498
499         case LFUN_BUFFER_NEW:
500         case LFUN_BUFFER_NEW_TEMPLATE:
501         case LFUN_FILE_OPEN:
502         case LFUN_SCREEN_FONT_UPDATE:
503         case LFUN_SET_COLOR:
504         case LFUN_WINDOW_NEW:
505         case LFUN_LYX_QUIT:
506                 enable = true;
507                 break;
508
509         default:
510                 return false;
511         }
512
513         if (!enable)
514                 flag.enabled(false);
515
516         return true;
517 }
518
519         
520 bool GuiApplication::dispatch(FuncRequest const & cmd)
521 {
522         switch (cmd.action) {
523
524         case LFUN_WINDOW_NEW:
525                 createView(toqstr(cmd.argument()));
526                 break;
527
528         case LFUN_WINDOW_CLOSE:
529                 // update bookmark pit of the current buffer before window close
530                 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
531                         theLyXFunc().gotoBookmark(i+1, false, false);
532                 current_view_->close();
533                 break;
534
535         case LFUN_LYX_QUIT:
536                 // quitting is triggered by the gui code
537                 // (leaving the event loop).
538                 if (current_view_)
539                         current_view_->message(from_utf8(N_("Exiting.")));
540                 if (closeAllViews())
541                         quit();
542                 break;
543
544         case LFUN_SCREEN_FONT_UPDATE: {
545                 // handle the screen font changes.
546                 d->font_loader_.update();
547                 // Backup current_view_
548                 GuiView * view = current_view_;
549                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
550                 // to skip the refresh.
551                 current_view_ = 0;
552                 BufferList::iterator it = theBufferList().begin();
553                 BufferList::iterator const end = theBufferList().end();
554                 for (; it != end; ++it)
555                         (*it)->changed();
556                 // Restore current_view_
557                 current_view_ = view;
558                 break;
559         }
560
561         case LFUN_BUFFER_NEW:
562                 if (d->views_.empty()
563                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
564                         createView(QString(), false); // keep hidden
565                         current_view_->newDocument(to_utf8(cmd.argument()), false);
566                         current_view_->show();
567                         setActiveWindow(current_view_);
568                 } else {
569                         current_view_->newDocument(to_utf8(cmd.argument()), false);
570                 }
571                 break;
572
573         case LFUN_BUFFER_NEW_TEMPLATE:
574                 if (d->views_.empty()
575                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
576                         createView();
577                         current_view_->newDocument(to_utf8(cmd.argument()), true);
578                         if (!current_view_->buffer())
579                                 current_view_->close();
580                 } else {
581                         current_view_->newDocument(to_utf8(cmd.argument()), true);
582                 }
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         QHash<int, GuiView *>::iterator it;
641         for (it = d->views_.begin(); it != d->views_.end(); ++it)
642                 (*it)->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 QList<int> GuiApplication::viewIds() const
722 {
723         return d->views_.keys();
724 }
725
726
727 ColorCache & GuiApplication::colorCache()
728 {
729         return d->color_cache_;
730 }
731
732
733 int GuiApplication::exec()
734 {
735         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
736         return QApplication::exec();
737 }
738
739
740 void GuiApplication::exit(int status)
741 {
742         QApplication::exit(status);
743 }
744
745
746 void GuiApplication::execBatchCommands()
747 {
748         // Read menus
749         if (!readUIFile(toqstr(lyxrc.ui_file)))
750                 // Gives some error box here.
751                 return;
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_.take(fd)->setEnabled(false);
961 }
962
963
964 void GuiApplication::commitData(QSessionManager & sm)
965 {
966         /// The implementation is required to avoid an application exit
967         /// when session state save is triggered by session manager.
968         /// The default implementation sends a close event to all
969         /// visible top level widgets when session managment allows
970         /// interaction.
971         /// We are changing that to close all wiew one by one.
972         /// FIXME: verify if the default implementation is enough now.
973         if (sm.allowsInteraction() && !closeAllViews())
974                 sm.cancel();
975 }
976
977
978 void GuiApplication::unregisterView(GuiView * gv)
979 {
980         LASSERT(d->views_[gv->id()] == gv, /**/);
981         d->views_.remove(gv->id());
982         if (current_view_ == gv) {
983                 current_view_ = 0;
984                 theLyXFunc().setLyXView(0);
985         }
986 }
987
988
989 bool GuiApplication::closeAllViews()
990 {
991         if (d->views_.empty())
992                 return true;
993
994         QList<GuiView *> views = d->views_.values();
995         foreach (GuiView * view, views) {
996                 if (!view->close())
997                         return false;
998         }
999
1000         d->views_.clear();
1001         return true;
1002 }
1003
1004
1005 GuiView & GuiApplication::view(int id) const
1006 {
1007         LASSERT(d->views_.contains(id), /**/);
1008         return *d->views_.value(id);
1009 }
1010
1011
1012 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1013 {
1014         QList<GuiView *> views = d->views_.values();
1015         foreach (GuiView * view, views)
1016                 view->hideDialog(name, inset);
1017 }
1018
1019
1020 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1021 {
1022         Buffer const * buffer_ = 0;
1023         QHash<int, GuiView *>::iterator end = d->views_.end();
1024         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1025                 if (Buffer const * ptr = (*it)->updateInset(inset))
1026                         buffer_ = ptr;
1027         }
1028         return buffer_;
1029 }
1030
1031
1032 bool GuiApplication::searchMenu(FuncRequest const & func,
1033         docstring_list & names) const
1034 {
1035         return d->menus_.searchMenu(func, names);
1036 }
1037
1038
1039 bool GuiApplication::readUIFile(QString const & name, bool include)
1040 {
1041         enum {
1042                 ui_menuset = 1,
1043                 ui_toolbars,
1044                 ui_toolbarset,
1045                 ui_include,
1046                 ui_last
1047         };
1048
1049         LexerKeyword uitags[] = {
1050                 { "include", ui_include },
1051                 { "menuset", ui_menuset },
1052                 { "toolbars", ui_toolbars },
1053                 { "toolbarset", ui_toolbarset }
1054         };
1055
1056         // Ensure that a file is read only once (prevents include loops)
1057         static QStringList uifiles;
1058         if (uifiles.contains(name)) {
1059                 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1060                                     << "Is this an include loop?");
1061                 return false;
1062         }
1063
1064         LYXERR(Debug::INIT, "About to read " << name << "...");
1065
1066         FileName ui_path;
1067         if (include) {
1068                 ui_path = libFileSearch("ui", name, "inc");
1069                 if (ui_path.empty())
1070                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1071         } else {
1072                 ui_path = libFileSearch("ui", name, "ui");
1073         }
1074
1075         if (ui_path.empty()) {
1076                 LYXERR(Debug::INIT, "Could not find " << name);
1077                 Alert::warning(_("Could not find UI defintion file"),
1078                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1079                                    "Please check your installation."), qstring_to_ucs4(name)));
1080                 return false;
1081         }
1082
1083         uifiles.push_back(name);
1084
1085         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1086         Lexer lex(uitags);
1087         lex.setFile(ui_path);
1088         if (!lex.isOK()) {
1089                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1090                        << endl;
1091         }
1092
1093         if (lyxerr.debugging(Debug::PARSER))
1094                 lex.printTable(lyxerr);
1095
1096         while (lex.isOK()) {
1097                 switch (lex.lex()) {
1098                 case ui_include: {
1099                         lex.next(true);
1100                         QString const file = toqstr(lex.getString());
1101                         if (!readUIFile(file, true))
1102                                 return false;
1103                         break;
1104                 }
1105                 case ui_menuset:
1106                         d->menus_.read(lex);
1107                         break;
1108
1109                 case ui_toolbarset:
1110                         toolbarbackend.readToolbars(lex);
1111                         break;
1112
1113                 case ui_toolbars:
1114                         toolbarbackend.readToolbarSettings(lex);
1115                         break;
1116
1117                 default:
1118                         if (!rtrim(lex.getString()).empty())
1119                                 lex.printError("LyX::ReadUIFile: "
1120                                                "Unknown menu tag: `$$Token'");
1121                         break;
1122                 }
1123         }
1124         return true;
1125 }
1126
1127
1128 void GuiApplication::onLastWindowClosed()
1129 {
1130         if (d->global_menubar_)
1131                 d->global_menubar_->grabKeyboard();
1132 }
1133
1134
1135 ////////////////////////////////////////////////////////////////////////
1136 //
1137 // X11 specific stuff goes here...
1138
1139 #ifdef Q_WS_X11
1140 bool GuiApplication::x11EventFilter(XEvent * xev)
1141 {
1142         if (!current_view_)
1143                 return false;
1144
1145         switch (xev->type) {
1146         case SelectionRequest: {
1147                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1148                         break;
1149                 LYXERR(Debug::GUI, "X requested selection.");
1150                 BufferView * bv = current_view_->view();
1151                 if (bv) {
1152                         docstring const sel = bv->requestSelection();
1153                         if (!sel.empty())
1154                                 d->selection_.put(sel);
1155                 }
1156                 break;
1157         }
1158         case SelectionClear: {
1159                 if (xev->xselectionclear.selection != XA_PRIMARY)
1160                         break;
1161                 LYXERR(Debug::GUI, "Lost selection.");
1162                 BufferView * bv = current_view_->view();
1163                 if (bv)
1164                         bv->clearSelection();
1165                 break;
1166         }
1167         }
1168         return false;
1169 }
1170 #endif
1171
1172 } // namespace frontend
1173
1174
1175 void hideDialogs(std::string const & name, Inset * inset)
1176 {
1177         if (theApp())
1178                 theApp()->hideDialogs(name, inset);
1179 }
1180
1181
1182 ////////////////////////////////////////////////////////////////////
1183 //
1184 // Font stuff
1185 //
1186 ////////////////////////////////////////////////////////////////////
1187
1188 frontend::FontLoader & theFontLoader()
1189 {
1190         LASSERT(frontend::guiApp, /**/);
1191         return frontend::guiApp->fontLoader();
1192 }
1193
1194
1195 frontend::FontMetrics const & theFontMetrics(Font const & f)
1196 {
1197         return theFontMetrics(f.fontInfo());
1198 }
1199
1200
1201 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1202 {
1203         LASSERT(frontend::guiApp, /**/);
1204         return frontend::guiApp->fontLoader().metrics(f);
1205 }
1206
1207
1208 ////////////////////////////////////////////////////////////////////
1209 //
1210 // Misc stuff
1211 //
1212 ////////////////////////////////////////////////////////////////////
1213
1214 frontend::Clipboard & theClipboard()
1215 {
1216         LASSERT(frontend::guiApp, /**/);
1217         return frontend::guiApp->clipboard();
1218 }
1219
1220
1221 frontend::Selection & theSelection()
1222 {
1223         LASSERT(frontend::guiApp, /**/);
1224         return frontend::guiApp->selection();
1225 }
1226
1227 } // namespace lyx
1228
1229 #include "GuiApplication_moc.cpp"