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