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