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