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