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