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