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