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