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