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