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