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