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