]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
c53331fb29e645ed5b2d1eb852d491f00d60abed
[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 "ColorSet.h"
19 #include "GuiClipboard.h"
20 #include "GuiImage.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
23 #include "GuiView.h"
24 #include "Menus.h"
25 #include "qt_helpers.h"
26 #include "Toolbars.h"
27
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
32
33 #include "Buffer.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
36 #include "CmdDef.h"
37 #include "Color.h"
38 #include "Font.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "Intl.h"
42 #include "KeyMap.h"
43 #include "Language.h"
44 #include "LaTeXFeatures.h"
45 #include "Lexer.h"
46 #include "LyX.h"
47 #include "LyXAction.h"
48 #include "LyXRC.h"
49 #include "Paragraph.h"
50 #include "Server.h"
51 #include "Session.h"
52 #include "SpellChecker.h"
53 #include "Thesaurus.h"
54 #include "version.h"
55
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/FileName.h"
60 #include "support/filetools.h"
61 #include "support/foreach.h"
62 #include "support/ForkedCalls.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/lyxalgo.h" // sorted
67 #include "support/Messages.h"
68 #include "support/os.h"
69 #include "support/Package.h"
70 #include "support/Path.h"
71 #include "support/Systemcall.h"
72
73 #ifdef Q_WS_MACX
74 #include "support/linkback/LinkBackProxy.h"
75 #endif
76
77 #include <queue>
78
79 #include <QByteArray>
80 #include <QClipboard>
81 #include <QDateTime>
82 #include <QDir>
83 #include <QEventLoop>
84 #include <QFileOpenEvent>
85 #include <QFileInfo>
86 #include <QHash>
87 #include <QIcon>
88 #include <QImageReader>
89 #include <QLocale>
90 #include <QLibraryInfo>
91 #include <QList>
92 #include <QMacPasteboardMime>
93 #include <QMenuBar>
94 #include <QMimeData>
95 #include <QObject>
96 #include <QPixmap>
97 #include <QPixmapCache>
98 #include <QRegExp>
99 #include <QSessionManager>
100 #include <QSettings>
101 #include <QSocketNotifier>
102 #include <QSortFilterProxyModel>
103 #include <QStandardItemModel>
104 #include <QTextCodec>
105 #include <QTimer>
106 #include <QTranslator>
107 #include <QWidget>
108
109 #ifdef Q_WS_X11
110 #include <X11/Xatom.h>
111 #include <X11/Xlib.h>
112 #undef CursorShape
113 #undef None
114 #endif
115
116 #ifdef Q_WS_WIN
117 #include <QWindowsMime>
118 #ifdef Q_CC_GNU
119 #include <wtypes.h>
120 #endif
121 #include <objidl.h>
122 #endif // Q_WS_WIN
123
124 #include <boost/bind.hpp>
125 #include <boost/crc.hpp>
126
127 #include <exception>
128 #include <sstream>
129 #include <vector>
130
131 using namespace std;
132 using namespace lyx::support;
133
134
135 static void initializeResources()
136 {
137         static bool initialized = false;
138         if (!initialized) {
139                 Q_INIT_RESOURCE(Resources); 
140                 initialized = true;
141         }
142 }
143
144
145 namespace lyx {
146
147 frontend::Application * createApplication(int & argc, char * argv[])
148 {
149 #ifndef Q_WS_X11
150         // prune -geometry argument(s) by shifting
151         // the following ones 2 places down.
152         for (int i = 0 ; i < argc ; ++i) {
153                 if (strcmp(argv[i], "-geometry") == 0) {
154                         int const remove = (i+1) < argc ? 2 : 1;
155                         argc -= remove;
156                         for (int j = i; j < argc; ++j)
157                                 argv[j] = argv[j + remove];
158                         --i;
159                 }
160         }
161 #endif
162         return new frontend::GuiApplication(argc, argv);
163 }
164
165 namespace frontend {
166
167
168 /// Return the list of loadable formats.
169 vector<string> loadableImageFormats()
170 {
171         vector<string> fmts;
172
173         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
174
175         LYXERR(Debug::GRAPHICS,
176                 "\nThe image loader can load the following directly:\n");
177
178         if (qt_formats.empty())
179                 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
180
181         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
182
183                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
184
185                 string ext = ascii_lowercase((const char *) *it);
186                 // special case
187                 if (ext == "jpeg")
188                         ext = "jpg";
189                 fmts.push_back(ext);
190         }
191
192         return fmts;
193 }
194
195
196 ////////////////////////////////////////////////////////////////////////
197 //
198 // Icon loading support code
199 //
200 ////////////////////////////////////////////////////////////////////////
201
202 namespace {
203
204 struct PngMap {
205         QString key;
206         QString value;
207 };
208
209
210 bool operator<(PngMap const & lhs, PngMap const & rhs)
211 {
212         return lhs.key < rhs.key;
213 }
214
215
216 class CompareKey {
217 public:
218         CompareKey(QString const & name) : name_(name) {}
219         bool operator()(PngMap const & other) const { return other.key == name_; }
220 private:
221         QString const name_;
222 };
223
224
225 // this must be sorted alphabetically
226 // Upper case comes before lower case
227 PngMap sorted_png_map[] = {
228         { "Bumpeq", "bumpeq2" },
229         { "Cap", "cap2" },
230         { "Cup", "cup2" },
231         { "Delta", "delta2" },
232         { "Diamond", "diamond2" },
233         { "Downarrow", "downarrow2" },
234         { "Gamma", "gamma2" },
235         { "Lambda", "lambda2" },
236         { "Leftarrow", "leftarrow2" },
237         { "Leftrightarrow", "leftrightarrow2" },
238         { "Longleftarrow", "longleftarrow2" },
239         { "Longleftrightarrow", "longleftrightarrow2" },
240         { "Longrightarrow", "longrightarrow2" },
241         { "Omega", "omega2" },
242         { "Phi", "phi2" },
243         { "Pi", "pi2" },
244         { "Psi", "psi2" },
245         { "Rightarrow", "rightarrow2" },
246         { "Sigma", "sigma2" },
247         { "Subset", "subset2" },
248         { "Supset", "supset2" },
249         { "Theta", "theta2" },
250         { "Uparrow", "uparrow2" },
251         { "Updownarrow", "updownarrow2" },
252         { "Upsilon", "upsilon2" },
253         { "Vdash", "vdash3" },
254         { "Vert", "vert2" },
255         { "Xi", "xi2" },
256         { "nLeftarrow", "nleftarrow2" },
257         { "nLeftrightarrow", "nleftrightarrow2" },
258         { "nRightarrow", "nrightarrow2" },
259         { "nVDash", "nvdash3" },
260         { "nvDash", "nvdash2" },
261         { "textrm \\AA", "textrm_AA"},
262         { "textrm \\O", "textrm_O"},
263         { "vDash", "vdash2" }
264 };
265
266 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
267
268
269 QString findPng(QString const & name)
270 {
271         PngMap const * const begin = sorted_png_map;
272         PngMap const * const end = begin + nr_sorted_png_map;
273         LASSERT(sorted(begin, end), /**/);
274
275         PngMap const * const it = find_if(begin, end, CompareKey(name));
276
277         QString png_name;
278         if (it != end) {
279                 png_name = it->value;
280         } else {
281                 png_name = name;
282                 png_name.replace('_', "underscore");
283                 png_name.replace(' ', '_');
284
285                 // This way we can have "math-delim { }" on the toolbar.
286                 png_name.replace('(', "lparen");
287                 png_name.replace(')', "rparen");
288                 png_name.replace('[', "lbracket");
289                 png_name.replace(']', "rbracket");
290                 png_name.replace('{', "lbrace");
291                 png_name.replace('}', "rbrace");
292                 png_name.replace('|', "bars");
293                 png_name.replace(',', "thinspace");
294                 png_name.replace(':', "mediumspace");
295                 png_name.replace(';', "thickspace");
296                 png_name.replace('!', "negthinspace");
297         }
298
299         LYXERR(Debug::GUI, "findPng(" << name << ")\n"
300                 << "Looking for math PNG called \"" << png_name << '"');
301         return png_name;
302 }
303
304 } // namespace anon
305
306
307 QString iconName(FuncRequest const & f, bool unknown)
308 {
309         initializeResources();
310         QString name1;
311         QString name2;
312         QString path;
313         switch (f.action) {
314         case LFUN_MATH_INSERT:
315                 if (!f.argument().empty()) {
316                         path = "math/";
317                         name1 = findPng(toqstr(f.argument()).mid(1));
318                 }
319                 break;
320         case LFUN_MATH_DELIM:
321         case LFUN_MATH_BIGDELIM:
322                 path = "math/";
323                 name1 = findPng(toqstr(f.argument()));
324                 break;
325         case LFUN_CALL:
326                 path = "commands/";
327                 name1 = toqstr(f.argument());
328                 break;
329         case LFUN_COMMAND_ALTERNATIVES: {
330                 // use the first of the alternative commands
331                 docstring firstcom;
332                 docstring dummy = split(f.argument(), firstcom, ';');
333                 name1 = toqstr(firstcom);
334                 // FIXME: we should rename the icons to tabular-xxx instead of
335                 // "tabular-feature-xxx"
336                 name1.replace("inset-modify tabular", "tabular-feature");
337                 name1.replace(' ', '_');
338                 break;
339         }
340         case LFUN_INSET_MODIFY: {
341                 // FIXME: we should rename the icons to tabular-xxx instead of
342                 // "tabular-feature-xxx" and generalize this naming to all
343                 // insets, not to tabular using ones.
344                 string inset_name;
345                 string const command = split(to_utf8(f.argument()), inset_name, ' ');
346                 if (insetCode(inset_name) == TABULAR_CODE) {
347                         name1 = "tabular-feature "+ toqstr(command);
348                         name1.replace(' ', '_');
349                         break;
350                 }
351         }
352         default:
353                 name2 = toqstr(lyxaction.getActionName(f.action));
354                 name1 = name2;
355
356                 if (!f.argument().empty()) {
357                         name1 = name2 + ' ' + toqstr(f.argument());
358                         name1.replace(' ', '_');
359                         name1.replace('\\', "backslash");
360                 }
361         }
362
363         FileName fname = libFileSearch("images/" + path, name1, "png");
364         if (fname.exists())
365                 return toqstr(fname.absFilename());
366
367         fname = libFileSearch("images/" + path, name2, "png");
368         if (fname.exists())
369                 return toqstr(fname.absFilename());
370
371         path = ":/images/" + path;
372         QDir res(path);
373         if (!res.exists()) {
374                 LYXERR0("Directory " << path << " not found in resource!"); 
375                 return QString();
376         }
377         name1 += ".png";
378         if (res.exists(name1))
379                 return path + name1;
380
381         name2 += ".png";
382         if (res.exists(name2))
383                 return path + name2;
384
385         LYXERR(Debug::GUI, "Cannot find icon with filename "
386                            << "\"" << name1 << "\""
387                            << " or filename "
388                            << "\"" << name2 << "\"" 
389                            << " for command \""
390                            << lyxaction.getActionName(f.action)
391                            << '(' << to_utf8(f.argument()) << ")\"");
392
393         if (unknown) {
394                 fname = libFileSearch(QString("images/"), "unknown", "png");
395                 if (fname.exists())
396                         return toqstr(fname.absFilename());
397                 return QString(":/images/unknown.png");
398         }
399
400         return QString();
401 }
402
403 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
404 {
405         QPixmap pixmap;
406         FileName fname = libFileSearch(path, name, ext);
407         QString path1 = toqstr(fname.absFilename());
408         QString path2 = ":/" + path + name + "." + ext;
409
410         if (pixmap.load(path1)) {
411                 return pixmap;
412         }
413         else if (pixmap.load(path2)) {
414                 return pixmap;
415         }
416
417         LYXERR0("Cannot load pixmap \""
418                 << path << name << '.' << ext
419                 << "\", please verify resource system!");
420
421         return QPixmap();
422 }
423
424 QIcon getIcon(FuncRequest const & f, bool unknown)
425 {
426         QString icon = iconName(f, unknown);
427         if (icon.isEmpty())
428                 return QIcon();
429
430         //LYXERR(Debug::GUI, "Found icon: " << icon);
431         QPixmap pm;
432         if (!pm.load(icon)) {
433                 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
434                 return QIcon();
435         }
436
437         return QIcon(pm);
438 }
439
440
441 ////////////////////////////////////////////////////////////////////////
442 //
443 // LyX server support code.
444 //
445 ////////////////////////////////////////////////////////////////////////
446
447 class SocketNotifier : public QSocketNotifier
448 {
449 public:
450         /// connect a connection notification from the LyXServerSocket
451         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
452                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
453         {}
454
455 public:
456         /// The callback function
457         Application::SocketCallback func_;
458 };
459
460
461 ////////////////////////////////////////////////////////////////////////
462 //
463 // Mac specific stuff goes here...
464 //
465 ////////////////////////////////////////////////////////////////////////
466
467 class MenuTranslator : public QTranslator
468 {
469 public:
470         MenuTranslator(QObject * parent)
471                 : QTranslator(parent)
472         {}
473
474         QString translate(const char * /*context*/, 
475           const char * sourceText, 
476           const char * /*comment*/ = 0) 
477         {
478                 string const s = sourceText;
479                 if (s == N_("About %1") || s == N_("Preferences") 
480                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
481                         return qt_(s);
482                 else 
483                         return QString();
484         }
485 };
486
487 class GlobalMenuBar : public QMenuBar
488 {
489 public:
490         ///
491         GlobalMenuBar() : QMenuBar(0) {}
492         
493         ///
494         bool event(QEvent * e)
495         {
496                 if (e->type() == QEvent::ShortcutOverride) {
497                         //          && activeWindow() == 0) {
498                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
499                         KeySymbol sym;
500                         setKeySymbol(&sym, ke);
501                         guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
502                         e->accept();
503                         return true;
504                 }
505                 return false;
506         }
507 };
508
509 #ifdef Q_WS_MACX
510 // QMacPasteboardMimeGraphics can only be compiled on Mac.
511
512 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
513 {
514 public:
515         QMacPasteboardMimeGraphics()
516                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
517         {}
518
519         QString convertorName() { return "Graphics"; }
520
521         QString flavorFor(QString const & mime)
522         {
523                 LYXERR(Debug::ACTION, "flavorFor " << mime);
524                 if (mime == pdfMimeType())
525                         return QLatin1String("com.adobe.pdf");
526                 return QString();
527         }
528
529         QString mimeFor(QString flav)
530         {
531                 LYXERR(Debug::ACTION, "mimeFor " << flav);
532                 if (flav == QLatin1String("com.adobe.pdf"))
533                         return pdfMimeType();
534                 return QString();
535         }
536
537         bool canConvert(QString const & mime, QString flav)
538         {
539                 return mimeFor(flav) == mime;
540         }
541
542         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
543                 QString /*flav*/)
544         {
545                 if(data.count() > 1)
546                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
547                 return data.first();
548         }
549
550         QList<QByteArray> convertFromMime(QString const & /*mime*/,
551                 QVariant data, QString /*flav*/)
552         {
553                 QList<QByteArray> ret;
554                 ret.append(data.toByteArray());
555                 return ret;
556         }
557 };
558 #endif
559
560 ///////////////////////////////////////////////////////////////
561 //
562 // You can find more platform specific stuff at the end of this file...
563 //
564 ///////////////////////////////////////////////////////////////
565
566 ////////////////////////////////////////////////////////////////////////
567 // Windows specific stuff goes here...
568
569 #ifdef Q_WS_WIN
570 // QWindowsMimeMetafile can only be compiled on Windows.
571
572 static FORMATETC cfFromMime(QString const & mimetype)
573 {
574         FORMATETC formatetc;
575         if (mimetype == emfMimeType()) {
576                 formatetc.cfFormat = CF_ENHMETAFILE;
577                 formatetc.tymed = TYMED_ENHMF;
578         } else if (mimetype == wmfMimeType()) {
579                 formatetc.cfFormat = CF_METAFILEPICT;
580                 formatetc.tymed = TYMED_MFPICT;
581         }
582         formatetc.ptd = 0;
583         formatetc.dwAspect = DVASPECT_CONTENT;
584         formatetc.lindex = -1;
585         return formatetc;
586 }
587
588
589 class QWindowsMimeMetafile : public QWindowsMime {
590 public:
591         QWindowsMimeMetafile() {}
592
593         bool canConvertFromMime(FORMATETC const & formatetc,
594                 QMimeData const * mimedata) const
595         {
596                 return false;
597         }
598
599         bool canConvertToMime(QString const & mimetype,
600                 IDataObject * pDataObj) const
601         {
602                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
603                         return false;
604                 FORMATETC formatetc = cfFromMime(mimetype);
605                 return pDataObj->QueryGetData(&formatetc) == S_OK;
606         }
607
608         bool convertFromMime(FORMATETC const & formatetc,
609                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
610         {
611                 return false;
612         }
613
614         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
615                 QVariant::Type preferredType) const
616         {
617                 QByteArray data;
618                 if (!canConvertToMime(mimetype, pDataObj))
619                         return data;
620
621                 FORMATETC formatetc = cfFromMime(mimetype);
622                 STGMEDIUM s;
623                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
624                         return data;
625
626                 int dataSize;
627                 if (s.tymed == TYMED_ENHMF) {
628                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
629                         data.resize(dataSize);
630                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
631                                 (LPBYTE)data.data());
632                 } else if (s.tymed == TYMED_MFPICT) {
633                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
634                         data.resize(dataSize);
635                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
636                                 (LPBYTE)data.data());
637                 }
638                 data.detach();
639                 ReleaseStgMedium(&s);
640
641                 return data;
642         }
643
644
645         QVector<FORMATETC> formatsForMime(QString const & mimetype,
646                 QMimeData const * mimedata) const
647         {
648                 QVector<FORMATETC> formats;
649                 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
650                         formats += cfFromMime(mimetype);
651                 return formats;
652         }
653
654         QString mimeForFormat(FORMATETC const & formatetc) const
655         {
656                 switch (formatetc.cfFormat) {
657                 case CF_ENHMETAFILE:
658                         return emfMimeType(); 
659                 case CF_METAFILEPICT:
660                         return wmfMimeType();
661                 }
662                 return QString();
663         }
664 };
665
666 #endif // Q_WS_WIN
667
668 ////////////////////////////////////////////////////////////////////////
669 // GuiApplication::Private definition and implementation.
670 ////////////////////////////////////////////////////////////////////////
671
672 struct GuiApplication::Private
673 {
674         Private(): language_model_(0), meta_fake_bit(NoModifier),
675                 global_menubar_(0)
676         {
677         #ifdef Q_WS_WIN
678                 /// WMF Mime handler for Windows clipboard.
679                 wmf_mime_ = new QWindowsMimeMetafile();
680         #endif
681                 initKeySequences(&theTopLevelKeymap());
682         }
683
684         void initKeySequences(KeyMap * kb)
685         {
686                 keyseq = KeySequence(kb, kb);
687                 cancel_meta_seq = KeySequence(kb, kb);
688         }
689
690         ///
691         QSortFilterProxyModel * language_model_;
692         ///
693         GuiClipboard clipboard_;
694         ///
695         GuiSelection selection_;
696         ///
697         FontLoader font_loader_;
698         ///
699         ColorCache color_cache_;
700         ///
701         QTranslator qt_trans_;
702         ///
703         QHash<int, SocketNotifier *> socket_notifiers_;
704         ///
705         Menus menus_;
706         ///
707         /// The global instance
708         Toolbars toolbars_;
709
710         /// this timer is used for any regular events one wants to
711         /// perform. at present it is used to check if forked processes
712         /// are done.
713         QTimer general_timer_;
714
715         /// delayed FuncRequests
716         std::queue<FuncRequest> func_request_queue_;
717
718         ///
719         KeySequence keyseq;
720         ///
721         KeySequence cancel_meta_seq;
722         ///
723         KeyModifier meta_fake_bit;
724
725         /// Multiple views container.
726         /**
727         * Warning: This must not be a smart pointer as the destruction of the
728         * object is handled by Qt when the view is closed
729         * \sa Qt::WA_DeleteOnClose attribute.
730         */
731         QHash<int, GuiView *> views_;
732
733         /// Only used on mac.
734         GlobalMenuBar * global_menubar_;
735
736 #ifdef Q_WS_MACX
737         /// Linkback mime handler for MacOSX.
738         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
739 #endif
740
741 #ifdef Q_WS_WIN
742         /// WMF Mime handler for Windows clipboard.
743         QWindowsMimeMetafile * wmf_mime_;
744 #endif
745 };
746
747
748 GuiApplication * guiApp;
749
750 GuiApplication::~GuiApplication()
751 {
752 #ifdef Q_WS_MACX
753         closeAllLinkBackLinks();
754 #endif
755         delete d;
756 }
757
758
759 GuiApplication::GuiApplication(int & argc, char ** argv)
760         : QApplication(argc, argv), current_view_(0),
761           d(new GuiApplication::Private)
762 {
763         QString app_name = "LyX";
764         QCoreApplication::setOrganizationName(app_name);
765         QCoreApplication::setOrganizationDomain("lyx.org");
766         QCoreApplication::setApplicationName(lyx_package);
767
768         // Install translator for GUI elements.
769         installTranslator(&d->qt_trans_);
770
771         // FIXME: quitOnLastWindowClosed is true by default. We should have a
772         // lyxrc setting for this in order to let the application stay resident.
773         // But then we need some kind of dock icon, at least on Windows.
774         /*
775         if (lyxrc.quit_on_last_window_closed)
776                 setQuitOnLastWindowClosed(false);
777         */
778 #ifdef Q_WS_MACX
779         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
780         // seems to be the default case for applications like LyX.
781         setQuitOnLastWindowClosed(false);
782
783         // This allows to translate the strings that appear in the LyX menu.
784         /// A translator suitable for the entries in the LyX menu.
785         /// Only needed with Qt/Mac.
786         installTranslator(new MenuTranslator(this));
787 #endif
788         
789 #ifdef Q_WS_X11
790         // doubleClickInterval() is 400 ms on X11 which is just too long.
791         // On Windows and Mac OS X, the operating system's value is used.
792         // On Microsoft Windows, calling this function sets the double
793         // click interval for all applications. So we don't!
794         QApplication::setDoubleClickInterval(300);
795 #endif
796
797         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
798
799         // needs to be done before reading lyxrc
800         QWidget w;
801         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
802
803         guiApp = this;
804
805         // Set the cache to 5120 kilobytes which corresponds to screen size of
806         // 1280 by 1024 pixels with a color depth of 32 bits.
807         QPixmapCache::setCacheLimit(5120);
808
809         // Initialize RC Fonts
810         if (lyxrc.roman_font_name.empty())
811                 lyxrc.roman_font_name = fromqstr(romanFontName());
812
813         if (lyxrc.sans_font_name.empty())
814                 lyxrc.sans_font_name = fromqstr(sansFontName());
815
816         if (lyxrc.typewriter_font_name.empty())
817                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
818
819         d->general_timer_.setInterval(500);
820         connect(&d->general_timer_, SIGNAL(timeout()),
821                 this, SLOT(handleRegularEvents()));
822         d->general_timer_.start();
823 }
824
825
826 GuiApplication * theGuiApp()
827 {
828         return dynamic_cast<GuiApplication *>(theApp());
829 }
830
831
832 void GuiApplication::clearSession()
833 {
834         QSettings settings;
835         settings.clear();
836 }
837
838
839 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
840 {
841         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
842 }
843
844
845 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
846 {
847         FuncStatus flag;
848
849         if (cmd.action == LFUN_NOACTION) {
850                 flag.message(from_utf8(N_("Nothing to do")));
851                 flag.setEnabled(false);
852                 return flag;
853         }
854
855         if (cmd.action == LFUN_UNKNOWN_ACTION) {
856                 flag.unknown(true);
857                 flag.setEnabled(false);
858                 flag.message(from_utf8(N_("Unknown action")));
859                 return flag;
860         }
861
862         // I would really like to avoid having this switch and rather try to
863         // encode this in the function itself.
864         // -- And I'd rather let an inset decide which LFUNs it is willing
865         // to handle (Andre')
866         bool enable = true;
867         switch (cmd.action) {
868
869         // This could be used for the no-GUI version. The GUI version is handled in
870         // GuiView::getStatus(). See above.
871         /*
872         case LFUN_BUFFER_WRITE:
873         case LFUN_BUFFER_WRITE_AS: {
874                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
875                 enable = b && (b->isUnnamed() || !b->isClean());
876                 break;
877         }
878         */
879
880         case LFUN_BOOKMARK_GOTO: {
881                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
882                 enable = theSession().bookmarks().isValid(num);
883                 break;
884         }
885
886         case LFUN_BOOKMARK_CLEAR:
887                 enable = theSession().bookmarks().hasValid();
888                 break;
889
890         // this one is difficult to get right. As a half-baked
891         // solution, we consider only the first action of the sequence
892         case LFUN_COMMAND_SEQUENCE: {
893                 // argument contains ';'-terminated commands
894                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
895                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
896                 func.origin = cmd.origin;
897                 flag = getStatus(func);
898                 break;
899         }
900
901         // we want to check if at least one of these is enabled
902         case LFUN_COMMAND_ALTERNATIVES: {
903                 // argument contains ';'-terminated commands
904                 string arg = to_utf8(cmd.argument());
905                 while (!arg.empty()) {
906                         string first;
907                         arg = split(arg, first, ';');
908                         FuncRequest func(lyxaction.lookupFunc(first));
909                         func.origin = cmd.origin;
910                         flag = getStatus(func);
911                         // if this one is enabled, the whole thing is
912                         if (flag.enabled())
913                                 break;
914                 }
915                 break;
916         }
917
918         case LFUN_CALL: {
919                 FuncRequest func;
920                 string name = to_utf8(cmd.argument());
921                 if (theTopLevelCmdDef().lock(name, func)) {
922                         func.origin = cmd.origin;
923                         flag = getStatus(func);
924                         theTopLevelCmdDef().release(name);
925                 } else {
926                         // catch recursion or unknown command
927                         // definition. all operations until the
928                         // recursion or unknown command definition
929                         // occurs are performed, so set the state to
930                         // enabled
931                         enable = true;
932                 }
933                 break;
934         }
935
936         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
937         case LFUN_REPEAT:
938         case LFUN_PREFERENCES_SAVE:
939         case LFUN_BUFFER_SAVE_AS_DEFAULT:
940         case LFUN_DEBUG_LEVEL_SET:
941                 // these are handled in our dispatch()
942                 break;
943
944         case LFUN_WINDOW_CLOSE:
945                 enable = d->views_.size() > 0;
946                 break;
947
948         case LFUN_BUFFER_NEW:
949         case LFUN_BUFFER_NEW_TEMPLATE:
950         case LFUN_FILE_OPEN:
951         case LFUN_HELP_OPEN:
952         case LFUN_SCREEN_FONT_UPDATE:
953         case LFUN_SET_COLOR:
954         case LFUN_WINDOW_NEW:
955         case LFUN_LYX_QUIT:
956         case LFUN_LYXRC_APPLY:
957         case LFUN_COMMAND_PREFIX:
958         case LFUN_CANCEL:
959         case LFUN_META_PREFIX:
960         case LFUN_RECONFIGURE:
961         case LFUN_SERVER_GET_FILENAME:
962         case LFUN_SERVER_NOTIFY:
963                 enable = true;
964                 break;
965
966         default:
967                 // Does the view know something?
968                 if (!current_view_) {
969                         enable = false;
970                         break;
971                 }
972
973                 if (current_view_->getStatus(cmd, flag))
974                         break;
975
976                 // In LyX/Mac, when a dialog is open, the menus of the
977                 // application can still be accessed without giving focus to
978                 // the main window. In this case, we want to disable the menu
979                 // entries that are buffer or view-related.
980                 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
981                 /*
982                 if (cmd.origin == FuncRequest::MENU && !current_view_->hasFocus()) {
983                         enable = false;
984                         break;
985                 }
986                 */
987
988                 BufferView * bv = current_view_->currentBufferView();
989                 BufferView * doc_bv = current_view_->documentBufferView();
990                 // If we do not have a BufferView, then other functions are disabled
991                 if (!bv) {
992                         enable = false;
993                         break;
994                 }
995                 // try the BufferView
996                 bool decided = bv->getStatus(cmd, flag);
997                 if (!decided)
998                         // try the Buffer
999                         decided = bv->buffer().getStatus(cmd, flag);
1000                 if (!decided && doc_bv)
1001                         // try the Document Buffer
1002                         decided = doc_bv->buffer().getStatus(cmd, flag);
1003         }
1004
1005         if (!enable)
1006                 flag.setEnabled(false);
1007
1008         // the default error message if we disable the command
1009         if (!flag.enabled() && flag.message().empty())
1010                 flag.message(from_utf8(N_("Command disabled")));
1011
1012         return flag;
1013 }
1014
1015 /// make a post-dispatch status message
1016 static docstring makeDispatchMessage(docstring const & msg,
1017                                      FuncRequest const & cmd)
1018 {
1019         const bool verbose = (cmd.origin == FuncRequest::MENU
1020                               || cmd.origin == FuncRequest::TOOLBAR
1021                               || cmd.origin == FuncRequest::COMMANDBUFFER);
1022
1023         if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1024                 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1025                 return msg;
1026         }
1027
1028         docstring dispatch_msg = msg;
1029         if (!dispatch_msg.empty())
1030                 dispatch_msg += ' ';
1031
1032         docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1033
1034         bool argsadded = false;
1035
1036         if (!cmd.argument().empty()) {
1037                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1038                         comname += ' ' + cmd.argument();
1039                         argsadded = true;
1040                 }
1041         }
1042         docstring const shortcuts = theTopLevelKeymap().
1043                 printBindings(cmd, KeySequence::ForGui);
1044
1045         if (!shortcuts.empty())
1046                 comname += ": " + shortcuts;
1047         else if (!argsadded && !cmd.argument().empty())
1048                 comname += ' ' + cmd.argument();
1049
1050         if (!comname.empty()) {
1051                 comname = rtrim(comname);
1052                 dispatch_msg += '(' + rtrim(comname) + ')';
1053         }
1054         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1055         return dispatch_msg;
1056 }
1057
1058
1059 void GuiApplication::dispatch(FuncRequest const & cmd)
1060 {
1061         if (current_view_ && current_view_->currentBufferView())
1062                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1063
1064         DispatchResult dr;
1065         // redraw the screen at the end (first of the two drawing steps).
1066         //This is done unless explicitly requested otherwise
1067         dr.update(Update::FitCursor);
1068         dispatch(cmd, dr);
1069
1070         if (!current_view_)
1071                 return;
1072
1073         BufferView * bv = current_view_->currentBufferView();
1074         if (bv) {
1075                 // BufferView::update() updates the ViewMetricsInfo and
1076                 // also initializes the position cache for all insets in
1077                 // (at least partially) visible top-level paragraphs.
1078                 // We will redraw the screen only if needed.
1079                 bv->processUpdateFlags(dr.update());
1080
1081                 // Do we have a selection?
1082                 theSelection().haveSelection(bv->cursor().selection());
1083
1084                 // update gui
1085                 current_view_->restartCursor();
1086         }
1087         // Some messages may already be translated, so we cannot use _()
1088         current_view_->message(makeDispatchMessage(
1089                         translateIfPossible(dr.message()), cmd));
1090 }
1091
1092
1093 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
1094 {
1095         GuiView * lv = current_view_;
1096         LASSERT(lv, /**/);
1097         if (!theSession().bookmarks().isValid(idx))
1098                 return;
1099         BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
1100         LASSERT(!bm.filename.empty(), /**/);
1101         string const file = bm.filename.absFilename();
1102         // if the file is not opened, open it.
1103         if (!theBufferList().exists(bm.filename)) {
1104                 if (openFile)
1105                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1106                 else
1107                         return;
1108         }
1109         // open may fail, so we need to test it again
1110         if (!theBufferList().exists(bm.filename))
1111                 return;
1112
1113         // bm can be changed when saving
1114         BookmarksSection::Bookmark tmp = bm;
1115
1116         // Special case idx == 0 used for back-from-back jump navigation
1117         if (idx == 0)
1118                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1119
1120         // if the current buffer is not that one, switch to it.
1121         if (!lv->documentBufferView()
1122                 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
1123                 if (!switchToBuffer)
1124                         return;
1125                 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1126         }
1127
1128         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1129         if (!lv->documentBufferView()->moveToPosition(
1130                 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1131                 return;
1132
1133         // bm changed
1134         if (idx == 0)
1135                 return;
1136
1137         // Cursor jump succeeded!
1138         Cursor const & cur = lv->documentBufferView()->cursor();
1139         pit_type new_pit = cur.pit();
1140         pos_type new_pos = cur.pos();
1141         int new_id = cur.paragraph().id();
1142
1143         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1144         // see http://www.lyx.org/trac/ticket/3092
1145         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1146                 || bm.top_id != new_id) {
1147                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1148                         new_pit, new_pos, new_id);
1149         }
1150 }
1151
1152 // This function runs "configure" and then rereads lyx.defaults to
1153 // reconfigure the automatic settings.
1154 static void reconfigure(GuiView * lv, string const & option)
1155 {
1156         // emit message signal.
1157         if (lv)
1158                 lv->message(_("Running configure..."));
1159
1160         // Run configure in user lyx directory
1161         PathChanger p(package().user_support());
1162         string configure_command = package().configure_command();
1163         configure_command += option;
1164         Systemcall one;
1165         int ret = one.startscript(Systemcall::Wait, configure_command);
1166         p.pop();
1167         // emit message signal.
1168         if (lv)
1169                 lv->message(_("Reloading configuration..."));
1170         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1171         // Re-read packages.lst
1172         LaTeXFeatures::getAvailable();
1173
1174         if (ret)
1175                 Alert::information(_("System reconfiguration failed"),
1176                            _("The system reconfiguration has failed.\n"
1177                                   "Default textclass is used but LyX may "
1178                                   "not be able to work properly.\n"
1179                                   "Please reconfigure again if needed."));
1180         else
1181
1182                 Alert::information(_("System reconfigured"),
1183                            _("The system has been reconfigured.\n"
1184                              "You need to restart LyX to make use of any\n"
1185                              "updated document class specifications."));
1186 }
1187
1188
1189
1190 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1191 {
1192         string const argument = to_utf8(cmd.argument());
1193         FuncCode const action = cmd.action;
1194
1195         LYXERR(Debug::ACTION, "cmd: " << cmd);
1196
1197         // we have not done anything wrong yet.
1198         dr.setError(false);
1199
1200         FuncStatus const flag = getStatus(cmd);
1201         if (!flag.enabled()) {
1202                 // We cannot use this function here
1203                 LYXERR(Debug::ACTION, "action "
1204                        << lyxaction.getActionName(action)
1205                        << " [" << action << "] is disabled at this location");
1206                 if (current_view_)
1207                         current_view_->restartCursor();
1208                 dr.setMessage(flag.message());
1209                 dr.setError(true);
1210                 dr.dispatched(false);
1211                 dr.update(Update::None);
1212                 return;
1213         };
1214
1215         // Assumes that the action will be dispatched.
1216         dr.dispatched(true);
1217
1218         switch (cmd.action) {
1219
1220         case LFUN_WINDOW_NEW:
1221                 createView(toqstr(cmd.argument()));
1222                 break;
1223
1224         case LFUN_WINDOW_CLOSE:
1225                 // update bookmark pit of the current buffer before window close
1226                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1227                         gotoBookmark(i+1, false, false);
1228                 // clear the last opened list, because
1229                 // maybe this will end the session
1230                 theSession().lastOpened().clear();
1231                 current_view_->close();
1232                 break;
1233
1234         case LFUN_LYX_QUIT:
1235                 // quitting is triggered by the gui code
1236                 // (leaving the event loop).
1237                 if (current_view_)
1238                         current_view_->message(from_utf8(N_("Exiting.")));
1239                 if (closeAllViews())
1240                         quit();
1241                 break;
1242
1243         case LFUN_SCREEN_FONT_UPDATE: {
1244                 // handle the screen font changes.
1245                 d->font_loader_.update();
1246                 // Backup current_view_
1247                 GuiView * view = current_view_;
1248                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1249                 // to skip the refresh.
1250                 current_view_ = 0;
1251                 theBufferList().changed(false);
1252                 // Restore current_view_
1253                 current_view_ = view;
1254                 break;
1255         }
1256
1257         case LFUN_BUFFER_NEW:
1258                 if (d->views_.empty()
1259                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1260                         createView(QString(), false); // keep hidden
1261                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1262                         current_view_->show();
1263                         setActiveWindow(current_view_);
1264                 } else {
1265                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1266                 }
1267                 break;
1268
1269         case LFUN_BUFFER_NEW_TEMPLATE:
1270                 if (d->views_.empty()
1271                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1272                         createView();
1273                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1274                         if (!current_view_->documentBufferView())
1275                                 current_view_->close();
1276                 } else {
1277                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1278                 }
1279                 break;
1280
1281         case LFUN_FILE_OPEN:
1282                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1283                 if (d->views_.empty()
1284                         || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1285                         string const fname = to_utf8(cmd.argument());
1286                         // We want the ui session to be saved per document and not per
1287                         // window number. The filename crc is a good enough identifier.
1288                         boost::crc_32_type crc;
1289                         crc = for_each(fname.begin(), fname.end(), crc);
1290                         createView(crc.checksum());
1291                         current_view_->openDocument(fname);
1292                         if (current_view_ && !current_view_->documentBufferView())
1293                                 current_view_->close();
1294                 } else
1295                         current_view_->openDocument(to_utf8(cmd.argument()));
1296                 break;
1297
1298         case LFUN_HELP_OPEN: {
1299                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1300                 if (current_view_ == 0)
1301                         createView();
1302                 string const arg = to_utf8(cmd.argument());
1303                 if (arg.empty()) {
1304                         current_view_->message(_("Missing argument"));
1305                         break;
1306                 }
1307                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1308                 if (fname.empty())
1309                         fname = i18nLibFileSearch("examples", arg, "lyx");
1310
1311                 if (fname.empty()) {
1312                         lyxerr << "LyX: unable to find documentation file `"
1313                                << arg << "'. Bad installation?" << endl;
1314                         break;
1315                 }
1316                 current_view_->message(bformat(_("Opening help file %1$s..."),
1317                                                makeDisplayPath(fname.absFilename())));
1318                 Buffer * buf = current_view_->loadDocument(fname, false);
1319                 if (buf) {
1320                         current_view_->setBuffer(buf);
1321 #ifndef DEVEL_VERSION
1322                         buf->setReadonly(true);
1323 #endif
1324                         buf->updateBuffer();
1325                         buf->errors("Parse");
1326                 }
1327                 break;
1328         }
1329
1330         case LFUN_SET_COLOR: {
1331                 string lyx_name;
1332                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1333                 if (lyx_name.empty() || x11_name.empty()) {
1334                         current_view_->message(
1335                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1336                         break;
1337                 }
1338
1339                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1340                 bool const graphicsbg_changed = 
1341                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1342                 if (graphicsbg_changed) {
1343                         // FIXME: The graphics cache no longer has a changeDisplay method.
1344 #if 0
1345                         graphics::GCache::get().changeDisplay(true);
1346 #endif
1347                 }
1348
1349                 if (!lcolor.setColor(lyx_name, x11_name)) {
1350                         current_view_->message(
1351                                 bformat(_("Set-color \"%1$s\" failed "
1352                                         "- color is undefined or "
1353                                         "may not be redefined"),
1354                                         from_utf8(lyx_name)));
1355                         break;
1356                 }
1357                 // Make sure we don't keep old colors in cache.
1358                 d->color_cache_.clear();
1359                 break;
1360         }
1361
1362         case LFUN_LYXRC_APPLY: {
1363                 // reset active key sequences, since the bindings
1364                 // are updated (bug 6064)
1365                 d->keyseq.reset();
1366                 LyXRC const lyxrc_orig = lyxrc;
1367
1368                 istringstream ss(to_utf8(cmd.argument()));
1369                 bool const success = lyxrc.read(ss) == 0;
1370
1371                 if (!success) {
1372                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1373                                         << "Unable to read lyxrc data"
1374                                         << endl;
1375                         break;
1376                 }
1377
1378                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1379                 setSpellChecker();
1380                 resetGui();
1381
1382                 break;
1383         }
1384
1385         case LFUN_COMMAND_PREFIX:
1386                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1387                 break;
1388
1389         case LFUN_CANCEL: {
1390                 d->keyseq.reset();
1391                 d->meta_fake_bit = NoModifier;
1392                 GuiView * gv = currentView();
1393                 if (gv && gv->currentBufferView())
1394                         // cancel any selection
1395                         lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1396                 dr.setMessage(from_ascii(N_("Cancel")));
1397                 break;
1398         }
1399         case LFUN_META_PREFIX:
1400                 d->meta_fake_bit = AltModifier;
1401                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1402                 break;
1403
1404         // --- Menus -----------------------------------------------
1405         case LFUN_RECONFIGURE:
1406                 // argument is any additional parameter to the configure.py command
1407                 reconfigure(currentView(), to_utf8(cmd.argument()));
1408                 break;
1409
1410         // --- lyxserver commands ----------------------------
1411         case LFUN_SERVER_GET_FILENAME: {
1412                 GuiView * lv = currentView();
1413                 LASSERT(lv && lv->documentBufferView(), return);
1414                 docstring const fname = from_utf8(
1415                                 lv->documentBufferView()->buffer().absFileName());
1416                 dr.setMessage(fname);
1417                 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1418                 break;
1419         }
1420         case LFUN_SERVER_NOTIFY: {
1421                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1422                 dr.setMessage(dispatch_buffer);
1423                 theServer().notifyClient(to_utf8(dispatch_buffer));
1424                 break;
1425         }
1426
1427         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1428                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1429                 break;
1430
1431         case LFUN_REPEAT: {
1432                 // repeat command
1433                 string countstr;
1434                 string rest = split(argument, countstr, ' ');
1435                 istringstream is(countstr);
1436                 int count = 0;
1437                 is >> count;
1438                 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1439                 for (int i = 0; i < count; ++i)
1440                         dispatch(lyxaction.lookupFunc(rest));
1441                 break;
1442         }
1443
1444         case LFUN_COMMAND_SEQUENCE: {
1445                 // argument contains ';'-terminated commands
1446                 string arg = argument;
1447                 // FIXME: this LFUN should also work without any view.
1448                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1449                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1450                 if (buffer)
1451                         buffer->undo().beginUndoGroup();
1452                 while (!arg.empty()) {
1453                         string first;
1454                         arg = split(arg, first, ';');
1455                         FuncRequest func(lyxaction.lookupFunc(first));
1456                         func.origin = cmd.origin;
1457                         dispatch(func);
1458                 }
1459                 // the buffer may have been closed by one action
1460                 if (theBufferList().isLoaded(buffer))
1461                         buffer->undo().endUndoGroup();
1462                 break;
1463         }
1464
1465         case LFUN_COMMAND_ALTERNATIVES: {
1466                 // argument contains ';'-terminated commands
1467                 string arg = argument;
1468                 while (!arg.empty()) {
1469                         string first;
1470                         arg = split(arg, first, ';');
1471                         FuncRequest func(lyxaction.lookupFunc(first));
1472                         func.origin = cmd.origin;
1473                         FuncStatus stat = getStatus(func);
1474                         if (stat.enabled()) {
1475                                 dispatch(func);
1476                                 break;
1477                         }
1478                 }
1479                 break;
1480         }
1481
1482         case LFUN_CALL: {
1483                 FuncRequest func;
1484                 if (theTopLevelCmdDef().lock(argument, func)) {
1485                         func.origin = cmd.origin;
1486                         dispatch(func);
1487                         theTopLevelCmdDef().release(argument);
1488                 } else {
1489                         if (func.action == LFUN_UNKNOWN_ACTION) {
1490                                 // unknown command definition
1491                                 lyxerr << "Warning: unknown command definition `"
1492                                                 << argument << "'"
1493                                                 << endl;
1494                         } else {
1495                                 // recursion detected
1496                                 lyxerr << "Warning: Recursion in the command definition `"
1497                                                 << argument << "' detected"
1498                                                 << endl;
1499                         }
1500                 }
1501                 break;
1502         }
1503
1504         case LFUN_PREFERENCES_SAVE:
1505                 lyxrc.write(support::makeAbsPath("preferences",
1506                         package().user_support().absFilename()), false);
1507                 break;
1508
1509         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1510                 string const fname = addName(addPath(package().user_support().absFilename(),
1511                         "templates/"), "defaults.lyx");
1512                 Buffer defaults(fname);
1513
1514                 istringstream ss(argument);
1515                 Lexer lex;
1516                 lex.setStream(ss);
1517                 int const unknown_tokens = defaults.readHeader(lex);
1518
1519                 if (unknown_tokens != 0) {
1520                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1521                                << unknown_tokens << " unknown token"
1522                                << (unknown_tokens == 1 ? "" : "s")
1523                                << endl;
1524                 }
1525
1526                 if (defaults.writeFile(FileName(defaults.absFileName())))
1527                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1528                                               makeDisplayPath(fname)));
1529                 else {
1530                         dr.setError(true);
1531                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1532                 }
1533                 break;
1534         }
1535
1536         case LFUN_BOOKMARK_GOTO:
1537                 // go to bookmark, open unopened file and switch to buffer if necessary
1538                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1539                 dr.update(Update::FitCursor);
1540                 break;
1541
1542         case LFUN_BOOKMARK_CLEAR:
1543                 theSession().bookmarks().clear();
1544                 break;
1545
1546         case LFUN_DEBUG_LEVEL_SET:
1547                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1548                 break;
1549
1550         default:
1551                 // Notify the caller that the action has not been dispatched.
1552                 dr.dispatched(false);
1553                 break;
1554         }
1555
1556         // The action has been dispatched in this method, nothing more to do.
1557         if (dr.dispatched())
1558                 return;
1559
1560         GuiView * lv = current_view_;
1561
1562         // Everything below is only for active window
1563         if (lv == 0)
1564                 return;
1565
1566         // Let the current GuiView dispatch its own actions.
1567         lv->dispatch(cmd, dr);
1568         if (dr.dispatched() && lv )
1569                 return;
1570
1571         BufferView * bv = lv->currentBufferView();
1572         LASSERT(bv, /**/);
1573
1574         // Let the current BufferView dispatch its own actions.
1575         bv->dispatch(cmd, dr);
1576         if (dr.dispatched())
1577                 return;
1578
1579         BufferView * doc_bv = lv->documentBufferView();
1580         // Try with the document BufferView dispatch if any.
1581         if (doc_bv) {
1582                 doc_bv->dispatch(cmd, dr);
1583                 if (dr.dispatched())
1584                         return;
1585         }
1586
1587         // OK, so try the current Buffer itself...
1588         bv->buffer().dispatch(cmd, dr);
1589         if (dr.dispatched())
1590                 return;
1591
1592         // and with the document Buffer.
1593         if (doc_bv) {
1594                 doc_bv->buffer().dispatch(cmd, dr);
1595                 if (dr.dispatched())
1596                         return;
1597         }
1598
1599         // Let the current Cursor dispatch its own actions.
1600         Cursor old = bv->cursor();
1601         bv->cursor().dispatch(cmd);
1602
1603         // notify insets we just left
1604         if (bv->cursor() != old) {
1605                 old.fixIfBroken();
1606                 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1607                 if (badcursor)
1608                         bv->cursor().fixIfBroken();
1609         }
1610
1611         // update completion. We do it here and not in
1612         // processKeySym to avoid another redraw just for a
1613         // changed inline completion
1614         if (cmd.origin == FuncRequest::KEYBOARD) {
1615                 if (cmd.action == LFUN_SELF_INSERT
1616                     || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1617                         lv->updateCompletion(bv->cursor(), true, true);
1618                 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
1619                         lv->updateCompletion(bv->cursor(), false, true);
1620                 else
1621                         lv->updateCompletion(bv->cursor(), false, false);
1622         }
1623
1624         dr = bv->cursor().result();
1625
1626         // if we executed a mutating lfun, mark the buffer as dirty
1627         Buffer * doc_buffer = (lv && lv->documentBufferView())
1628                       ? &(lv->documentBufferView()->buffer()) : 0;
1629         if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1630                 && flag.enabled()
1631                 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1632                 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1633                 lv->currentBufferView()->buffer().markDirty();
1634 }
1635
1636
1637 docstring GuiApplication::viewStatusMessage()
1638 {
1639         // When meta-fake key is pressed, show the key sequence so far + "M-".
1640         if (d->meta_fake_bit != NoModifier)
1641                 return d->keyseq.print(KeySequence::ForGui) + "M-";
1642
1643         // Else, when a non-complete key sequence is pressed,
1644         // show the available options.
1645         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1646                 return d->keyseq.printOptions(true);
1647
1648         return docstring();
1649 }
1650
1651
1652 void GuiApplication::handleKeyFunc(FuncCode action)
1653 {
1654         char_type c = 0;
1655
1656         if (d->keyseq.length())
1657                 c = 0;
1658         GuiView * gv = currentView();
1659         LASSERT(gv && gv->currentBufferView(), return);
1660         BufferView * bv = gv->currentBufferView();
1661         bv->getIntl().getTransManager().deadkey(
1662                 c, get_accent(action).accent, bv->cursor().innerText(),
1663                 bv->cursor());
1664         // Need to clear, in case the minibuffer calls these
1665         // actions
1666         d->keyseq.clear();
1667         // copied verbatim from do_accent_char
1668         bv->cursor().resetAnchor();
1669         bv->processUpdateFlags(Update::FitCursor);
1670 }
1671
1672
1673 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1674 {
1675         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1676
1677         GuiView * lv = currentView();
1678
1679         // Do nothing if we have nothing (JMarc)
1680         if (!keysym.isOK()) {
1681                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1682                 lv->restartCursor();
1683                 return;
1684         }
1685
1686         if (keysym.isModifier()) {
1687                 LYXERR(Debug::KEY, "isModifier true");
1688                 if (lv)
1689                         lv->restartCursor();
1690                 return;
1691         }
1692
1693         char_type encoded_last_key = keysym.getUCSEncoded();
1694
1695         // Do a one-deep top-level lookup for
1696         // cancel and meta-fake keys. RVDK_PATCH_5
1697         d->cancel_meta_seq.reset();
1698
1699         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1700         LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
1701
1702         // When not cancel or meta-fake, do the normal lookup.
1703         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1704         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1705         if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
1706                 // remove Caps Lock and Mod2 as a modifiers
1707                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1708                 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
1709         }
1710
1711         // Dont remove this unless you know what you are doing.
1712         d->meta_fake_bit = NoModifier;
1713
1714         // Can this happen now ?
1715         if (func.action == LFUN_NOACTION)
1716                 func = FuncRequest(LFUN_COMMAND_PREFIX);
1717
1718         LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
1719                 << d->keyseq.print(KeySequence::Portable) << ']');
1720
1721         // already here we know if it any point in going further
1722         // why not return already here if action == -1 and
1723         // num_bytes == 0? (Lgb)
1724
1725         if (d->keyseq.length() > 1)
1726                 lv->message(d->keyseq.print(KeySequence::ForGui));
1727
1728
1729         // Maybe user can only reach the key via holding down shift.
1730         // Let's see. But only if shift is the only modifier
1731         if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1732                 LYXERR(Debug::KEY, "Trying without shift");
1733                 func = d->keyseq.addkey(keysym, NoModifier);
1734                 LYXERR(Debug::KEY, "Action now " << func.action);
1735         }
1736
1737         if (func.action == LFUN_UNKNOWN_ACTION) {
1738                 // Hmm, we didn't match any of the keysequences. See
1739                 // if it's normal insertable text not already covered
1740                 // by a binding
1741                 if (keysym.isText() && d->keyseq.length() == 1) {
1742                         LYXERR(Debug::KEY, "isText() is true, inserting.");
1743                         func = FuncRequest(LFUN_SELF_INSERT,
1744                                            FuncRequest::KEYBOARD);
1745                 } else {
1746                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1747                         lv->message(_("Unknown function."));
1748                         lv->restartCursor();
1749                         return;
1750                 }
1751         }
1752
1753         if (func.action == LFUN_SELF_INSERT) {
1754                 if (encoded_last_key != 0) {
1755                         docstring const arg(1, encoded_last_key);
1756                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
1757                                              FuncRequest::KEYBOARD));
1758                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1759                 }
1760         } else {
1761                 lyx::dispatch(func);
1762                 if (!lv)
1763                         return;
1764         }
1765 }
1766
1767
1768 void GuiApplication::dispatchDelayed(FuncRequest const & func)
1769 {
1770         d->func_request_queue_.push(func);
1771         QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
1772 }
1773
1774
1775 void GuiApplication::resetGui()
1776 {
1777         // Set the language defined by the user.
1778         setGuiLanguage();
1779
1780         // Read menus
1781         if (!readUIFile(toqstr(lyxrc.ui_file)))
1782                 // Gives some error box here.
1783                 return;
1784
1785         if (d->global_menubar_)
1786                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1787
1788         QHash<int, GuiView *>::iterator it;
1789         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1790                 GuiView * gv = *it;
1791                 setCurrentView(gv);
1792                 gv->setLayoutDirection(layoutDirection());
1793                 gv->resetDialogs();
1794         }
1795
1796         lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1797 }
1798
1799
1800 void GuiApplication::createView(int view_id)
1801 {
1802         createView(QString(), true, view_id);
1803 }
1804
1805
1806 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1807         int view_id)
1808 {
1809         // release the keyboard which might have been grabed by the global
1810         // menubar on Mac to catch shortcuts even without any GuiView.
1811         if (d->global_menubar_)
1812                 d->global_menubar_->releaseKeyboard();
1813
1814         // create new view
1815         int id = view_id;
1816         while (d->views_.find(id) != d->views_.end())
1817                 id++;
1818
1819         LYXERR(Debug::GUI, "About to create new window with ID " << id);
1820         GuiView * view = new GuiView(id);
1821         // register view
1822         d->views_[id] = view;
1823
1824         if (autoShow) {
1825                 view->show();
1826                 setActiveWindow(view);
1827         }
1828
1829         if (!geometry_arg.isEmpty()) {
1830 #ifdef Q_WS_WIN
1831                 int x, y;
1832                 int w, h;
1833                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1834                 re.indexIn(geometry_arg);
1835                 w = re.cap(1).toInt();
1836                 h = re.cap(2).toInt();
1837                 x = re.cap(3).toInt();
1838                 y = re.cap(4).toInt();
1839                 view->setGeometry(x, y, w, h);
1840 #endif
1841         }
1842         view->setFocus();
1843 }
1844
1845
1846 Clipboard & GuiApplication::clipboard()
1847 {
1848         return d->clipboard_;
1849 }
1850
1851
1852 Selection & GuiApplication::selection()
1853 {
1854         return d->selection_;
1855 }
1856
1857
1858 FontLoader & GuiApplication::fontLoader() 
1859 {
1860         return d->font_loader_;
1861 }
1862
1863
1864 Toolbars const & GuiApplication::toolbars() const 
1865 {
1866         return d->toolbars_;
1867 }
1868
1869
1870 Toolbars & GuiApplication::toolbars()
1871 {
1872         return d->toolbars_; 
1873 }
1874
1875
1876 Menus const & GuiApplication::menus() const 
1877 {
1878         return d->menus_;
1879 }
1880
1881
1882 Menus & GuiApplication::menus()
1883 {
1884         return d->menus_; 
1885 }
1886
1887
1888 QList<int> GuiApplication::viewIds() const
1889 {
1890         return d->views_.keys();
1891 }
1892
1893
1894 ColorCache & GuiApplication::colorCache()
1895 {
1896         return d->color_cache_;
1897 }
1898
1899
1900 int GuiApplication::exec()
1901 {
1902         // asynchronously handle batch commands. This event will be in
1903         // the event queue in front of other asynchronous events. Hence,
1904         // we can assume in the latter that the gui is setup already.
1905         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1906
1907         return QApplication::exec();
1908 }
1909
1910
1911 void GuiApplication::exit(int status)
1912 {
1913         QApplication::exit(status);
1914 }
1915
1916
1917 void GuiApplication::setGuiLanguage()
1918 {
1919         // Set the language defined by the user.
1920         setRcGuiLanguage();
1921
1922         QString const default_language = toqstr(Messages::defaultLanguage());
1923         LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1924         QLocale const default_locale(default_language);
1925         QLocale::setDefault(default_locale);
1926
1927         // install translation file for Qt built-in dialogs
1928         QString const language_name = QString("qt_") + default_locale.name();
1929
1930         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1931         // Short-named translator can be loaded from a long name, but not the
1932         // opposite. Therefore, long name should be used without truncation.
1933         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1934         if (!d->qt_trans_.load(language_name,
1935                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1936                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1937                         << language_name);
1938         } else {
1939                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1940                         << language_name);
1941         }
1942
1943         switch (default_locale.language()) {
1944         case QLocale::Arabic :
1945         case QLocale::Hebrew :
1946         case QLocale::Persian :
1947         case QLocale::Urdu :
1948                 setLayoutDirection(Qt::RightToLeft);
1949                 break;
1950         default:
1951                 setLayoutDirection(Qt::LeftToRight);
1952         }
1953 }
1954
1955
1956 void GuiApplication::processFuncRequestQueue()
1957 {
1958         while (!d->func_request_queue_.empty()) {
1959                 lyx::dispatch(d->func_request_queue_.back());
1960                 d->func_request_queue_.pop();
1961         }
1962 }
1963
1964
1965 void GuiApplication::execBatchCommands()
1966 {
1967         setGuiLanguage();
1968
1969         // Read menus
1970         if (!readUIFile(toqstr(lyxrc.ui_file)))
1971                 // Gives some error box here.
1972                 return;
1973
1974 #ifdef Q_WS_MACX
1975         // Create the global default menubar which is shown for the dialogs
1976         // and if no GuiView is visible.
1977         // This must be done after the session was recovered to know the "last files".
1978         d->global_menubar_ = new GlobalMenuBar();
1979         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1980 #endif
1981
1982         lyx::execBatchCommands();
1983 }
1984
1985
1986 QAbstractItemModel * GuiApplication::languageModel()
1987 {
1988         if (d->language_model_)
1989                 return d->language_model_;
1990
1991         QStandardItemModel * lang_model = new QStandardItemModel(this);
1992         lang_model->insertColumns(0, 3);
1993         int current_row;
1994         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
1995         QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
1996         Languages::const_iterator it = lyx::languages.begin();
1997         Languages::const_iterator end = lyx::languages.end();
1998         for (; it != end; ++it) {
1999                 current_row = lang_model->rowCount();
2000                 lang_model->insertRows(current_row, 1);
2001                 QModelIndex pl_item = lang_model->index(current_row, 0);
2002                 QModelIndex sp_item = lang_model->index(current_row, 1);
2003                 QModelIndex th_item = lang_model->index(current_row, 2);
2004                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2005                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2006                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2007                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2008                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2009                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2010                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2011                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2012                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2013                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2014         }
2015         d->language_model_ = new QSortFilterProxyModel(this);
2016         d->language_model_->setSourceModel(lang_model);
2017 #if QT_VERSION >= 0x040300
2018         d->language_model_->setSortLocaleAware(true);
2019 #endif
2020         return d->language_model_;
2021 }
2022
2023
2024 void GuiApplication::restoreGuiSession()
2025 {
2026         if (!lyxrc.load_session)
2027                 return;
2028
2029         Session & session = theSession();
2030         LastOpenedSection::LastOpened const & lastopened = 
2031                 session.lastOpened().getfiles();
2032
2033         FileName active_file;
2034         // do not add to the lastfile list since these files are restored from
2035         // last session, and should be already there (regular files), or should
2036         // not be added at all (help files).
2037         for (size_t i = 0; i < lastopened.size(); ++i) {
2038                 FileName const & file_name = lastopened[i].file_name;
2039                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2040                           && current_view_->documentBufferView() != 0)) {
2041                         boost::crc_32_type crc;
2042                         string const & fname = file_name.absFilename();
2043                         crc = for_each(fname.begin(), fname.end(), crc);
2044                         createView(crc.checksum());
2045                 }
2046                 current_view_->loadDocument(file_name, false);
2047
2048                 if (lastopened[i].active)
2049                         active_file = file_name;
2050         }
2051
2052         // Restore last active buffer
2053         Buffer * buffer = theBufferList().getBuffer(active_file);
2054         if (buffer)
2055                 current_view_->setBuffer(buffer);
2056
2057         // clear this list to save a few bytes of RAM
2058         session.lastOpened().clear();
2059 }
2060
2061
2062 QString const GuiApplication::romanFontName()
2063 {
2064         QFont font;
2065         font.setKerning(false);
2066         font.setStyleHint(QFont::Serif);
2067         font.setFamily("serif");
2068
2069         return QFontInfo(font).family();
2070 }
2071
2072
2073 QString const GuiApplication::sansFontName()
2074 {
2075         QFont font;
2076         font.setKerning(false);
2077         font.setStyleHint(QFont::SansSerif);
2078         font.setFamily("sans");
2079
2080         return QFontInfo(font).family();
2081 }
2082
2083
2084 QString const GuiApplication::typewriterFontName()
2085 {
2086         QFont font;
2087         font.setKerning(false);
2088         font.setStyleHint(QFont::TypeWriter);
2089         font.setFamily("monospace");
2090
2091         return QFontInfo(font).family();
2092 }
2093
2094
2095 void GuiApplication::handleRegularEvents()
2096 {
2097         ForkedCallsController::handleCompletedProcesses();
2098 }
2099
2100
2101 bool GuiApplication::event(QEvent * e)
2102 {
2103         switch(e->type()) {
2104         case QEvent::FileOpen: {
2105                 // Open a file; this happens only on Mac OS X for now.
2106                 //
2107                 // We do this asynchronously because on startup the batch
2108                 // commands are not executed here yet and the gui is not ready
2109                 // therefore.
2110                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2111                 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
2112                 e->accept();
2113                 return true;
2114         }
2115         default:
2116                 return QApplication::event(e);
2117         }
2118 }
2119
2120
2121 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2122 {
2123         try {
2124                 return QApplication::notify(receiver, event);
2125         }
2126         catch (ExceptionMessage const & e) {
2127                 switch(e.type_) { 
2128                 case ErrorException:
2129                         emergencyCleanup();
2130                         setQuitOnLastWindowClosed(false);
2131                         closeAllViews();
2132                         Alert::error(e.title_, e.details_);
2133 #ifndef NDEBUG
2134                         // Properly crash in debug mode in order to get a useful backtrace.
2135                         abort();
2136 #endif
2137                         // In release mode, try to exit gracefully.
2138                         this->exit(1);
2139
2140                 case BufferException: {
2141                         if (!current_view_->documentBufferView())
2142                                 return false;
2143                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2144                         docstring details = e.details_ + '\n';
2145                         details += buf->emergencyWrite();
2146                         theBufferList().release(buf);
2147                         details += "\n" + _("The current document was closed.");
2148                         Alert::error(e.title_, details);
2149                         return false;
2150                 }
2151                 case WarningException:
2152                         Alert::warning(e.title_, e.details_);
2153                         return false;
2154                 }
2155         }
2156         catch (exception const & e) {
2157                 docstring s = _("LyX has caught an exception, it will now "
2158                         "attempt to save all unsaved documents and exit."
2159                         "\n\nException: ");
2160                 s += from_ascii(e.what());
2161                 Alert::error(_("Software exception Detected"), s);
2162                 lyx_exit(1);
2163         }
2164         catch (...) {
2165                 docstring s = _("LyX has caught some really weird exception, it will "
2166                         "now attempt to save all unsaved documents and exit.");
2167                 Alert::error(_("Software exception Detected"), s);
2168                 lyx_exit(1);
2169         }
2170
2171         return false;
2172 }
2173
2174
2175 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2176 {
2177         QColor const & qcol = d->color_cache_.get(col);
2178         if (!qcol.isValid()) {
2179                 rgbcol.r = 0;
2180                 rgbcol.g = 0;
2181                 rgbcol.b = 0;
2182                 return false;
2183         }
2184         rgbcol.r = qcol.red();
2185         rgbcol.g = qcol.green();
2186         rgbcol.b = qcol.blue();
2187         return true;
2188 }
2189
2190
2191 string const GuiApplication::hexName(ColorCode col)
2192 {
2193         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2194 }
2195
2196
2197 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2198 {
2199         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2200         d->socket_notifiers_[fd] = sn;
2201         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2202 }
2203
2204
2205 void GuiApplication::socketDataReceived(int fd)
2206 {
2207         d->socket_notifiers_[fd]->func_();
2208 }
2209
2210
2211 void GuiApplication::unregisterSocketCallback(int fd)
2212 {
2213         d->socket_notifiers_.take(fd)->setEnabled(false);
2214 }
2215
2216
2217 void GuiApplication::commitData(QSessionManager & sm)
2218 {
2219         /// The implementation is required to avoid an application exit
2220         /// when session state save is triggered by session manager.
2221         /// The default implementation sends a close event to all
2222         /// visible top level widgets when session managment allows
2223         /// interaction.
2224         /// We are changing that to close all wiew one by one.
2225         /// FIXME: verify if the default implementation is enough now.
2226         if (sm.allowsInteraction() && !closeAllViews())
2227                 sm.cancel();
2228 }
2229
2230
2231 void GuiApplication::unregisterView(GuiView * gv)
2232 {
2233         LASSERT(d->views_[gv->id()] == gv, /**/);
2234         d->views_.remove(gv->id());
2235         if (current_view_ == gv)
2236                 current_view_ = 0;
2237 }
2238
2239
2240 bool GuiApplication::closeAllViews()
2241 {
2242         if (d->views_.empty())
2243                 return true;
2244
2245         // When a view/window was closed before without quitting LyX, there
2246         // are already entries in the lastOpened list.
2247         theSession().lastOpened().clear();
2248
2249         QList<GuiView *> views = d->views_.values();
2250         foreach (GuiView * view, views) {
2251                 if (!view->close())
2252                         return false;
2253         }
2254
2255         d->views_.clear();
2256         return true;
2257 }
2258
2259
2260 GuiView & GuiApplication::view(int id) const
2261 {
2262         LASSERT(d->views_.contains(id), /**/);
2263         return *d->views_.value(id);
2264 }
2265
2266
2267 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2268 {
2269         QList<GuiView *> views = d->views_.values();
2270         foreach (GuiView * view, views)
2271                 view->hideDialog(name, inset);
2272 }
2273
2274
2275 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2276 {
2277         Buffer const * buffer_ = 0;
2278         QHash<int, GuiView *>::iterator end = d->views_.end();
2279         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2280                 if (Buffer const * ptr = (*it)->updateInset(inset))
2281                         buffer_ = ptr;
2282         }
2283         return buffer_;
2284 }
2285
2286
2287 bool GuiApplication::searchMenu(FuncRequest const & func,
2288         docstring_list & names) const
2289 {
2290         return d->menus_.searchMenu(func, names);
2291 }
2292
2293
2294 bool GuiApplication::readUIFile(QString const & name, bool include)
2295 {
2296         LYXERR(Debug::INIT, "About to read " << name << "...");
2297
2298         FileName ui_path;
2299         if (include) {
2300                 ui_path = libFileSearch("ui", name, "inc");
2301                 if (ui_path.empty())
2302                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2303         } else {
2304                 ui_path = libFileSearch("ui", name, "ui");
2305         }
2306
2307         if (ui_path.empty()) {
2308                 static const QString defaultUIFile = "default";
2309                 LYXERR(Debug::INIT, "Could not find " << name);
2310                 if (include) {
2311                         Alert::warning(_("Could not find UI definition file"),
2312                                 bformat(_("Error while reading the included file\n%1$s\n"
2313                                         "Please check your installation."), qstring_to_ucs4(name)));
2314                         return false;
2315                 }
2316                 if (name == defaultUIFile) {
2317                         LYXERR(Debug::INIT, "Could not find default UI file!!");
2318                         Alert::warning(_("Could not find default UI file"),
2319                                 _("LyX could not find the default UI file!\n"
2320                                   "Please check your installation."));
2321                         return false;
2322                 }
2323                 Alert::warning(_("Could not find UI definition file"),
2324                 bformat(_("Error while reading the configuration file\n%1$s\n"
2325                         "Falling back to default.\n"
2326                         "Please look under Tools>Preferences>User Interface and\n"
2327                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
2328                 return readUIFile(defaultUIFile, false);
2329         }
2330
2331         // Ensure that a file is read only once (prevents include loops)
2332         static QStringList uifiles;
2333         QString const uifile = toqstr(ui_path.absFilename());
2334         if (uifiles.contains(uifile)) {
2335                 if (!include) {
2336                         // We are reading again the top uifile so reset the safeguard:
2337                         uifiles.clear();
2338                         d->menus_.reset();
2339                         d->toolbars_.reset();
2340                 } else {
2341                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2342                                 << "Is this an include loop?");
2343                         return false;
2344                 }
2345         }
2346         uifiles.push_back(uifile);
2347
2348         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2349
2350         enum {
2351                 ui_menuset = 1,
2352                 ui_toolbars,
2353                 ui_toolbarset,
2354                 ui_include,
2355                 ui_last
2356         };
2357
2358         LexerKeyword uitags[] = {
2359                 { "include", ui_include },
2360                 { "menuset", ui_menuset },
2361                 { "toolbars", ui_toolbars },
2362                 { "toolbarset", ui_toolbarset }
2363         };
2364
2365         Lexer lex(uitags);
2366         lex.setFile(ui_path);
2367         if (!lex.isOK()) {
2368                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2369                        << endl;
2370         }
2371
2372         if (lyxerr.debugging(Debug::PARSER))
2373                 lex.printTable(lyxerr);
2374
2375         // store which ui files define Toolbars
2376         static QStringList toolbar_uifiles;
2377
2378         while (lex.isOK()) {
2379                 switch (lex.lex()) {
2380                 case ui_include: {
2381                         lex.next(true);
2382                         QString const file = toqstr(lex.getString());
2383                         if (!readUIFile(file, true))
2384                                 return false;
2385                         break;
2386                 }
2387                 case ui_menuset:
2388                         d->menus_.read(lex);
2389                         break;
2390
2391                 case ui_toolbarset:
2392                         d->toolbars_.readToolbars(lex);
2393                         break;
2394
2395                 case ui_toolbars:
2396                         d->toolbars_.readToolbarSettings(lex);
2397                         toolbar_uifiles.push_back(uifile);
2398                         break;
2399
2400                 default:
2401                         if (!rtrim(lex.getString()).empty())
2402                                 lex.printError("LyX::ReadUIFile: "
2403                                                "Unknown menu tag: `$$Token'");
2404                         break;
2405                 }
2406         }
2407
2408         if (include)
2409                 return true;
2410
2411         QSettings settings;
2412         settings.beginGroup("ui_files");
2413         bool touched = false;
2414         for (int i = 0; i != uifiles.size(); ++i) {
2415                 QFileInfo fi(uifiles[i]);
2416                 QDateTime const date_value = fi.lastModified();
2417                 QString const name_key = QString::number(i);
2418                 // if an ui file which defines Toolbars has changed,
2419                 // we have to reset the settings
2420                 if (toolbar_uifiles.contains(uifiles[i])
2421                  && (!settings.contains(name_key)
2422                  || settings.value(name_key).toString() != uifiles[i]
2423                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
2424                         touched = true;
2425                         settings.setValue(name_key, uifiles[i]);
2426                         settings.setValue(name_key + "/date", date_value);
2427                 }
2428         }
2429         settings.endGroup();
2430         if (touched)
2431                 settings.remove("views");
2432
2433         return true;
2434 }
2435
2436
2437 void GuiApplication::onLastWindowClosed()
2438 {
2439         if (d->global_menubar_)
2440                 d->global_menubar_->grabKeyboard();
2441 }
2442
2443
2444 ////////////////////////////////////////////////////////////////////////
2445 //
2446 // X11 specific stuff goes here...
2447
2448 #ifdef Q_WS_X11
2449 bool GuiApplication::x11EventFilter(XEvent * xev)
2450 {
2451         if (!current_view_)
2452                 return false;
2453
2454         switch (xev->type) {
2455         case SelectionRequest: {
2456                 if (xev->xselectionrequest.selection != XA_PRIMARY)
2457                         break;
2458                 LYXERR(Debug::SELECTION, "X requested selection.");
2459                 BufferView * bv = current_view_->currentBufferView();
2460                 if (bv) {
2461                         docstring const sel = bv->requestSelection();
2462                         if (!sel.empty())
2463                                 d->selection_.put(sel);
2464                 }
2465                 break;
2466         }
2467         case SelectionClear: {
2468                 if (xev->xselectionclear.selection != XA_PRIMARY)
2469                         break;
2470                 LYXERR(Debug::SELECTION, "Lost selection.");
2471                 BufferView * bv = current_view_->currentBufferView();
2472                 if (bv)
2473                         bv->clearSelection();
2474                 break;
2475         }
2476         }
2477         return false;
2478 }
2479 #endif
2480
2481 } // namespace frontend
2482
2483
2484 void hideDialogs(std::string const & name, Inset * inset)
2485 {
2486         if (theApp())
2487                 frontend::guiApp->hideDialogs(name, inset);
2488 }
2489
2490
2491 ////////////////////////////////////////////////////////////////////
2492 //
2493 // Font stuff
2494 //
2495 ////////////////////////////////////////////////////////////////////
2496
2497 frontend::FontLoader & theFontLoader()
2498 {
2499         LASSERT(frontend::guiApp, /**/);
2500         return frontend::guiApp->fontLoader();
2501 }
2502
2503
2504 frontend::FontMetrics const & theFontMetrics(Font const & f)
2505 {
2506         return theFontMetrics(f.fontInfo());
2507 }
2508
2509
2510 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2511 {
2512         LASSERT(frontend::guiApp, /**/);
2513         return frontend::guiApp->fontLoader().metrics(f);
2514 }
2515
2516
2517 ////////////////////////////////////////////////////////////////////
2518 //
2519 // Misc stuff
2520 //
2521 ////////////////////////////////////////////////////////////////////
2522
2523 frontend::Clipboard & theClipboard()
2524 {
2525         LASSERT(frontend::guiApp, /**/);
2526         return frontend::guiApp->clipboard();
2527 }
2528
2529
2530 frontend::Selection & theSelection()
2531 {
2532         LASSERT(frontend::guiApp, /**/);
2533         return frontend::guiApp->selection();
2534 }
2535
2536
2537 } // namespace lyx
2538
2539 #include "moc_GuiApplication.cpp"