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