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