]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
#7292 make the modifiers Option and Control act on there own on mac - adjust the...
[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         // This allows to translate the strings that appear in the LyX menu.
790         /// A translator suitable for the entries in the LyX menu.
791         /// Only needed with Qt/Mac.
792         installTranslator(new MenuTranslator(this));
793 #endif
794
795 #ifdef Q_WS_X11
796         // doubleClickInterval() is 400 ms on X11 which is just too long.
797         // On Windows and Mac OS X, the operating system's value is used.
798         // On Microsoft Windows, calling this function sets the double
799         // click interval for all applications. So we don't!
800         QApplication::setDoubleClickInterval(300);
801 #endif
802
803         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
804
805         // needs to be done before reading lyxrc
806         QWidget w;
807         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
808
809         guiApp = this;
810
811         // Set the cache to 5120 kilobytes which corresponds to screen size of
812         // 1280 by 1024 pixels with a color depth of 32 bits.
813         QPixmapCache::setCacheLimit(5120);
814
815         // Initialize RC Fonts
816         if (lyxrc.roman_font_name.empty())
817                 lyxrc.roman_font_name = fromqstr(romanFontName());
818
819         if (lyxrc.sans_font_name.empty())
820                 lyxrc.sans_font_name = fromqstr(sansFontName());
821
822         if (lyxrc.typewriter_font_name.empty())
823                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
824
825         d->general_timer_.setInterval(500);
826         connect(&d->general_timer_, SIGNAL(timeout()),
827                 this, SLOT(handleRegularEvents()));
828         d->general_timer_.start();
829
830 #if QT_VERSION >= 0x040400
831         // maxThreadCount() defaults in general to 2 on single or dual-processor.
832         // This is clearly not enough in a time where we use threads for
833         // document preview and/or export. 20 should be OK.
834         QThreadPool::globalInstance()->setMaxThreadCount(20);
835 #endif
836 }
837
838
839 GuiApplication * theGuiApp()
840 {
841         return dynamic_cast<GuiApplication *>(theApp());
842 }
843
844
845 void GuiApplication::clearSession()
846 {
847         QSettings settings;
848         settings.clear();
849 }
850
851
852 docstring Application::iconName(FuncRequest const & f, bool unknown)
853 {
854         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
855 }
856
857
858 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
859 {
860         FuncStatus status;
861
862         BufferView * bv = 0;
863         BufferView * doc_bv = 0;
864
865         if (cmd.action() == LFUN_NOACTION) {
866                 status.message(from_utf8(N_("Nothing to do")));
867                 status.setEnabled(false);
868         }
869
870         else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
871                 status.setUnknown(true);
872                 status.message(from_utf8(N_("Unknown action")));
873                 status.setEnabled(false);
874         }
875
876         // Does the GuiApplication know something?
877         else if (getStatus(cmd, status)) { }
878
879         // If we do not have a GuiView, then other functions are disabled
880         else if (!current_view_)
881                 status.setEnabled(false);
882
883         // Does the GuiView know something?
884         else if (current_view_->getStatus(cmd, status)) { }
885
886         // In LyX/Mac, when a dialog is open, the menus of the
887         // application can still be accessed without giving focus to
888         // the main window. In this case, we want to disable the menu
889         // entries that are buffer or view-related.
890         //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
891         /*
892         else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
893                 status.setEnabled(false);
894         */
895
896         // If we do not have a BufferView, then other functions are disabled
897         else if (!(bv = current_view_->currentBufferView()))
898                 status.setEnabled(false);
899
900         // Does the current BufferView know something?
901         else if (bv->getStatus(cmd, status)) { }
902
903         // Does the current Buffer know something?
904         else if (bv->buffer().getStatus(cmd, status)) { }
905
906         // If we do not have a document BufferView, different from the
907         // current BufferView, then other functions are disabled
908         else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
909                 status.setEnabled(false);
910
911         // Does the document Buffer know something?
912         else if (doc_bv->buffer().getStatus(cmd, status)) { }
913
914         else {
915                 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
916                 status.message(from_utf8(N_("Command not handled")));
917                 status.setEnabled(false);
918         }
919
920         // the default error message if we disable the command
921         if (!status.enabled() && status.message().empty())
922                 status.message(from_utf8(N_("Command disabled")));
923
924         return status;
925 }
926
927
928 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
929 {
930         // I would really like to avoid having this switch and rather try to
931         // encode this in the function itself.
932         // -- And I'd rather let an inset decide which LFUNs it is willing
933         // to handle (Andre')
934         bool enable = true;
935         switch (cmd.action()) {
936
937         // This could be used for the no-GUI version. The GUI version is handled in
938         // GuiView::getStatus(). See above.
939         /*
940         case LFUN_BUFFER_WRITE:
941         case LFUN_BUFFER_WRITE_AS: {
942                 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
943                 enable = b && (b->isUnnamed() || !b->isClean());
944                 break;
945         }
946         */
947
948         case LFUN_BOOKMARK_GOTO: {
949                 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
950                 enable = theSession().bookmarks().isValid(num);
951                 break;
952         }
953
954         case LFUN_BOOKMARK_CLEAR:
955                 enable = theSession().bookmarks().hasValid();
956                 break;
957
958         // this one is difficult to get right. As a half-baked
959         // solution, we consider only the first action of the sequence
960         case LFUN_COMMAND_SEQUENCE: {
961                 // argument contains ';'-terminated commands
962                 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
963                 FuncRequest func(lyxaction.lookupFunc(firstcmd));
964                 func.setOrigin(cmd.origin());
965                 flag = getStatus(func);
966                 break;
967         }
968
969         // we want to check if at least one of these is enabled
970         case LFUN_COMMAND_ALTERNATIVES: {
971                 // argument contains ';'-terminated commands
972                 string arg = to_utf8(cmd.argument());
973                 while (!arg.empty()) {
974                         string first;
975                         arg = split(arg, first, ';');
976                         FuncRequest func(lyxaction.lookupFunc(first));
977                         func.setOrigin(cmd.origin());
978                         flag = getStatus(func);
979                         // if this one is enabled, the whole thing is
980                         if (flag.enabled())
981                                 break;
982                 }
983                 break;
984         }
985
986         case LFUN_CALL: {
987                 FuncRequest func;
988                 string name = to_utf8(cmd.argument());
989                 if (theTopLevelCmdDef().lock(name, func)) {
990                         func.setOrigin(cmd.origin());
991                         flag = getStatus(func);
992                         theTopLevelCmdDef().release(name);
993                 } else {
994                         // catch recursion or unknown command
995                         // definition. all operations until the
996                         // recursion or unknown command definition
997                         // occurs are performed, so set the state to
998                         // enabled
999                         enable = true;
1000                 }
1001                 break;
1002         }
1003
1004         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1005         case LFUN_REPEAT:
1006         case LFUN_PREFERENCES_SAVE:
1007         case LFUN_BUFFER_SAVE_AS_DEFAULT:
1008         case LFUN_DEBUG_LEVEL_SET:
1009                 // these are handled in our dispatch()
1010                 break;
1011
1012         case LFUN_WINDOW_CLOSE:
1013                 enable = d->views_.size() > 0;
1014                 break;
1015
1016         case LFUN_BUFFER_NEW:
1017         case LFUN_BUFFER_NEW_TEMPLATE:
1018         case LFUN_FILE_OPEN:
1019         case LFUN_HELP_OPEN:
1020         case LFUN_SCREEN_FONT_UPDATE:
1021         case LFUN_SET_COLOR:
1022         case LFUN_WINDOW_NEW:
1023         case LFUN_LYX_QUIT:
1024         case LFUN_LYXRC_APPLY:
1025         case LFUN_COMMAND_PREFIX:
1026         case LFUN_CANCEL:
1027         case LFUN_META_PREFIX:
1028         case LFUN_RECONFIGURE:
1029         case LFUN_SERVER_GET_FILENAME:
1030         case LFUN_SERVER_NOTIFY:
1031                 enable = true;
1032                 break;
1033
1034         default:
1035                 return false;
1036         }
1037
1038         if (!enable)
1039                 flag.setEnabled(false);
1040         return true;
1041 }
1042
1043 /// make a post-dispatch status message
1044 static docstring makeDispatchMessage(docstring const & msg,
1045                                      FuncRequest const & cmd)
1046 {
1047         const bool verbose = (cmd.origin() == FuncRequest::MENU
1048                               || cmd.origin() == FuncRequest::TOOLBAR
1049                               || cmd.origin() == FuncRequest::COMMANDBUFFER);
1050
1051         if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1052                 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1053                 return msg;
1054         }
1055
1056         docstring dispatch_msg = msg;
1057         if (!dispatch_msg.empty())
1058                 dispatch_msg += ' ';
1059
1060         docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1061
1062         bool argsadded = false;
1063
1064         if (!cmd.argument().empty()) {
1065                 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1066                         comname += ' ' + cmd.argument();
1067                         argsadded = true;
1068                 }
1069         }
1070         docstring const shortcuts = theTopLevelKeymap().
1071                 printBindings(cmd, KeySequence::ForGui);
1072
1073         if (!shortcuts.empty())
1074                 comname += ": " + shortcuts;
1075         else if (!argsadded && !cmd.argument().empty())
1076                 comname += ' ' + cmd.argument();
1077
1078         if (!comname.empty()) {
1079                 comname = rtrim(comname);
1080                 dispatch_msg += '(' + rtrim(comname) + ')';
1081         }
1082         LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1083         return dispatch_msg;
1084 }
1085
1086
1087 void GuiApplication::dispatch(FuncRequest const & cmd)
1088 {
1089         if (current_view_ && current_view_->currentBufferView())
1090                 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1091
1092         DispatchResult dr;
1093         // redraw the screen at the end (first of the two drawing steps).
1094         // This is done unless explicitly requested otherwise
1095         dr.screenUpdate(Update::FitCursor);
1096         dispatch(cmd, dr);
1097
1098         if (!current_view_)
1099                 return;
1100
1101         BufferView * bv = current_view_->currentBufferView();
1102         if (bv) {
1103                 Cursor & cursor = bv->cursor();
1104                 Buffer & buf = bv->buffer();
1105
1106                 // FIXME
1107                 // This check out to be done somewhere else. It got moved here
1108                 // from TextMetrics.cpp, where it definitely didn't need to be.
1109                 // Actually, this test ought not to be done at all, since the
1110                 // whole InsetBibitem business is a mess. But that is a different
1111                 // story.
1112                 int moveCursor = 0;
1113                 if (cursor.inTexted()) {
1114                         moveCursor = cursor.paragraph().checkBiblio(buf);
1115                         if (moveCursor > 0)
1116                                 cursor.posForward();
1117                         else if (moveCursor < 0 && cursor.pos() >= -moveCursor)
1118                                 cursor.posBackward();
1119                 }
1120                 if (moveCursor != 0 || dr.needBufferUpdate()) {
1121                         cursor.clearBufferUpdate();
1122                         buf.updateBuffer();
1123                 }
1124                 // BufferView::update() updates the ViewMetricsInfo and
1125                 // also initializes the position cache for all insets in
1126                 // (at least partially) visible top-level paragraphs.
1127                 // We will redraw the screen only if needed.
1128                 bv->processUpdateFlags(dr.screenUpdate());
1129
1130                 // Do we have a selection?
1131                 theSelection().haveSelection(bv->cursor().selection());
1132
1133                 // update gui
1134                 current_view_->restartCursor();
1135         }
1136         if (dr.needMessageUpdate()) {
1137                 // Some messages may already be translated, so we cannot use _()
1138                 current_view_->message(makeDispatchMessage(
1139                                 translateIfPossible(dr.message()), cmd));
1140         }
1141 }
1142
1143
1144 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1145         bool switchToBuffer)
1146 {
1147         if (!theSession().bookmarks().isValid(idx))
1148                 return;
1149         BookmarksSection::Bookmark const & bm =
1150                 theSession().bookmarks().bookmark(idx);
1151         LASSERT(!bm.filename.empty(), /**/);
1152         string const file = bm.filename.absFileName();
1153         // if the file is not opened, open it.
1154         if (!theBufferList().exists(bm.filename)) {
1155                 if (openFile)
1156                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1157                 else
1158                         return;
1159         }
1160         // open may fail, so we need to test it again
1161         if (!theBufferList().exists(bm.filename))
1162                 return;
1163
1164         // bm can be changed when saving
1165         BookmarksSection::Bookmark tmp = bm;
1166
1167         // Special case idx == 0 used for back-from-back jump navigation
1168         if (idx == 0)
1169                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1170
1171         // if the current buffer is not that one, switch to it.
1172         BufferView * doc_bv = current_view_ ?
1173                 current_view_->documentBufferView() : 0;
1174         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1175                 if (switchToBuffer) {
1176                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1177                         if (!current_view_)
1178                                 return;
1179                         doc_bv = current_view_->documentBufferView();
1180                 } else
1181                         return;
1182         }
1183
1184         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1185         if (!doc_bv->moveToPosition(
1186                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1187                 return;
1188
1189         // bm changed
1190         if (idx == 0)
1191                 return;
1192
1193         // Cursor jump succeeded!
1194         Cursor const & cur = doc_bv->cursor();
1195         pit_type new_pit = cur.pit();
1196         pos_type new_pos = cur.pos();
1197         int new_id = cur.paragraph().id();
1198
1199         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1200         // see http://www.lyx.org/trac/ticket/3092
1201         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1202                 || bm.top_id != new_id) {
1203                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1204                         new_pit, new_pos, new_id);
1205         }
1206 }
1207
1208 // This function runs "configure" and then rereads lyx.defaults to
1209 // reconfigure the automatic settings.
1210 void GuiApplication::reconfigure(string const & option)
1211 {
1212         // emit message signal.
1213         if (current_view_)
1214                 current_view_->message(_("Running configure..."));
1215
1216         // Run configure in user lyx directory
1217         PathChanger p(package().user_support());
1218         string configure_command = package().configure_command();
1219         configure_command += option;
1220         Systemcall one;
1221         int ret = one.startscript(Systemcall::Wait, configure_command);
1222         p.pop();
1223         // emit message signal.
1224         if (current_view_)
1225                 current_view_->message(_("Reloading configuration..."));
1226         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1227         // Re-read packages.lst
1228         LaTeXFeatures::getAvailable();
1229
1230         if (ret)
1231                 Alert::information(_("System reconfiguration failed"),
1232                            _("The system reconfiguration has failed.\n"
1233                                   "Default textclass is used but LyX may "
1234                                   "not be able to work properly.\n"
1235                                   "Please reconfigure again if needed."));
1236         else
1237                 Alert::information(_("System reconfigured"),
1238                            _("The system has been reconfigured.\n"
1239                              "You need to restart LyX to make use of any\n"
1240                              "updated document class specifications."));
1241 }
1242
1243 void GuiApplication::validateCurrentView()
1244 {
1245         if (!d->views_.empty() && !current_view_) {
1246                 // currently at least one view exists but no view has the focus.
1247                 // choose the last view to make it current.
1248                 // a view without any open document is preferred.
1249                 GuiView * candidate = 0;
1250                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1251                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1252                 for (; it != end; ++it) {
1253                         candidate = *it;
1254                         if (!candidate->documentBufferView())
1255                                 break;
1256                 }
1257                 setCurrentView(candidate);
1258         }
1259 }
1260
1261 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1262 {
1263         string const argument = to_utf8(cmd.argument());
1264         FuncCode const action = cmd.action();
1265
1266         LYXERR(Debug::ACTION, "cmd: " << cmd);
1267
1268         // we have not done anything wrong yet.
1269         dr.setError(false);
1270
1271         FuncStatus const flag = getStatus(cmd);
1272         if (!flag.enabled()) {
1273                 // We cannot use this function here
1274                 LYXERR(Debug::ACTION, "action "
1275                        << lyxaction.getActionName(action)
1276                        << " [" << action << "] is disabled at this location");
1277                 dr.setMessage(flag.message());
1278                 dr.setError(true);
1279                 dr.dispatched(false);
1280                 dr.screenUpdate(Update::None);
1281                 dr.clearBufferUpdate();
1282                 return;
1283         };
1284
1285         // Assumes that the action will be dispatched.
1286         dr.dispatched(true);
1287
1288         switch (cmd.action()) {
1289
1290         case LFUN_WINDOW_NEW:
1291                 createView(toqstr(cmd.argument()));
1292                 break;
1293
1294         case LFUN_WINDOW_CLOSE:
1295                 // update bookmark pit of the current buffer before window close
1296                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1297                         gotoBookmark(i+1, false, false);
1298                 // clear the last opened list, because
1299                 // maybe this will end the session
1300                 theSession().lastOpened().clear();
1301                 // check for valid current_view_
1302                 validateCurrentView();
1303                 if (current_view_)
1304                         current_view_->closeScheduled();
1305                 break;
1306
1307         case LFUN_LYX_QUIT:
1308                 // quitting is triggered by the gui code
1309                 // (leaving the event loop).
1310                 if (current_view_)
1311                         current_view_->message(from_utf8(N_("Exiting.")));
1312                 if (closeAllViews())
1313                         quit();
1314                 break;
1315
1316         case LFUN_SCREEN_FONT_UPDATE: {
1317                 // handle the screen font changes.
1318                 d->font_loader_.update();
1319                 // Backup current_view_
1320                 GuiView * view = current_view_;
1321                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1322                 // to skip the refresh.
1323                 current_view_ = 0;
1324                 theBufferList().changed(false);
1325                 // Restore current_view_
1326                 current_view_ = view;
1327                 break;
1328         }
1329
1330         case LFUN_BUFFER_NEW:
1331                 validateCurrentView();
1332                 if (d->views_.empty()
1333                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1334                         createView(QString(), false); // keep hidden
1335                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1336                         current_view_->show();
1337                         setActiveWindow(current_view_);
1338                 } else {
1339                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1340                 }
1341                 break;
1342
1343         case LFUN_BUFFER_NEW_TEMPLATE:
1344                 validateCurrentView();
1345                 if (d->views_.empty()
1346                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1347                         createView();
1348                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1349                         if (!current_view_->documentBufferView())
1350                                 current_view_->close();
1351                 } else {
1352                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1353                 }
1354                 break;
1355
1356         case LFUN_FILE_OPEN: {
1357                 validateCurrentView();
1358                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1359                 string const fname = to_utf8(cmd.argument());
1360                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1361                           && current_view_->documentBufferView() != 0)) {
1362                         // We want the ui session to be saved per document and not per
1363                         // window number. The filename crc is a good enough identifier.
1364                         boost::crc_32_type crc;
1365                         crc = for_each(fname.begin(), fname.end(), crc);
1366                         createView(crc.checksum());
1367                         current_view_->openDocument(fname);
1368                         if (current_view_ && !current_view_->documentBufferView())
1369                                 current_view_->close();
1370                 } else
1371                         current_view_->openDocument(fname);
1372                 break;
1373         }
1374
1375         case LFUN_HELP_OPEN: {
1376                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1377                 if (current_view_ == 0)
1378                         createView();
1379                 string const arg = to_utf8(cmd.argument());
1380                 if (arg.empty()) {
1381                         current_view_->message(_("Missing argument"));
1382                         break;
1383                 }
1384                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1385                 if (fname.empty())
1386                         fname = i18nLibFileSearch("examples", arg, "lyx");
1387
1388                 if (fname.empty()) {
1389                         lyxerr << "LyX: unable to find documentation file `"
1390                                << arg << "'. Bad installation?" << endl;
1391                         break;
1392                 }
1393                 current_view_->message(bformat(_("Opening help file %1$s..."),
1394                                                makeDisplayPath(fname.absFileName())));
1395                 Buffer * buf = current_view_->loadDocument(fname, false);
1396
1397 #ifndef DEVEL_VERSION
1398                 if (buf)
1399                         buf->setReadonly(true);
1400 #else
1401                 (void) buf;
1402 #endif
1403                 break;
1404         }
1405
1406         case LFUN_SET_COLOR: {
1407                 string lyx_name;
1408                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1409                 if (lyx_name.empty() || x11_name.empty()) {
1410                         if (current_view_)
1411                                 current_view_->message(
1412                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1413                         break;
1414                 }
1415
1416 #if 0
1417                 // FIXME: The graphics cache no longer has a changeDisplay method.
1418                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1419                 bool const graphicsbg_changed =
1420                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1421                 if (graphicsbg_changed)
1422                         graphics::GCache::get().changeDisplay(true);
1423 #endif
1424
1425                 if (!lcolor.setColor(lyx_name, x11_name)) {
1426                         if (current_view_)
1427                                 current_view_->message(
1428                                         bformat(_("Set-color \"%1$s\" failed "
1429                                         "- color is undefined or "
1430                                         "may not be redefined"),
1431                                         from_utf8(lyx_name)));
1432                         break;
1433                 }
1434                 // Make sure we don't keep old colors in cache.
1435                 d->color_cache_.clear();
1436                 break;
1437         }
1438
1439         case LFUN_LYXRC_APPLY: {
1440                 // reset active key sequences, since the bindings
1441                 // are updated (bug 6064)
1442                 d->keyseq.reset();
1443                 LyXRC const lyxrc_orig = lyxrc;
1444
1445                 istringstream ss(to_utf8(cmd.argument()));
1446                 bool const success = lyxrc.read(ss);
1447
1448                 if (!success) {
1449                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1450                                         << "Unable to read lyxrc data"
1451                                         << endl;
1452                         break;
1453                 }
1454
1455                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1456                 setSpellChecker();
1457                 resetGui();
1458
1459                 break;
1460         }
1461
1462         case LFUN_COMMAND_PREFIX:
1463                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1464                 break;
1465
1466         case LFUN_CANCEL: {
1467                 d->keyseq.reset();
1468                 d->meta_fake_bit = NoModifier;
1469                 GuiView * gv = currentView();
1470                 if (gv && gv->currentBufferView())
1471                         // cancel any selection
1472                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1473                 dr.setMessage(from_ascii(N_("Cancel")));
1474                 break;
1475         }
1476         case LFUN_META_PREFIX:
1477                 d->meta_fake_bit = AltModifier;
1478                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1479                 break;
1480
1481         // --- Menus -----------------------------------------------
1482         case LFUN_RECONFIGURE:
1483                 // argument is any additional parameter to the configure.py command
1484                 reconfigure(to_utf8(cmd.argument()));
1485                 break;
1486
1487         // --- lyxserver commands ----------------------------
1488         case LFUN_SERVER_GET_FILENAME: {
1489                 if (current_view_ && current_view_->documentBufferView()) {
1490                         docstring const fname = from_utf8(
1491                                 current_view_->documentBufferView()->buffer().absFileName());
1492                         dr.setMessage(fname);
1493                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1494                 } else {
1495                         dr.setMessage(docstring());
1496                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1497                 }
1498                 break;
1499         }
1500
1501         case LFUN_SERVER_NOTIFY: {
1502                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1503                 dr.setMessage(dispatch_buffer);
1504                 theServer().notifyClient(to_utf8(dispatch_buffer));
1505                 break;
1506         }
1507
1508         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1509                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1510                 break;
1511
1512         case LFUN_REPEAT: {
1513                 // repeat command
1514                 string countstr;
1515                 string rest = split(argument, countstr, ' ');
1516                 istringstream is(countstr);
1517                 int count = 0;
1518                 is >> count;
1519                 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1520                 for (int i = 0; i < count; ++i)
1521                         dispatch(lyxaction.lookupFunc(rest));
1522                 break;
1523         }
1524
1525         case LFUN_COMMAND_SEQUENCE: {
1526                 // argument contains ';'-terminated commands
1527                 string arg = argument;
1528                 // FIXME: this LFUN should also work without any view.
1529                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1530                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1531                 if (buffer)
1532                         buffer->undo().beginUndoGroup();
1533                 while (!arg.empty()) {
1534                         string first;
1535                         arg = split(arg, first, ';');
1536                         FuncRequest func(lyxaction.lookupFunc(first));
1537                         func.setOrigin(cmd.origin());
1538                         dispatch(func);
1539                 }
1540                 // the buffer may have been closed by one action
1541                 if (theBufferList().isLoaded(buffer))
1542                         buffer->undo().endUndoGroup();
1543                 break;
1544         }
1545
1546         case LFUN_COMMAND_ALTERNATIVES: {
1547                 // argument contains ';'-terminated commands
1548                 string arg = argument;
1549                 while (!arg.empty()) {
1550                         string first;
1551                         arg = split(arg, first, ';');
1552                         FuncRequest func(lyxaction.lookupFunc(first));
1553                         func.setOrigin(cmd.origin());
1554                         FuncStatus const stat = getStatus(func);
1555                         if (stat.enabled()) {
1556                                 dispatch(func);
1557                                 break;
1558                         }
1559                 }
1560                 break;
1561         }
1562
1563         case LFUN_CALL: {
1564                 FuncRequest func;
1565                 if (theTopLevelCmdDef().lock(argument, func)) {
1566                         func.setOrigin(cmd.origin());
1567                         dispatch(func);
1568                         theTopLevelCmdDef().release(argument);
1569                 } else {
1570                         if (func.action() == LFUN_UNKNOWN_ACTION) {
1571                                 // unknown command definition
1572                                 lyxerr << "Warning: unknown command definition `"
1573                                                 << argument << "'"
1574                                                 << endl;
1575                         } else {
1576                                 // recursion detected
1577                                 lyxerr << "Warning: Recursion in the command definition `"
1578                                                 << argument << "' detected"
1579                                                 << endl;
1580                         }
1581                 }
1582                 break;
1583         }
1584
1585         case LFUN_PREFERENCES_SAVE:
1586                 lyxrc.write(support::makeAbsPath("preferences",
1587                         package().user_support().absFileName()), false);
1588                 break;
1589
1590         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1591                 string const fname = addName(addPath(package().user_support().absFileName(),
1592                         "templates/"), "defaults.lyx");
1593                 Buffer defaults(fname);
1594
1595                 istringstream ss(argument);
1596                 Lexer lex;
1597                 lex.setStream(ss);
1598                 int const unknown_tokens = defaults.readHeader(lex);
1599
1600                 if (unknown_tokens != 0) {
1601                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1602                                << unknown_tokens << " unknown token"
1603                                << (unknown_tokens == 1 ? "" : "s")
1604                                << endl;
1605                 }
1606
1607                 if (defaults.writeFile(FileName(defaults.absFileName())))
1608                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1609                                               makeDisplayPath(fname)));
1610                 else {
1611                         dr.setError(true);
1612                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1613                 }
1614                 break;
1615         }
1616
1617         case LFUN_BOOKMARK_GOTO:
1618                 // go to bookmark, open unopened file and switch to buffer if necessary
1619                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1620                 dr.screenUpdate(Update::Force | Update::FitCursor);
1621                 break;
1622
1623         case LFUN_BOOKMARK_CLEAR:
1624                 theSession().bookmarks().clear();
1625                 break;
1626
1627         case LFUN_DEBUG_LEVEL_SET:
1628                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1629                 break;
1630
1631         default:
1632                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1633                 // let's try that:
1634                 if (current_view_)
1635                         current_view_->dispatch(cmd, dr);
1636                 break;
1637         }
1638 }
1639
1640
1641 docstring GuiApplication::viewStatusMessage()
1642 {
1643         // When meta-fake key is pressed, show the key sequence so far + "M-".
1644         if (d->meta_fake_bit != NoModifier)
1645                 return d->keyseq.print(KeySequence::ForGui) + "M-";
1646
1647         // Else, when a non-complete key sequence is pressed,
1648         // show the available options.
1649         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1650                 return d->keyseq.printOptions(true);
1651
1652         return docstring();
1653 }
1654
1655
1656 void GuiApplication::handleKeyFunc(FuncCode action)
1657 {
1658         char_type c = 0;
1659
1660         if (d->keyseq.length())
1661                 c = 0;
1662         GuiView * gv = currentView();
1663         LASSERT(gv && gv->currentBufferView(), return);
1664         BufferView * bv = gv->currentBufferView();
1665         bv->getIntl().getTransManager().deadkey(
1666                 c, get_accent(action).accent, bv->cursor().innerText(),
1667                 bv->cursor());
1668         // Need to clear, in case the minibuffer calls these
1669         // actions
1670         d->keyseq.clear();
1671         // copied verbatim from do_accent_char
1672         bv->cursor().resetAnchor();
1673 }
1674
1675
1676 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1677 {
1678         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1679
1680         // Do nothing if we have nothing (JMarc)
1681         if (!keysym.isOK()) {
1682                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1683                 if (current_view_)
1684                         current_view_->restartCursor();
1685                 return;
1686         }
1687
1688         if (keysym.isModifier()) {
1689                 if (current_view_)
1690                         current_view_->restartCursor();
1691                 return;
1692         }
1693
1694         char_type encoded_last_key = keysym.getUCSEncoded();
1695
1696         // Do a one-deep top-level lookup for
1697         // cancel and meta-fake keys. RVDK_PATCH_5
1698         d->cancel_meta_seq.reset();
1699
1700         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1701         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1702
1703         // When not cancel or meta-fake, do the normal lookup.
1704         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1705         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1706         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1707                 // remove Caps Lock and Mod2 as a modifiers
1708                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1709                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1710         }
1711
1712         // Dont remove this unless you know what you are doing.
1713         d->meta_fake_bit = NoModifier;
1714
1715         // Can this happen now ?
1716         if (func.action() == LFUN_NOACTION)
1717                 func = FuncRequest(LFUN_COMMAND_PREFIX);
1718
1719         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1720                 << d->keyseq.print(KeySequence::Portable) << ']');
1721
1722         // already here we know if it any point in going further
1723         // why not return already here if action == -1 and
1724         // num_bytes == 0? (Lgb)
1725
1726         if (d->keyseq.length() > 1 && current_view_)
1727                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1728
1729
1730         // Maybe user can only reach the key via holding down shift.
1731         // Let's see. But only if shift is the only modifier
1732         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1733                 LYXERR(Debug::KEY, "Trying without shift");
1734                 func = d->keyseq.addkey(keysym, NoModifier);
1735                 LYXERR(Debug::KEY, "Action now " << func.action());
1736         }
1737
1738         if (func.action() == LFUN_UNKNOWN_ACTION) {
1739                 // Hmm, we didn't match any of the keysequences. See
1740                 // if it's normal insertable text not already covered
1741                 // by a binding
1742                 if (keysym.isText() && d->keyseq.length() == 1) {
1743                         LYXERR(Debug::KEY, "isText() is true, inserting.");
1744                         func = FuncRequest(LFUN_SELF_INSERT,
1745                                            FuncRequest::KEYBOARD);
1746                 } else {
1747                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1748                         if (current_view_) {
1749                                 current_view_->message(_("Unknown function."));
1750                                 current_view_->restartCursor();
1751                         }
1752                         return;
1753                 }
1754         }
1755
1756         if (func.action() == LFUN_SELF_INSERT) {
1757                 if (encoded_last_key != 0) {
1758                         docstring const arg(1, encoded_last_key);
1759                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1760                                              FuncRequest::KEYBOARD));
1761                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1762                 }
1763         } else
1764                 processFuncRequest(func);
1765 }
1766
1767
1768 void GuiApplication::processFuncRequest(FuncRequest const & func)
1769 {
1770         lyx::dispatch(func);
1771 }
1772
1773
1774 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1775 {
1776         addToFuncRequestQueue(func);
1777         processFuncRequestQueueAsync();
1778 }
1779
1780
1781 void GuiApplication::processFuncRequestQueue()
1782 {
1783         while (!d->func_request_queue_.empty()) {
1784                 processFuncRequest(d->func_request_queue_.front());
1785                 d->func_request_queue_.pop();
1786         }
1787 }
1788
1789
1790 void GuiApplication::processFuncRequestQueueAsync()
1791 {
1792         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1793 }
1794
1795
1796 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1797 {
1798         d->func_request_queue_.push(func);
1799 }
1800
1801
1802 void GuiApplication::resetGui()
1803 {
1804         // Set the language defined by the user.
1805         setGuiLanguage();
1806
1807         // Read menus
1808         if (!readUIFile(toqstr(lyxrc.ui_file)))
1809                 // Gives some error box here.
1810                 return;
1811
1812         if (d->global_menubar_)
1813                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1814
1815         QHash<int, GuiView *>::iterator it;
1816         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1817                 GuiView * gv = *it;
1818                 setCurrentView(gv);
1819                 gv->setLayoutDirection(layoutDirection());
1820                 gv->resetDialogs();
1821         }
1822
1823         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1824 }
1825
1826
1827 void GuiApplication::createView(int view_id)
1828 {
1829         createView(QString(), true, view_id);
1830 }
1831
1832
1833 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1834         int view_id)
1835 {
1836         // release the keyboard which might have been grabed by the global
1837         // menubar on Mac to catch shortcuts even without any GuiView.
1838         if (d->global_menubar_)
1839                 d->global_menubar_->releaseKeyboard();
1840
1841         // create new view
1842         int id = view_id;
1843         while (d->views_.find(id) != d->views_.end())
1844                 id++;
1845
1846         LYXERR(Debug::GUI, "About to create new window with ID " << id);
1847         GuiView * view = new GuiView(id);
1848         // register view
1849         d->views_[id] = view;
1850
1851         if (autoShow) {
1852                 view->show();
1853                 setActiveWindow(view);
1854         }
1855
1856         if (!geometry_arg.isEmpty()) {
1857 #ifdef Q_WS_WIN
1858                 int x, y;
1859                 int w, h;
1860                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1861                 re.indexIn(geometry_arg);
1862                 w = re.cap(1).toInt();
1863                 h = re.cap(2).toInt();
1864                 x = re.cap(3).toInt();
1865                 y = re.cap(4).toInt();
1866                 view->setGeometry(x, y, w, h);
1867 #endif
1868         }
1869         view->setFocus();
1870 }
1871
1872
1873 Clipboard & GuiApplication::clipboard()
1874 {
1875         return d->clipboard_;
1876 }
1877
1878
1879 Selection & GuiApplication::selection()
1880 {
1881         return d->selection_;
1882 }
1883
1884
1885 FontLoader & GuiApplication::fontLoader()
1886 {
1887         return d->font_loader_;
1888 }
1889
1890
1891 Toolbars const & GuiApplication::toolbars() const
1892 {
1893         return d->toolbars_;
1894 }
1895
1896
1897 Toolbars & GuiApplication::toolbars()
1898 {
1899         return d->toolbars_;
1900 }
1901
1902
1903 Menus const & GuiApplication::menus() const
1904 {
1905         return d->menus_;
1906 }
1907
1908
1909 Menus & GuiApplication::menus()
1910 {
1911         return d->menus_;
1912 }
1913
1914
1915 QList<int> GuiApplication::viewIds() const
1916 {
1917         return d->views_.keys();
1918 }
1919
1920
1921 ColorCache & GuiApplication::colorCache()
1922 {
1923         return d->color_cache_;
1924 }
1925
1926
1927 int GuiApplication::exec()
1928 {
1929         // asynchronously handle batch commands. This event will be in
1930         // the event queue in front of other asynchronous events. Hence,
1931         // we can assume in the latter that the gui is setup already.
1932         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1933
1934         return QApplication::exec();
1935 }
1936
1937
1938 void GuiApplication::exit(int status)
1939 {
1940         QApplication::exit(status);
1941 }
1942
1943
1944 void GuiApplication::setGuiLanguage()
1945 {
1946         // Set the language defined by the user.
1947         setRcGuiLanguage();
1948
1949         QString const default_language = toqstr(Messages::defaultLanguage());
1950         LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1951         QLocale const default_locale(default_language);
1952         QLocale::setDefault(default_locale);
1953
1954         // install translation file for Qt built-in dialogs
1955         QString const language_name = QString("qt_") + default_locale.name();
1956
1957         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1958         // Short-named translator can be loaded from a long name, but not the
1959         // opposite. Therefore, long name should be used without truncation.
1960         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1961         if (!d->qt_trans_.load(language_name,
1962                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1963                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1964                         << language_name);
1965         } else {
1966                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1967                         << language_name);
1968         }
1969
1970         switch (default_locale.language()) {
1971         case QLocale::Arabic :
1972         case QLocale::Hebrew :
1973         case QLocale::Persian :
1974         case QLocale::Urdu :
1975                 setLayoutDirection(Qt::RightToLeft);
1976                 break;
1977         default:
1978                 setLayoutDirection(Qt::LeftToRight);
1979         }
1980 }
1981
1982
1983 void GuiApplication::execBatchCommands()
1984 {
1985         setGuiLanguage();
1986
1987         // Read menus
1988         if (!readUIFile(toqstr(lyxrc.ui_file)))
1989                 // Gives some error box here.
1990                 return;
1991
1992 #ifdef Q_WS_MACX
1993 #if QT_VERSION > 0x040600
1994         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
1995 #endif
1996         // Create the global default menubar which is shown for the dialogs
1997         // and if no GuiView is visible.
1998         // This must be done after the session was recovered to know the "last files".
1999         d->global_menubar_ = new GlobalMenuBar();
2000         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2001 #endif
2002
2003         lyx::execBatchCommands();
2004 }
2005
2006
2007 QAbstractItemModel * GuiApplication::languageModel()
2008 {
2009         if (d->language_model_)
2010                 return d->language_model_;
2011
2012         QStandardItemModel * lang_model = new QStandardItemModel(this);
2013         lang_model->insertColumns(0, 3);
2014         int current_row;
2015         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2016         QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2017         Languages::const_iterator it = lyx::languages.begin();
2018         Languages::const_iterator end = lyx::languages.end();
2019         for (; it != end; ++it) {
2020                 current_row = lang_model->rowCount();
2021                 lang_model->insertRows(current_row, 1);
2022                 QModelIndex pl_item = lang_model->index(current_row, 0);
2023                 QModelIndex sp_item = lang_model->index(current_row, 1);
2024                 QModelIndex th_item = lang_model->index(current_row, 2);
2025                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2026                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2027                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2028                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2029                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2030                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2031                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2032                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2033                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2034                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2035         }
2036         d->language_model_ = new QSortFilterProxyModel(this);
2037         d->language_model_->setSourceModel(lang_model);
2038 #if QT_VERSION >= 0x040300
2039         d->language_model_->setSortLocaleAware(true);
2040 #endif
2041         return d->language_model_;
2042 }
2043
2044
2045 void GuiApplication::restoreGuiSession()
2046 {
2047         if (!lyxrc.load_session)
2048                 return;
2049
2050         Session & session = theSession();
2051         LastOpenedSection::LastOpened const & lastopened =
2052                 session.lastOpened().getfiles();
2053
2054         validateCurrentView();
2055
2056         FileName active_file;
2057         // do not add to the lastfile list since these files are restored from
2058         // last session, and should be already there (regular files), or should
2059         // not be added at all (help files).
2060         for (size_t i = 0; i < lastopened.size(); ++i) {
2061                 FileName const & file_name = lastopened[i].file_name;
2062                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2063                           && current_view_->documentBufferView() != 0)) {
2064                         boost::crc_32_type crc;
2065                         string const & fname = file_name.absFileName();
2066                         crc = for_each(fname.begin(), fname.end(), crc);
2067                         createView(crc.checksum());
2068                 }
2069                 current_view_->loadDocument(file_name, false);
2070
2071                 if (lastopened[i].active)
2072                         active_file = file_name;
2073         }
2074
2075         // Restore last active buffer
2076         Buffer * buffer = theBufferList().getBuffer(active_file);
2077         if (buffer && current_view_)
2078                 current_view_->setBuffer(buffer);
2079
2080         // clear this list to save a few bytes of RAM
2081         session.lastOpened().clear();
2082 }
2083
2084
2085 QString const GuiApplication::romanFontName()
2086 {
2087         QFont font;
2088         font.setKerning(false);
2089         font.setStyleHint(QFont::Serif);
2090         font.setFamily("serif");
2091
2092         return QFontInfo(font).family();
2093 }
2094
2095
2096 QString const GuiApplication::sansFontName()
2097 {
2098         QFont font;
2099         font.setKerning(false);
2100         font.setStyleHint(QFont::SansSerif);
2101         font.setFamily("sans");
2102
2103         return QFontInfo(font).family();
2104 }
2105
2106
2107 QString const GuiApplication::typewriterFontName()
2108 {
2109         QFont font;
2110         font.setKerning(false);
2111         font.setStyleHint(QFont::TypeWriter);
2112         font.setFamily("monospace");
2113
2114         return QFontInfo(font).family();
2115 }
2116
2117
2118 void GuiApplication::handleRegularEvents()
2119 {
2120         ForkedCallsController::handleCompletedProcesses();
2121 }
2122
2123
2124 bool GuiApplication::event(QEvent * e)
2125 {
2126         switch(e->type()) {
2127         case QEvent::FileOpen: {
2128                 // Open a file; this happens only on Mac OS X for now.
2129                 //
2130                 // We do this asynchronously because on startup the batch
2131                 // commands are not executed here yet and the gui is not ready
2132                 // therefore.
2133                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2134                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2135                 processFuncRequestAsync(fr);
2136                 e->accept();
2137                 return true;
2138         }
2139         default:
2140                 return QApplication::event(e);
2141         }
2142 }
2143
2144
2145 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2146 {
2147         try {
2148                 return QApplication::notify(receiver, event);
2149         }
2150         catch (ExceptionMessage const & e) {
2151                 switch(e.type_) {
2152                 case ErrorException:
2153                         emergencyCleanup();
2154                         setQuitOnLastWindowClosed(false);
2155                         closeAllViews();
2156                         Alert::error(e.title_, e.details_);
2157 #ifndef NDEBUG
2158                         // Properly crash in debug mode in order to get a useful backtrace.
2159                         abort();
2160 #endif
2161                         // In release mode, try to exit gracefully.
2162                         this->exit(1);
2163
2164                 case BufferException: {
2165                         if (!current_view_ || !current_view_->documentBufferView())
2166                                 return false;
2167                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2168                         docstring details = e.details_ + '\n';
2169                         details += buf->emergencyWrite();
2170                         theBufferList().release(buf);
2171                         details += "\n" + _("The current document was closed.");
2172                         Alert::error(e.title_, details);
2173                         return false;
2174                 }
2175                 case WarningException:
2176                         Alert::warning(e.title_, e.details_);
2177                         return false;
2178                 }
2179         }
2180         catch (exception const & e) {
2181                 docstring s = _("LyX has caught an exception, it will now "
2182                         "attempt to save all unsaved documents and exit."
2183                         "\n\nException: ");
2184                 s += from_ascii(e.what());
2185                 Alert::error(_("Software exception Detected"), s);
2186                 lyx_exit(1);
2187         }
2188         catch (...) {
2189                 docstring s = _("LyX has caught some really weird exception, it will "
2190                         "now attempt to save all unsaved documents and exit.");
2191                 Alert::error(_("Software exception Detected"), s);
2192                 lyx_exit(1);
2193         }
2194
2195         return false;
2196 }
2197
2198
2199 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2200 {
2201         QColor const & qcol = d->color_cache_.get(col);
2202         if (!qcol.isValid()) {
2203                 rgbcol.r = 0;
2204                 rgbcol.g = 0;
2205                 rgbcol.b = 0;
2206                 return false;
2207         }
2208         rgbcol.r = qcol.red();
2209         rgbcol.g = qcol.green();
2210         rgbcol.b = qcol.blue();
2211         return true;
2212 }
2213
2214
2215 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2216 {
2217         QColor const qcol(lcolor.getX11Name(col).c_str());
2218         if (!qcol.isValid()) {
2219                 rgbcol.r = 0;
2220                 rgbcol.g = 0;
2221                 rgbcol.b = 0;
2222                 return false;
2223         }
2224         rgbcol.r = qcol.red();
2225         rgbcol.g = qcol.green();
2226         rgbcol.b = qcol.blue();
2227         return true;
2228 }
2229
2230
2231 string const GuiApplication::hexName(ColorCode col)
2232 {
2233         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2234 }
2235
2236
2237 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2238 {
2239         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2240         d->socket_notifiers_[fd] = sn;
2241         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2242 }
2243
2244
2245 void GuiApplication::socketDataReceived(int fd)
2246 {
2247         d->socket_notifiers_[fd]->func_();
2248 }
2249
2250
2251 void GuiApplication::unregisterSocketCallback(int fd)
2252 {
2253         d->socket_notifiers_.take(fd)->setEnabled(false);
2254 }
2255
2256
2257 void GuiApplication::commitData(QSessionManager & sm)
2258 {
2259         /// The implementation is required to avoid an application exit
2260         /// when session state save is triggered by session manager.
2261         /// The default implementation sends a close event to all
2262         /// visible top level widgets when session managment allows
2263         /// interaction.
2264         /// We are changing that to close all wiew one by one.
2265         /// FIXME: verify if the default implementation is enough now.
2266         #ifdef QT_NO_SESSIONMANAGER
2267                 #warning Qt is compiled without session manager
2268                 (void) sm;
2269         #else
2270                 if (sm.allowsInteraction() && !closeAllViews())
2271                         sm.cancel();
2272         #endif
2273 }
2274
2275
2276 void GuiApplication::unregisterView(GuiView * gv)
2277 {
2278         LASSERT(d->views_[gv->id()] == gv, /**/);
2279         d->views_.remove(gv->id());
2280         if (current_view_ == gv)
2281                 current_view_ = 0;
2282 }
2283
2284
2285 bool GuiApplication::closeAllViews()
2286 {
2287         if (d->views_.empty())
2288                 return true;
2289
2290         // When a view/window was closed before without quitting LyX, there
2291         // are already entries in the lastOpened list.
2292         theSession().lastOpened().clear();
2293
2294         QList<GuiView *> views = d->views_.values();
2295         foreach (GuiView * view, views) {
2296                 if (!view->closeScheduled())
2297                         return false;
2298         }
2299
2300         d->views_.clear();
2301         return true;
2302 }
2303
2304
2305 GuiView & GuiApplication::view(int id) const
2306 {
2307         LASSERT(d->views_.contains(id), /**/);
2308         return *d->views_.value(id);
2309 }
2310
2311
2312 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2313 {
2314         QList<GuiView *> views = d->views_.values();
2315         foreach (GuiView * view, views)
2316                 view->hideDialog(name, inset);
2317 }
2318
2319
2320 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2321 {
2322         Buffer const * buffer_ = 0;
2323         QHash<int, GuiView *>::iterator end = d->views_.end();
2324         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2325                 if (Buffer const * ptr = (*it)->updateInset(inset))
2326                         buffer_ = ptr;
2327         }
2328         return buffer_;
2329 }
2330
2331
2332 bool GuiApplication::searchMenu(FuncRequest const & func,
2333         docstring_list & names) const
2334 {
2335         return d->menus_.searchMenu(func, names);
2336 }
2337
2338
2339 // Ensure that a file is read only once (prevents include loops)
2340 static QStringList uifiles;
2341 // store which ui files define Toolbars
2342 static QStringList toolbar_uifiles;
2343
2344
2345 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2346 {
2347         enum {
2348                 ui_menuset = 1,
2349                 ui_toolbars,
2350                 ui_toolbarset,
2351                 ui_include,
2352                 ui_format,
2353                 ui_last
2354         };
2355
2356         LexerKeyword uitags[] = {
2357                 { "format", ui_format },
2358                 { "include", ui_include },
2359                 { "menuset", ui_menuset },
2360                 { "toolbars", ui_toolbars },
2361                 { "toolbarset", ui_toolbarset }
2362         };
2363
2364         Lexer lex(uitags);
2365         lex.setFile(ui_path);
2366         if (!lex.isOK()) {
2367                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2368                                          << endl;
2369         }
2370
2371         if (lyxerr.debugging(Debug::PARSER))
2372                 lex.printTable(lyxerr);
2373
2374         bool error = false;
2375         // format before introduction of format tag
2376         unsigned int format = 0;
2377         while (lex.isOK()) {
2378                 int const status = lex.lex();
2379
2380                 // we have to do this check here, outside the switch,
2381                 // because otherwise we would start reading include files,
2382                 // e.g., if the first tag we hit was an include tag.
2383                 if (status == ui_format)
2384                         if (lex.next()) {
2385                                 format = lex.getInteger();
2386                                 continue;
2387                         }
2388
2389                 // this will trigger unless the first tag we hit is a format
2390                 // tag, with the right format.
2391                 if (format != LFUN_FORMAT)
2392                         return FormatMismatch;
2393
2394                 switch (status) {
2395                 case Lexer::LEX_FEOF:
2396                         continue;
2397
2398                 case ui_include: {
2399                         lex.next(true);
2400                         QString const file = toqstr(lex.getString());
2401                         bool const success = readUIFile(file, true);
2402                         if (!success) {
2403                                 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2404                                 return ReadError;
2405                         }
2406                         break;
2407                 }
2408
2409                 case ui_menuset:
2410                         d->menus_.read(lex);
2411                         break;
2412
2413                 case ui_toolbarset:
2414                         d->toolbars_.readToolbars(lex);
2415                         break;
2416
2417                 case ui_toolbars:
2418                         d->toolbars_.readToolbarSettings(lex);
2419                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2420                         break;
2421
2422                 default:
2423                         if (!rtrim(lex.getString()).empty())
2424                                 lex.printError("LyX::ReadUIFile: "
2425                                                "Unknown menu tag: `$$Token'");
2426                         else
2427                                 LYXERR0("Error with status: " << status);
2428                         error = true;
2429                         break;
2430                 }
2431
2432         }
2433         return (error ? ReadError : ReadOK);
2434 }
2435
2436
2437 bool GuiApplication::readUIFile(QString const & name, bool include)
2438 {
2439         LYXERR(Debug::INIT, "About to read " << name << "...");
2440
2441         FileName ui_path;
2442         if (include) {
2443                 ui_path = libFileSearch("ui", name, "inc");
2444                 if (ui_path.empty())
2445                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2446         } else {
2447                 ui_path = libFileSearch("ui", name, "ui");
2448         }
2449
2450         if (ui_path.empty()) {
2451                 static const QString defaultUIFile = "default";
2452                 LYXERR(Debug::INIT, "Could not find " << name);
2453                 if (include) {
2454                         Alert::warning(_("Could not find UI definition file"),
2455                                 bformat(_("Error while reading the included file\n%1$s\n"
2456                                         "Please check your installation."), qstring_to_ucs4(name)));
2457                         return false;
2458                 }
2459                 if (name == defaultUIFile) {
2460                         LYXERR(Debug::INIT, "Could not find default UI file!!");
2461                         Alert::warning(_("Could not find default UI file"),
2462                                 _("LyX could not find the default UI file!\n"
2463                                   "Please check your installation."));
2464                         return false;
2465                 }
2466                 Alert::warning(_("Could not find UI definition file"),
2467                 bformat(_("Error while reading the configuration file\n%1$s\n"
2468                         "Falling back to default.\n"
2469                         "Please look under Tools>Preferences>User Interface and\n"
2470                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
2471                 return readUIFile(defaultUIFile, false);
2472         }
2473
2474         QString const uifile = toqstr(ui_path.absFileName());
2475         if (uifiles.contains(uifile)) {
2476                 if (!include) {
2477                         // We are reading again the top uifile so reset the safeguard:
2478                         uifiles.clear();
2479                         d->menus_.reset();
2480                         d->toolbars_.reset();
2481                 } else {
2482                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2483                                 << "Is this an include loop?");
2484                         return false;
2485                 }
2486         }
2487         uifiles.push_back(uifile);
2488
2489         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2490
2491         ReturnValues retval = readUIFile(ui_path);
2492
2493         if (retval == FormatMismatch) {
2494                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2495                 FileName const tempfile = FileName::tempName("convert_ui");
2496                 bool const success = prefs2prefs(ui_path, tempfile, true);
2497                 if (!success) {
2498                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
2499                                 " to format " << LFUN_FORMAT << ".");
2500                 } else {
2501                         retval = readUIFile(tempfile);
2502                         tempfile.removeFile();
2503                 }
2504         }
2505
2506         if (retval != ReadOK) {
2507                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2508                 return false;
2509         }
2510
2511         if (include)
2512                 return true;
2513
2514         QSettings settings;
2515         settings.beginGroup("ui_files");
2516         bool touched = false;
2517         for (int i = 0; i != uifiles.size(); ++i) {
2518                 QFileInfo fi(uifiles[i]);
2519                 QDateTime const date_value = fi.lastModified();
2520                 QString const name_key = QString::number(i);
2521                 // if an ui file which defines Toolbars has changed,
2522                 // we have to reset the settings
2523                 if (toolbar_uifiles.contains(uifiles[i])
2524                  && (!settings.contains(name_key)
2525                  || settings.value(name_key).toString() != uifiles[i]
2526                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
2527                         touched = true;
2528                         settings.setValue(name_key, uifiles[i]);
2529                         settings.setValue(name_key + "/date", date_value);
2530                 }
2531         }
2532         settings.endGroup();
2533         if (touched)
2534                 settings.remove("views");
2535
2536         return true;
2537 }
2538
2539
2540 void GuiApplication::onLastWindowClosed()
2541 {
2542         if (d->global_menubar_)
2543                 d->global_menubar_->grabKeyboard();
2544 }
2545
2546
2547 ////////////////////////////////////////////////////////////////////////
2548 //
2549 // X11 specific stuff goes here...
2550
2551 #ifdef Q_WS_X11
2552 bool GuiApplication::x11EventFilter(XEvent * xev)
2553 {
2554         if (!current_view_)
2555                 return false;
2556
2557         switch (xev->type) {
2558         case SelectionRequest: {
2559                 if (xev->xselectionrequest.selection != XA_PRIMARY)
2560                         break;
2561                 LYXERR(Debug::SELECTION, "X requested selection.");
2562                 BufferView * bv = current_view_->currentBufferView();
2563                 if (bv) {
2564                         docstring const sel = bv->requestSelection();
2565                         if (!sel.empty())
2566                                 d->selection_.put(sel);
2567                 }
2568                 break;
2569         }
2570         case SelectionClear: {
2571                 if (xev->xselectionclear.selection != XA_PRIMARY)
2572                         break;
2573                 LYXERR(Debug::SELECTION, "Lost selection.");
2574                 BufferView * bv = current_view_->currentBufferView();
2575                 if (bv)
2576                         bv->clearSelection();
2577                 break;
2578         }
2579         }
2580         return false;
2581 }
2582 #endif
2583
2584 } // namespace frontend
2585
2586
2587 void hideDialogs(std::string const & name, Inset * inset)
2588 {
2589         if (theApp())
2590                 frontend::guiApp->hideDialogs(name, inset);
2591 }
2592
2593
2594 ////////////////////////////////////////////////////////////////////
2595 //
2596 // Font stuff
2597 //
2598 ////////////////////////////////////////////////////////////////////
2599
2600 frontend::FontLoader & theFontLoader()
2601 {
2602         LASSERT(frontend::guiApp, /**/);
2603         return frontend::guiApp->fontLoader();
2604 }
2605
2606
2607 frontend::FontMetrics const & theFontMetrics(Font const & f)
2608 {
2609         return theFontMetrics(f.fontInfo());
2610 }
2611
2612
2613 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2614 {
2615         LASSERT(frontend::guiApp, /**/);
2616         return frontend::guiApp->fontLoader().metrics(f);
2617 }
2618
2619
2620 ////////////////////////////////////////////////////////////////////
2621 //
2622 // Misc stuff
2623 //
2624 ////////////////////////////////////////////////////////////////////
2625
2626 frontend::Clipboard & theClipboard()
2627 {
2628         LASSERT(frontend::guiApp, /**/);
2629         return frontend::guiApp->clipboard();
2630 }
2631
2632
2633 frontend::Selection & theSelection()
2634 {
2635         LASSERT(frontend::guiApp, /**/);
2636         return frontend::guiApp->selection();
2637 }
2638
2639
2640 } // namespace lyx
2641
2642 #include "moc_GuiApplication.cpp"