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