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