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