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