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