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