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