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