]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
Fix bug #10469
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ColorCache.h"
18 #include "ColorSet.h"
19 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
22 #include "GuiView.h"
23 #include "Menus.h"
24 #include "qt_helpers.h"
25 #include "Toolbars.h"
26
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
31
32 #include "Buffer.h"
33 #include "BufferList.h"
34 #include "BufferParams.h"
35 #include "BufferView.h"
36 #include "CmdDef.h"
37 #include "Color.h"
38 #include "CutAndPaste.h"
39 #include "ErrorList.h"
40 #include "Font.h"
41 #include "FuncRequest.h"
42 #include "FuncStatus.h"
43 #include "GuiWorkArea.h"
44 #include "Intl.h"
45 #include "KeyMap.h"
46 #include "Language.h"
47 #include "LaTeXPackages.h"
48 #include "Lexer.h"
49 #include "LyX.h"
50 #include "LyXAction.h"
51 #include "LyXRC.h"
52 #include "Paragraph.h"
53 #include "Server.h"
54 #include "Session.h"
55 #include "SpellChecker.h"
56 #include "Thesaurus.h"
57 #include "version.h"
58
59 #include "insets/InsetText.h"
60
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/ExceptionMessage.h"
64 #include "support/FileName.h"
65 #include "support/filetools.h"
66 #include "support/foreach.h"
67 #include "support/ForkedCalls.h"
68 #include "support/gettext.h"
69 #include "support/lassert.h"
70 #include "support/lstrings.h"
71 #include "support/lyxalgo.h" // sorted
72 #include "support/textutils.h"
73 #include "support/Messages.h"
74 #include "support/os.h"
75 #include "support/Package.h"
76 #include "support/TempFile.h"
77
78 #ifdef Q_OS_MAC
79 #include "support/AppleScript.h"
80 #include "support/linkback/LinkBackProxy.h"
81 #endif
82
83 #include <queue>
84
85 #include <QFontDatabase>
86 #include <QByteArray>
87 #include <QClipboard>
88 #include <QDateTime>
89 #include <QDesktopWidget>
90 #include <QDir>
91 #include <QEvent>
92 #include <QEventLoop>
93 #include <QFileOpenEvent>
94 #include <QFileInfo>
95 #include <QHash>
96 #include <QIcon>
97 #include <QImageReader>
98 #include <QKeyEvent>
99 #include <QLocale>
100 #include <QLibraryInfo>
101 #include <QList>
102 #include <QMenuBar>
103 #include <QMimeData>
104 #include <QObject>
105 #include <QPixmap>
106 #include <QPixmapCache>
107 #include <QRegExp>
108 #include <QSessionManager>
109 #include <QSettings>
110 #include <QShowEvent>
111 #include <QSocketNotifier>
112 #include <QSortFilterProxyModel>
113 #include <QStandardItemModel>
114 #include <QTextCodec>
115 #include <QTimer>
116 #include <QTranslator>
117 #include <QThreadPool>
118 #include <QWidget>
119
120 #ifdef Q_WS_X11
121 #include <X11/Xatom.h>
122 #include <X11/Xlib.h>
123 #undef CursorShape
124 #undef None
125 #elif defined(QPA_XCB)
126 #include <xcb/xcb.h>
127 #endif
128
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
134 #else
135 #include <QWinMime>
136 #define QWINDOWSMIME QWinMime
137 #endif
138 #ifdef Q_CC_GNU
139 #include <wtypes.h>
140 #endif
141 #include <objidl.h>
142 #endif
143 #endif
144
145 #ifdef Q_OS_MAC
146 #include <QMacPasteboardMime>
147 #endif // Q_OS_MAC
148
149 #include "support/bind.h"
150 #include <boost/crc.hpp>
151
152 #include <exception>
153 #include <sstream>
154 #include <vector>
155
156 using namespace std;
157 using namespace lyx::support;
158
159
160 static void initializeResources()
161 {
162         static bool initialized = false;
163         if (!initialized) {
164                 Q_INIT_RESOURCE(Resources);
165                 initialized = true;
166         }
167 }
168
169
170 namespace lyx {
171
172 frontend::Application * createApplication(int & argc, char * argv[])
173 {
174 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
175         // prune -geometry argument(s) by shifting
176         // the following ones 2 places down.
177         for (int i = 0 ; i < argc ; ++i) {
178                 if (strcmp(argv[i], "-geometry") == 0) {
179                         int const remove = (i+1) < argc ? 2 : 1;
180                         argc -= remove;
181                         for (int j = i; j < argc; ++j)
182                                 argv[j] = argv[j + remove];
183                         --i;
184                 }
185         }
186 #endif
187
188 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
189         // On Windows, allow bringing the LyX window to top
190         AllowSetForegroundWindow(ASFW_ANY);
191 #endif
192
193         frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
194         // I'd rather do that in the constructor, but I do not think that
195         // the palette is accessible there.
196         guiApp->colorCache().setPalette(guiApp->palette());
197         return guiApp;
198 }
199
200
201 void setLocale()
202 {
203         QLocale theLocale;
204         string code;
205         if (lyxrc.gui_language == "auto") {
206                 theLocale = QLocale::system();
207                 code = fromqstr(theLocale.name());
208         } else {
209                 Language const * l = languages.getLanguage(lyxrc.gui_language);
210                 code = l ? l->code() : "C";
211                 theLocale = QLocale(toqstr(code));
212         }
213         // Qt tries to outsmart us and transforms en_US to C.
214         Messages::guiLanguage((code == "C") ? "en_US" : code);
215         QLocale::setDefault(theLocale);
216         setlocale(LC_NUMERIC, "C");
217 }
218
219
220 namespace frontend {
221
222
223 /// Return the list of loadable formats.
224 vector<string> loadableImageFormats()
225 {
226         vector<string> fmts;
227
228         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
229
230         LYXERR(Debug::GRAPHICS,
231                 "\nThe image loader can load the following directly:\n");
232
233         if (qt_formats.empty())
234                 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
235
236         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
237
238                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
239
240                 string ext = ascii_lowercase((const char *) *it);
241                 // special case
242                 if (ext == "jpeg")
243                         ext = "jpg";
244                 fmts.push_back(ext);
245         }
246
247         return fmts;
248 }
249
250
251 ////////////////////////////////////////////////////////////////////////
252 //
253 // Icon loading support code
254 //
255 ////////////////////////////////////////////////////////////////////////
256
257 namespace {
258
259 struct ImgMap {
260         QString key;
261         QString value;
262 };
263
264
265 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
266 {
267         return lhs.key < rhs.key;
268 }
269
270
271 class CompareKey {
272 public:
273         CompareKey(QString const & name) : name_(name) {}
274         bool operator()(ImgMap const & other) const { return other.key == name_; }
275 private:
276         QString const name_;
277 };
278
279
280 // this must be sorted alphabetically
281 // Upper case comes before lower case
282 // Please don't change the formatting, this list is parsed by
283 // development/tools/generate_symbols_images.py.
284 ImgMap sorted_img_map[] = {
285         { "Arrownot", "arrownot2"},
286         { "Arrowvert", "arrowvert2"},
287         { "Bowtie", "bowtie2" },
288         { "Box", "box2" },
289         { "Bumpeq", "bumpeq2" },
290         { "CIRCLE", "circle3" },
291         { "Cap", "cap2" },
292         { "CheckedBox", "checkedbox2" },
293         { "Circle", "circle2" },
294         { "Colonapprox", "colonapprox2" },
295         { "Coloneq", "coloneq2" },
296         { "Coloneqq", "coloneqq2" },
297         { "Colonsim", "colonsim2" },
298         { "Cup", "cup2" },
299         { "DOWNarrow", "downarrow3" },
300         { "Delta", "delta2" },
301         { "Diamond", "diamond2" },
302         { "Doteq", "doteq2" },
303         { "Downarrow", "downarrow2" },
304         { "Eqcolon", "eqcolon2" },
305         { "Eqqcolon", "eqqcolon2" },
306         { "Gamma", "gamma2" },
307         { "Join", "join2" },
308         { "LEFTCIRCLE", "leftcircle3" },
309         { "LEFTarrow", "leftarrow3" },
310         { "LEFTcircle", "leftcircle4" },
311         { "LHD", "lhd2" },
312         { "Lambda", "lambda2" },
313         { "Lbag", "lbag2"},
314         { "Leftarrow", "leftarrow2" },
315         { "Leftcircle", "leftcircle2" },
316         { "Leftrightarrow", "leftrightarrow2" },
317         { "Longarrownot", "longarrownot2"},
318         { "Longleftarrow", "longleftarrow2" },
319         { "Longleftrightarrow", "longleftrightarrow2" },
320         { "Longmapsfrom", "longmapsfrom2"},
321         { "Longmapsto", "longmapsto2"},
322         { "Longrightarrow", "longrightarrow2" },
323         { "Mapsfrom", "mapsfrom2"},
324         { "Mapsfromchar", "mapsfromchar2"},
325         { "Mapsto", "mapsto2"},
326         { "Mapstochar", "mapstochar2"},
327         { "Omega", "omega2" },
328         { "Phi", "phi2" },
329         { "Pi", "pi2" },
330         { "Psi", "psi2" },
331         { "RHD", "rhd2" },
332         { "RIGHTCIRCLE", "rightcircle3" },
333         { "RIGHTarrow", "rightarrow3" },
334         { "RIGHTcircle", "rightcircle4" },
335         { "Rbag", "rbag2"},
336         { "Rightarrow", "rightarrow2" },
337         { "Rightcircle", "rightcircle2" },
338         { "Sigma", "sigma2" },
339         { "Square", "square2" },
340         { "Subset", "subset2" },
341         { "Supset", "supset2" },
342         { "Theta", "theta2" },
343         { "Thorn", "thorn2" },
344         { "UParrow", "uparrow3" },
345         { "Uparrow", "uparrow2" },
346         { "Updownarrow", "updownarrow2" },
347         { "Upsilon", "upsilon2" },
348         { "Vdash", "vdash3" },
349         { "Vert", "vert2" },
350         { "XBox", "xbox3" },
351         { "Xbox", "xbox2" },
352         { "Xi", "xi2" },
353         { "lVert", "vert2" },
354         { "lvert", "vert" },
355         { "nLeftarrow", "nleftarrow2" },
356         { "nLeftrightarrow", "nleftrightarrow2" },
357         { "nRightarrow", "nrightarrow2" },
358         { "nVDash", "nvdash3" },
359         { "nVdash", "nvdash4" },
360         { "nvDash", "nvdash2" },
361         { "rVert", "vert2" },
362         { "rvert", "vert" },
363         { "textrm \\AA", "textrm_AA"},
364         { "textrm \\O", "textrm_O"},
365         { "vDash", "vdash2" },
366         { "varDelta", "vardelta2" },
367         { "varGamma", "vargamma2" },
368         { "varLambda", "varlambda2" },
369         { "varOmega", "varomega2" },
370         { "varPhi", "varphi2" },
371         { "varPi", "varpi2" },
372         { "varPsi", "varpsi2" },
373         { "varSigma", "varsigma2" },
374         { "varTheta", "vartheta2" },
375         { "varUpsilon", "varupsilon2" },
376         { "varXi", "varxi2" }
377 };
378
379
380 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
381
382 // This list specifies which system's theme icon is related to which lyx
383 // command. It was based on:
384 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
385 // this must be sorted alphabetically
386 // Upper case comes before lower case
387 ImgMap sorted_theme_icon_map[] = {
388         { "bookmark-goto 0", "go-jump" },
389         { "buffer-new", "document-new" },
390         { "buffer-write", "document-save" },
391         { "buffer-write-as", "document-save-as" },
392         { "buffer-zoom-in", "zoom-in" },
393         { "buffer-zoom-out", "zoom-out" },
394         { "copy", "edit-copy" },
395         { "cut", "edit-cut" },
396         { "depth-decrement", "format-indent-less" },
397         { "depth-increment", "format-indent-more" },
398         { "dialog-show spellchecker", "tools-check-spelling" },
399         { "dialog-show-new-inset graphics", "insert-image" },
400         { "dialog-toggle findreplaceadv", "edit-find-replace" },
401         { "file-open", "document-open" },
402         { "font-bold", "format-text-bold" },
403         { "font-ital", "format-text-italic" },
404         { "font-strikeout", "format-text-strikethrough" },
405         { "font-underline", "format-text-underline" },
406         { "lyx-quit", "application-exit" },
407         { "paste", "edit-paste" },
408         { "redo", "edit-redo" },
409         { "undo", "edit-undo" },
410         { "window-close", "window-close" },
411         { "window-new", "window-new" }
412 };
413
414 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
415
416
417 QString findImg(QString const & name)
418 {
419         ImgMap const * const begin = sorted_img_map;
420         ImgMap const * const end = begin + nr_sorted_img_map;
421         LATTEST(sorted(begin, end));
422
423         ImgMap const * const it = find_if(begin, end, CompareKey(name));
424
425         QString img_name;
426         if (it != end) {
427                 img_name = it->value;
428         } else {
429                 img_name = name;
430                 img_name.replace('_', "underscore");
431                 img_name.replace(' ', '_');
432
433                 // This way we can have "math-delim { }" on the toolbar.
434                 img_name.replace('(', "lparen");
435                 img_name.replace(')', "rparen");
436                 img_name.replace('[', "lbracket");
437                 img_name.replace(']', "rbracket");
438                 img_name.replace('{', "lbrace");
439                 img_name.replace('}', "rbrace");
440                 img_name.replace('|', "bars");
441                 img_name.replace(',', "thinspace");
442                 img_name.replace(':', "mediumspace");
443                 img_name.replace(';', "thickspace");
444                 img_name.replace('!', "negthinspace");
445         }
446
447         LYXERR(Debug::GUI, "findImg(" << name << ")\n"
448                 << "Looking for math icon called \"" << img_name << '"');
449         return img_name;
450 }
451
452 } // namespace anon
453
454
455 QString themeIconName(QString const & action)
456 {
457         ImgMap const * const begin = sorted_theme_icon_map;
458         ImgMap const * const end = begin + nr_sorted_theme_icon_map;
459         LASSERT(sorted(begin, end), /**/);
460
461         ImgMap const * const it = find_if(begin, end, CompareKey(action));
462
463         if (it != end)
464                 return it->value;
465         return QString();
466 }
467
468
469 QString iconName(FuncRequest const & f, bool unknown)
470 {
471         initializeResources();
472         QString name1;
473         QString name2;
474         QString path;
475         switch (f.action()) {
476         case LFUN_MATH_INSERT:
477                 if (!f.argument().empty()) {
478                         path = "math/";
479                         name1 = findImg(toqstr(f.argument()).mid(1));
480                 }
481                 break;
482         case LFUN_MATH_DELIM:
483         case LFUN_MATH_BIGDELIM:
484                 path = "math/";
485                 name1 = findImg(toqstr(f.argument()));
486                 break;
487         case LFUN_CALL:
488                 path = "commands/";
489                 name1 = toqstr(f.argument());
490                 break;
491         case LFUN_COMMAND_ALTERNATIVES: {
492                 // use the first of the alternative commands
493                 docstring firstcom;
494                 docstring dummy = split(f.argument(), firstcom, ';');
495                 name1 = toqstr(firstcom);
496                 name1.replace(' ', '_');
497                 break;
498         }
499         default:
500                 name2 = toqstr(lyxaction.getActionName(f.action()));
501                 name1 = name2;
502
503                 if (!f.argument().empty()) {
504                         name1 = name2 + ' ' + toqstr(f.argument());
505                         name1.replace(' ', '_');
506                         name1.replace('\\', "backslash");
507                 }
508         }
509
510         QStringList imagedirs;
511         imagedirs << "images/" << "images/ipa/";
512         search_mode mode = theGuiApp()->imageSearchMode();
513         for (int i = 0; i < imagedirs.size(); ++i) {
514                 QString imagedir = imagedirs.at(i) + path;
515                 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
516                 if (fname.exists())
517                         return toqstr(fname.absFileName());
518
519                 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
520                 if (fname.exists())
521                         return toqstr(fname.absFileName());
522         }
523
524         path = ":/images/" + path;
525         QDir res(path);
526         if (!res.exists()) {
527                 LYXERR0("Directory " << path << " not found in resource!");
528                 return QString();
529         }
530         if (res.exists(name1 + ".svgz"))
531                 return path + name1 + ".svgz";
532         else if (res.exists(name1 + ".png"))
533                 return path + name1 + ".png";
534
535         if (res.exists(name2 + ".svgz"))
536                 return path + name2 + ".svgz";
537         else if (res.exists(name2 + ".png"))
538                 return path + name2 + ".png";
539
540         LYXERR(Debug::GUI, "Cannot find icon with filename "
541                            << "\"" << name1 << ".{svgz,png}\""
542                            << " or filename "
543                            << "\"" << name2 << ".{svgz,png}\""
544                            << " for command \""
545                            << lyxaction.getActionName(f.action())
546                            << '(' << to_utf8(f.argument()) << ")\"");
547
548         if (unknown) {
549                 QString imagedir = "images/";
550                 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
551                 if (fname.exists())
552                         return toqstr(fname.absFileName());
553                 return QString(":/images/unknown.svgz");
554         }
555
556         return QString();
557 }
558
559
560 bool getPixmap(QPixmap & pixmap, QString const & path)
561 {
562         return pixmap.load(path);
563 }
564
565
566 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
567 {
568         QString imagedir = path;
569         FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
570         QString fpath = toqstr(fname.absFileName());
571         QPixmap pixmap = QPixmap();
572
573         if (getPixmap(pixmap, fpath)) {
574                 return pixmap;
575         }
576         
577         QStringList exts = ext.split(",");
578         fpath = ":/" + path + name + ".";
579         for (int i = 0; i < exts.size(); ++i) {
580                 if (getPixmap(pixmap, fpath + exts.at(i))) {
581                         return pixmap;
582                 }
583         }
584
585         bool const list = ext.contains(",");
586         LYXERR0("Cannot load pixmap \""
587                 << path << name << "." << (list ? "{" : "") << ext
588                 << (list ? "}" : "") << "\", please verify resource system!");
589
590         return QPixmap();
591 }
592
593
594 QIcon getIcon(FuncRequest const & f, bool unknown)
595 {
596 #if (QT_VERSION >= 0x040600)
597         if (lyxrc.use_system_theme_icons) {
598                 // use the icons from system theme that are available
599                 QString action = toqstr(lyxaction.getActionName(f.action()));
600                 if (!f.argument().empty())
601                         action += " " + toqstr(f.argument());
602                 QString const theme_icon = themeIconName(action);
603                 if (QIcon::hasThemeIcon(theme_icon)) {
604                         QIcon const thmicn = QIcon::fromTheme(theme_icon);
605                         if (!thmicn.isNull())
606                                 return thmicn;
607                 }
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                 } else if (dr.needChangesUpdate()) {
1398                         // updateBuffer() already updates the change-tracking presence flag
1399                         bv->buffer().updateChangesPresent();
1400                 }
1401                 // BufferView::update() updates the ViewMetricsInfo and
1402                 // also initializes the position cache for all insets in
1403                 // (at least partially) visible top-level paragraphs.
1404                 // We will redraw the screen only if needed.
1405                 bv->processUpdateFlags(dr.screenUpdate());
1406
1407                 // Do we have a selection?
1408                 theSelection().haveSelection(bv->cursor().selection());
1409
1410                 // update gui
1411                 current_view_->restartCursor();
1412         }
1413         if (dr.needMessageUpdate()) {
1414                 // Some messages may already be translated, so we cannot use _()
1415                 current_view_->message(makeDispatchMessage(
1416                                 translateIfPossible(dr.message()), cmd));
1417         }
1418 }
1419
1420
1421 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1422         bool switchToBuffer)
1423 {
1424         if (!theSession().bookmarks().isValid(idx))
1425                 return;
1426         BookmarksSection::Bookmark const & bm =
1427                 theSession().bookmarks().bookmark(idx);
1428         LASSERT(!bm.filename.empty(), return);
1429         string const file = bm.filename.absFileName();
1430         // if the file is not opened, open it.
1431         if (!theBufferList().exists(bm.filename)) {
1432                 if (openFile)
1433                         dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1434                 else
1435                         return;
1436         }
1437         // open may fail, so we need to test it again
1438         if (!theBufferList().exists(bm.filename))
1439                 return;
1440
1441         // bm can be changed when saving
1442         BookmarksSection::Bookmark tmp = bm;
1443
1444         // Special case idx == 0 used for back-from-back jump navigation
1445         if (idx == 0)
1446                 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1447
1448         // if the current buffer is not that one, switch to it.
1449         BufferView * doc_bv = current_view_ ?
1450                 current_view_->documentBufferView() : 0;
1451         Cursor const old = doc_bv->cursor();
1452         if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1453                 if (switchToBuffer) {
1454                         dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1455                         if (!current_view_)
1456                                 return;
1457                         doc_bv = current_view_->documentBufferView();
1458                 } else
1459                         return;
1460         }
1461
1462         // moveToPosition try paragraph id first and then paragraph (pit, pos).
1463         if (!doc_bv->moveToPosition(
1464                         tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1465                 return;
1466
1467         Cursor & cur = doc_bv->cursor();
1468         if (cur != old)
1469                 notifyCursorLeavesOrEnters(old, cur);
1470
1471         // bm changed
1472         if (idx == 0)
1473                 return;
1474
1475         // Cursor jump succeeded!
1476         pit_type new_pit = cur.pit();
1477         pos_type new_pos = cur.pos();
1478         int new_id = cur.paragraph().id();
1479
1480         // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1481         // see http://www.lyx.org/trac/ticket/3092
1482         if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1483                 || bm.top_id != new_id) {
1484                 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1485                         new_pit, new_pos, new_id);
1486         }
1487 }
1488
1489 // This function runs "configure" and then rereads lyx.defaults to
1490 // reconfigure the automatic settings.
1491 void GuiApplication::reconfigure(string const & option)
1492 {
1493         // emit message signal.
1494         if (current_view_)
1495                 current_view_->message(_("Running configure..."));
1496
1497         // Run configure in user lyx directory
1498         string const lock_file = package().getConfigureLockName();
1499         int fd = fileLock(lock_file.c_str());
1500         int const ret = package().reconfigureUserLyXDir(option);
1501         // emit message signal.
1502         if (current_view_)
1503                 current_view_->message(_("Reloading configuration..."));
1504         lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1505         // Re-read packages.lst
1506         LaTeXPackages::getAvailable();
1507         fileUnlock(fd, lock_file.c_str());
1508
1509         if (ret)
1510                 Alert::information(_("System reconfiguration failed"),
1511                            _("The system reconfiguration has failed.\n"
1512                                   "Default textclass is used but LyX may\n"
1513                                   "not be able to work properly.\n"
1514                                   "Please reconfigure again if needed."));
1515         else
1516                 Alert::information(_("System reconfigured"),
1517                            _("The system has been reconfigured.\n"
1518                              "You need to restart LyX to make use of any\n"
1519                              "updated document class specifications."));
1520 }
1521
1522 void GuiApplication::validateCurrentView()
1523 {
1524         if (!d->views_.empty() && !current_view_) {
1525                 // currently at least one view exists but no view has the focus.
1526                 // choose the last view to make it current.
1527                 // a view without any open document is preferred.
1528                 GuiView * candidate = 0;
1529                 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1530                 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1531                 for (; it != end; ++it) {
1532                         candidate = *it;
1533                         if (!candidate->documentBufferView())
1534                                 break;
1535                 }
1536                 setCurrentView(candidate);
1537         }
1538 }
1539
1540 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1541 {
1542         string const argument = to_utf8(cmd.argument());
1543         FuncCode const action = cmd.action();
1544
1545         LYXERR(Debug::ACTION, "cmd: " << cmd);
1546
1547         // we have not done anything wrong yet.
1548         dr.setError(false);
1549
1550         FuncStatus const flag = getStatus(cmd);
1551         if (!flag.enabled()) {
1552                 // We cannot use this function here
1553                 LYXERR(Debug::ACTION, "action "
1554                        << lyxaction.getActionName(action)
1555                        << " [" << action << "] is disabled at this location");
1556                 dr.setMessage(flag.message());
1557                 dr.setError(true);
1558                 dr.dispatched(false);
1559                 dr.screenUpdate(Update::None);
1560                 dr.clearBufferUpdate();
1561                 return;
1562         };
1563
1564         if (cmd.origin() == FuncRequest::LYXSERVER) {
1565                 if (current_view_ && current_view_->currentBufferView())
1566                         current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1567                 // we will also need to redraw the screen at the end
1568                 dr.screenUpdate(Update::FitCursor);
1569         }
1570
1571         // Assumes that the action will be dispatched.
1572         dr.dispatched(true);
1573
1574         switch (cmd.action()) {
1575
1576         case LFUN_WINDOW_NEW:
1577                 createView(toqstr(cmd.argument()));
1578                 break;
1579
1580         case LFUN_WINDOW_CLOSE:
1581                 // update bookmark pit of the current buffer before window close
1582                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1583                         gotoBookmark(i+1, false, false);
1584                 // clear the last opened list, because
1585                 // maybe this will end the session
1586                 theSession().lastOpened().clear();
1587                 // check for valid current_view_
1588                 validateCurrentView();
1589                 if (current_view_)
1590                         current_view_->closeScheduled();
1591                 break;
1592
1593         case LFUN_LYX_QUIT:
1594                 // quitting is triggered by the gui code
1595                 // (leaving the event loop).
1596                 if (current_view_)
1597                         current_view_->message(from_utf8(N_("Exiting.")));
1598                 if (closeAllViews())
1599                         quit();
1600                 break;
1601
1602         case LFUN_SCREEN_FONT_UPDATE: {
1603                 // handle the screen font changes.
1604                 d->font_loader_.update();
1605                 // Backup current_view_
1606                 GuiView * view = current_view_;
1607                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1608                 // to skip the refresh.
1609                 current_view_ = 0;
1610                 theBufferList().changed(false);
1611                 // Restore current_view_
1612                 current_view_ = view;
1613                 break;
1614         }
1615
1616         case LFUN_BUFFER_NEW:
1617                 validateCurrentView();
1618                 if (d->views_.empty()
1619                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1620                         createView(QString(), false); // keep hidden
1621                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1622                         current_view_->show();
1623                         setActiveWindow(current_view_);
1624                 } else {
1625                         current_view_->newDocument(to_utf8(cmd.argument()), false);
1626                 }
1627                 break;
1628
1629         case LFUN_BUFFER_NEW_TEMPLATE:
1630                 validateCurrentView();
1631                 if (d->views_.empty()
1632                    || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1633                         createView();
1634                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1635                         if (!current_view_->documentBufferView())
1636                                 current_view_->close();
1637                 } else {
1638                         current_view_->newDocument(to_utf8(cmd.argument()), true);
1639                 }
1640                 break;
1641
1642         case LFUN_FILE_OPEN: {
1643                 validateCurrentView();
1644                 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1645                 string const fname = to_utf8(cmd.argument());
1646                 bool const is_open = FileName::isAbsolute(fname)
1647                         && theBufferList().getBuffer(FileName(fname));
1648                 if (d->views_.empty()
1649                     || (!lyxrc.open_buffers_in_tabs
1650                         && current_view_->documentBufferView() != 0
1651                         && !is_open)) {
1652                         // We want the ui session to be saved per document and not per
1653                         // window number. The filename crc is a good enough identifier.
1654                         boost::crc_32_type crc;
1655                         crc = for_each(fname.begin(), fname.end(), crc);
1656                         createView(crc.checksum());
1657                         current_view_->openDocument(fname);
1658                         if (!current_view_->documentBufferView())
1659                                 current_view_->close();
1660                         else if (cmd.origin() == FuncRequest::LYXSERVER) {
1661                                 current_view_->raise();
1662                                 current_view_->activateWindow();
1663                                 current_view_->showNormal();
1664                         }
1665                 } else {
1666                         current_view_->openDocument(fname);
1667                         if (cmd.origin() == FuncRequest::LYXSERVER) {
1668                                 current_view_->raise();
1669                                 current_view_->activateWindow();
1670                                 current_view_->showNormal();
1671                         }
1672                 }
1673                 break;
1674         }
1675
1676         case LFUN_HELP_OPEN: {
1677                 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1678                 if (current_view_ == 0)
1679                         createView();
1680                 string const arg = to_utf8(cmd.argument());
1681                 if (arg.empty()) {
1682                         current_view_->message(_("Missing argument"));
1683                         break;
1684                 }
1685                 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1686                 if (fname.empty())
1687                         fname = i18nLibFileSearch("examples", arg, "lyx");
1688
1689                 if (fname.empty()) {
1690                         lyxerr << "LyX: unable to find documentation file `"
1691                                << arg << "'. Bad installation?" << endl;
1692                         break;
1693                 }
1694                 current_view_->message(bformat(_("Opening help file %1$s..."),
1695                                                makeDisplayPath(fname.absFileName())));
1696                 Buffer * buf = current_view_->loadDocument(fname, false);
1697
1698 #ifndef DEVEL_VERSION
1699                 if (buf)
1700                         buf->setReadonly(true);
1701 #else
1702                 (void) buf;
1703 #endif
1704                 break;
1705         }
1706
1707         case LFUN_SET_COLOR: {
1708                 string lyx_name;
1709                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1710                 if (lyx_name.empty() || x11_name.empty()) {
1711                         if (current_view_)
1712                                 current_view_->message(
1713                                         _("Syntax: set-color <lyx_name> <x11_name>"));
1714                         break;
1715                 }
1716
1717 #if 0
1718                 // FIXME: The graphics cache no longer has a changeDisplay method.
1719                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1720                 bool const graphicsbg_changed =
1721                                 lyx_name == graphicsbg && x11_name != graphicsbg;
1722                 if (graphicsbg_changed)
1723                         graphics::GCache::get().changeDisplay(true);
1724 #endif
1725
1726                 if (!lcolor.setColor(lyx_name, x11_name)) {
1727                         if (current_view_)
1728                                 current_view_->message(
1729                                         bformat(_("Set-color \"%1$s\" failed "
1730                                         "- color is undefined or "
1731                                         "may not be redefined"),
1732                                         from_utf8(lyx_name)));
1733                         break;
1734                 }
1735                 // Make sure we don't keep old colors in cache.
1736                 d->color_cache_.clear();
1737                 // Update the current view
1738                 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1739                 break;
1740         }
1741
1742         case LFUN_LYXRC_APPLY: {
1743                 // reset active key sequences, since the bindings
1744                 // are updated (bug 6064)
1745                 d->keyseq.reset();
1746                 LyXRC const lyxrc_orig = lyxrc;
1747
1748                 istringstream ss(to_utf8(cmd.argument()));
1749                 bool const success = lyxrc.read(ss);
1750
1751                 if (!success) {
1752                         lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1753                                         << "Unable to read lyxrc data"
1754                                         << endl;
1755                         break;
1756                 }
1757
1758                 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1759
1760                 // If the request comes from the minibuffer, then we can't reset
1761                 // the GUI, since that would destory the minibuffer itself and
1762                 // cause a crash, since we are currently in one of the methods of
1763                 // GuiCommandBuffer. See bug #8540.
1764                 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1765                         resetGui();
1766                 // else
1767                 //   FIXME Unfortunately, that leaves a bug here, since we cannot
1768                 //   reset the GUI in this case. If the changes to lyxrc affected the
1769                 //   UI, then, nothing would happen. This seems fairly unlikely, but
1770                 //   it definitely is a bug.
1771
1772                 break;
1773         }
1774
1775         case LFUN_COMMAND_PREFIX:
1776                 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1777                 break;
1778
1779         case LFUN_CANCEL: {
1780                 d->keyseq.reset();
1781                 d->meta_fake_bit = NoModifier;
1782                 GuiView * gv = currentView();
1783                 if (gv && gv->currentBufferView())
1784                         // cancel any selection
1785                         processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1786                 dr.setMessage(from_ascii(N_("Cancel")));
1787                 break;
1788         }
1789         case LFUN_META_PREFIX:
1790                 d->meta_fake_bit = AltModifier;
1791                 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1792                 break;
1793
1794         // --- Menus -----------------------------------------------
1795         case LFUN_RECONFIGURE:
1796                 // argument is any additional parameter to the configure.py command
1797                 reconfigure(to_utf8(cmd.argument()));
1798                 break;
1799
1800         // --- lyxserver commands ----------------------------
1801         case LFUN_SERVER_GET_FILENAME: {
1802                 if (current_view_ && current_view_->documentBufferView()) {
1803                         docstring const fname = from_utf8(
1804                                 current_view_->documentBufferView()->buffer().absFileName());
1805                         dr.setMessage(fname);
1806                         LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1807                 } else {
1808                         dr.setMessage(docstring());
1809                         LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1810                 }
1811                 break;
1812         }
1813
1814         case LFUN_SERVER_NOTIFY: {
1815                 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1816                 dr.setMessage(dispatch_buffer);
1817                 theServer().notifyClient(to_utf8(dispatch_buffer));
1818                 break;
1819         }
1820
1821         case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1822                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1823                 break;
1824
1825         case LFUN_REPEAT: {
1826                 // repeat command
1827                 string countstr;
1828                 string rest = split(argument, countstr, ' ');
1829                 istringstream is(countstr);
1830                 int count = 0;
1831                 is >> count;
1832                 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1833                 for (int i = 0; i < count; ++i)
1834                         dispatch(lyxaction.lookupFunc(rest));
1835                 break;
1836         }
1837
1838         case LFUN_COMMAND_SEQUENCE: {
1839                 // argument contains ';'-terminated commands
1840                 string arg = argument;
1841                 // FIXME: this LFUN should also work without any view.
1842                 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1843                                   ? &(current_view_->documentBufferView()->buffer()) : 0;
1844                 if (buffer)
1845                         buffer->undo().beginUndoGroup();
1846                 while (!arg.empty()) {
1847                         string first;
1848                         arg = split(arg, first, ';');
1849                         FuncRequest func(lyxaction.lookupFunc(first));
1850                         func.setOrigin(cmd.origin());
1851                         dispatch(func);
1852                 }
1853                 // the buffer may have been closed by one action
1854                 if (theBufferList().isLoaded(buffer))
1855                         buffer->undo().endUndoGroup();
1856                 break;
1857         }
1858
1859         case LFUN_BUFFER_FORALL: {
1860                 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1861
1862                 map<Buffer *, GuiView *> views_lVisible;
1863                 map<GuiView *, Buffer *> activeBuffers;
1864
1865                 QList<GuiView *> allViews = d->views_.values();
1866
1867                 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1868                 // and on which buffer is active in each view.
1869                 Buffer * const last = theBufferList().last();
1870                 foreach (GuiView * view, allViews) {
1871                         // all of the buffers might be locally hidden. That is, there is no active buffer.
1872                         if (!view || !view->currentBufferView())
1873                                 activeBuffers[view] = 0;
1874                         else
1875                                 activeBuffers[view] = &view->currentBufferView()->buffer();
1876
1877                         // find out if each is locally visible or locally hidden.
1878                         // we don't use a for loop as the buffer list cycles.
1879                         Buffer * b = theBufferList().first();
1880                         while (true) {
1881                                 bool const locallyVisible = view && view->workArea(*b);
1882                                 if (locallyVisible) {
1883                                         bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1884                                         // only need to overwrite/add if we don't already know a buffer is globally
1885                                         // visible or we do know but we would prefer to dispatch LFUN from the
1886                                         // current view because of cursor position issues.
1887                                         if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1888                                                 views_lVisible[b] = view;
1889                                 }
1890                                 if (b == last)
1891                                         break;
1892                                 b = theBufferList().next(b);
1893                         }
1894                 }
1895
1896                 GuiView * const homeView = currentView();
1897                 Buffer * b = theBufferList().first();
1898                 Buffer * nextBuf = 0;
1899                 int numProcessed = 0;
1900                 while (true) {
1901                         if (b != last)
1902                                 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1903
1904                         bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1905                         if (visible) {
1906                                 // first change to a view where b is locally visible, preferably current_view_.
1907                                 GuiView * const vLv = views_lVisible[b];
1908                                 vLv->setBuffer(b);
1909                                 lyx::dispatch(funcToRun);
1910                                 numProcessed++;
1911                         }
1912                         if (b == last)
1913                                 break;
1914                         b = nextBuf;
1915                 }
1916
1917                 // put things back to how they were (if possible).
1918                 foreach (GuiView * view, allViews) {
1919                         Buffer * originalBuf = activeBuffers[view];
1920                         // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1921                         if (theBufferList().isLoaded(originalBuf))
1922                                 view->setBuffer(originalBuf);
1923                 }
1924                 homeView->setFocus();
1925
1926                 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1927                 break;
1928         }
1929
1930         case LFUN_COMMAND_ALTERNATIVES: {
1931                 // argument contains ';'-terminated commands
1932                 string arg = argument;
1933                 while (!arg.empty()) {
1934                         string first;
1935                         arg = split(arg, first, ';');
1936                         FuncRequest func(lyxaction.lookupFunc(first));
1937                         func.setOrigin(cmd.origin());
1938                         FuncStatus const stat = getStatus(func);
1939                         if (stat.enabled()) {
1940                                 dispatch(func);
1941                                 break;
1942                         }
1943                 }
1944                 break;
1945         }
1946
1947         case LFUN_CALL: {
1948                 FuncRequest func;
1949                 if (theTopLevelCmdDef().lock(argument, func)) {
1950                         func.setOrigin(cmd.origin());
1951                         dispatch(func);
1952                         theTopLevelCmdDef().release(argument);
1953                 } else {
1954                         if (func.action() == LFUN_UNKNOWN_ACTION) {
1955                                 // unknown command definition
1956                                 lyxerr << "Warning: unknown command definition `"
1957                                                 << argument << "'"
1958                                                 << endl;
1959                         } else {
1960                                 // recursion detected
1961                                 lyxerr << "Warning: Recursion in the command definition `"
1962                                                 << argument << "' detected"
1963                                                 << endl;
1964                         }
1965                 }
1966                 break;
1967         }
1968
1969         case LFUN_PREFERENCES_SAVE:
1970                 lyxrc.write(support::makeAbsPath("preferences",
1971                         package().user_support().absFileName()), false);
1972                 break;
1973
1974         case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1975                 string const fname = addName(addPath(package().user_support().absFileName(),
1976                         "templates/"), "defaults.lyx");
1977                 Buffer defaults(fname);
1978
1979                 istringstream ss(argument);
1980                 Lexer lex;
1981                 lex.setStream(ss);
1982
1983                 // See #9236
1984                 // We need to make sure that, after we recreat the DocumentClass,
1985                 // which we do in readHeader, we apply it to the document itself.
1986                 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
1987                 int const unknown_tokens = defaults.readHeader(lex);
1988                 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
1989                 ErrorList el;
1990                 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
1991                 cap::switchBetweenClasses(olddc, newdc, theinset, el);
1992
1993                 if (unknown_tokens != 0) {
1994                         lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1995                                << unknown_tokens << " unknown token"
1996                                << (unknown_tokens == 1 ? "" : "s")
1997                                << endl;
1998                 }
1999
2000                 if (defaults.writeFile(FileName(defaults.absFileName())))
2001                         dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2002                                               makeDisplayPath(fname)));
2003                 else {
2004                         dr.setError(true);
2005                         dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2006                 }
2007                 break;
2008         }
2009
2010         case LFUN_BOOKMARK_GOTO:
2011                 // go to bookmark, open unopened file and switch to buffer if necessary
2012                 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2013                 dr.screenUpdate(Update::Force | Update::FitCursor);
2014                 break;
2015
2016         case LFUN_BOOKMARK_CLEAR:
2017                 theSession().bookmarks().clear();
2018                 break;
2019
2020         case LFUN_DEBUG_LEVEL_SET:
2021                 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2022                 break;
2023
2024         case LFUN_DIALOG_SHOW: {
2025                 string const name = cmd.getArg(0);
2026
2027                 if ( name == "aboutlyx"
2028                         || name == "prefs"
2029                         || name == "texinfo"
2030                         || name == "progress"
2031                         || name == "compare")
2032                 {
2033                         // work around: on Mac OS the application
2034                         // is not terminated when closing the last view.
2035                         // Create a new one to be able to dispatch the
2036                         // LFUN_DIALOG_SHOW to this view.
2037                         if (current_view_ == 0)
2038                                 createView();
2039                 }
2040                 // fall through
2041         }
2042
2043         default:
2044                 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2045                 // let's try that:
2046                 if (current_view_)
2047                         current_view_->dispatch(cmd, dr);
2048                 break;
2049         }
2050
2051         if (cmd.origin() == FuncRequest::LYXSERVER)
2052                 updateCurrentView(cmd, dr);
2053 }
2054
2055
2056 docstring GuiApplication::viewStatusMessage()
2057 {
2058         // When meta-fake key is pressed, show the key sequence so far + "M-".
2059         if (d->meta_fake_bit != NoModifier)
2060                 return d->keyseq.print(KeySequence::ForGui) + "M-";
2061
2062         // Else, when a non-complete key sequence is pressed,
2063         // show the available options.
2064         if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2065                 return d->keyseq.printOptions(true);
2066
2067         return docstring();
2068 }
2069
2070
2071 void GuiApplication::handleKeyFunc(FuncCode action)
2072 {
2073         char_type c = 0;
2074
2075         if (d->keyseq.length())
2076                 c = 0;
2077         GuiView * gv = currentView();
2078         LASSERT(gv && gv->currentBufferView(), return);
2079         BufferView * bv = gv->currentBufferView();
2080         bv->getIntl().getTransManager().deadkey(
2081                 c, get_accent(action).accent, bv->cursor().innerText(),
2082                 bv->cursor());
2083         // Need to clear, in case the minibuffer calls these
2084         // actions
2085         d->keyseq.clear();
2086         // copied verbatim from do_accent_char
2087         bv->cursor().resetAnchor();
2088 }
2089
2090
2091 //Keep this in sync with GuiApplication::processKeySym below
2092 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2093                                  KeyModifier state) const
2094 {
2095         // Do nothing if we have nothing
2096         if (!keysym.isOK() || keysym.isModifier())
2097                 return false;
2098         // Do a one-deep top-level lookup for cancel and meta-fake keys.
2099         KeySequence seq;
2100         FuncRequest func = seq.addkey(keysym, state);
2101         // When not cancel or meta-fake, do the normal lookup.
2102         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2103                 seq = d->keyseq;
2104                 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2105         }
2106         // Maybe user can only reach the key via holding down shift.
2107         // Let's see. But only if shift is the only modifier
2108         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2109                 // If addkey looked up a command and did not find further commands then
2110                 // seq has been reset at this point
2111                 func = seq.addkey(keysym, NoModifier);
2112
2113         LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2114                << seq.print(KeySequence::Portable) << ']');
2115         return func.action() != LFUN_UNKNOWN_ACTION;
2116 }
2117
2118
2119 //Keep this in sync with GuiApplication::queryKeySym above
2120 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2121 {
2122         LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2123
2124         // Do nothing if we have nothing (JMarc)
2125         if (!keysym.isOK() || keysym.isModifier()) {
2126                 if (!keysym.isOK())
2127                         LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2128                 if (current_view_)
2129                         current_view_->restartCursor();
2130                 return;
2131         }
2132
2133         char_type encoded_last_key = keysym.getUCSEncoded();
2134
2135         // Do a one-deep top-level lookup for
2136         // cancel and meta-fake keys. RVDK_PATCH_5
2137         d->cancel_meta_seq.reset();
2138
2139         FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2140         LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2141
2142         // When not cancel or meta-fake, do the normal lookup.
2143         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2144         // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2145         if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2146                 // remove Caps Lock and Mod2 as a modifiers
2147                 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2148                 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2149         }
2150
2151         // Dont remove this unless you know what you are doing.
2152         d->meta_fake_bit = NoModifier;
2153
2154         // Can this happen now ?
2155         if (func.action() == LFUN_NOACTION)
2156                 func = FuncRequest(LFUN_COMMAND_PREFIX);
2157
2158         LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2159                 << d->keyseq.print(KeySequence::Portable) << ']');
2160
2161         // already here we know if it any point in going further
2162         // why not return already here if action == -1 and
2163         // num_bytes == 0? (Lgb)
2164
2165         if (d->keyseq.length() > 1 && current_view_)
2166                 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2167
2168
2169         // Maybe user can only reach the key via holding down shift.
2170         // Let's see. But only if shift is the only modifier
2171         if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2172                 LYXERR(Debug::KEY, "Trying without shift");
2173                 // If addkey looked up a command and did not find further commands then
2174                 // seq has been reset at this point
2175                 func = d->keyseq.addkey(keysym, NoModifier);
2176                 LYXERR(Debug::KEY, "Action now " << func.action());
2177         }
2178
2179         if (func.action() == LFUN_UNKNOWN_ACTION) {
2180                 // We didn't match any of the key sequences.
2181                 // See if it's normal insertable text not already
2182                 // covered by a binding
2183                 if (keysym.isText() && d->keyseq.length() == 1) {
2184                         // Non-printable characters (such as ASCII control characters)
2185                         // must not be inserted (#5704)
2186                         if (!isPrintable(encoded_last_key)) {
2187                                 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2188                                 if (current_view_)
2189                                         current_view_->restartCursor();
2190                                 return;
2191                         }
2192                         // The following modifier check is not needed on Mac.
2193                         // The keysym is either not text or it is different
2194                         // from the non-modifier keysym. See #9875 for the
2195                         // broken alt-modifier effect of having this code active.
2196 #if !defined(Q_OS_MAC)
2197                         // If a non-Shift Modifier is used we have a non-bound key sequence
2198                         // (such as Alt+j = j). This should be omitted (#5575).
2199                         // On Windows, AltModifier and ControlModifier are both
2200                         // set when AltGr is pressed. Therefore, in order to not
2201                         // break AltGr-bound symbols (see #5575 for details),
2202                         // unbound Ctrl+Alt key sequences are allowed.
2203                         if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2204 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2205                             && !(state & AltModifier && state & ControlModifier)
2206 #endif
2207                             )
2208                         {
2209                                 if (current_view_) {
2210                                         current_view_->message(_("Unknown function."));
2211                                         current_view_->restartCursor();
2212                                 }
2213                                 return;
2214                         }
2215 #endif
2216                         // Since all checks above were passed, we now really have text that
2217                         // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2218                         // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2219                         // below.
2220                         LYXERR(Debug::KEY, "isText() is true, inserting.");
2221                         func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2222                 } else {
2223                         LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2224                         if (current_view_) {
2225                                 current_view_->message(_("Unknown function."));
2226                                 current_view_->restartCursor();
2227                         }
2228                         return;
2229                 }
2230         }
2231
2232         if (func.action() == LFUN_SELF_INSERT) {
2233                 if (encoded_last_key != 0) {
2234                         docstring const arg(1, encoded_last_key);
2235                         processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2236                                              FuncRequest::KEYBOARD));
2237                         LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2238                 }
2239         } else
2240                 processFuncRequest(func);
2241 }
2242
2243
2244 void GuiApplication::processFuncRequest(FuncRequest const & func)
2245 {
2246         lyx::dispatch(func);
2247 }
2248
2249
2250 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2251 {
2252         addToFuncRequestQueue(func);
2253         processFuncRequestQueueAsync();
2254 }
2255
2256
2257 void GuiApplication::processFuncRequestQueue()
2258 {
2259         while (!d->func_request_queue_.empty()) {
2260                 processFuncRequest(d->func_request_queue_.front());
2261                 d->func_request_queue_.pop();
2262         }
2263 }
2264
2265
2266 void GuiApplication::processFuncRequestQueueAsync()
2267 {
2268         QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2269 }
2270
2271
2272 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2273 {
2274         d->func_request_queue_.push(func);
2275 }
2276
2277
2278 void GuiApplication::resetGui()
2279 {
2280         // Set the language defined by the user.
2281         setGuiLanguage();
2282
2283         // Read menus
2284         if (!readUIFile(toqstr(lyxrc.ui_file)))
2285                 // Gives some error box here.
2286                 return;
2287
2288         if (d->global_menubar_)
2289                 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2290
2291         QHash<int, GuiView *>::iterator it;
2292         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2293                 GuiView * gv = *it;
2294                 setCurrentView(gv);
2295                 gv->setLayoutDirection(layoutDirection());
2296                 gv->resetDialogs();
2297         }
2298
2299         processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2300 }
2301
2302
2303 void GuiApplication::createView(int view_id)
2304 {
2305         createView(QString(), true, view_id);
2306 }
2307
2308
2309 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2310         int view_id)
2311 {
2312         // release the keyboard which might have been grabed by the global
2313         // menubar on Mac to catch shortcuts even without any GuiView.
2314         if (d->global_menubar_)
2315                 d->global_menubar_->releaseKeyboard();
2316
2317         // create new view
2318         int id = view_id;
2319         while (d->views_.find(id) != d->views_.end())
2320                 id++;
2321
2322         LYXERR(Debug::GUI, "About to create new window with ID " << id);
2323         GuiView * view = new GuiView(id);
2324         // register view
2325         d->views_[id] = view;
2326
2327         if (autoShow) {
2328                 view->show();
2329                 setActiveWindow(view);
2330         }
2331
2332         if (!geometry_arg.isEmpty()) {
2333 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2334                 int x, y;
2335                 int w, h;
2336                 QChar sx, sy;
2337                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2338                 re.indexIn(geometry_arg);
2339                 w = re.cap(1).toInt();
2340                 h = re.cap(2).toInt();
2341                 x = re.cap(3).toInt();
2342                 y = re.cap(4).toInt();
2343                 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2344                 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2345                 // Set initial geometry such that we can get the frame size.
2346                 view->setGeometry(x, y, w, h);
2347                 int framewidth = view->geometry().x() - view->x();
2348                 int titleheight = view->geometry().y() - view->y();
2349                 // Negative displacements must be interpreted as distances
2350                 // from the right or bottom screen borders.
2351                 if (sx == '-' || sy == '-') {
2352                         QRect rec = QApplication::desktop()->screenGeometry();
2353                         if (sx == '-')
2354                                 x += rec.width() - w - framewidth;
2355                         if (sy == '-')
2356                                 y += rec.height() - h - titleheight;
2357                         view->setGeometry(x, y, w, h);
2358                 }
2359                 // Make sure that the left and top frame borders are visible.
2360                 if (view->x() < 0 || view->y() < 0) {
2361                         if (view->x() < 0)
2362                                 x = framewidth;
2363                         if (view->y() < 0)
2364                                 y = titleheight;
2365                         view->setGeometry(x, y, w, h);
2366                 }
2367 #endif
2368         }
2369         view->setFocus();
2370 }
2371
2372
2373 Clipboard & GuiApplication::clipboard()
2374 {
2375         return d->clipboard_;
2376 }
2377
2378
2379 Selection & GuiApplication::selection()
2380 {
2381         return d->selection_;
2382 }
2383
2384
2385 FontLoader & GuiApplication::fontLoader()
2386 {
2387         return d->font_loader_;
2388 }
2389
2390
2391 Toolbars const & GuiApplication::toolbars() const
2392 {
2393         return d->toolbars_;
2394 }
2395
2396
2397 Toolbars & GuiApplication::toolbars()
2398 {
2399         return d->toolbars_;
2400 }
2401
2402
2403 Menus const & GuiApplication::menus() const
2404 {
2405         return d->menus_;
2406 }
2407
2408
2409 Menus & GuiApplication::menus()
2410 {
2411         return d->menus_;
2412 }
2413
2414
2415 QList<int> GuiApplication::viewIds() const
2416 {
2417         return d->views_.keys();
2418 }
2419
2420
2421 ColorCache & GuiApplication::colorCache()
2422 {
2423         return d->color_cache_;
2424 }
2425
2426
2427 int GuiApplication::exec()
2428 {
2429         // asynchronously handle batch commands. This event will be in
2430         // the event queue in front of other asynchronous events. Hence,
2431         // we can assume in the latter that the gui is setup already.
2432         QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2433
2434         return QApplication::exec();
2435 }
2436
2437
2438 void GuiApplication::exit(int status)
2439 {
2440         QApplication::exit(status);
2441 }
2442
2443
2444 void GuiApplication::setGuiLanguage()
2445 {
2446         setLocale();
2447         QLocale theLocale;
2448         // install translation file for Qt built-in dialogs
2449         QString const language_name = QString("qt_") + theLocale.name();
2450         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2451         // Short-named translator can be loaded from a long name, but not the
2452         // opposite. Therefore, long name should be used without truncation.
2453         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2454         if (!d->qt_trans_.load(language_name,
2455                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2456                 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2457                         << language_name);
2458         } else {
2459                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2460                         << language_name);
2461         }
2462
2463         switch (theLocale.language()) {
2464         case QLocale::Arabic :
2465         case QLocale::Hebrew :
2466         case QLocale::Persian :
2467         case QLocale::Urdu :
2468                 setLayoutDirection(Qt::RightToLeft);
2469                 break;
2470         default:
2471                 setLayoutDirection(Qt::LeftToRight);
2472         }
2473 }
2474
2475
2476 void GuiApplication::execBatchCommands()
2477 {
2478         setGuiLanguage();
2479
2480         // Read menus
2481         if (!readUIFile(toqstr(lyxrc.ui_file)))
2482                 // Gives some error box here.
2483                 return;
2484
2485 #ifdef Q_OS_MAC
2486 #if QT_VERSION > 0x040600
2487         setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2488 #endif
2489 #if QT_VERSION > 0x050100
2490         setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2491 #endif
2492         // Create the global default menubar which is shown for the dialogs
2493         // and if no GuiView is visible.
2494         // This must be done after the session was recovered to know the "last files".
2495         d->global_menubar_ = new QMenuBar(0);
2496         d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2497 #endif
2498
2499         lyx::execBatchCommands();
2500 }
2501
2502
2503 QAbstractItemModel * GuiApplication::languageModel()
2504 {
2505         if (d->language_model_)
2506                 return d->language_model_;
2507
2508         QStandardItemModel * lang_model = new QStandardItemModel(this);
2509         lang_model->insertColumns(0, 3);
2510         QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2511         QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2512         Languages::const_iterator it = lyx::languages.begin();
2513         Languages::const_iterator end = lyx::languages.end();
2514         for (; it != end; ++it) {
2515                 int current_row = lang_model->rowCount();
2516                 lang_model->insertRows(current_row, 1);
2517                 QModelIndex pl_item = lang_model->index(current_row, 0);
2518                 QModelIndex sp_item = lang_model->index(current_row, 1);
2519                 QModelIndex th_item = lang_model->index(current_row, 2);
2520                 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2521                 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2522                 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2523                 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2524                 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2525                         lang_model->setData(sp_item, speller, Qt::DecorationRole);
2526                 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2527                 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2528                 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2529                         lang_model->setData(th_item, saurus, Qt::DecorationRole);
2530         }
2531         d->language_model_ = new QSortFilterProxyModel(this);
2532         d->language_model_->setSourceModel(lang_model);
2533         d->language_model_->setSortLocaleAware(true);
2534         return d->language_model_;
2535 }
2536
2537
2538 void GuiApplication::restoreGuiSession()
2539 {
2540         if (!lyxrc.load_session)
2541                 return;
2542
2543         Session & session = theSession();
2544         LastOpenedSection::LastOpened const & lastopened =
2545                 session.lastOpened().getfiles();
2546
2547         validateCurrentView();
2548
2549         FileName active_file;
2550         // do not add to the lastfile list since these files are restored from
2551         // last session, and should be already there (regular files), or should
2552         // not be added at all (help files).
2553         for (size_t i = 0; i < lastopened.size(); ++i) {
2554                 FileName const & file_name = lastopened[i].file_name;
2555                 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2556                           && current_view_->documentBufferView() != 0)) {
2557                         boost::crc_32_type crc;
2558                         string const & fname = file_name.absFileName();
2559                         crc = for_each(fname.begin(), fname.end(), crc);
2560                         createView(crc.checksum());
2561                 }
2562                 current_view_->loadDocument(file_name, false);
2563
2564                 if (lastopened[i].active)
2565                         active_file = file_name;
2566         }
2567
2568         // Restore last active buffer
2569         Buffer * buffer = theBufferList().getBuffer(active_file);
2570         if (buffer && current_view_)
2571                 current_view_->setBuffer(buffer);
2572
2573         // clear this list to save a few bytes of RAM
2574         session.lastOpened().clear();
2575 }
2576
2577
2578 QString const GuiApplication::romanFontName()
2579 {
2580         QFont font;
2581         font.setStyleHint(QFont::Serif);
2582         font.setFamily("serif");
2583
2584         return QFontInfo(font).family();
2585 }
2586
2587
2588 QString const GuiApplication::sansFontName()
2589 {
2590         QFont font;
2591         font.setStyleHint(QFont::SansSerif);
2592         font.setFamily("sans");
2593
2594         return QFontInfo(font).family();
2595 }
2596
2597
2598 QString const GuiApplication::typewriterFontName()
2599 {
2600         return QFontInfo(typewriterSystemFont()).family();
2601 }
2602
2603
2604 namespace {
2605         // We cannot use QFont::fixedPitch() because it doesn't
2606         // return the fact but only if it is requested.
2607         static bool isFixedPitch(const QFont & font) {
2608                 const QFontInfo fi(font);
2609                 return fi.fixedPitch();
2610         }
2611 }
2612
2613
2614 QFont const GuiApplication::typewriterSystemFont()
2615 {
2616 #if QT_VERSION >= 0x050200
2617         QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2618 #else
2619         QFont font("monospace");
2620 #endif
2621         if (!isFixedPitch(font)) {
2622 #if QT_VERSION >= 0x040700
2623                 // try to enforce a real monospaced font
2624                 font.setStyleHint(QFont::Monospace);
2625 #endif
2626                 if (!isFixedPitch(font)) {
2627                         font.setStyleHint(QFont::TypeWriter);
2628                         if (!isFixedPitch(font)) font.setFamily("courier");
2629                 }
2630         }
2631 #ifdef Q_OS_MAC
2632         // On a Mac the result is too small and it's not practical to
2633         // rely on Qtconfig utility to change the system settings of Qt.
2634         font.setPointSize(12);
2635 #endif
2636         return font;
2637 }
2638
2639
2640 void GuiApplication::handleRegularEvents()
2641 {
2642         ForkedCallsController::handleCompletedProcesses();
2643 }
2644
2645
2646 bool GuiApplication::event(QEvent * e)
2647 {
2648         switch(e->type()) {
2649         case QEvent::FileOpen: {
2650                 // Open a file; this happens only on Mac OS X for now.
2651                 //
2652                 // We do this asynchronously because on startup the batch
2653                 // commands are not executed here yet and the gui is not ready
2654                 // therefore.
2655                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2656                 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2657                 processFuncRequestAsync(fr);
2658                 e->accept();
2659                 return true;
2660         }
2661         default:
2662                 return QApplication::event(e);
2663         }
2664 }
2665
2666
2667 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2668 {
2669         try {
2670                 return QApplication::notify(receiver, event);
2671         }
2672         catch (ExceptionMessage const & e) {
2673                 switch(e.type_) {
2674                 case ErrorException:
2675                         emergencyCleanup();
2676                         setQuitOnLastWindowClosed(false);
2677                         closeAllViews();
2678                         Alert::error(e.title_, e.details_);
2679 #ifndef NDEBUG
2680                         // Properly crash in debug mode in order to get a useful backtrace.
2681                         abort();
2682 #endif
2683                         // In release mode, try to exit gracefully.
2684                         this->exit(1);
2685
2686                 case BufferException: {
2687                         if (!current_view_ || !current_view_->documentBufferView())
2688                                 return false;
2689                         Buffer * buf = &current_view_->documentBufferView()->buffer();
2690                         docstring details = e.details_ + '\n';
2691                         details += buf->emergencyWrite();
2692                         theBufferList().release(buf);
2693                         details += "\n" + _("The current document was closed.");
2694                         Alert::error(e.title_, details);
2695                         return false;
2696                 }
2697                 case WarningException:
2698                         Alert::warning(e.title_, e.details_);
2699                         return false;
2700                 }
2701         }
2702         catch (exception const & e) {
2703                 docstring s = _("LyX has caught an exception, it will now "
2704                         "attempt to save all unsaved documents and exit."
2705                         "\n\nException: ");
2706                 s += from_ascii(e.what());
2707                 Alert::error(_("Software exception Detected"), s);
2708                 lyx_exit(1);
2709         }
2710         catch (...) {
2711                 docstring s = _("LyX has caught some really weird exception, it will "
2712                         "now attempt to save all unsaved documents and exit.");
2713                 Alert::error(_("Software exception Detected"), s);
2714                 lyx_exit(1);
2715         }
2716
2717         return false;
2718 }
2719
2720
2721 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2722 {
2723         QColor const & qcol = d->color_cache_.get(col);
2724         if (!qcol.isValid()) {
2725                 rgbcol.r = 0;
2726                 rgbcol.g = 0;
2727                 rgbcol.b = 0;
2728                 return false;
2729         }
2730         rgbcol.r = qcol.red();
2731         rgbcol.g = qcol.green();
2732         rgbcol.b = qcol.blue();
2733         return true;
2734 }
2735
2736
2737 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2738 {
2739         QColor const qcol(lcolor.getX11Name(col).c_str());
2740         if (!qcol.isValid()) {
2741                 rgbcol.r = 0;
2742                 rgbcol.g = 0;
2743                 rgbcol.b = 0;
2744                 return false;
2745         }
2746         rgbcol.r = qcol.red();
2747         rgbcol.g = qcol.green();
2748         rgbcol.b = qcol.blue();
2749         return true;
2750 }
2751
2752
2753 string const GuiApplication::hexName(ColorCode col)
2754 {
2755         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2756 }
2757
2758
2759 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2760 {
2761         SocketNotifier * sn = new SocketNotifier(this, fd, func);
2762         d->socket_notifiers_[fd] = sn;
2763         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2764 }
2765
2766
2767 void GuiApplication::socketDataReceived(int fd)
2768 {
2769         d->socket_notifiers_[fd]->func_();
2770 }
2771
2772
2773 void GuiApplication::unregisterSocketCallback(int fd)
2774 {
2775         d->socket_notifiers_.take(fd)->setEnabled(false);
2776 }
2777
2778
2779 void GuiApplication::commitData(QSessionManager & sm)
2780 {
2781         /** The implementation is required to avoid an application exit
2782          ** when session state save is triggered by session manager.
2783          ** The default implementation sends a close event to all
2784          ** visible top level widgets when session managment allows
2785          ** interaction.
2786          ** We are changing that to check the state of each buffer in all
2787          ** views and ask the users what to do if buffers are dirty.
2788          ** Furthermore, we save the session state.
2789          ** We do NOT close the views here since the user still can cancel
2790          ** the logout process (see #9277); also, this would hide LyX from
2791          ** an OSes own session handling (application restoration).
2792          **/
2793         #ifdef QT_NO_SESSIONMANAGER
2794                 #ifndef _MSC_VER
2795                         #warning Qt is compiled without session manager
2796                 #else
2797                         #pragma message("warning: Qt is compiled without session manager")
2798                 #endif
2799                 (void) sm;
2800         #else
2801                 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2802                         sm.cancel();
2803                 else
2804                         sm.release();
2805         #endif
2806 }
2807
2808
2809 void GuiApplication::unregisterView(GuiView * gv)
2810 {
2811         if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2812                 d->views_.remove(gv->id());
2813                 if (current_view_ == gv)
2814                         current_view_ = 0;
2815         }
2816 }
2817
2818
2819 bool GuiApplication::closeAllViews()
2820 {
2821         if (d->views_.empty())
2822                 return true;
2823
2824         // When a view/window was closed before without quitting LyX, there
2825         // are already entries in the lastOpened list.
2826         theSession().lastOpened().clear();
2827
2828         QList<GuiView *> const views = d->views_.values();
2829         foreach (GuiView * view, views) {
2830                 if (!view->closeScheduled())
2831                         return false;
2832         }
2833
2834         d->views_.clear();
2835         return true;
2836 }
2837
2838
2839 bool GuiApplication::prepareAllViewsForLogout()
2840 {
2841         if (d->views_.empty())
2842                 return true;
2843
2844         QList<GuiView *> const views = d->views_.values();
2845         foreach (GuiView * view, views) {
2846                 if (!view->prepareAllBuffersForLogout())
2847                         return false;
2848         }
2849
2850         return true;
2851 }
2852
2853
2854 GuiView & GuiApplication::view(int id) const
2855 {
2856         LAPPERR(d->views_.contains(id));
2857         return *d->views_.value(id);
2858 }
2859
2860
2861 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2862 {
2863         QList<GuiView *> const views = d->views_.values();
2864         foreach (GuiView * view, views)
2865                 view->hideDialog(name, inset);
2866 }
2867
2868
2869 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2870 {
2871         Buffer const * buffer_ = 0;
2872         QHash<int, GuiView *>::const_iterator end = d->views_.end();
2873         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2874                 if (Buffer const * ptr = (*it)->updateInset(inset))
2875                         buffer_ = ptr;
2876         }
2877         return buffer_;
2878 }
2879
2880
2881 bool GuiApplication::searchMenu(FuncRequest const & func,
2882         docstring_list & names) const
2883 {
2884         return d->menus_.searchMenu(func, names);
2885 }
2886
2887
2888 // Ensure that a file is read only once (prevents include loops)
2889 static QStringList uifiles;
2890 // store which ui files define Toolbars
2891 static QStringList toolbar_uifiles;
2892
2893
2894 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2895 {
2896         enum {
2897                 ui_menuset = 1,
2898                 ui_toolbars,
2899                 ui_toolbarset,
2900                 ui_include,
2901                 ui_format,
2902                 ui_last
2903         };
2904
2905         LexerKeyword uitags[] = {
2906                 { "format", ui_format },
2907                 { "include", ui_include },
2908                 { "menuset", ui_menuset },
2909                 { "toolbars", ui_toolbars },
2910                 { "toolbarset", ui_toolbarset }
2911         };
2912
2913         Lexer lex(uitags);
2914         lex.setFile(ui_path);
2915         if (!lex.isOK()) {
2916                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2917                                          << endl;
2918         }
2919
2920         if (lyxerr.debugging(Debug::PARSER))
2921                 lex.printTable(lyxerr);
2922
2923         bool error = false;
2924         // format before introduction of format tag
2925         unsigned int format = 0;
2926         while (lex.isOK()) {
2927                 int const status = lex.lex();
2928
2929                 // we have to do this check here, outside the switch,
2930                 // because otherwise we would start reading include files,
2931                 // e.g., if the first tag we hit was an include tag.
2932                 if (status == ui_format)
2933                         if (lex.next()) {
2934                                 format = lex.getInteger();
2935                                 continue;
2936                         }
2937
2938                 // this will trigger unless the first tag we hit is a format
2939                 // tag, with the right format.
2940                 if (format != LFUN_FORMAT)
2941                         return FormatMismatch;
2942
2943                 switch (status) {
2944                 case Lexer::LEX_FEOF:
2945                         continue;
2946
2947                 case ui_include: {
2948                         lex.next(true);
2949                         QString const file = toqstr(lex.getString());
2950                         bool const success = readUIFile(file, true);
2951                         if (!success) {
2952                                 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2953                                 return ReadError;
2954                         }
2955                         break;
2956                 }
2957
2958                 case ui_menuset:
2959                         d->menus_.read(lex);
2960                         break;
2961
2962                 case ui_toolbarset:
2963                         d->toolbars_.readToolbars(lex);
2964                         break;
2965
2966                 case ui_toolbars:
2967                         d->toolbars_.readToolbarSettings(lex);
2968                         toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2969                         break;
2970
2971                 default:
2972                         if (!rtrim(lex.getString()).empty())
2973                                 lex.printError("LyX::ReadUIFile: "
2974                                                "Unknown menu tag: `$$Token'");
2975                         else
2976                                 LYXERR0("Error with status: " << status);
2977                         error = true;
2978                         break;
2979                 }
2980
2981         }
2982         return (error ? ReadError : ReadOK);
2983 }
2984
2985
2986 bool GuiApplication::readUIFile(QString const & name, bool include)
2987 {
2988         LYXERR(Debug::INIT, "About to read " << name << "...");
2989
2990         FileName ui_path;
2991         if (include) {
2992                 ui_path = libFileSearch("ui", name, "inc");
2993                 if (ui_path.empty())
2994                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2995         } else {
2996                 ui_path = libFileSearch("ui", name, "ui");
2997         }
2998
2999         if (ui_path.empty()) {
3000                 static const QString defaultUIFile = "default";
3001                 LYXERR(Debug::INIT, "Could not find " << name);
3002                 if (include) {
3003                         Alert::warning(_("Could not find UI definition file"),
3004                                 bformat(_("Error while reading the included file\n%1$s\n"
3005                                         "Please check your installation."), qstring_to_ucs4(name)));
3006                         return false;
3007                 }
3008                 if (name == defaultUIFile) {
3009                         LYXERR(Debug::INIT, "Could not find default UI file!!");
3010                         Alert::warning(_("Could not find default UI file"),
3011                                 _("LyX could not find the default UI file!\n"
3012                                   "Please check your installation."));
3013                         return false;
3014                 }
3015                 Alert::warning(_("Could not find UI definition file"),
3016                 bformat(_("Error while reading the configuration file\n%1$s\n"
3017                         "Falling back to default.\n"
3018                         "Please look under Tools>Preferences>User Interface and\n"
3019                         "check which User Interface file you are using."), qstring_to_ucs4(name)));
3020                 return readUIFile(defaultUIFile, false);
3021         }
3022
3023         QString const uifile = toqstr(ui_path.absFileName());
3024         if (uifiles.contains(uifile)) {
3025                 if (!include) {
3026                         // We are reading again the top uifile so reset the safeguard:
3027                         uifiles.clear();
3028                         d->menus_.reset();
3029                         d->toolbars_.reset();
3030                 } else {
3031                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3032                                 << "Is this an include loop?");
3033                         return false;
3034                 }
3035         }
3036         uifiles.push_back(uifile);
3037
3038         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3039
3040         ReturnValues retval = readUIFile(ui_path);
3041
3042         if (retval == FormatMismatch) {
3043                 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3044                 TempFile tmp("convertXXXXXX.ui");
3045                 FileName const tempfile = tmp.name();
3046                 bool const success = prefs2prefs(ui_path, tempfile, true);
3047                 if (!success) {
3048                         LYXERR0("Unable to convert " << ui_path.absFileName() <<
3049                                 " to format " << LFUN_FORMAT << ".");
3050                 } else {
3051                         retval = readUIFile(tempfile);
3052                 }
3053         }
3054
3055         if (retval != ReadOK) {
3056                 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3057                 return false;
3058         }
3059
3060         if (include)
3061                 return true;
3062
3063         QSettings settings;
3064         settings.beginGroup("ui_files");
3065         bool touched = false;
3066         for (int i = 0; i != uifiles.size(); ++i) {
3067                 QFileInfo fi(uifiles[i]);
3068                 QDateTime const date_value = fi.lastModified();
3069                 QString const name_key = QString::number(i);
3070                 // if an ui file which defines Toolbars has changed,
3071                 // we have to reset the settings
3072                 if (toolbar_uifiles.contains(uifiles[i])
3073                  && (!settings.contains(name_key)
3074                  || settings.value(name_key).toString() != uifiles[i]
3075                  || settings.value(name_key + "/date").toDateTime() != date_value)) {
3076                         touched = true;
3077                         settings.setValue(name_key, uifiles[i]);
3078                         settings.setValue(name_key + "/date", date_value);
3079                 }
3080         }
3081         settings.endGroup();
3082         if (touched)
3083                 settings.remove("views");
3084
3085         return true;
3086 }
3087
3088
3089 void GuiApplication::onLastWindowClosed()
3090 {
3091         if (d->global_menubar_)
3092                 d->global_menubar_->grabKeyboard();
3093 }
3094
3095
3096 void GuiApplication::startLongOperation() {
3097         d->key_checker_.start();
3098 }
3099
3100
3101 bool GuiApplication::longOperationCancelled() {
3102         return d->key_checker_.pressed();
3103 }
3104
3105
3106 void GuiApplication::stopLongOperation() {
3107         d->key_checker_.stop();
3108 }
3109
3110
3111 bool GuiApplication::longOperationStarted() {
3112         return d->key_checker_.started();
3113 }
3114
3115
3116 ////////////////////////////////////////////////////////////////////////
3117 //
3118 // X11 specific stuff goes here...
3119
3120 #ifdef Q_WS_X11
3121 bool GuiApplication::x11EventFilter(XEvent * xev)
3122 {
3123         if (!current_view_)
3124                 return false;
3125
3126         switch (xev->type) {
3127         case SelectionRequest: {
3128                 if (xev->xselectionrequest.selection != XA_PRIMARY)
3129                         break;
3130                 LYXERR(Debug::SELECTION, "X requested selection.");
3131                 BufferView * bv = current_view_->currentBufferView();
3132                 if (bv) {
3133                         docstring const sel = bv->requestSelection();
3134                         if (!sel.empty())
3135                                 d->selection_.put(sel);
3136                 }
3137                 break;
3138         }
3139         case SelectionClear: {
3140                 if (xev->xselectionclear.selection != XA_PRIMARY)
3141                         break;
3142                 LYXERR(Debug::SELECTION, "Lost selection.");
3143                 BufferView * bv = current_view_->currentBufferView();
3144                 if (bv)
3145                         bv->clearSelection();
3146                 break;
3147         }
3148         }
3149         return false;
3150 }
3151 #elif defined(QPA_XCB)
3152 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3153                                        void * message, long *)
3154 {
3155         if (!current_view_ || eventType != "xcb_generic_event_t")
3156                 return false;
3157
3158         xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3159
3160         switch (ev->response_type) {
3161         case XCB_SELECTION_REQUEST: {
3162                 xcb_selection_request_event_t * srev =
3163                         reinterpret_cast<xcb_selection_request_event_t *>(ev);
3164                 if (srev->selection != XCB_ATOM_PRIMARY)
3165                         break;
3166                 LYXERR(Debug::SELECTION, "X requested selection.");
3167                 BufferView * bv = current_view_->currentBufferView();
3168                 if (bv) {
3169                         docstring const sel = bv->requestSelection();
3170                         if (!sel.empty())
3171                                 d->selection_.put(sel);
3172                 }
3173                 break;
3174         }
3175         case XCB_SELECTION_CLEAR: {
3176                 xcb_selection_clear_event_t * scev =
3177                         reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3178                 if (scev->selection != XCB_ATOM_PRIMARY)
3179                         break;
3180                 LYXERR(Debug::SELECTION, "Lost selection.");
3181                 BufferView * bv = current_view_->currentBufferView();
3182                 if (bv)
3183                         bv->clearSelection();
3184                 break;
3185         }
3186         }
3187         return false;
3188 }
3189 #endif
3190
3191 } // namespace frontend
3192
3193
3194 void hideDialogs(std::string const & name, Inset * inset)
3195 {
3196         if (theApp())
3197                 frontend::guiApp->hideDialogs(name, inset);
3198 }
3199
3200
3201 ////////////////////////////////////////////////////////////////////
3202 //
3203 // Font stuff
3204 //
3205 ////////////////////////////////////////////////////////////////////
3206
3207 frontend::FontLoader & theFontLoader()
3208 {
3209         LAPPERR(frontend::guiApp);
3210         return frontend::guiApp->fontLoader();
3211 }
3212
3213
3214 frontend::FontMetrics const & theFontMetrics(Font const & f)
3215 {
3216         return theFontMetrics(f.fontInfo());
3217 }
3218
3219
3220 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3221 {
3222         LAPPERR(frontend::guiApp);
3223         return frontend::guiApp->fontLoader().metrics(f);
3224 }
3225
3226
3227 ////////////////////////////////////////////////////////////////////
3228 //
3229 // Misc stuff
3230 //
3231 ////////////////////////////////////////////////////////////////////
3232
3233 frontend::Clipboard & theClipboard()
3234 {
3235         LAPPERR(frontend::guiApp);
3236         return frontend::guiApp->clipboard();
3237 }
3238
3239
3240 frontend::Selection & theSelection()
3241 {
3242         LAPPERR(frontend::guiApp);
3243         return frontend::guiApp->selection();
3244 }
3245
3246
3247 } // namespace lyx
3248
3249 #include "moc_GuiApplication.cpp"