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