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