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