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