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