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