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