]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
move spellchecker backend change action to actOnUpdatedPrefs where it belongs to...
[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                 resetGui();
1443
1444                 break;
1445         }
1446
1447         case LFUN_COMMAND_PREFIX:
1448                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1449                 break;
1450
1451         case LFUN_CANCEL: {
1452                 d->keyseq.reset();
1453                 d->meta_fake_bit = NoModifier;
1454                 GuiView * gv = currentView();
1455                 if (gv && gv->currentBufferView())
1456                         // cancel any selection
1457                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1458                 dr.setMessage(from_ascii(N_("Cancel")));
1459                 break;
1460         }
1461         case LFUN_META_PREFIX:
1462                 d->meta_fake_bit = AltModifier;
1463                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1464                 break;
1465
1466         // --- Menus -----------------------------------------------
1467         case LFUN_RECONFIGURE:
1468                 // argument is any additional parameter to the configure.py command
1469                 reconfigure(to_utf8(cmd.argument()));
1470                 break;
1471
1472         // --- lyxserver commands ----------------------------
1473         case LFUN_SERVER_GET_FILENAME: {
1474                 if (current_view_ && current_view_->documentBufferView()) {
1475                         docstring const fname = from_utf8(
1476                                 current_view_->documentBufferView()->buffer().absFileName());
1477                         dr.setMessage(fname);
1478                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1479                 } else {
1480                         dr.setMessage(docstring());
1481                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1482                 }
1483                 break;
1484         }
1485
1486         case LFUN_SERVER_NOTIFY: {
1487                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1488                 dr.setMessage(dispatch_buffer);
1489                 theServer().notifyClient(to_utf8(dispatch_buffer));
1490                 break;
1491         }
1492
1493         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1494                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1495                 break;
1496
1497         case LFUN_REPEAT: {
1498                 // repeat command
1499                 string countstr;
1500                 string rest = split(argument, countstr, ' ');
1501                 istringstream is(countstr);
1502                 int count = 0;
1503                 is >> count;
1504                 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1505                 for (int i = 0; i < count; ++i)
1506                         dispatch(lyxaction.lookupFunc(rest));
1507                 break;
1508         }
1509
1510         case LFUN_COMMAND_SEQUENCE: {
1511                 // argument contains ';'-terminated commands
1512                 string arg = argument;
1513                 // FIXME: this LFUN should also work without any view.
1514                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1515                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1516                 if (buffer)
1517                         buffer->undo().beginUndoGroup();
1518                 while (!arg.empty()) {
1519                         string first;
1520                         arg = split(arg, first, ';');
1521                         FuncRequest func(lyxaction.lookupFunc(first));
1522                         func.setOrigin(cmd.origin());
1523                         dispatch(func);
1524                 }
1525                 // the buffer may have been closed by one action
1526                 if (theBufferList().isLoaded(buffer))
1527                         buffer->undo().endUndoGroup();
1528                 break;
1529         }
1530
1531         case LFUN_COMMAND_ALTERNATIVES: {
1532                 // argument contains ';'-terminated commands
1533                 string arg = argument;
1534                 while (!arg.empty()) {
1535                         string first;
1536                         arg = split(arg, first, ';');
1537                         FuncRequest func(lyxaction.lookupFunc(first));
1538                         func.setOrigin(cmd.origin());
1539                         FuncStatus const stat = getStatus(func);
1540                         if (stat.enabled()) {
1541                                 dispatch(func);
1542                                 break;
1543                         }
1544                 }
1545                 break;
1546         }
1547
1548         case LFUN_CALL: {
1549                 FuncRequest func;
1550                 if (theTopLevelCmdDef().lock(argument, func)) {
1551                         func.setOrigin(cmd.origin());
1552                         dispatch(func);
1553                         theTopLevelCmdDef().release(argument);
1554                 } else {
1555                         if (func.action() == LFUN_UNKNOWN_ACTION) {
1556                                 // unknown command definition
1557                                 lyxerr << "Warning: unknown command definition `"
1558                                                 << argument << "'"
1559                                                 << endl;
1560                         } else {
1561                                 // recursion detected
1562                                 lyxerr << "Warning: Recursion in the command definition `"
1563                                                 << argument << "' detected"
1564                                                 << endl;
1565                         }
1566                 }
1567                 break;
1568         }
1569
1570         case LFUN_PREFERENCES_SAVE:
1571                 lyxrc.write(support::makeAbsPath("preferences",
1572                         package().user_support().absFileName()), false);
1573                 break;
1574
1575         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1576                 string const fname = addName(addPath(package().user_support().absFileName(),
1577                         "templates/"), "defaults.lyx");
1578                 Buffer defaults(fname);
1579
1580                 istringstream ss(argument);
1581                 Lexer lex;
1582                 lex.setStream(ss);
1583                 int const unknown_tokens = defaults.readHeader(lex);
1584
1585                 if (unknown_tokens != 0) {
1586                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1587                                << unknown_tokens << " unknown token"
1588                                << (unknown_tokens == 1 ? "" : "s")
1589                                << endl;
1590                 }
1591
1592                 if (defaults.writeFile(FileName(defaults.absFileName())))
1593                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1594                                               makeDisplayPath(fname)));
1595                 else {
1596                         dr.setError(true);
1597                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1598                 }
1599                 break;
1600         }
1601
1602         case LFUN_BOOKMARK_GOTO:
1603                 // go to bookmark, open unopened file and switch to buffer if necessary
1604                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1605                 dr.screenUpdate(Update::Force | Update::FitCursor);
1606                 break;
1607
1608         case LFUN_BOOKMARK_CLEAR:
1609                 theSession().bookmarks().clear();
1610                 break;
1611
1612         case LFUN_DEBUG_LEVEL_SET:
1613                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1614                 break;
1615
1616         default:
1617                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1618                 // let's try that:
1619                 if (current_view_)
1620                         current_view_->dispatch(cmd, dr);
1621                 break;
1622         }
1623 }
1624
1625
1626 docstring GuiApplication::viewStatusMessage()
1627 {
1628         // When meta-fake key is pressed, show the key sequence so far + "M-".
1629         if (d->meta_fake_bit != NoModifier)
1630                 return d->keyseq.print(KeySequence::ForGui) + "M-";
1631
1632         // Else, when a non-complete key sequence is pressed,
1633         // show the available options.
1634         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1635                 return d->keyseq.printOptions(true);
1636
1637         return docstring();
1638 }
1639
1640
1641 void GuiApplication::handleKeyFunc(FuncCode action)
1642 {
1643         char_type c = 0;
1644
1645         if (d->keyseq.length())
1646                 c = 0;
1647         GuiView * gv = currentView();
1648         LASSERT(gv && gv->currentBufferView(), return);
1649         BufferView * bv = gv->currentBufferView();
1650         bv->getIntl().getTransManager().deadkey(
1651                 c, get_accent(action).accent, bv->cursor().innerText(),
1652                 bv->cursor());
1653         // Need to clear, in case the minibuffer calls these
1654         // actions
1655         d->keyseq.clear();
1656         // copied verbatim from do_accent_char
1657         bv->cursor().resetAnchor();
1658 }
1659
1660
1661 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1662 {
1663         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1664
1665         // Do nothing if we have nothing (JMarc)
1666         if (!keysym.isOK()) {
1667                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1668                 if (current_view_)
1669                         current_view_->restartCursor();
1670                 return;
1671         }
1672
1673         if (keysym.isModifier()) {
1674                 if (current_view_)
1675                         current_view_->restartCursor();
1676                 return;
1677         }
1678
1679         char_type encoded_last_key = keysym.getUCSEncoded();
1680
1681         // Do a one-deep top-level lookup for
1682         // cancel and meta-fake keys. RVDK_PATCH_5
1683         d->cancel_meta_seq.reset();
1684
1685         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1686         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1687
1688         // When not cancel or meta-fake, do the normal lookup.
1689         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1690         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1691         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1692                 // remove Caps Lock and Mod2 as a modifiers
1693                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1694                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1695         }
1696
1697         // Dont remove this unless you know what you are doing.
1698         d->meta_fake_bit = NoModifier;
1699
1700         // Can this happen now ?
1701         if (func.action() == LFUN_NOACTION)
1702                 func = FuncRequest(LFUN_COMMAND_PREFIX);
1703
1704         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1705                 << d->keyseq.print(KeySequence::Portable) << ']');
1706
1707         // already here we know if it any point in going further
1708         // why not return already here if action == -1 and
1709         // num_bytes == 0? (Lgb)
1710
1711         if (d->keyseq.length() > 1 && current_view_)
1712                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1713
1714
1715         // Maybe user can only reach the key via holding down shift.
1716         // Let's see. But only if shift is the only modifier
1717         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1718                 LYXERR(Debug::KEY, "Trying without shift");
1719                 func = d->keyseq.addkey(keysym, NoModifier);
1720                 LYXERR(Debug::KEY, "Action now " << func.action());
1721         }
1722
1723         if (func.action() == LFUN_UNKNOWN_ACTION) {
1724                 // Hmm, we didn't match any of the keysequences. See
1725                 // if it's normal insertable text not already covered
1726                 // by a binding
1727                 if (keysym.isText() && d->keyseq.length() == 1) {
1728                         LYXERR(Debug::KEY, "isText() is true, inserting.");
1729                         func = FuncRequest(LFUN_SELF_INSERT,
1730                                            FuncRequest::KEYBOARD);
1731                 } else {
1732                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1733                         if (current_view_) {
1734                                 current_view_->message(_("Unknown function."));
1735                                 current_view_->restartCursor();
1736                         }
1737                         return;
1738                 }
1739         }
1740
1741         if (func.action() == LFUN_SELF_INSERT) {
1742                 if (encoded_last_key != 0) {
1743                         docstring const arg(1, encoded_last_key);
1744                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1745                                              FuncRequest::KEYBOARD));
1746                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1747                 }
1748         } else
1749                 processFuncRequest(func);
1750 }
1751
1752
1753 void GuiApplication::processFuncRequest(FuncRequest const & func)
1754 {
1755         lyx::dispatch(func);
1756 }
1757
1758
1759 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1760 {
1761         addToFuncRequestQueue(func);
1762         processFuncRequestQueueAsync();
1763 }
1764
1765
1766 void GuiApplication::processFuncRequestQueue()
1767 {
1768         while (!d->func_request_queue_.empty()) {
1769                 processFuncRequest(d->func_request_queue_.front());
1770                 d->func_request_queue_.pop();
1771         }
1772 }
1773
1774
1775 void GuiApplication::processFuncRequestQueueAsync()
1776 {
1777         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1778 }
1779
1780
1781 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1782 {
1783         d->func_request_queue_.push(func);
1784 }
1785
1786
1787 void GuiApplication::resetGui()
1788 {
1789         // Set the language defined by the user.
1790         setGuiLanguage();
1791
1792         // Read menus
1793         if (!readUIFile(toqstr(lyxrc.ui_file)))
1794                 // Gives some error box here.
1795                 return;
1796
1797         if (d->global_menubar_)
1798                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1799
1800         QHash<int, GuiView *>::iterator it;
1801         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1802                 GuiView * gv = *it;
1803                 setCurrentView(gv);
1804                 gv->setLayoutDirection(layoutDirection());
1805                 gv->resetDialogs();
1806         }
1807
1808         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1809 }
1810
1811
1812 void GuiApplication::createView(int view_id)
1813 {
1814         createView(QString(), true, view_id);
1815 }
1816
1817
1818 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1819         int view_id)
1820 {
1821         // release the keyboard which might have been grabed by the global
1822         // menubar on Mac to catch shortcuts even without any GuiView.
1823         if (d->global_menubar_)
1824                 d->global_menubar_->releaseKeyboard();
1825
1826         // create new view
1827         int id = view_id;
1828         while (d->views_.find(id) != d->views_.end())
1829                 id++;
1830
1831         LYXERR(Debug::GUI, "About to create new window with ID " << id);
1832         GuiView * view = new GuiView(id);
1833         // register view
1834         d->views_[id] = view;
1835
1836         if (autoShow) {
1837                 view->show();
1838                 setActiveWindow(view);
1839         }
1840
1841         if (!geometry_arg.isEmpty()) {
1842 #ifdef Q_WS_WIN
1843                 int x, y;
1844                 int w, h;
1845                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1846                 re.indexIn(geometry_arg);
1847                 w = re.cap(1).toInt();
1848                 h = re.cap(2).toInt();
1849                 x = re.cap(3).toInt();
1850                 y = re.cap(4).toInt();
1851                 view->setGeometry(x, y, w, h);
1852 #endif
1853         }
1854         view->setFocus();
1855 }
1856
1857
1858 Clipboard & GuiApplication::clipboard()
1859 {
1860         return d->clipboard_;
1861 }
1862
1863
1864 Selection & GuiApplication::selection()
1865 {
1866         return d->selection_;
1867 }
1868
1869
1870 FontLoader & GuiApplication::fontLoader()
1871 {
1872         return d->font_loader_;
1873 }
1874
1875
1876 Toolbars const & GuiApplication::toolbars() const
1877 {
1878         return d->toolbars_;
1879 }
1880
1881
1882 Toolbars & GuiApplication::toolbars()
1883 {
1884         return d->toolbars_;
1885 }
1886
1887
1888 Menus const & GuiApplication::menus() const
1889 {
1890         return d->menus_;
1891 }
1892
1893
1894 Menus & GuiApplication::menus()
1895 {
1896         return d->menus_;
1897 }
1898
1899
1900 QList<int> GuiApplication::viewIds() const
1901 {
1902         return d->views_.keys();
1903 }
1904
1905
1906 ColorCache & GuiApplication::colorCache()
1907 {
1908         return d->color_cache_;
1909 }
1910
1911
1912 int GuiApplication::exec()
1913 {
1914         // asynchronously handle batch commands. This event will be in
1915         // the event queue in front of other asynchronous events. Hence,
1916         // we can assume in the latter that the gui is setup already.
1917         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1918
1919         return QApplication::exec();
1920 }
1921
1922
1923 void GuiApplication::exit(int status)
1924 {
1925         QApplication::exit(status);
1926 }
1927
1928
1929 void GuiApplication::setGuiLanguage()
1930 {
1931         // Set the language defined by the user.
1932         setRcGuiLanguage();
1933
1934         QString const default_language = toqstr(Messages::defaultLanguage());
1935         LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1936         QLocale const default_locale(default_language);
1937         QLocale::setDefault(default_locale);
1938
1939         // install translation file for Qt built-in dialogs
1940         QString const language_name = QString("qt_") + default_locale.name();
1941
1942         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1943         // Short-named translator can be loaded from a long name, but not the
1944         // opposite. Therefore, long name should be used without truncation.
1945         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1946         if (!d->qt_trans_.load(language_name,
1947                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1948                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1949                         << language_name);
1950         } else {
1951                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1952                         << language_name);
1953         }
1954
1955         switch (default_locale.language()) {
1956         case QLocale::Arabic :
1957         case QLocale::Hebrew :
1958         case QLocale::Persian :
1959         case QLocale::Urdu :
1960                 setLayoutDirection(Qt::RightToLeft);
1961                 break;
1962         default:
1963                 setLayoutDirection(Qt::LeftToRight);
1964         }
1965 }
1966
1967
1968 void GuiApplication::execBatchCommands()
1969 {
1970         setGuiLanguage();
1971
1972         // Read menus
1973         if (!readUIFile(toqstr(lyxrc.ui_file)))
1974                 // Gives some error box here.
1975                 return;
1976
1977 #ifdef Q_WS_MACX
1978 #if QT_VERSION > 0x040600
1979         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
1980 #endif
1981         // Create the global default menubar which is shown for the dialogs
1982         // and if no GuiView is visible.
1983         // This must be done after the session was recovered to know the "last files".
1984         d->global_menubar_ = new GlobalMenuBar();
1985         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1986 #endif
1987
1988         lyx::execBatchCommands();
1989 }
1990
1991
1992 QAbstractItemModel * GuiApplication::languageModel()
1993 {
1994         if (d->language_model_)
1995                 return d->language_model_;
1996
1997         QStandardItemModel * lang_model = new QStandardItemModel(this);
1998         lang_model->insertColumns(0, 3);
1999         int current_row;
2000         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2001         QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2002         Languages::const_iterator it = lyx::languages.begin();
2003         Languages::const_iterator end = lyx::languages.end();
2004         for (; it != end; ++it) {
2005                 current_row = lang_model->rowCount();
2006                 lang_model->insertRows(current_row, 1);
2007                 QModelIndex pl_item = lang_model->index(current_row, 0);
2008                 QModelIndex sp_item = lang_model->index(current_row, 1);
2009                 QModelIndex th_item = lang_model->index(current_row, 2);
2010                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2011                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2012                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2013                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2014                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2015                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2016                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2017                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2018                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2019                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2020         }
2021         d->language_model_ = new QSortFilterProxyModel(this);
2022         d->language_model_->setSourceModel(lang_model);
2023 #if QT_VERSION >= 0x040300
2024         d->language_model_->setSortLocaleAware(true);
2025 #endif
2026         return d->language_model_;
2027 }
2028
2029
2030 void GuiApplication::restoreGuiSession()
2031 {
2032         if (!lyxrc.load_session)
2033                 return;
2034
2035         Session & session = theSession();
2036         LastOpenedSection::LastOpened const & lastopened =
2037                 session.lastOpened().getfiles();
2038
2039         validateCurrentView();
2040
2041         FileName active_file;
2042         // do not add to the lastfile list since these files are restored from
2043         // last session, and should be already there (regular files), or should
2044         // not be added at all (help files).
2045         for (size_t i = 0; i < lastopened.size(); ++i) {
2046                 FileName const & file_name = lastopened[i].file_name;
2047                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2048                           && current_view_->documentBufferView() != 0)) {
2049                         boost::crc_32_type crc;
2050                         string const & fname = file_name.absFileName();
2051                         crc = for_each(fname.begin(), fname.end(), crc);
2052                         createView(crc.checksum());
2053                 }
2054                 current_view_->loadDocument(file_name, false);
2055
2056                 if (lastopened[i].active)
2057                         active_file = file_name;
2058         }
2059
2060         // Restore last active buffer
2061         Buffer * buffer = theBufferList().getBuffer(active_file);
2062         if (buffer && current_view_)
2063                 current_view_->setBuffer(buffer);
2064
2065         // clear this list to save a few bytes of RAM
2066         session.lastOpened().clear();
2067 }
2068
2069
2070 QString const GuiApplication::romanFontName()
2071 {
2072         QFont font;
2073         font.setKerning(false);
2074         font.setStyleHint(QFont::Serif);
2075         font.setFamily("serif");
2076
2077         return QFontInfo(font).family();
2078 }
2079
2080
2081 QString const GuiApplication::sansFontName()
2082 {
2083         QFont font;
2084         font.setKerning(false);
2085         font.setStyleHint(QFont::SansSerif);
2086         font.setFamily("sans");
2087
2088         return QFontInfo(font).family();
2089 }
2090
2091
2092 QString const GuiApplication::typewriterFontName()
2093 {
2094         QFont font;
2095         font.setKerning(false);
2096         font.setStyleHint(QFont::TypeWriter);
2097         font.setFamily("monospace");
2098
2099         return QFontInfo(font).family();
2100 }
2101
2102
2103 void GuiApplication::handleRegularEvents()
2104 {
2105         ForkedCallsController::handleCompletedProcesses();
2106 }
2107
2108
2109 bool GuiApplication::event(QEvent * e)
2110 {
2111         switch(e->type()) {
2112         case QEvent::FileOpen: {
2113                 // Open a file; this happens only on Mac OS X for now.
2114                 //
2115                 // We do this asynchronously because on startup the batch
2116                 // commands are not executed here yet and the gui is not ready
2117                 // therefore.
2118                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2119                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2120                 processFuncRequestAsync(fr);
2121                 e->accept();
2122                 return true;
2123         }
2124         default:
2125                 return QApplication::event(e);
2126         }
2127 }
2128
2129
2130 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2131 {
2132         try {
2133                 return QApplication::notify(receiver, event);
2134         }
2135         catch (ExceptionMessage const & e) {
2136                 switch(e.type_) {
2137                 case ErrorException:
2138                         emergencyCleanup();
2139                         setQuitOnLastWindowClosed(false);
2140                         closeAllViews();
2141                         Alert::error(e.title_, e.details_);
2142 #ifndef NDEBUG
2143                         // Properly crash in debug mode in order to get a useful backtrace.
2144                         abort();
2145 #endif
2146                         // In release mode, try to exit gracefully.
2147                         this->exit(1);
2148
2149                 case BufferException: {
2150                         if (!current_view_ || !current_view_->documentBufferView())
2151                                 return false;
2152                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2153                         docstring details = e.details_ + '\n';
2154                         details += buf->emergencyWrite();
2155                         theBufferList().release(buf);
2156                         details += "\n" + _("The current document was closed.");
2157                         Alert::error(e.title_, details);
2158                         return false;
2159                 }
2160                 case WarningException:
2161                         Alert::warning(e.title_, e.details_);
2162                         return false;
2163                 }
2164         }
2165         catch (exception const & e) {
2166                 docstring s = _("LyX has caught an exception, it will now "
2167                         "attempt to save all unsaved documents and exit."
2168                         "\n\nException: ");
2169                 s += from_ascii(e.what());
2170                 Alert::error(_("Software exception Detected"), s);
2171                 lyx_exit(1);
2172         }
2173         catch (...) {
2174                 docstring s = _("LyX has caught some really weird exception, it will "
2175                         "now attempt to save all unsaved documents and exit.");
2176                 Alert::error(_("Software exception Detected"), s);
2177                 lyx_exit(1);
2178         }
2179
2180         return false;
2181 }
2182
2183
2184 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2185 {
2186         QColor const & qcol = d->color_cache_.get(col);
2187         if (!qcol.isValid()) {
2188                 rgbcol.r = 0;
2189                 rgbcol.g = 0;
2190                 rgbcol.b = 0;
2191                 return false;
2192         }
2193         rgbcol.r = qcol.red();
2194         rgbcol.g = qcol.green();
2195         rgbcol.b = qcol.blue();
2196         return true;
2197 }
2198
2199
2200 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2201 {
2202         QColor const qcol(lcolor.getX11Name(col).c_str());
2203         if (!qcol.isValid()) {
2204                 rgbcol.r = 0;
2205                 rgbcol.g = 0;
2206                 rgbcol.b = 0;
2207                 return false;
2208         }
2209         rgbcol.r = qcol.red();
2210         rgbcol.g = qcol.green();
2211         rgbcol.b = qcol.blue();
2212         return true;
2213 }
2214
2215
2216 string const GuiApplication::hexName(ColorCode col)
2217 {
2218         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2219 }
2220
2221
2222 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2223 {
2224         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2225         d->socket_notifiers_[fd] = sn;
2226         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2227 }
2228
2229
2230 void GuiApplication::socketDataReceived(int fd)
2231 {
2232         d->socket_notifiers_[fd]->func_();
2233 }
2234
2235
2236 void GuiApplication::unregisterSocketCallback(int fd)
2237 {
2238         d->socket_notifiers_.take(fd)->setEnabled(false);
2239 }
2240
2241
2242 void GuiApplication::commitData(QSessionManager & sm)
2243 {
2244         /// The implementation is required to avoid an application exit
2245         /// when session state save is triggered by session manager.
2246         /// The default implementation sends a close event to all
2247         /// visible top level widgets when session managment allows
2248         /// interaction.
2249         /// We are changing that to close all wiew one by one.
2250         /// FIXME: verify if the default implementation is enough now.
2251         #ifdef QT_NO_SESSIONMANAGER
2252                 #warning Qt is compiled without session manager
2253                 (void) sm;
2254         #else
2255                 if (sm.allowsInteraction() && !closeAllViews())
2256                         sm.cancel();
2257         #endif
2258 }
2259
2260
2261 void GuiApplication::unregisterView(GuiView * gv)
2262 {
2263         LASSERT(d->views_[gv->id()] == gv, /**/);
2264         d->views_.remove(gv->id());
2265         if (current_view_ == gv)
2266                 current_view_ = 0;
2267 }
2268
2269
2270 bool GuiApplication::closeAllViews()
2271 {
2272         if (d->views_.empty())
2273                 return true;
2274
2275         // When a view/window was closed before without quitting LyX, there
2276         // are already entries in the lastOpened list.
2277         theSession().lastOpened().clear();
2278
2279         QList<GuiView *> views = d->views_.values();
2280         foreach (GuiView * view, views) {
2281                 if (!view->closeScheduled())
2282                         return false;
2283         }
2284
2285         d->views_.clear();
2286         return true;
2287 }
2288
2289
2290 GuiView & GuiApplication::view(int id) const
2291 {
2292         LASSERT(d->views_.contains(id), /**/);
2293         return *d->views_.value(id);
2294 }
2295
2296
2297 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2298 {
2299         QList<GuiView *> views = d->views_.values();
2300         foreach (GuiView * view, views)
2301                 view->hideDialog(name, inset);
2302 }
2303
2304
2305 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2306 {
2307         Buffer const * buffer_ = 0;
2308         QHash<int, GuiView *>::iterator end = d->views_.end();
2309         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2310                 if (Buffer const * ptr = (*it)->updateInset(inset))
2311                         buffer_ = ptr;
2312         }
2313         return buffer_;
2314 }
2315
2316
2317 bool GuiApplication::searchMenu(FuncRequest const & func,
2318         docstring_list & names) const
2319 {
2320         return d->menus_.searchMenu(func, names);
2321 }
2322
2323
2324 // Ensure that a file is read only once (prevents include loops)
2325 static QStringList uifiles;
2326 // store which ui files define Toolbars
2327 static QStringList toolbar_uifiles;
2328
2329
2330 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2331 {
2332         enum {
2333                 ui_menuset = 1,
2334                 ui_toolbars,
2335                 ui_toolbarset,
2336                 ui_include,
2337                 ui_format,
2338                 ui_last
2339         };
2340
2341         LexerKeyword uitags[] = {
2342                 { "format", ui_format },
2343                 { "include", ui_include },
2344                 { "menuset", ui_menuset },
2345                 { "toolbars", ui_toolbars },
2346                 { "toolbarset", ui_toolbarset }
2347         };
2348
2349         Lexer lex(uitags);
2350         lex.setFile(ui_path);
2351         if (!lex.isOK()) {
2352                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2353                                          << endl;
2354         }
2355
2356         if (lyxerr.debugging(Debug::PARSER))
2357                 lex.printTable(lyxerr);
2358
2359         bool error = false;
2360         // format before introduction of format tag
2361         unsigned int format = 0;
2362         while (lex.isOK()) {
2363                 int const status = lex.lex();
2364
2365                 // we have to do this check here, outside the switch,
2366                 // because otherwise we would start reading include files,
2367                 // e.g., if the first tag we hit was an include tag.
2368                 if (status == ui_format)
2369                         if (lex.next()) {
2370                                 format = lex.getInteger();
2371                                 continue;
2372                         }
2373
2374                 // this will trigger unless the first tag we hit is a format
2375                 // tag, with the right format.
2376                 if (format != LFUN_FORMAT)
2377                         return FormatMismatch;
2378
2379                 switch (status) {
2380                 case Lexer::LEX_FEOF:
2381                         continue;
2382
2383                 case ui_include: {
2384                         lex.next(true);
2385                         QString const file = toqstr(lex.getString());
2386                         bool const success = readUIFile(file, true);
2387                         if (!success) {
2388                                 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2389                                 return ReadError;
2390                         }
2391                         break;
2392                 }
2393
2394                 case ui_menuset:
2395                         d->menus_.read(lex);
2396                         break;
2397
2398                 case ui_toolbarset:
2399                         d->toolbars_.readToolbars(lex);
2400                         break;
2401
2402                 case ui_toolbars:
2403                         d->toolbars_.readToolbarSettings(lex);
2404                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2405                         break;
2406
2407                 default:
2408                         if (!rtrim(lex.getString()).empty())
2409                                 lex.printError("LyX::ReadUIFile: "
2410                                                "Unknown menu tag: `$$Token'");
2411                         else
2412                                 LYXERR0("Error with status: " << status);
2413                         error = true;
2414                         break;
2415                 }
2416
2417         }
2418         return (error ? ReadError : ReadOK);
2419 }
2420
2421
2422 bool GuiApplication::readUIFile(QString const & name, bool include)
2423 {
2424         LYXERR(Debug::INIT, "About to read " << name << "...");
2425
2426         FileName ui_path;
2427         if (include) {
2428                 ui_path = libFileSearch("ui", name, "inc");
2429                 if (ui_path.empty())
2430                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2431         } else {
2432                 ui_path = libFileSearch("ui", name, "ui");
2433         }
2434
2435         if (ui_path.empty()) {
2436                 static const QString defaultUIFile = "default";
2437                 LYXERR(Debug::INIT, "Could not find " << name);
2438                 if (include) {
2439                         Alert::warning(_("Could not find UI definition file"),
2440                                 bformat(_("Error while reading the included file\n%1$s\n"
2441                                         "Please check your installation."), qstring_to_ucs4(name)));
2442                         return false;
2443                 }
2444                 if (name == defaultUIFile) {
2445                         LYXERR(Debug::INIT, "Could not find default UI file!!");
2446                         Alert::warning(_("Could not find default UI file"),
2447                                 _("LyX could not find the default UI file!\n"
2448                                   "Please check your installation."));
2449                         return false;
2450                 }
2451                 Alert::warning(_("Could not find UI definition file"),
2452                 bformat(_("Error while reading the configuration file\n%1$s\n"
2453                         "Falling back to default.\n"
2454                         "Please look under Tools>Preferences>User Interface and\n"
2455                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
2456                 return readUIFile(defaultUIFile, false);
2457         }
2458
2459         QString const uifile = toqstr(ui_path.absFileName());
2460         if (uifiles.contains(uifile)) {
2461                 if (!include) {
2462                         // We are reading again the top uifile so reset the safeguard:
2463                         uifiles.clear();
2464                         d->menus_.reset();
2465                         d->toolbars_.reset();
2466                 } else {
2467                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2468                                 << "Is this an include loop?");
2469                         return false;
2470                 }
2471         }
2472         uifiles.push_back(uifile);
2473
2474         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2475
2476         ReturnValues retval = readUIFile(ui_path);
2477
2478         if (retval == FormatMismatch) {
2479                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2480                 FileName const tempfile = FileName::tempName("convert_ui");
2481                 bool const success = prefs2prefs(ui_path, tempfile, true);
2482                 if (!success) {
2483                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
2484                                 " to format " << LFUN_FORMAT << ".");
2485                 } else {
2486                         retval = readUIFile(tempfile);
2487                         tempfile.removeFile();
2488                 }
2489         }
2490
2491         if (retval != ReadOK) {
2492                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2493                 return false;
2494         }
2495
2496         if (include)
2497                 return true;
2498
2499         QSettings settings;
2500         settings.beginGroup("ui_files");
2501         bool touched = false;
2502         for (int i = 0; i != uifiles.size(); ++i) {
2503                 QFileInfo fi(uifiles[i]);
2504                 QDateTime const date_value = fi.lastModified();
2505                 QString const name_key = QString::number(i);
2506                 // if an ui file which defines Toolbars has changed,
2507                 // we have to reset the settings
2508                 if (toolbar_uifiles.contains(uifiles[i])
2509                  && (!settings.contains(name_key)
2510                  || settings.value(name_key).toString() != uifiles[i]
2511                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
2512                         touched = true;
2513                         settings.setValue(name_key, uifiles[i]);
2514                         settings.setValue(name_key + "/date", date_value);
2515                 }
2516         }
2517         settings.endGroup();
2518         if (touched)
2519                 settings.remove("views");
2520
2521         return true;
2522 }
2523
2524
2525 void GuiApplication::onLastWindowClosed()
2526 {
2527         if (d->global_menubar_)
2528                 d->global_menubar_->grabKeyboard();
2529 }
2530
2531
2532 ////////////////////////////////////////////////////////////////////////
2533 //
2534 // X11 specific stuff goes here...
2535
2536 #ifdef Q_WS_X11
2537 bool GuiApplication::x11EventFilter(XEvent * xev)
2538 {
2539         if (!current_view_)
2540                 return false;
2541
2542         switch (xev->type) {
2543         case SelectionRequest: {
2544                 if (xev->xselectionrequest.selection != XA_PRIMARY)
2545                         break;
2546                 LYXERR(Debug::SELECTION, "X requested selection.");
2547                 BufferView * bv = current_view_->currentBufferView();
2548                 if (bv) {
2549                         docstring const sel = bv->requestSelection();
2550                         if (!sel.empty())
2551                                 d->selection_.put(sel);
2552                 }
2553                 break;
2554         }
2555         case SelectionClear: {
2556                 if (xev->xselectionclear.selection != XA_PRIMARY)
2557                         break;
2558                 LYXERR(Debug::SELECTION, "Lost selection.");
2559                 BufferView * bv = current_view_->currentBufferView();
2560                 if (bv)
2561                         bv->clearSelection();
2562                 break;
2563         }
2564         }
2565         return false;
2566 }
2567 #endif
2568
2569 } // namespace frontend
2570
2571
2572 void hideDialogs(std::string const & name, Inset * inset)
2573 {
2574         if (theApp())
2575                 frontend::guiApp->hideDialogs(name, inset);
2576 }
2577
2578
2579 ////////////////////////////////////////////////////////////////////
2580 //
2581 // Font stuff
2582 //
2583 ////////////////////////////////////////////////////////////////////
2584
2585 frontend::FontLoader & theFontLoader()
2586 {
2587         LASSERT(frontend::guiApp, /**/);
2588         return frontend::guiApp->fontLoader();
2589 }
2590
2591
2592 frontend::FontMetrics const & theFontMetrics(Font const & f)
2593 {
2594         return theFontMetrics(f.fontInfo());
2595 }
2596
2597
2598 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2599 {
2600         LASSERT(frontend::guiApp, /**/);
2601         return frontend::guiApp->fontLoader().metrics(f);
2602 }
2603
2604
2605 ////////////////////////////////////////////////////////////////////
2606 //
2607 // Misc stuff
2608 //
2609 ////////////////////////////////////////////////////////////////////
2610
2611 frontend::Clipboard & theClipboard()
2612 {
2613         LASSERT(frontend::guiApp, /**/);
2614         return frontend::guiApp->clipboard();
2615 }
2616
2617
2618 frontend::Selection & theSelection()
2619 {
2620         LASSERT(frontend::guiApp, /**/);
2621         return frontend::guiApp->selection();
2622 }
2623
2624
2625 } // namespace lyx
2626
2627 #include "moc_GuiApplication.cpp"