]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
fix #1983 (rest of #4606): add missing \var*** characters (gig Greek math letters)
[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                 if (dr.needBufferUpdate()) {
1108                         bv->cursor().clearBufferUpdate();
1109                         bv->buffer().updateBuffer();
1110                 }
1111                 // BufferView::update() updates the ViewMetricsInfo and
1112                 // also initializes the position cache for all insets in
1113                 // (at least partially) visible top-level paragraphs.
1114                 // We will redraw the screen only if needed.
1115                 bv->processUpdateFlags(dr.screenUpdate());
1116
1117                 // Do we have a selection?
1118                 theSelection().haveSelection(bv->cursor().selection());
1119
1120                 // update gui
1121                 current_view_->restartCursor();
1122         }
1123         if (dr.needMessageUpdate()) {
1124                 // Some messages may already be translated, so we cannot use _()
1125                 current_view_->message(makeDispatchMessage(
1126                                 translateIfPossible(dr.message()), cmd));
1127         }
1128 }
1129
1130
1131 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1132         bool switchToBuffer)
1133 {
1134         if (!theSession().bookmarks().isValid(idx))
1135                 return;
1136         BookmarksSection::Bookmark const & bm =
1137                 theSession().bookmarks().bookmark(idx);
1138         LASSERT(!bm.filename.empty(), /**/);
1139         string const file = bm.filename.absFileName();
1140         // if the file is not opened, open it.
1141         if (!theBufferList().exists(bm.filename)) {
1142                 if (openFile)
1143                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1144                 else
1145                         return;
1146         }
1147         // open may fail, so we need to test it again
1148         if (!theBufferList().exists(bm.filename))
1149                 return;
1150
1151         // bm can be changed when saving
1152         BookmarksSection::Bookmark tmp = bm;
1153
1154         // Special case idx == 0 used for back-from-back jump navigation
1155         if (idx == 0)
1156                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1157
1158         // if the current buffer is not that one, switch to it.
1159         BufferView * doc_bv = current_view_->documentBufferView();
1160         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1161                 if (switchToBuffer) {
1162                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1163                         doc_bv = current_view_->documentBufferView();
1164                 } else
1165                         return;
1166         }
1167
1168         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1169         if (!doc_bv->moveToPosition(
1170                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1171                 return;
1172
1173         // bm changed
1174         if (idx == 0)
1175                 return;
1176
1177         // Cursor jump succeeded!
1178         Cursor const & cur = doc_bv->cursor();
1179         pit_type new_pit = cur.pit();
1180         pos_type new_pos = cur.pos();
1181         int new_id = cur.paragraph().id();
1182
1183         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1184         // see http://www.lyx.org/trac/ticket/3092
1185         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1186                 || bm.top_id != new_id) {
1187                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1188                         new_pit, new_pos, new_id);
1189         }
1190 }
1191
1192 // This function runs "configure" and then rereads lyx.defaults to
1193 // reconfigure the automatic settings.
1194 void GuiApplication::reconfigure(string const & option)
1195 {
1196         // emit message signal.
1197         if (current_view_)
1198                 current_view_->message(_("Running configure..."));
1199
1200         // Run configure in user lyx directory
1201         PathChanger p(package().user_support());
1202         string configure_command = package().configure_command();
1203         configure_command += option;
1204         Systemcall one;
1205         int ret = one.startscript(Systemcall::Wait, configure_command);
1206         p.pop();
1207         // emit message signal.
1208         if (current_view_)
1209                 current_view_->message(_("Reloading configuration..."));
1210         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1211         // Re-read packages.lst
1212         LaTeXFeatures::getAvailable();
1213
1214         if (ret)
1215                 Alert::information(_("System reconfiguration failed"),
1216                            _("The system reconfiguration has failed.\n"
1217                                   "Default textclass is used but LyX may "
1218                                   "not be able to work properly.\n"
1219                                   "Please reconfigure again if needed."));
1220         else
1221                 Alert::information(_("System reconfigured"),
1222                            _("The system has been reconfigured.\n"
1223                              "You need to restart LyX to make use of any\n"
1224                              "updated document class specifications."));
1225 }
1226
1227
1228 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1229 {
1230         string const argument = to_utf8(cmd.argument());
1231         FuncCode const action = cmd.action();
1232
1233         LYXERR(Debug::ACTION, "cmd: " << cmd);
1234
1235         // we have not done anything wrong yet.
1236         dr.setError(false);
1237
1238         FuncStatus const flag = getStatus(cmd);
1239         if (!flag.enabled()) {
1240                 // We cannot use this function here
1241                 LYXERR(Debug::ACTION, "action "
1242                        << lyxaction.getActionName(action)
1243                        << " [" << action << "] is disabled at this location");
1244                 if (current_view_)
1245                         current_view_->restartCursor();
1246                 dr.setMessage(flag.message());
1247                 dr.setError(true);
1248                 dr.dispatched(false);
1249                 dr.screenUpdate(Update::None);
1250                 dr.clearBufferUpdate();
1251                 return;
1252         };
1253
1254         // Assumes that the action will be dispatched.
1255         dr.dispatched(true);
1256
1257         switch (cmd.action()) {
1258
1259         case LFUN_WINDOW_NEW:
1260                 createView(toqstr(cmd.argument()));
1261                 break;
1262
1263         case LFUN_WINDOW_CLOSE:
1264                 // update bookmark pit of the current buffer before window close
1265                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1266                         gotoBookmark(i+1, false, false);
1267                 // clear the last opened list, because
1268                 // maybe this will end the session
1269                 theSession().lastOpened().clear();
1270                 current_view_->closeScheduled();
1271                 break;
1272
1273         case LFUN_LYX_QUIT:
1274                 // quitting is triggered by the gui code
1275                 // (leaving the event loop).
1276                 if (current_view_)
1277                         current_view_->message(from_utf8(N_("Exiting.")));
1278                 if (closeAllViews())
1279                         quit();
1280                 break;
1281
1282         case LFUN_SCREEN_FONT_UPDATE: {
1283                 // handle the screen font changes.
1284                 d->font_loader_.update();
1285                 // Backup current_view_
1286                 GuiView * view = current_view_;
1287                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1288                 // to skip the refresh.
1289                 current_view_ = 0;
1290                 theBufferList().changed(false);
1291                 // Restore current_view_
1292                 current_view_ = view;
1293                 break;
1294         }
1295
1296         case LFUN_BUFFER_NEW:
1297                 if (d->views_.empty()
1298                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1299                         createView(QString(), false); // keep hidden
1300                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1301                         current_view_->show();
1302                         setActiveWindow(current_view_);
1303                 } else {
1304                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1305                 }
1306                 break;
1307
1308         case LFUN_BUFFER_NEW_TEMPLATE:
1309                 if (d->views_.empty()
1310                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1311                         createView();
1312                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1313                         if (!current_view_->documentBufferView())
1314                                 current_view_->close();
1315                 } else {
1316                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1317                 }
1318                 break;
1319
1320         case LFUN_FILE_OPEN: {
1321                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1322                 string const fname = to_utf8(cmd.argument());
1323                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs 
1324                           && current_view_->documentBufferView() != 0)) {
1325                         // We want the ui session to be saved per document and not per
1326                         // window number. The filename crc is a good enough identifier.
1327                         boost::crc_32_type crc;
1328                         crc = for_each(fname.begin(), fname.end(), crc);
1329                         createView(crc.checksum());
1330                         current_view_->openDocument(fname);
1331                         if (current_view_ && !current_view_->documentBufferView())
1332                                 current_view_->close();
1333                 } else
1334                         current_view_->openDocument(fname);
1335                 break;
1336         }
1337
1338         case LFUN_HELP_OPEN: {
1339                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1340                 if (current_view_ == 0)
1341                         createView();
1342                 string const arg = to_utf8(cmd.argument());
1343                 if (arg.empty()) {
1344                         current_view_->message(_("Missing argument"));
1345                         break;
1346                 }
1347                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1348                 if (fname.empty())
1349                         fname = i18nLibFileSearch("examples", arg, "lyx");
1350
1351                 if (fname.empty()) {
1352                         lyxerr << "LyX: unable to find documentation file `"
1353                                << arg << "'. Bad installation?" << endl;
1354                         break;
1355                 }
1356                 current_view_->message(bformat(_("Opening help file %1$s..."),
1357                                                makeDisplayPath(fname.absFileName())));
1358                 Buffer * buf = current_view_->loadDocument(fname, false);
1359
1360 #ifndef DEVEL_VERSION
1361                 if (buf)
1362                         buf->setReadonly(true);
1363 #else
1364                 (void) buf;
1365 #endif
1366                 break;
1367         }
1368
1369         case LFUN_SET_COLOR: {
1370                 string lyx_name;
1371                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1372                 if (lyx_name.empty() || x11_name.empty()) {
1373                         if (current_view_)
1374                                 current_view_->message(
1375                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1376                         break;
1377                 }
1378
1379                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1380                 bool const graphicsbg_changed = 
1381                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1382                 if (graphicsbg_changed) {
1383                         // FIXME: The graphics cache no longer has a changeDisplay method.
1384 #if 0
1385                         graphics::GCache::get().changeDisplay(true);
1386 #endif
1387                 }
1388
1389                 if (!lcolor.setColor(lyx_name, x11_name)) {
1390                         current_view_->message(
1391                                 bformat(_("Set-color \"%1$s\" failed "
1392                                         "- color is undefined or "
1393                                         "may not be redefined"),
1394                                         from_utf8(lyx_name)));
1395                         break;
1396                 }
1397                 // Make sure we don't keep old colors in cache.
1398                 d->color_cache_.clear();
1399                 break;
1400         }
1401
1402         case LFUN_LYXRC_APPLY: {
1403                 // reset active key sequences, since the bindings
1404                 // are updated (bug 6064)
1405                 d->keyseq.reset();
1406                 LyXRC const lyxrc_orig = lyxrc;
1407
1408                 istringstream ss(to_utf8(cmd.argument()));
1409                 bool const success = lyxrc.read(ss) == 0;
1410
1411                 if (!success) {
1412                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1413                                         << "Unable to read lyxrc data"
1414                                         << endl;
1415                         break;
1416                 }
1417
1418                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1419                 setSpellChecker();
1420                 resetGui();
1421
1422                 break;
1423         }
1424
1425         case LFUN_COMMAND_PREFIX:
1426                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1427                 break;
1428
1429         case LFUN_CANCEL: {
1430                 d->keyseq.reset();
1431                 d->meta_fake_bit = NoModifier;
1432                 GuiView * gv = currentView();
1433                 if (gv && gv->currentBufferView())
1434                         // cancel any selection
1435                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1436                 dr.setMessage(from_ascii(N_("Cancel")));
1437                 break;
1438         }
1439         case LFUN_META_PREFIX:
1440                 d->meta_fake_bit = AltModifier;
1441                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1442                 break;
1443
1444         // --- Menus -----------------------------------------------
1445         case LFUN_RECONFIGURE:
1446                 // argument is any additional parameter to the configure.py command
1447                 reconfigure(to_utf8(cmd.argument()));
1448                 break;
1449
1450         // --- lyxserver commands ----------------------------
1451         case LFUN_SERVER_GET_FILENAME: {
1452                 LASSERT(current_view_ && current_view_->documentBufferView(), return);
1453                 docstring const fname = from_utf8(
1454                                 current_view_->documentBufferView()->buffer().absFileName());
1455                 dr.setMessage(fname);
1456                 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1457                 break;
1458         }
1459         case LFUN_SERVER_NOTIFY: {
1460                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1461                 dr.setMessage(dispatch_buffer);
1462                 theServer().notifyClient(to_utf8(dispatch_buffer));
1463                 break;
1464         }
1465
1466         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1467                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1468                 break;
1469
1470         case LFUN_REPEAT: {
1471                 // repeat command
1472                 string countstr;
1473                 string rest = split(argument, countstr, ' ');
1474                 istringstream is(countstr);
1475                 int count = 0;
1476                 is >> count;
1477                 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1478                 for (int i = 0; i < count; ++i)
1479                         dispatch(lyxaction.lookupFunc(rest));
1480                 break;
1481         }
1482
1483         case LFUN_COMMAND_SEQUENCE: {
1484                 // argument contains ';'-terminated commands
1485                 string arg = argument;
1486                 // FIXME: this LFUN should also work without any view.
1487                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1488                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1489                 if (buffer)
1490                         buffer->undo().beginUndoGroup();
1491                 while (!arg.empty()) {
1492                         string first;
1493                         arg = split(arg, first, ';');
1494                         FuncRequest func(lyxaction.lookupFunc(first));
1495                         func.setOrigin(cmd.origin());
1496                         dispatch(func);
1497                 }
1498                 // the buffer may have been closed by one action
1499                 if (theBufferList().isLoaded(buffer))
1500                         buffer->undo().endUndoGroup();
1501                 break;
1502         }
1503
1504         case LFUN_COMMAND_ALTERNATIVES: {
1505                 // argument contains ';'-terminated commands
1506                 string arg = argument;
1507                 while (!arg.empty()) {
1508                         string first;
1509                         arg = split(arg, first, ';');
1510                         FuncRequest func(lyxaction.lookupFunc(first));
1511                         func.setOrigin(cmd.origin());
1512                         FuncStatus const stat = getStatus(func);
1513                         if (stat.enabled()) {
1514                                 dispatch(func);
1515                                 break;
1516                         }
1517                 }
1518                 break;
1519         }
1520
1521         case LFUN_CALL: {
1522                 FuncRequest func;
1523                 if (theTopLevelCmdDef().lock(argument, func)) {
1524                         func.setOrigin(cmd.origin());
1525                         dispatch(func);
1526                         theTopLevelCmdDef().release(argument);
1527                 } else {
1528                         if (func.action() == LFUN_UNKNOWN_ACTION) {
1529                                 // unknown command definition
1530                                 lyxerr << "Warning: unknown command definition `"
1531                                                 << argument << "'"
1532                                                 << endl;
1533                         } else {
1534                                 // recursion detected
1535                                 lyxerr << "Warning: Recursion in the command definition `"
1536                                                 << argument << "' detected"
1537                                                 << endl;
1538                         }
1539                 }
1540                 break;
1541         }
1542
1543         case LFUN_PREFERENCES_SAVE:
1544                 lyxrc.write(support::makeAbsPath("preferences",
1545                         package().user_support().absFileName()), false);
1546                 break;
1547
1548         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1549                 string const fname = addName(addPath(package().user_support().absFileName(),
1550                         "templates/"), "defaults.lyx");
1551                 Buffer defaults(fname);
1552
1553                 istringstream ss(argument);
1554                 Lexer lex;
1555                 lex.setStream(ss);
1556                 int const unknown_tokens = defaults.readHeader(lex);
1557
1558                 if (unknown_tokens != 0) {
1559                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1560                                << unknown_tokens << " unknown token"
1561                                << (unknown_tokens == 1 ? "" : "s")
1562                                << endl;
1563                 }
1564
1565                 if (defaults.writeFile(FileName(defaults.absFileName())))
1566                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1567                                               makeDisplayPath(fname)));
1568                 else {
1569                         dr.setError(true);
1570                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1571                 }
1572                 break;
1573         }
1574
1575         case LFUN_BOOKMARK_GOTO:
1576                 // go to bookmark, open unopened file and switch to buffer if necessary
1577                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1578                 dr.screenUpdate(Update::Force | Update::FitCursor);
1579                 break;
1580
1581         case LFUN_BOOKMARK_CLEAR:
1582                 theSession().bookmarks().clear();
1583                 break;
1584
1585         case LFUN_DEBUG_LEVEL_SET:
1586                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1587                 break;
1588
1589         default:
1590                 // Everything below is only for active window
1591                 if (current_view_ == 0)
1592                         break;
1593         
1594                 // Let the current GuiView dispatch its own actions.
1595                 current_view_->dispatch(cmd, dr);
1596
1597                 if (dr.dispatched())
1598                         break;
1599
1600                 BufferView * bv = current_view_->currentBufferView();
1601                 LASSERT(bv, /**/);
1602         
1603                 // Let the current BufferView dispatch its own actions.
1604                 bv->dispatch(cmd, dr);
1605                 if (dr.dispatched())
1606                         break;
1607         
1608                 BufferView * doc_bv = current_view_->documentBufferView();
1609                 // Try with the document BufferView dispatch if any.
1610                 if (doc_bv) {
1611                         doc_bv->dispatch(cmd, dr);
1612                         if (dr.dispatched())
1613                                 break;
1614                 }
1615         
1616                 // OK, so try the current Buffer itself...
1617                 bv->buffer().dispatch(cmd, dr);
1618                 if (dr.dispatched())
1619                         break;
1620         
1621                 // and with the document Buffer.
1622                 if (doc_bv) {
1623                         doc_bv->buffer().dispatch(cmd, dr);
1624                         if (dr.dispatched())
1625                                 break;
1626                 }
1627         
1628                 // Let the current Cursor dispatch its own actions.
1629                 Cursor old = bv->cursor();
1630                 bv->cursor().dispatch(cmd);
1631         
1632                 // notify insets we just left
1633                 if (bv->cursor() != old) {
1634                         old.fixIfBroken();
1635                         bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1636                         if (badcursor)
1637                                 bv->cursor().fixIfBroken();
1638                 }
1639         
1640                 // update completion. We do it here and not in
1641                 // processKeySym to avoid another redraw just for a
1642                 // changed inline completion
1643                 if (cmd.origin() == FuncRequest::KEYBOARD) {
1644                         if (cmd.action() == LFUN_SELF_INSERT
1645                                         || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1646                                 current_view_->updateCompletion(bv->cursor(), true, true);
1647                         else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
1648                                 current_view_->updateCompletion(bv->cursor(), false, true);
1649                         else
1650                                 current_view_->updateCompletion(bv->cursor(), false, false);
1651                 }
1652         
1653                 dr = bv->cursor().result();
1654         }
1655         
1656         // if we executed a mutating lfun, mark the buffer as dirty
1657         Buffer * doc_buffer = (current_view_ && current_view_->documentBufferView())
1658                       ? &(current_view_->documentBufferView()->buffer()) : 0;
1659         if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1660                 && flag.enabled()
1661                 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1662                 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1663                 current_view_->currentBufferView()->buffer().markDirty();
1664 }
1665
1666
1667 docstring GuiApplication::viewStatusMessage()
1668 {
1669         // When meta-fake key is pressed, show the key sequence so far + "M-".
1670         if (d->meta_fake_bit != NoModifier)
1671                 return d->keyseq.print(KeySequence::ForGui) + "M-";
1672
1673         // Else, when a non-complete key sequence is pressed,
1674         // show the available options.
1675         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1676                 return d->keyseq.printOptions(true);
1677
1678         return docstring();
1679 }
1680
1681
1682 void GuiApplication::handleKeyFunc(FuncCode action)
1683 {
1684         char_type c = 0;
1685
1686         if (d->keyseq.length())
1687                 c = 0;
1688         GuiView * gv = currentView();
1689         LASSERT(gv && gv->currentBufferView(), return);
1690         BufferView * bv = gv->currentBufferView();
1691         bv->getIntl().getTransManager().deadkey(
1692                 c, get_accent(action).accent, bv->cursor().innerText(),
1693                 bv->cursor());
1694         // Need to clear, in case the minibuffer calls these
1695         // actions
1696         d->keyseq.clear();
1697         // copied verbatim from do_accent_char
1698         bv->cursor().resetAnchor();
1699 }
1700
1701
1702 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1703 {
1704         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1705
1706         // Do nothing if we have nothing (JMarc)
1707         if (!keysym.isOK()) {
1708                 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1709                 if (current_view_)
1710                         current_view_->restartCursor();
1711                 return;
1712         }
1713
1714         if (keysym.isModifier()) {
1715                 LYXERR(Debug::KEY, "isModifier true");
1716                 if (current_view_)
1717                         current_view_->restartCursor();
1718                 return;
1719         }
1720
1721         char_type encoded_last_key = keysym.getUCSEncoded();
1722
1723         // Do a one-deep top-level lookup for
1724         // cancel and meta-fake keys. RVDK_PATCH_5
1725         d->cancel_meta_seq.reset();
1726
1727         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1728         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1729
1730         // When not cancel or meta-fake, do the normal lookup.
1731         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1732         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1733         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1734                 // remove Caps Lock and Mod2 as a modifiers
1735                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1736                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1737         }
1738
1739         // Dont remove this unless you know what you are doing.
1740         d->meta_fake_bit = NoModifier;
1741
1742         // Can this happen now ?
1743         if (func.action() == LFUN_NOACTION)
1744                 func = FuncRequest(LFUN_COMMAND_PREFIX);
1745
1746         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1747                 << d->keyseq.print(KeySequence::Portable) << ']');
1748
1749         // already here we know if it any point in going further
1750         // why not return already here if action == -1 and
1751         // num_bytes == 0? (Lgb)
1752
1753         if (d->keyseq.length() > 1 && current_view_)
1754                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1755
1756
1757         // Maybe user can only reach the key via holding down shift.
1758         // Let's see. But only if shift is the only modifier
1759         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1760                 LYXERR(Debug::KEY, "Trying without shift");
1761                 func = d->keyseq.addkey(keysym, NoModifier);
1762                 LYXERR(Debug::KEY, "Action now " << func.action());
1763         }
1764
1765         if (func.action() == LFUN_UNKNOWN_ACTION) {
1766                 // Hmm, we didn't match any of the keysequences. See
1767                 // if it's normal insertable text not already covered
1768                 // by a binding
1769                 if (keysym.isText() && d->keyseq.length() == 1) {
1770                         LYXERR(Debug::KEY, "isText() is true, inserting.");
1771                         func = FuncRequest(LFUN_SELF_INSERT,
1772                                            FuncRequest::KEYBOARD);
1773                 } else {
1774                         LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1775                         if (current_view_) {
1776                                 current_view_->message(_("Unknown function."));
1777                                 current_view_->restartCursor();
1778                         }
1779                         return;
1780                 }
1781         }
1782
1783         if (func.action() == LFUN_SELF_INSERT) {
1784                 if (encoded_last_key != 0) {
1785                         docstring const arg(1, encoded_last_key);
1786                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1787                                              FuncRequest::KEYBOARD));
1788                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1789                 }
1790         } else
1791                 processFuncRequest(func);
1792 }
1793
1794
1795 void GuiApplication::processFuncRequest(FuncRequest const & func)
1796 {
1797         lyx::dispatch(func);
1798 }
1799
1800
1801 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1802 {
1803         addToFuncRequestQueue(func);
1804         processFuncRequestQueueAsync();
1805 }
1806
1807
1808 void GuiApplication::processFuncRequestQueue()
1809 {
1810         while (!d->func_request_queue_.empty()) {
1811                 processFuncRequest(d->func_request_queue_.front());
1812                 d->func_request_queue_.pop();
1813         }
1814 }
1815
1816
1817 void GuiApplication::processFuncRequestQueueAsync()
1818 {
1819         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1820 }
1821
1822
1823 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1824 {
1825         d->func_request_queue_.push(func);
1826 }
1827
1828
1829 void GuiApplication::resetGui()
1830 {
1831         // Set the language defined by the user.
1832         setGuiLanguage();
1833
1834         // Read menus
1835         if (!readUIFile(toqstr(lyxrc.ui_file)))
1836                 // Gives some error box here.
1837                 return;
1838
1839         if (d->global_menubar_)
1840                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1841
1842         QHash<int, GuiView *>::iterator it;
1843         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1844                 GuiView * gv = *it;
1845                 setCurrentView(gv);
1846                 gv->setLayoutDirection(layoutDirection());
1847                 gv->resetDialogs();
1848         }
1849
1850         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1851 }
1852
1853
1854 void GuiApplication::createView(int view_id)
1855 {
1856         createView(QString(), true, view_id);
1857 }
1858
1859
1860 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1861         int view_id)
1862 {
1863         // release the keyboard which might have been grabed by the global
1864         // menubar on Mac to catch shortcuts even without any GuiView.
1865         if (d->global_menubar_)
1866                 d->global_menubar_->releaseKeyboard();
1867
1868         // create new view
1869         int id = view_id;
1870         while (d->views_.find(id) != d->views_.end())
1871                 id++;
1872
1873         LYXERR(Debug::GUI, "About to create new window with ID " << id);
1874         GuiView * view = new GuiView(id);
1875         // register view
1876         d->views_[id] = view;
1877
1878         if (autoShow) {
1879                 view->show();
1880                 setActiveWindow(view);
1881         }
1882
1883         if (!geometry_arg.isEmpty()) {
1884 #ifdef Q_WS_WIN
1885                 int x, y;
1886                 int w, h;
1887                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1888                 re.indexIn(geometry_arg);
1889                 w = re.cap(1).toInt();
1890                 h = re.cap(2).toInt();
1891                 x = re.cap(3).toInt();
1892                 y = re.cap(4).toInt();
1893                 view->setGeometry(x, y, w, h);
1894 #endif
1895         }
1896         view->setFocus();
1897 }
1898
1899
1900 Clipboard & GuiApplication::clipboard()
1901 {
1902         return d->clipboard_;
1903 }
1904
1905
1906 Selection & GuiApplication::selection()
1907 {
1908         return d->selection_;
1909 }
1910
1911
1912 FontLoader & GuiApplication::fontLoader() 
1913 {
1914         return d->font_loader_;
1915 }
1916
1917
1918 Toolbars const & GuiApplication::toolbars() const 
1919 {
1920         return d->toolbars_;
1921 }
1922
1923
1924 Toolbars & GuiApplication::toolbars()
1925 {
1926         return d->toolbars_; 
1927 }
1928
1929
1930 Menus const & GuiApplication::menus() const 
1931 {
1932         return d->menus_;
1933 }
1934
1935
1936 Menus & GuiApplication::menus()
1937 {
1938         return d->menus_; 
1939 }
1940
1941
1942 QList<int> GuiApplication::viewIds() const
1943 {
1944         return d->views_.keys();
1945 }
1946
1947
1948 ColorCache & GuiApplication::colorCache()
1949 {
1950         return d->color_cache_;
1951 }
1952
1953
1954 int GuiApplication::exec()
1955 {
1956         // asynchronously handle batch commands. This event will be in
1957         // the event queue in front of other asynchronous events. Hence,
1958         // we can assume in the latter that the gui is setup already.
1959         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1960
1961         return QApplication::exec();
1962 }
1963
1964
1965 void GuiApplication::exit(int status)
1966 {
1967         QApplication::exit(status);
1968 }
1969
1970
1971 void GuiApplication::setGuiLanguage()
1972 {
1973         // Set the language defined by the user.
1974         setRcGuiLanguage();
1975
1976         QString const default_language = toqstr(Messages::defaultLanguage());
1977         LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1978         QLocale const default_locale(default_language);
1979         QLocale::setDefault(default_locale);
1980
1981         // install translation file for Qt built-in dialogs
1982         QString const language_name = QString("qt_") + default_locale.name();
1983
1984         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1985         // Short-named translator can be loaded from a long name, but not the
1986         // opposite. Therefore, long name should be used without truncation.
1987         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1988         if (!d->qt_trans_.load(language_name,
1989                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1990                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1991                         << language_name);
1992         } else {
1993                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1994                         << language_name);
1995         }
1996
1997         switch (default_locale.language()) {
1998         case QLocale::Arabic :
1999         case QLocale::Hebrew :
2000         case QLocale::Persian :
2001         case QLocale::Urdu :
2002                 setLayoutDirection(Qt::RightToLeft);
2003                 break;
2004         default:
2005                 setLayoutDirection(Qt::LeftToRight);
2006         }
2007 }
2008
2009
2010 void GuiApplication::execBatchCommands()
2011 {
2012         setGuiLanguage();
2013
2014         // Read menus
2015         if (!readUIFile(toqstr(lyxrc.ui_file)))
2016                 // Gives some error box here.
2017                 return;
2018
2019 #ifdef Q_WS_MACX
2020 #if QT_VERSION > 0x040600
2021         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2022 #endif
2023         // Create the global default menubar which is shown for the dialogs
2024         // and if no GuiView is visible.
2025         // This must be done after the session was recovered to know the "last files".
2026         d->global_menubar_ = new GlobalMenuBar();
2027         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2028 #endif
2029
2030         lyx::execBatchCommands();
2031 }
2032
2033
2034 QAbstractItemModel * GuiApplication::languageModel()
2035 {
2036         if (d->language_model_)
2037                 return d->language_model_;
2038
2039         QStandardItemModel * lang_model = new QStandardItemModel(this);
2040         lang_model->insertColumns(0, 3);
2041         int current_row;
2042         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2043         QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2044         Languages::const_iterator it = lyx::languages.begin();
2045         Languages::const_iterator end = lyx::languages.end();
2046         for (; it != end; ++it) {
2047                 current_row = lang_model->rowCount();
2048                 lang_model->insertRows(current_row, 1);
2049                 QModelIndex pl_item = lang_model->index(current_row, 0);
2050                 QModelIndex sp_item = lang_model->index(current_row, 1);
2051                 QModelIndex th_item = lang_model->index(current_row, 2);
2052                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2053                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2054                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2055                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2056                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2057                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2058                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2059                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2060                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2061                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2062         }
2063         d->language_model_ = new QSortFilterProxyModel(this);
2064         d->language_model_->setSourceModel(lang_model);
2065 #if QT_VERSION >= 0x040300
2066         d->language_model_->setSortLocaleAware(true);
2067 #endif
2068         return d->language_model_;
2069 }
2070
2071
2072 void GuiApplication::restoreGuiSession()
2073 {
2074         if (!lyxrc.load_session)
2075                 return;
2076
2077         Session & session = theSession();
2078         LastOpenedSection::LastOpened const & lastopened = 
2079                 session.lastOpened().getfiles();
2080
2081         FileName active_file;
2082         // do not add to the lastfile list since these files are restored from
2083         // last session, and should be already there (regular files), or should
2084         // not be added at all (help files).
2085         for (size_t i = 0; i < lastopened.size(); ++i) {
2086                 FileName const & file_name = lastopened[i].file_name;
2087                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2088                           && current_view_->documentBufferView() != 0)) {
2089                         boost::crc_32_type crc;
2090                         string const & fname = file_name.absFileName();
2091                         crc = for_each(fname.begin(), fname.end(), crc);
2092                         createView(crc.checksum());
2093                 }
2094                 current_view_->loadDocument(file_name, false);
2095
2096                 if (lastopened[i].active)
2097                         active_file = file_name;
2098         }
2099
2100         // Restore last active buffer
2101         Buffer * buffer = theBufferList().getBuffer(active_file);
2102         if (buffer)
2103                 current_view_->setBuffer(buffer);
2104
2105         // clear this list to save a few bytes of RAM
2106         session.lastOpened().clear();
2107 }
2108
2109
2110 QString const GuiApplication::romanFontName()
2111 {
2112         QFont font;
2113         font.setKerning(false);
2114         font.setStyleHint(QFont::Serif);
2115         font.setFamily("serif");
2116
2117         return QFontInfo(font).family();
2118 }
2119
2120
2121 QString const GuiApplication::sansFontName()
2122 {
2123         QFont font;
2124         font.setKerning(false);
2125         font.setStyleHint(QFont::SansSerif);
2126         font.setFamily("sans");
2127
2128         return QFontInfo(font).family();
2129 }
2130
2131
2132 QString const GuiApplication::typewriterFontName()
2133 {
2134         QFont font;
2135         font.setKerning(false);
2136         font.setStyleHint(QFont::TypeWriter);
2137         font.setFamily("monospace");
2138
2139         return QFontInfo(font).family();
2140 }
2141
2142
2143 void GuiApplication::handleRegularEvents()
2144 {
2145         ForkedCallsController::handleCompletedProcesses();
2146 }
2147
2148
2149 bool GuiApplication::event(QEvent * e)
2150 {
2151         switch(e->type()) {
2152         case QEvent::FileOpen: {
2153                 // Open a file; this happens only on Mac OS X for now.
2154                 //
2155                 // We do this asynchronously because on startup the batch
2156                 // commands are not executed here yet and the gui is not ready
2157                 // therefore.
2158                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2159                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2160                 processFuncRequestAsync(fr);
2161                 e->accept();
2162                 return true;
2163         }
2164         default:
2165                 return QApplication::event(e);
2166         }
2167 }
2168
2169
2170 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2171 {
2172         try {
2173                 return QApplication::notify(receiver, event);
2174         }
2175         catch (ExceptionMessage const & e) {
2176                 switch(e.type_) { 
2177                 case ErrorException:
2178                         emergencyCleanup();
2179                         setQuitOnLastWindowClosed(false);
2180                         closeAllViews();
2181                         Alert::error(e.title_, e.details_);
2182 #ifndef NDEBUG
2183                         // Properly crash in debug mode in order to get a useful backtrace.
2184                         abort();
2185 #endif
2186                         // In release mode, try to exit gracefully.
2187                         this->exit(1);
2188
2189                 case BufferException: {
2190                         if (!current_view_->documentBufferView())
2191                                 return false;
2192                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2193                         docstring details = e.details_ + '\n';
2194                         details += buf->emergencyWrite();
2195                         theBufferList().release(buf);
2196                         details += "\n" + _("The current document was closed.");
2197                         Alert::error(e.title_, details);
2198                         return false;
2199                 }
2200                 case WarningException:
2201                         Alert::warning(e.title_, e.details_);
2202                         return false;
2203                 }
2204         }
2205         catch (exception const & e) {
2206                 docstring s = _("LyX has caught an exception, it will now "
2207                         "attempt to save all unsaved documents and exit."
2208                         "\n\nException: ");
2209                 s += from_ascii(e.what());
2210                 Alert::error(_("Software exception Detected"), s);
2211                 lyx_exit(1);
2212         }
2213         catch (...) {
2214                 docstring s = _("LyX has caught some really weird exception, it will "
2215                         "now attempt to save all unsaved documents and exit.");
2216                 Alert::error(_("Software exception Detected"), s);
2217                 lyx_exit(1);
2218         }
2219
2220         return false;
2221 }
2222
2223
2224 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2225 {
2226         QColor const & qcol = d->color_cache_.get(col);
2227         if (!qcol.isValid()) {
2228                 rgbcol.r = 0;
2229                 rgbcol.g = 0;
2230                 rgbcol.b = 0;
2231                 return false;
2232         }
2233         rgbcol.r = qcol.red();
2234         rgbcol.g = qcol.green();
2235         rgbcol.b = qcol.blue();
2236         return true;
2237 }
2238
2239
2240 string const GuiApplication::hexName(ColorCode col)
2241 {
2242         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2243 }
2244
2245
2246 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2247 {
2248         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2249         d->socket_notifiers_[fd] = sn;
2250         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2251 }
2252
2253
2254 void GuiApplication::socketDataReceived(int fd)
2255 {
2256         d->socket_notifiers_[fd]->func_();
2257 }
2258
2259
2260 void GuiApplication::unregisterSocketCallback(int fd)
2261 {
2262         d->socket_notifiers_.take(fd)->setEnabled(false);
2263 }
2264
2265
2266 void GuiApplication::commitData(QSessionManager & sm)
2267 {
2268         /// The implementation is required to avoid an application exit
2269         /// when session state save is triggered by session manager.
2270         /// The default implementation sends a close event to all
2271         /// visible top level widgets when session managment allows
2272         /// interaction.
2273         /// We are changing that to close all wiew one by one.
2274         /// FIXME: verify if the default implementation is enough now.
2275         #ifdef QT_NO_SESSIONMANAGER
2276                 #warning Qt is compiled without session manager
2277                 (void) sm;
2278         #else
2279                 if (sm.allowsInteraction() && !closeAllViews())
2280                         sm.cancel();
2281         #endif
2282 }
2283
2284
2285 void GuiApplication::unregisterView(GuiView * gv)
2286 {
2287         LASSERT(d->views_[gv->id()] == gv, /**/);
2288         d->views_.remove(gv->id());
2289         if (current_view_ == gv)
2290                 current_view_ = 0;
2291 }
2292
2293
2294 bool GuiApplication::closeAllViews()
2295 {
2296         if (d->views_.empty())
2297                 return true;
2298
2299         // When a view/window was closed before without quitting LyX, there
2300         // are already entries in the lastOpened list.
2301         theSession().lastOpened().clear();
2302
2303         QList<GuiView *> views = d->views_.values();
2304         foreach (GuiView * view, views) {
2305                 if (!view->closeScheduled())
2306                         return false;
2307         }
2308
2309         d->views_.clear();
2310         return true;
2311 }
2312
2313
2314 GuiView & GuiApplication::view(int id) const
2315 {
2316         LASSERT(d->views_.contains(id), /**/);
2317         return *d->views_.value(id);
2318 }
2319
2320
2321 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2322 {
2323         QList<GuiView *> views = d->views_.values();
2324         foreach (GuiView * view, views)
2325                 view->hideDialog(name, inset);
2326 }
2327
2328
2329 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2330 {
2331         Buffer const * buffer_ = 0;
2332         QHash<int, GuiView *>::iterator end = d->views_.end();
2333         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2334                 if (Buffer const * ptr = (*it)->updateInset(inset))
2335                         buffer_ = ptr;
2336         }
2337         return buffer_;
2338 }
2339
2340
2341 bool GuiApplication::searchMenu(FuncRequest const & func,
2342         docstring_list & names) const
2343 {
2344         return d->menus_.searchMenu(func, names);
2345 }
2346
2347
2348 bool GuiApplication::readUIFile(QString const & name, bool include)
2349 {
2350         LYXERR(Debug::INIT, "About to read " << name << "...");
2351
2352         FileName ui_path;
2353         if (include) {
2354                 ui_path = libFileSearch("ui", name, "inc");
2355                 if (ui_path.empty())
2356                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2357         } else {
2358                 ui_path = libFileSearch("ui", name, "ui");
2359         }
2360
2361         if (ui_path.empty()) {
2362                 static const QString defaultUIFile = "default";
2363                 LYXERR(Debug::INIT, "Could not find " << name);
2364                 if (include) {
2365                         Alert::warning(_("Could not find UI definition file"),
2366                                 bformat(_("Error while reading the included file\n%1$s\n"
2367                                         "Please check your installation."), qstring_to_ucs4(name)));
2368                         return false;
2369                 }
2370                 if (name == defaultUIFile) {
2371                         LYXERR(Debug::INIT, "Could not find default UI file!!");
2372                         Alert::warning(_("Could not find default UI file"),
2373                                 _("LyX could not find the default UI file!\n"
2374                                   "Please check your installation."));
2375                         return false;
2376                 }
2377                 Alert::warning(_("Could not find UI definition file"),
2378                 bformat(_("Error while reading the configuration file\n%1$s\n"
2379                         "Falling back to default.\n"
2380                         "Please look under Tools>Preferences>User Interface and\n"
2381                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
2382                 return readUIFile(defaultUIFile, false);
2383         }
2384
2385         // Ensure that a file is read only once (prevents include loops)
2386         static QStringList uifiles;
2387         QString const uifile = toqstr(ui_path.absFileName());
2388         if (uifiles.contains(uifile)) {
2389                 if (!include) {
2390                         // We are reading again the top uifile so reset the safeguard:
2391                         uifiles.clear();
2392                         d->menus_.reset();
2393                         d->toolbars_.reset();
2394                 } else {
2395                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2396                                 << "Is this an include loop?");
2397                         return false;
2398                 }
2399         }
2400         uifiles.push_back(uifile);
2401
2402         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2403
2404         enum {
2405                 ui_menuset = 1,
2406                 ui_toolbars,
2407                 ui_toolbarset,
2408                 ui_include,
2409                 ui_last
2410         };
2411
2412         LexerKeyword uitags[] = {
2413                 { "include", ui_include },
2414                 { "menuset", ui_menuset },
2415                 { "toolbars", ui_toolbars },
2416                 { "toolbarset", ui_toolbarset }
2417         };
2418
2419         Lexer lex(uitags);
2420         lex.setFile(ui_path);
2421         if (!lex.isOK()) {
2422                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2423                        << endl;
2424         }
2425
2426         if (lyxerr.debugging(Debug::PARSER))
2427                 lex.printTable(lyxerr);
2428
2429         // store which ui files define Toolbars
2430         static QStringList toolbar_uifiles;
2431
2432         while (lex.isOK()) {
2433                 switch (lex.lex()) {
2434                 case ui_include: {
2435                         lex.next(true);
2436                         QString const file = toqstr(lex.getString());
2437                         if (!readUIFile(file, true))
2438                                 return false;
2439                         break;
2440                 }
2441                 case ui_menuset:
2442                         d->menus_.read(lex);
2443                         break;
2444
2445                 case ui_toolbarset:
2446                         d->toolbars_.readToolbars(lex);
2447                         break;
2448
2449                 case ui_toolbars:
2450                         d->toolbars_.readToolbarSettings(lex);
2451                         toolbar_uifiles.push_back(uifile);
2452                         break;
2453
2454                 default:
2455                         if (!rtrim(lex.getString()).empty())
2456                                 lex.printError("LyX::ReadUIFile: "
2457                                                "Unknown menu tag: `$$Token'");
2458                         break;
2459                 }
2460         }
2461
2462         if (include)
2463                 return true;
2464
2465         QSettings settings;
2466         settings.beginGroup("ui_files");
2467         bool touched = false;
2468         for (int i = 0; i != uifiles.size(); ++i) {
2469                 QFileInfo fi(uifiles[i]);
2470                 QDateTime const date_value = fi.lastModified();
2471                 QString const name_key = QString::number(i);
2472                 // if an ui file which defines Toolbars has changed,
2473                 // we have to reset the settings
2474                 if (toolbar_uifiles.contains(uifiles[i])
2475                  && (!settings.contains(name_key)
2476                  || settings.value(name_key).toString() != uifiles[i]
2477                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
2478                         touched = true;
2479                         settings.setValue(name_key, uifiles[i]);
2480                         settings.setValue(name_key + "/date", date_value);
2481                 }
2482         }
2483         settings.endGroup();
2484         if (touched)
2485                 settings.remove("views");
2486
2487         return true;
2488 }
2489
2490
2491 void GuiApplication::onLastWindowClosed()
2492 {
2493         if (d->global_menubar_)
2494                 d->global_menubar_->grabKeyboard();
2495 }
2496
2497
2498 ////////////////////////////////////////////////////////////////////////
2499 //
2500 // X11 specific stuff goes here...
2501
2502 #ifdef Q_WS_X11
2503 bool GuiApplication::x11EventFilter(XEvent * xev)
2504 {
2505         if (!current_view_)
2506                 return false;
2507
2508         switch (xev->type) {
2509         case SelectionRequest: {
2510                 if (xev->xselectionrequest.selection != XA_PRIMARY)
2511                         break;
2512                 LYXERR(Debug::SELECTION, "X requested selection.");
2513                 BufferView * bv = current_view_->currentBufferView();
2514                 if (bv) {
2515                         docstring const sel = bv->requestSelection();
2516                         if (!sel.empty())
2517                                 d->selection_.put(sel);
2518                 }
2519                 break;
2520         }
2521         case SelectionClear: {
2522                 if (xev->xselectionclear.selection != XA_PRIMARY)
2523                         break;
2524                 LYXERR(Debug::SELECTION, "Lost selection.");
2525                 BufferView * bv = current_view_->currentBufferView();
2526                 if (bv)
2527                         bv->clearSelection();
2528                 break;
2529         }
2530         }
2531         return false;
2532 }
2533 #endif
2534
2535 } // namespace frontend
2536
2537
2538 void hideDialogs(std::string const & name, Inset * inset)
2539 {
2540         if (theApp())
2541                 frontend::guiApp->hideDialogs(name, inset);
2542 }
2543
2544
2545 ////////////////////////////////////////////////////////////////////
2546 //
2547 // Font stuff
2548 //
2549 ////////////////////////////////////////////////////////////////////
2550
2551 frontend::FontLoader & theFontLoader()
2552 {
2553         LASSERT(frontend::guiApp, /**/);
2554         return frontend::guiApp->fontLoader();
2555 }
2556
2557
2558 frontend::FontMetrics const & theFontMetrics(Font const & f)
2559 {
2560         return theFontMetrics(f.fontInfo());
2561 }
2562
2563
2564 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2565 {
2566         LASSERT(frontend::guiApp, /**/);
2567         return frontend::guiApp->fontLoader().metrics(f);
2568 }
2569
2570
2571 ////////////////////////////////////////////////////////////////////
2572 //
2573 // Misc stuff
2574 //
2575 ////////////////////////////////////////////////////////////////////
2576
2577 frontend::Clipboard & theClipboard()
2578 {
2579         LASSERT(frontend::guiApp, /**/);
2580         return frontend::guiApp->clipboard();
2581 }
2582
2583
2584 frontend::Selection & theSelection()
2585 {
2586         LASSERT(frontend::guiApp, /**/);
2587         return frontend::guiApp->selection();
2588 }
2589
2590
2591 } // namespace lyx
2592
2593 #include "moc_GuiApplication.cpp"