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