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