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