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