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