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