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