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