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