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