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