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