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