]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
d3c8439492ed610d046dcaafc2ac070c669592db
[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 "Toolbars.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 == pdfMimeType())
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 pdfMimeType();
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 == emfMimeType()) {
236                 formatetc.cfFormat = CF_ENHMETAFILE;
237                 formatetc.tymed = TYMED_ENHMF;
238         } else if (mimetype == wmfMimeType()) {
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 != emfMimeType() && mimetype != wmfMimeType())
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 emfMimeType(); 
318                 case CF_METAFILEPICT:
319                         return wmfMimeType();
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         ///
360         /// The global instance
361         Toolbars toolbars_;
362
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.setEnabled(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 Toolbars const & GuiApplication::toolbars() const 
714 {
715         return d->toolbars_;
716 }
717
718
719 Toolbars & GuiApplication::toolbars()
720 {
721         return d->toolbars_; 
722 }
723
724
725 Menus const & GuiApplication::menus() const 
726 {
727         return d->menus_;
728 }
729
730
731 Menus & GuiApplication::menus()
732 {
733         return d->menus_; 
734 }
735
736
737 QList<int> GuiApplication::viewIds() const
738 {
739         return d->views_.keys();
740 }
741
742
743 ColorCache & GuiApplication::colorCache()
744 {
745         return d->color_cache_;
746 }
747
748
749 int GuiApplication::exec()
750 {
751         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
752         return QApplication::exec();
753 }
754
755
756 void GuiApplication::exit(int status)
757 {
758         QApplication::exit(status);
759 }
760
761
762 void GuiApplication::execBatchCommands()
763 {
764         // Read menus
765         if (!readUIFile(toqstr(lyxrc.ui_file)))
766                 // Gives some error box here.
767                 return;
768
769         // init the global menubar on Mac. This must be done after the session
770         // was recovered to know the "last files".
771         if (d->global_menubar_)
772                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
773
774         LyX::ref().execBatchCommands();
775 }
776
777 QAbstractItemModel * GuiApplication::languageModel()
778 {
779         if (d->language_model_)
780                 return d->language_model_;
781
782         QStandardItemModel * lang_model = new QStandardItemModel(this);
783         lang_model->insertColumns(0, 1);
784         int current_row;
785         Languages::const_iterator it = languages.begin();
786         Languages::const_iterator end = languages.end();
787         for (; it != end; ++it) {
788                 current_row = lang_model->rowCount();
789                 lang_model->insertRows(current_row, 1);
790                 QModelIndex item = lang_model->index(current_row, 0);
791                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
792                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
793         }
794         d->language_model_ = new QSortFilterProxyModel(this);
795         d->language_model_->setSourceModel(lang_model);
796 #if QT_VERSION >= 0x040300
797         d->language_model_->setSortLocaleAware(true);
798 #endif
799         return d->language_model_;
800 }
801
802
803 void GuiApplication::restoreGuiSession()
804 {
805         if (!lyxrc.load_session)
806                 return;
807
808         Session & session = LyX::ref().session();
809         vector<FileName> const & lastopened = session.lastOpened().getfiles();
810         // do not add to the lastfile list since these files are restored from
811         // last session, and should be already there (regular files), or should
812         // not be added at all (help files).
813         for_each(lastopened.begin(), lastopened.end(),
814                 bind(&GuiView::loadDocument, current_view_, _1, false));
815
816         // clear this list to save a few bytes of RAM
817         session.lastOpened().clear();
818 }
819
820
821 QString const GuiApplication::romanFontName()
822 {
823         QFont font;
824         font.setKerning(false);
825         font.setStyleHint(QFont::Serif);
826         font.setFamily("serif");
827
828         return QFontInfo(font).family();
829 }
830
831
832 QString const GuiApplication::sansFontName()
833 {
834         QFont font;
835         font.setKerning(false);
836         font.setStyleHint(QFont::SansSerif);
837         font.setFamily("sans");
838
839         return QFontInfo(font).family();
840 }
841
842
843 QString const GuiApplication::typewriterFontName()
844 {
845         QFont font;
846         font.setKerning(false);
847         font.setStyleHint(QFont::TypeWriter);
848         font.setFamily("monospace");
849
850         return QFontInfo(font).family();
851 }
852
853
854 void GuiApplication::handleRegularEvents()
855 {
856         ForkedCallsController::handleCompletedProcesses();
857 }
858
859
860 bool GuiApplication::event(QEvent * e)
861 {
862         switch(e->type()) {
863         case QEvent::FileOpen: {
864                 // Open a file; this happens only on Mac OS X for now
865                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
866
867                 if (!current_view_ || !current_view_->view())
868                         // The application is not properly initialized yet.
869                         // So we acknowledge the event and delay the file opening
870                         // until LyX is ready.
871                         // FIXME UNICODE: FileName accept an utf8 encoded string.
872                         LyX::ref().addFileToLoad(fromqstr(foe->file()));
873                 else
874                         lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
875                                 qstring_to_ucs4(foe->file())));
876
877                 e->accept();
878                 return true;
879         }
880         default:
881                 return QApplication::event(e);
882         }
883 }
884
885
886 bool GuiApplication::notify(QObject * receiver, QEvent * event)
887 {
888         try {
889                 return QApplication::notify(receiver, event);
890         }
891         catch (ExceptionMessage const & e) {
892                 switch(e.type_) { 
893                 case ErrorException:
894                         LyX::cref().emergencyCleanup();
895                         setQuitOnLastWindowClosed(false);
896                         closeAllViews();
897                         Alert::error(e.title_, e.details_);
898 #ifndef NDEBUG
899                         // Properly crash in debug mode in order to get a useful backtrace.
900                         abort();
901 #endif
902                         // In release mode, try to exit gracefully.
903                         this->exit(1);
904
905                 case BufferException: {
906                         Buffer * buf = current_view_->buffer();
907                         docstring details = e.details_ + '\n';
908                         details += theBufferList().emergencyWrite(buf);
909                         theBufferList().release(buf);
910                         details += "\n" + _("The current document was closed.");
911                         Alert::error(e.title_, details);
912                         return false;
913                 }
914                 case WarningException:
915                         Alert::warning(e.title_, e.details_);
916                         return false;
917                 }
918         }
919         catch (exception const & e) {
920                 docstring s = _("LyX has caught an exception, it will now "
921                         "attempt to save all unsaved documents and exit."
922                         "\n\nException: ");
923                 s += from_ascii(e.what());
924                 Alert::error(_("Software exception Detected"), s);
925                 LyX::cref().exit(1);
926         }
927         catch (...) {
928                 docstring s = _("LyX has caught some really weird exception, it will "
929                         "now attempt to save all unsaved documents and exit.");
930                 Alert::error(_("Software exception Detected"), s);
931                 LyX::cref().exit(1);
932         }
933
934         return false;
935 }
936
937
938 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
939 {
940         QColor const & qcol = d->color_cache_.get(col);
941         if (!qcol.isValid()) {
942                 rgbcol.r = 0;
943                 rgbcol.g = 0;
944                 rgbcol.b = 0;
945                 return false;
946         }
947         rgbcol.r = qcol.red();
948         rgbcol.g = qcol.green();
949         rgbcol.b = qcol.blue();
950         return true;
951 }
952
953
954 string const GuiApplication::hexName(ColorCode col)
955 {
956         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
957 }
958
959
960 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
961 {
962         SocketNotifier * sn = new SocketNotifier(this, fd, func);
963         d->socket_notifiers_[fd] = sn;
964         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
965 }
966
967
968 void GuiApplication::socketDataReceived(int fd)
969 {
970         d->socket_notifiers_[fd]->func_();
971 }
972
973
974 void GuiApplication::unregisterSocketCallback(int fd)
975 {
976         d->socket_notifiers_.take(fd)->setEnabled(false);
977 }
978
979
980 void GuiApplication::commitData(QSessionManager & sm)
981 {
982         /// The implementation is required to avoid an application exit
983         /// when session state save is triggered by session manager.
984         /// The default implementation sends a close event to all
985         /// visible top level widgets when session managment allows
986         /// interaction.
987         /// We are changing that to close all wiew one by one.
988         /// FIXME: verify if the default implementation is enough now.
989         if (sm.allowsInteraction() && !closeAllViews())
990                 sm.cancel();
991 }
992
993
994 void GuiApplication::unregisterView(GuiView * gv)
995 {
996         LASSERT(d->views_[gv->id()] == gv, /**/);
997         d->views_.remove(gv->id());
998         if (current_view_ == gv) {
999                 current_view_ = 0;
1000                 theLyXFunc().setLyXView(0);
1001         }
1002 }
1003
1004
1005 bool GuiApplication::closeAllViews()
1006 {
1007         if (d->views_.empty())
1008                 return true;
1009
1010         QList<GuiView *> views = d->views_.values();
1011         foreach (GuiView * view, views) {
1012                 if (!view->close())
1013                         return false;
1014         }
1015
1016         d->views_.clear();
1017         return true;
1018 }
1019
1020
1021 GuiView & GuiApplication::view(int id) const
1022 {
1023         LASSERT(d->views_.contains(id), /**/);
1024         return *d->views_.value(id);
1025 }
1026
1027
1028 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1029 {
1030         QList<GuiView *> views = d->views_.values();
1031         foreach (GuiView * view, views)
1032                 view->hideDialog(name, inset);
1033 }
1034
1035
1036 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1037 {
1038         Buffer const * buffer_ = 0;
1039         QHash<int, GuiView *>::iterator end = d->views_.end();
1040         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1041                 if (Buffer const * ptr = (*it)->updateInset(inset))
1042                         buffer_ = ptr;
1043         }
1044         return buffer_;
1045 }
1046
1047
1048 bool GuiApplication::searchMenu(FuncRequest const & func,
1049         docstring_list & names) const
1050 {
1051         return d->menus_.searchMenu(func, names);
1052 }
1053
1054
1055 bool GuiApplication::readUIFile(QString const & name, bool include)
1056 {
1057         enum {
1058                 ui_menuset = 1,
1059                 ui_toolbars,
1060                 ui_toolbarset,
1061                 ui_include,
1062                 ui_last
1063         };
1064
1065         LexerKeyword uitags[] = {
1066                 { "include", ui_include },
1067                 { "menuset", ui_menuset },
1068                 { "toolbars", ui_toolbars },
1069                 { "toolbarset", ui_toolbarset }
1070         };
1071
1072         // Ensure that a file is read only once (prevents include loops)
1073         static QStringList uifiles;
1074         if (uifiles.contains(name)) {
1075                 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1076                                     << "Is this an include loop?");
1077                 return false;
1078         }
1079
1080         LYXERR(Debug::INIT, "About to read " << name << "...");
1081
1082         FileName ui_path;
1083         if (include) {
1084                 ui_path = libFileSearch("ui", name, "inc");
1085                 if (ui_path.empty())
1086                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1087         } else {
1088                 ui_path = libFileSearch("ui", name, "ui");
1089         }
1090
1091         if (ui_path.empty()) {
1092                 LYXERR(Debug::INIT, "Could not find " << name);
1093                 Alert::warning(_("Could not find UI defintion file"),
1094                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1095                                    "Please check your installation."), qstring_to_ucs4(name)));
1096                 return false;
1097         }
1098
1099         uifiles.push_back(name);
1100
1101         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1102         Lexer lex(uitags);
1103         lex.setFile(ui_path);
1104         if (!lex.isOK()) {
1105                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1106                        << endl;
1107         }
1108
1109         if (lyxerr.debugging(Debug::PARSER))
1110                 lex.printTable(lyxerr);
1111
1112         while (lex.isOK()) {
1113                 switch (lex.lex()) {
1114                 case ui_include: {
1115                         lex.next(true);
1116                         QString const file = toqstr(lex.getString());
1117                         if (!readUIFile(file, true))
1118                                 return false;
1119                         break;
1120                 }
1121                 case ui_menuset:
1122                         d->menus_.read(lex);
1123                         break;
1124
1125                 case ui_toolbarset:
1126                         d->toolbars_.readToolbars(lex);
1127                         break;
1128
1129                 case ui_toolbars:
1130                         d->toolbars_.readToolbarSettings(lex);
1131                         break;
1132
1133                 default:
1134                         if (!rtrim(lex.getString()).empty())
1135                                 lex.printError("LyX::ReadUIFile: "
1136                                                "Unknown menu tag: `$$Token'");
1137                         break;
1138                 }
1139         }
1140         return true;
1141 }
1142
1143
1144 void GuiApplication::onLastWindowClosed()
1145 {
1146         if (d->global_menubar_)
1147                 d->global_menubar_->grabKeyboard();
1148 }
1149
1150
1151 ////////////////////////////////////////////////////////////////////////
1152 //
1153 // X11 specific stuff goes here...
1154
1155 #ifdef Q_WS_X11
1156 bool GuiApplication::x11EventFilter(XEvent * xev)
1157 {
1158         if (!current_view_)
1159                 return false;
1160
1161         switch (xev->type) {
1162         case SelectionRequest: {
1163                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1164                         break;
1165                 LYXERR(Debug::GUI, "X requested selection.");
1166                 BufferView * bv = current_view_->view();
1167                 if (bv) {
1168                         docstring const sel = bv->requestSelection();
1169                         if (!sel.empty())
1170                                 d->selection_.put(sel);
1171                 }
1172                 break;
1173         }
1174         case SelectionClear: {
1175                 if (xev->xselectionclear.selection != XA_PRIMARY)
1176                         break;
1177                 LYXERR(Debug::GUI, "Lost selection.");
1178                 BufferView * bv = current_view_->view();
1179                 if (bv)
1180                         bv->clearSelection();
1181                 break;
1182         }
1183         }
1184         return false;
1185 }
1186 #endif
1187
1188 } // namespace frontend
1189
1190
1191 void hideDialogs(std::string const & name, Inset * inset)
1192 {
1193         if (theApp())
1194                 theApp()->hideDialogs(name, inset);
1195 }
1196
1197
1198 ////////////////////////////////////////////////////////////////////
1199 //
1200 // Font stuff
1201 //
1202 ////////////////////////////////////////////////////////////////////
1203
1204 frontend::FontLoader & theFontLoader()
1205 {
1206         LASSERT(frontend::guiApp, /**/);
1207         return frontend::guiApp->fontLoader();
1208 }
1209
1210
1211 frontend::FontMetrics const & theFontMetrics(Font const & f)
1212 {
1213         return theFontMetrics(f.fontInfo());
1214 }
1215
1216
1217 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1218 {
1219         LASSERT(frontend::guiApp, /**/);
1220         return frontend::guiApp->fontLoader().metrics(f);
1221 }
1222
1223
1224 ////////////////////////////////////////////////////////////////////
1225 //
1226 // Misc stuff
1227 //
1228 ////////////////////////////////////////////////////////////////////
1229
1230 frontend::Clipboard & theClipboard()
1231 {
1232         LASSERT(frontend::guiApp, /**/);
1233         return frontend::guiApp->clipboard();
1234 }
1235
1236
1237 frontend::Selection & theSelection()
1238 {
1239         LASSERT(frontend::guiApp, /**/);
1240         return frontend::guiApp->selection();
1241 }
1242
1243 } // namespace lyx
1244
1245 #include "GuiApplication_moc.cpp"