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