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