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