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