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