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