]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/GuiApplication.cpp
better naming for encoding default, as discussed in bug 4971.
[lyx.git] / src / frontends / qt4 / GuiApplication.cpp
1 /**
2  * \file GuiApplication.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author unknown
7  * \author John Levon
8  * \author Abdelrazak Younes
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GuiApplication.h"
16
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
19 #include "GuiImage.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
22 #include "GuiView.h"
23 #include "Menus.h"
24 #include "qt_helpers.h"
25 #include "Toolbars.h"
26
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
31
32 #include "Buffer.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
35 #include "Color.h"
36 #include "Font.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
39 #include "Language.h"
40 #include "Lexer.h"
41 #include "LyX.h"
42 #include "LyXAction.h"
43 #include "LyXFunc.h"
44 #include "LyXRC.h"
45 #include "Session.h"
46 #include "version.h"
47
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/ExceptionMessage.h"
51 #include "support/FileName.h"
52 #include "support/foreach.h"
53 #include "support/ForkedCalls.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // sorted
57 #include "support/Messages.h"
58 #include "support/os.h"
59 #include "support/Package.h"
60
61 #ifdef Q_WS_MACX
62 #include "support/linkback/LinkBackProxy.h"
63 #endif
64
65 #include <QByteArray>
66 #include <QClipboard>
67 #include <QDir>
68 #include <QEventLoop>
69 #include <QFileOpenEvent>
70 #include <QHash>
71 #include <QIcon>
72 #include <QImageReader>
73 #include <QLocale>
74 #include <QLibraryInfo>
75 #include <QList>
76 #include <QMacPasteboardMime>
77 #include <QMenuBar>
78 #include <QMimeData>
79 #include <QObject>
80 #include <QPixmap>
81 #include <QPixmapCache>
82 #include <QRegExp>
83 #include <QSessionManager>
84 #include <QSocketNotifier>
85 #include <QSortFilterProxyModel>
86 #include <QStandardItemModel>
87 #include <QTextCodec>
88 #include <QTimer>
89 #include <QTranslator>
90 #include <QWidget>
91
92 #ifdef Q_WS_X11
93 #include <X11/Xatom.h>
94 #include <X11/Xlib.h>
95 #undef CursorShape
96 #undef None
97 #endif
98
99 #ifdef Q_WS_WIN
100 #include <QWindowsMime>
101 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
102 #include <wtypes.h>
103 #endif
104 #include <objidl.h>
105 #endif // Q_WS_WIN
106
107 #include <boost/bind.hpp>
108 #include <boost/crc.hpp>
109
110 #include <exception>
111 #include <vector>
112
113 using namespace std;
114 using namespace lyx::support;
115
116
117 static void initializeResources()
118 {
119         static bool initialized = false;
120         if (!initialized) {
121                 Q_INIT_RESOURCE(Resources); 
122                 initialized = true;
123         }
124 }
125
126
127 namespace lyx {
128
129 frontend::Application * createApplication(int & argc, char * argv[])
130 {
131         return new frontend::GuiApplication(argc, argv);
132 }
133
134 namespace frontend {
135
136
137 /// Return the list of loadable formats.
138 vector<string> loadableImageFormats()
139 {
140         vector<string> fmts;
141
142         QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
143
144         LYXERR(Debug::GRAPHICS,
145                 "\nThe image loader can load the following directly:\n");
146
147         if (qt_formats.empty())
148                 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
149
150         for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
151
152                 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
153
154                 string ext = ascii_lowercase((const char *) *it);
155                 // special case
156                 if (ext == "jpeg")
157                         ext = "jpg";
158                 fmts.push_back(ext);
159         }
160
161         return fmts;
162 }
163         
164 ////////////////////////////////////////////////////////////////////////
165 // Icon loading support code.
166 ////////////////////////////////////////////////////////////////////////
167
168 namespace {
169
170 struct PngMap {
171         QString key;
172         QString value;
173 };
174
175
176 bool operator<(PngMap const & lhs, PngMap const & rhs)
177 {
178         return lhs.key < rhs.key;
179 }
180
181
182 class CompareKey {
183 public:
184         CompareKey(QString const & name) : name_(name) {}
185         bool operator()(PngMap const & other) const { return other.key == name_; }
186 private:
187         QString const name_;
188 };
189
190
191 // this must be sorted alphabetically
192 // Upper case comes before lower case
193 PngMap sorted_png_map[] = {
194         { "Bumpeq", "bumpeq2" },
195         { "Cap", "cap2" },
196         { "Cup", "cup2" },
197         { "Delta", "delta2" },
198         { "Downarrow", "downarrow2" },
199         { "Gamma", "gamma2" },
200         { "Lambda", "lambda2" },
201         { "Leftarrow", "leftarrow2" },
202         { "Leftrightarrow", "leftrightarrow2" },
203         { "Longleftarrow", "longleftarrow2" },
204         { "Longleftrightarrow", "longleftrightarrow2" },
205         { "Longrightarrow", "longrightarrow2" },
206         { "Omega", "omega2" },
207         { "Phi", "phi2" },
208         { "Pi", "pi2" },
209         { "Psi", "psi2" },
210         { "Rightarrow", "rightarrow2" },
211         { "Sigma", "sigma2" },
212         { "Subset", "subset2" },
213         { "Supset", "supset2" },
214         { "Theta", "theta2" },
215         { "Uparrow", "uparrow2" },
216         { "Updownarrow", "updownarrow2" },
217         { "Upsilon", "upsilon2" },
218         { "Vdash", "vdash3" },
219         { "Vert", "vert2" },
220         { "Xi", "xi2" },
221         { "nLeftarrow", "nleftarrow2" },
222         { "nLeftrightarrow", "nleftrightarrow2" },
223         { "nRightarrow", "nrightarrow2" },
224         { "nVDash", "nvdash3" },
225         { "nvDash", "nvdash2" },
226         { "textrm \\AA", "textrm_AA"},
227         { "textrm \\O", "textrm_O"},
228         { "vDash", "vdash2" }
229 };
230
231 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
232
233
234 QString findPng(QString const & name)
235 {
236         PngMap const * const begin = sorted_png_map;
237         PngMap const * const end = begin + nr_sorted_png_map;
238         LASSERT(sorted(begin, end), /**/);
239
240         PngMap const * const it = find_if(begin, end, CompareKey(name));
241
242         QString png_name;
243         if (it != end) {
244                 png_name = it->value;
245         } else {
246                 png_name = name;
247                 png_name.replace('_', "underscore");
248                 png_name.replace(' ', '_');
249
250                 // This way we can have "math-delim { }" on the toolbar.
251                 png_name.replace('(', "lparen");
252                 png_name.replace(')', "rparen");
253                 png_name.replace('[', "lbracket");
254                 png_name.replace(']', "rbracket");
255                 png_name.replace('{', "lbrace");
256                 png_name.replace('}', "rbrace");
257                 png_name.replace('|', "bars");
258                 png_name.replace(',', "thinspace");
259                 png_name.replace(':', "mediumspace");
260                 png_name.replace(';', "thickspace");
261                 png_name.replace('!', "negthinspace");
262         }
263
264         LYXERR(Debug::GUI, "findPng(" << name << ")\n"
265                 << "Looking for math PNG called \"" << png_name << '"');
266         return png_name;
267 }
268
269 } // namespace anon
270
271
272 QString iconName(FuncRequest const & f, bool unknown)
273 {
274         initializeResources();
275         QString name1;
276         QString name2;
277         QString path;
278         switch (f.action) {
279         case LFUN_MATH_INSERT:
280                 if (!f.argument().empty()) {
281                         path = "math/";
282                         name1 = findPng(toqstr(f.argument()).mid(1));
283                 }
284                 break;
285         case LFUN_MATH_DELIM:
286         case LFUN_MATH_BIGDELIM:
287                 path = "math/";
288                 name1 = findPng(toqstr(f.argument()));
289                 break;
290         case LFUN_CALL:
291                 path = "commands/";
292                 name1 = toqstr(f.argument());
293                 break;
294         default:
295                 name2 = toqstr(lyxaction.getActionName(f.action));
296                 name1 = name2;
297
298                 if (!f.argument().empty()) {
299                         name1 = name2 + ' ' + toqstr(f.argument());
300                         name1.replace(' ', '_');
301                 }
302         }
303
304         FileName fname = libFileSearch("images/" + path, name1, "png");
305         if (fname.exists())
306                 return toqstr(fname.absFilename());
307
308         fname = libFileSearch("images/" + path, name2, "png");
309         if (fname.exists())
310                 return toqstr(fname.absFilename());
311
312         path = ":/images/" + path;
313         QDir res(path);
314         if (!res.exists()) {
315                 LYXERR0("Directory " << path << " not found in resource!"); 
316                 return QString();
317         }
318         name1 += ".png";
319         if (res.exists(name1))
320                 return path + name1;
321
322         name2 += ".png";
323         if (res.exists(name2))
324                 return path + name2;
325
326         LYXERR(Debug::GUI, "Cannot find icon for command \""
327                            << lyxaction.getActionName(f.action)
328                            << '(' << to_utf8(f.argument()) << ")\"");
329
330         if (unknown)
331                 return QString(":/images/unknown.png");
332
333         return QString();
334 }
335
336
337 QIcon getIcon(FuncRequest const & f, bool unknown)
338 {
339         QString icon = iconName(f, unknown);
340         if (icon.isEmpty())
341                 return QIcon();
342
343         //LYXERR(Debug::GUI, "Found icon: " << icon);
344         QPixmap pm;
345         if (!pm.load(icon)) {
346                 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
347                 return QIcon();
348         }
349
350         return QIcon(pm);
351 }
352
353
354 ////////////////////////////////////////////////////////////////////////
355 // LyX server support code.
356 ////////////////////////////////////////////////////////////////////////
357 class SocketNotifier : public QSocketNotifier
358 {
359 public:
360         /// connect a connection notification from the LyXServerSocket
361         SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
362                 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
363         {}
364
365 public:
366         /// The callback function
367         Application::SocketCallback func_;
368 };
369
370
371 ////////////////////////////////////////////////////////////////////////
372 // Mac specific stuff goes here...
373 ////////////////////////////////////////////////////////////////////////
374
375 class MenuTranslator : public QTranslator
376 {
377 public:
378         MenuTranslator(QObject * parent)
379                 : QTranslator(parent)
380         {}
381
382         QString translate(const char * /*context*/, 
383           const char * sourceText, 
384           const char * /*comment*/ = 0) 
385         {
386                 string const s = sourceText;
387                 if (s == N_("About %1") || s == N_("Preferences") 
388                                 || s == N_("Reconfigure") || s == N_("Quit %1"))
389                         return qt_(s);
390                 else 
391                         return QString();
392         }
393 };
394
395 class GlobalMenuBar : public QMenuBar
396 {
397 public:
398         ///
399         GlobalMenuBar() : QMenuBar(0) {}
400         
401         ///
402         bool event(QEvent * e)
403         {
404                 if (e->type() == QEvent::ShortcutOverride) {
405                         //          && activeWindow() == 0) {
406                         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
407                         KeySymbol sym;
408                         setKeySymbol(&sym, ke);
409                         theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
410                         e->accept();
411                         return true;
412                 }
413                 return false;
414         }
415 };
416
417 #ifdef Q_WS_MACX
418 // QMacPasteboardMimeGraphics can only be compiled on Mac.
419
420 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
421 {
422 public:
423         QMacPasteboardMimeGraphics()
424                 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
425         {}
426
427         QString convertorName() { return "Graphics"; }
428
429         QString flavorFor(QString const & mime)
430         {
431                 LYXERR(Debug::ACTION, "flavorFor " << mime);
432                 if (mime == pdfMimeType())
433                         return QLatin1String("com.adobe.pdf");
434                 return QString();
435         }
436
437         QString mimeFor(QString flav)
438         {
439                 LYXERR(Debug::ACTION, "mimeFor " << flav);
440                 if (flav == QLatin1String("com.adobe.pdf"))
441                         return pdfMimeType();
442                 return QString();
443         }
444
445         bool canConvert(QString const & mime, QString flav)
446         {
447                 return mimeFor(flav) == mime;
448         }
449
450         QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
451                 QString /*flav*/)
452         {
453                 if(data.count() > 1)
454                         qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
455                 return data.first();
456         }
457
458         QList<QByteArray> convertFromMime(QString const & /*mime*/,
459                 QVariant data, QString /*flav*/)
460         {
461                 QList<QByteArray> ret;
462                 ret.append(data.toByteArray());
463                 return ret;
464         }
465 };
466 #endif
467
468 ///////////////////////////////////////////////////////////////
469 // You can find more platform specific stuff
470 // at the end of this file...
471 ///////////////////////////////////////////////////////////////
472
473 ////////////////////////////////////////////////////////////////////////
474 // Windows specific stuff goes here...
475
476 #ifdef Q_WS_WIN
477 // QWindowsMimeMetafile can only be compiled on Windows.
478
479 static FORMATETC cfFromMime(QString const & mimetype)
480 {
481         FORMATETC formatetc;
482         if (mimetype == emfMimeType()) {
483                 formatetc.cfFormat = CF_ENHMETAFILE;
484                 formatetc.tymed = TYMED_ENHMF;
485         } else if (mimetype == wmfMimeType()) {
486                 formatetc.cfFormat = CF_METAFILEPICT;
487                 formatetc.tymed = TYMED_MFPICT;
488         }
489         formatetc.ptd = 0;
490         formatetc.dwAspect = DVASPECT_CONTENT;
491         formatetc.lindex = -1;
492         return formatetc;
493 }
494
495
496 class QWindowsMimeMetafile : public QWindowsMime {
497 public:
498         QWindowsMimeMetafile() {}
499
500         bool canConvertFromMime(FORMATETC const & formatetc,
501                 QMimeData const * mimedata) const
502         {
503                 return false;
504         }
505
506         bool canConvertToMime(QString const & mimetype,
507                 IDataObject * pDataObj) const
508         {
509                 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
510                         return false;
511                 FORMATETC formatetc = cfFromMime(mimetype);
512                 return pDataObj->QueryGetData(&formatetc) == S_OK;
513         }
514
515         bool convertFromMime(FORMATETC const & formatetc,
516                 const QMimeData * mimedata, STGMEDIUM * pmedium) const
517         {
518                 return false;
519         }
520
521         QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
522                 QVariant::Type preferredType) const
523         {
524                 QByteArray data;
525                 if (!canConvertToMime(mimetype, pDataObj))
526                         return data;
527
528                 FORMATETC formatetc = cfFromMime(mimetype);
529                 STGMEDIUM s;
530                 if (pDataObj->GetData(&formatetc, &s) != S_OK)
531                         return data;
532
533                 int dataSize;
534                 if (s.tymed == TYMED_ENHMF) {
535                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
536                         data.resize(dataSize);
537                         dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
538                                 (LPBYTE)data.data());
539                 } else if (s.tymed == TYMED_MFPICT) {
540                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
541                         data.resize(dataSize);
542                         dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
543                                 (LPBYTE)data.data());
544                 }
545                 data.detach();
546                 ReleaseStgMedium(&s);
547
548                 return data;
549         }
550
551
552         QVector<FORMATETC> formatsForMime(QString const & mimeType,
553                 QMimeData const * mimeData) const
554         {
555                 QVector<FORMATETC> formats;
556                 formats += cfFromMime(mimeType);
557                 return formats;
558         }
559
560         QString mimeForFormat(FORMATETC const & formatetc) const
561         {
562                 switch (formatetc.cfFormat) {
563                 case CF_ENHMETAFILE:
564                         return emfMimeType(); 
565                 case CF_METAFILEPICT:
566                         return wmfMimeType();
567                 }
568                 return QString();
569         }
570 };
571
572 #endif // Q_WS_WIN
573
574 ////////////////////////////////////////////////////////////////////////
575 // GuiApplication::Private definition and implementation.
576 ////////////////////////////////////////////////////////////////////////
577
578 struct GuiApplication::Private
579 {
580         Private()
581                 : language_model_(0), global_menubar_(0)
582         {
583 #ifdef Q_WS_MACX
584                 // Create the global default menubar which is shown for the dialogs
585                 // and if no GuiView is visible.
586                 global_menubar_ = new GlobalMenuBar();
587 #endif
588         }
589
590         ///
591         QSortFilterProxyModel * language_model_;
592         ///
593         GuiClipboard clipboard_;
594         ///
595         GuiSelection selection_;
596         ///
597         FontLoader font_loader_;
598         ///
599         ColorCache color_cache_;
600         ///
601         QTranslator qt_trans_;
602         ///
603         QHash<int, SocketNotifier *> socket_notifiers_;
604         ///
605         Menus menus_;
606         ///
607         /// The global instance
608         Toolbars toolbars_;
609
610         /// this timer is used for any regular events one wants to
611         /// perform. at present it is used to check if forked processes
612         /// are done.
613         QTimer general_timer_;
614
615         /// Multiple views container.
616         /**
617         * Warning: This must not be a smart pointer as the destruction of the
618         * object is handled by Qt when the view is closed
619         * \sa Qt::WA_DeleteOnClose attribute.
620         */
621         QHash<int, GuiView *> views_;
622
623         /// Only used on mac.
624         GlobalMenuBar * global_menubar_;
625
626 #ifdef Q_WS_MACX
627         /// Linkback mime handler for MacOSX.
628         QMacPasteboardMimeGraphics mac_pasteboard_mime_;
629 #endif
630
631 #ifdef Q_WS_WIN
632         /// WMF Mime handler for Windows clipboard.
633         /// \warning: see comment in ~GuiApplication and in bug 4846.
634         QWindowsMimeMetafile wmf_mime_;
635 #endif
636 };
637
638
639 GuiApplication * guiApp;
640
641 GuiApplication::~GuiApplication()
642 {
643 #ifdef Q_WS_MACX
644         closeAllLinkBackLinks();
645 #endif
646         // FIXME: Work around bug 4846 for Windows Vista and Qt4
647         // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
648         // If the clipboard is not cleared, LyX crashes on exit when it is
649         // compiled in release mode and if there is something in the clipboard.
650         // This is related to QWindowsMimeMetafile which is apparently not 
651         // properly destroyed.
652         qApp->clipboard()->clear(QClipboard::Clipboard);
653         delete d;
654 }
655
656
657 GuiApplication::GuiApplication(int & argc, char ** argv)
658         : QApplication(argc, argv),     current_view_(0), d(new GuiApplication::Private)
659 {
660         QString app_name = "LyX";
661         QCoreApplication::setOrganizationName(app_name);
662         QCoreApplication::setOrganizationDomain("lyx.org");
663         QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
664
665         // Install translator for GUI elements.
666         installTranslator(&d->qt_trans_);
667
668         // FIXME: quitOnLastWindowClosed is true by default. We should have a
669         // lyxrc setting for this in order to let the application stay resident.
670         // But then we need some kind of dock icon, at least on Windows.
671         /*
672         if (lyxrc.quit_on_last_window_closed)
673                 setQuitOnLastWindowClosed(false);
674         */
675 #ifdef Q_WS_MACX
676         // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
677         // seems to be the default case for applications like LyX.
678         setQuitOnLastWindowClosed(false);
679
680         // This allows to translate the strings that appear in the LyX menu.
681         /// A translator suitable for the entries in the LyX menu.
682         /// Only needed with Qt/Mac.
683         installTranslator(new MenuTranslator(this));
684 #endif
685         
686 #ifdef Q_WS_X11
687         // doubleClickInterval() is 400 ms on X11 which is just too long.
688         // On Windows and Mac OS X, the operating system's value is used.
689         // On Microsoft Windows, calling this function sets the double
690         // click interval for all applications. So we don't!
691         QApplication::setDoubleClickInterval(300);
692 #endif
693
694         connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
695
696         using namespace lyx::graphics;
697
698         Image::newImage = boost::bind(&GuiImage::newImage);
699
700         // needs to be done before reading lyxrc
701         QWidget w;
702         lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
703
704         guiApp = this;
705
706         // Set the cache to 5120 kilobytes which corresponds to screen size of
707         // 1280 by 1024 pixels with a color depth of 32 bits.
708         QPixmapCache::setCacheLimit(5120);
709
710         // Initialize RC Fonts
711         if (lyxrc.roman_font_name.empty())
712                 lyxrc.roman_font_name = fromqstr(romanFontName());
713
714         if (lyxrc.sans_font_name.empty())
715                 lyxrc.sans_font_name = fromqstr(sansFontName());
716
717         if (lyxrc.typewriter_font_name.empty())
718                 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
719
720         d->general_timer_.setInterval(500);
721         connect(&d->general_timer_, SIGNAL(timeout()),
722                 this, SLOT(handleRegularEvents()));
723         d->general_timer_.start();
724 }
725
726
727 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
728 {
729         return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
730 }
731
732
733
734 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
735 {
736         bool enable = true;
737
738         switch(cmd.action) {
739
740         case LFUN_WINDOW_CLOSE:
741                 enable = d->views_.size() > 0;
742                 break;
743
744         case LFUN_BUFFER_NEW:
745         case LFUN_BUFFER_NEW_TEMPLATE:
746         case LFUN_FILE_OPEN:
747         case LFUN_SCREEN_FONT_UPDATE:
748         case LFUN_SET_COLOR:
749         case LFUN_WINDOW_NEW:
750         case LFUN_LYX_QUIT:
751                 enable = true;
752                 break;
753
754         default:
755                 return false;
756         }
757
758         if (!enable)
759                 flag.setEnabled(false);
760
761         return true;
762 }
763
764         
765 bool GuiApplication::dispatch(FuncRequest const & cmd)
766 {
767         switch (cmd.action) {
768
769         case LFUN_WINDOW_NEW:
770                 createView(toqstr(cmd.argument()));
771                 break;
772
773         case LFUN_WINDOW_CLOSE:
774                 // update bookmark pit of the current buffer before window close
775                 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
776                         theLyXFunc().gotoBookmark(i+1, false, false);
777                 current_view_->close();
778                 break;
779
780         case LFUN_LYX_QUIT:
781                 // quitting is triggered by the gui code
782                 // (leaving the event loop).
783                 if (current_view_)
784                         current_view_->message(from_utf8(N_("Exiting.")));
785                 if (closeAllViews())
786                         quit();
787                 break;
788
789         case LFUN_SCREEN_FONT_UPDATE: {
790                 // handle the screen font changes.
791                 d->font_loader_.update();
792                 // Backup current_view_
793                 GuiView * view = current_view_;
794                 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
795                 // to skip the refresh.
796                 current_view_ = 0;
797                 BufferList::iterator it = theBufferList().begin();
798                 BufferList::iterator const end = theBufferList().end();
799                 for (; it != end; ++it)
800                         (*it)->changed();
801                 // Restore current_view_
802                 current_view_ = view;
803                 break;
804         }
805
806         case LFUN_BUFFER_NEW:
807                 if (d->views_.empty()
808                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
809                         createView(QString(), false); // keep hidden
810                         current_view_->newDocument(to_utf8(cmd.argument()), false);
811                         current_view_->show();
812                         setActiveWindow(current_view_);
813                 } else {
814                         current_view_->newDocument(to_utf8(cmd.argument()), false);
815                 }
816                 break;
817
818         case LFUN_BUFFER_NEW_TEMPLATE:
819                 if (d->views_.empty()
820                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
821                         createView();
822                         current_view_->newDocument(to_utf8(cmd.argument()), true);
823                         if (!current_view_->buffer())
824                                 current_view_->close();
825                 } else {
826                         current_view_->newDocument(to_utf8(cmd.argument()), true);
827                 }
828                 break;
829
830         case LFUN_FILE_OPEN:
831                 if (d->views_.empty()
832                     || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
833                         string const fname = to_utf8(cmd.argument());
834                         // We want the ui session to be saved per document and not per
835                         // window number. The filename crc is a good enough identifier.
836                         boost::crc_32_type crc;
837                         crc = for_each(fname.begin(), fname.end(), crc);
838                         createView(crc.checksum());
839                         current_view_->openDocument(fname);
840                         if (!current_view_->buffer())
841                                 current_view_->close();
842                 } else
843                         current_view_->openDocument(to_utf8(cmd.argument()));
844                 break;
845
846         case LFUN_SET_COLOR: {
847                 string lyx_name;
848                 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
849                 if (lyx_name.empty() || x11_name.empty()) {
850                         current_view_->message(
851                                 _("Syntax: set-color <lyx_name> <x11_name>"));
852                         break;
853                 }
854
855                 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
856                 bool const graphicsbg_changed = lyx_name == graphicsbg
857                         && x11_name != graphicsbg;
858                 if (graphicsbg_changed) {
859                         // FIXME: The graphics cache no longer has a changeDisplay method.
860 #if 0
861                         graphics::GCache::get().changeDisplay(true);
862 #endif
863                 }
864
865                 if (!lcolor.setColor(lyx_name, x11_name)) {
866                         current_view_->message(
867                                         bformat(_("Set-color \"%1$s\" failed "
868                                                                "- color is undefined or "
869                                                                "may not be redefined"),
870                                                                    from_utf8(lyx_name)));
871                         break;
872                 }
873                 // Make sure we don't keep old colors in cache.
874                 d->color_cache_.clear();
875                 break;
876         }
877
878         default:
879                 // Notify the caller that the action has not been dispatched.
880                 return false;
881         }
882
883         // The action has been dispatched.
884         return true;
885 }
886
887
888 void GuiApplication::resetGui()
889 {
890         // Set the language defined by the user.
891         setGuiLanguage();
892
893         // Read menus
894         if (!readUIFile(toqstr(lyxrc.ui_file)))
895                 // Gives some error box here.
896                 return;
897
898         // init the global menubar on Mac. This must be done after the session
899         // was recovered to know the "last files".
900         if (d->global_menubar_) {
901                 d->global_menubar_->clear();
902                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
903         }
904
905         QHash<int, GuiView *>::iterator it;
906         for (it = d->views_.begin(); it != d->views_.end(); ++it) {
907                 GuiView * gv = *it;
908                 gv->setLayoutDirection(layoutDirection());
909                 gv->resetDialogs();
910         }
911
912         dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
913 }
914
915
916 void GuiApplication::createView(int view_id)
917 {
918         createView(QString(), true, view_id);
919 }
920
921
922 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
923         int view_id)
924 {
925         // release the keyboard which might have been grabed by the global
926         // menubar on Mac to catch shortcuts even without any GuiView.
927         if (d->global_menubar_)
928                 d->global_menubar_->releaseKeyboard();
929
930         // create new view
931         int id = view_id;
932         if (id == 0) {
933                 while (d->views_.find(id) != d->views_.end())
934                         id++;
935         }
936         LYXERR(Debug::GUI, "About to create new window with ID " << id);
937         GuiView * view = new GuiView(id);
938         // register view
939         d->views_[id] = view;
940
941         if (autoShow) {
942                 view->show();
943                 setActiveWindow(view);
944         }
945
946         if (!geometry_arg.isEmpty()) {
947 #ifdef Q_WS_WIN
948                 int x, y;
949                 int w, h;
950                 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
951                 re.indexIn(geometry_arg);
952                 w = re.cap(1).toInt();
953                 h = re.cap(2).toInt();
954                 x = re.cap(3).toInt();
955                 y = re.cap(4).toInt();
956                 view->setGeometry(x, y, w, h);
957 #endif
958         }
959         view->setFocus();
960         setCurrentView(view);
961 }
962
963
964 Clipboard & GuiApplication::clipboard()
965 {
966         return d->clipboard_;
967 }
968
969
970 Selection & GuiApplication::selection()
971 {
972         return d->selection_;
973 }
974
975
976 FontLoader & GuiApplication::fontLoader() 
977 {
978         return d->font_loader_;
979 }
980
981
982 Toolbars const & GuiApplication::toolbars() const 
983 {
984         return d->toolbars_;
985 }
986
987
988 Toolbars & GuiApplication::toolbars()
989 {
990         return d->toolbars_; 
991 }
992
993
994 Menus const & GuiApplication::menus() const 
995 {
996         return d->menus_;
997 }
998
999
1000 Menus & GuiApplication::menus()
1001 {
1002         return d->menus_; 
1003 }
1004
1005
1006 QList<int> GuiApplication::viewIds() const
1007 {
1008         return d->views_.keys();
1009 }
1010
1011
1012 ColorCache & GuiApplication::colorCache()
1013 {
1014         return d->color_cache_;
1015 }
1016
1017
1018 int GuiApplication::exec()
1019 {
1020         QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1021         return QApplication::exec();
1022 }
1023
1024
1025 void GuiApplication::exit(int status)
1026 {
1027         QApplication::exit(status);
1028 }
1029
1030
1031 void GuiApplication::setGuiLanguage()
1032 {
1033         // Set the language defined by the user.
1034         setRcGuiLanguage();
1035
1036         QString const default_language = toqstr(Messages::defaultLanguage());
1037         LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1038         QLocale const default_locale(default_language);
1039         QLocale::setDefault(default_locale);
1040
1041         // install translation file for Qt built-in dialogs
1042         QString const language_name = QString("qt_") + default_locale.name();
1043
1044         // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN). 
1045         // Short-named translator can be loaded from a long name, but not the
1046         // opposite. Therefore, long name should be used without truncation.
1047         // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1048         if (!d->qt_trans_.load(language_name,
1049                         QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1050                 LYXERR(Debug::LOCALE, "Could not find  Qt translations for locale "
1051                         << language_name);
1052         } else {
1053                 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1054                         << language_name);
1055         }
1056
1057         switch (default_locale.language()) {
1058         case QLocale::Arabic :
1059         case QLocale::Hebrew :
1060         case QLocale::Persian :
1061         case QLocale::Urdu :
1062         setLayoutDirection(Qt::RightToLeft);
1063                 break;
1064         default:
1065         setLayoutDirection(Qt::LeftToRight);
1066         }
1067 }
1068
1069
1070 void GuiApplication::execBatchCommands()
1071 {
1072         setGuiLanguage();
1073
1074         // Read menus
1075         if (!readUIFile(toqstr(lyxrc.ui_file)))
1076                 // Gives some error box here.
1077                 return;
1078
1079         // init the global menubar on Mac. This must be done after the session
1080         // was recovered to know the "last files".
1081         if (d->global_menubar_)
1082                 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1083
1084         lyx::execBatchCommands();
1085 }
1086
1087 QAbstractItemModel * GuiApplication::languageModel()
1088 {
1089         if (d->language_model_)
1090                 return d->language_model_;
1091
1092         QStandardItemModel * lang_model = new QStandardItemModel(this);
1093         lang_model->insertColumns(0, 1);
1094         int current_row;
1095         Languages::const_iterator it = languages.begin();
1096         Languages::const_iterator end = languages.end();
1097         for (; it != end; ++it) {
1098                 current_row = lang_model->rowCount();
1099                 lang_model->insertRows(current_row, 1);
1100                 QModelIndex item = lang_model->index(current_row, 0);
1101                 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1102                 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1103         }
1104         d->language_model_ = new QSortFilterProxyModel(this);
1105         d->language_model_->setSourceModel(lang_model);
1106 #if QT_VERSION >= 0x040300
1107         d->language_model_->setSortLocaleAware(true);
1108 #endif
1109         return d->language_model_;
1110 }
1111
1112
1113 void GuiApplication::restoreGuiSession()
1114 {
1115         if (!lyxrc.load_session)
1116                 return;
1117
1118         Session & session = theSession();
1119         vector<FileName> const & lastopened = session.lastOpened().getfiles();
1120         // do not add to the lastfile list since these files are restored from
1121         // last session, and should be already there (regular files), or should
1122         // not be added at all (help files).
1123         for_each(lastopened.begin(), lastopened.end(),
1124                 bind(&GuiView::loadDocument, current_view_, _1, false));
1125
1126         // clear this list to save a few bytes of RAM
1127         session.lastOpened().clear();
1128 }
1129
1130
1131 QString const GuiApplication::romanFontName()
1132 {
1133         QFont font;
1134         font.setKerning(false);
1135         font.setStyleHint(QFont::Serif);
1136         font.setFamily("serif");
1137
1138         return QFontInfo(font).family();
1139 }
1140
1141
1142 QString const GuiApplication::sansFontName()
1143 {
1144         QFont font;
1145         font.setKerning(false);
1146         font.setStyleHint(QFont::SansSerif);
1147         font.setFamily("sans");
1148
1149         return QFontInfo(font).family();
1150 }
1151
1152
1153 QString const GuiApplication::typewriterFontName()
1154 {
1155         QFont font;
1156         font.setKerning(false);
1157         font.setStyleHint(QFont::TypeWriter);
1158         font.setFamily("monospace");
1159
1160         return QFontInfo(font).family();
1161 }
1162
1163
1164 void GuiApplication::handleRegularEvents()
1165 {
1166         ForkedCallsController::handleCompletedProcesses();
1167 }
1168
1169
1170 bool GuiApplication::event(QEvent * e)
1171 {
1172         switch(e->type()) {
1173         case QEvent::FileOpen: {
1174                 // Open a file; this happens only on Mac OS X for now
1175                 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1176                 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1177                         qstring_to_ucs4(foe->file())));
1178                 e->accept();
1179                 return true;
1180         }
1181         default:
1182                 return QApplication::event(e);
1183         }
1184 }
1185
1186
1187 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1188 {
1189         try {
1190                 return QApplication::notify(receiver, event);
1191         }
1192         catch (ExceptionMessage const & e) {
1193                 switch(e.type_) { 
1194                 case ErrorException:
1195                         emergencyCleanup();
1196                         setQuitOnLastWindowClosed(false);
1197                         closeAllViews();
1198                         Alert::error(e.title_, e.details_);
1199 #ifndef NDEBUG
1200                         // Properly crash in debug mode in order to get a useful backtrace.
1201                         abort();
1202 #endif
1203                         // In release mode, try to exit gracefully.
1204                         this->exit(1);
1205
1206                 case BufferException: {
1207                         Buffer * buf = current_view_->buffer();
1208                         docstring details = e.details_ + '\n';
1209                         details += theBufferList().emergencyWrite(buf);
1210                         theBufferList().release(buf);
1211                         details += "\n" + _("The current document was closed.");
1212                         Alert::error(e.title_, details);
1213                         return false;
1214                 }
1215                 case WarningException:
1216                         Alert::warning(e.title_, e.details_);
1217                         return false;
1218                 }
1219         }
1220         catch (exception const & e) {
1221                 docstring s = _("LyX has caught an exception, it will now "
1222                         "attempt to save all unsaved documents and exit."
1223                         "\n\nException: ");
1224                 s += from_ascii(e.what());
1225                 Alert::error(_("Software exception Detected"), s);
1226                 lyx_exit(1);
1227         }
1228         catch (...) {
1229                 docstring s = _("LyX has caught some really weird exception, it will "
1230                         "now attempt to save all unsaved documents and exit.");
1231                 Alert::error(_("Software exception Detected"), s);
1232                 lyx_exit(1);
1233         }
1234
1235         return false;
1236 }
1237
1238
1239 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1240 {
1241         QColor const & qcol = d->color_cache_.get(col);
1242         if (!qcol.isValid()) {
1243                 rgbcol.r = 0;
1244                 rgbcol.g = 0;
1245                 rgbcol.b = 0;
1246                 return false;
1247         }
1248         rgbcol.r = qcol.red();
1249         rgbcol.g = qcol.green();
1250         rgbcol.b = qcol.blue();
1251         return true;
1252 }
1253
1254
1255 string const GuiApplication::hexName(ColorCode col)
1256 {
1257         return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1258 }
1259
1260
1261 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1262 {
1263         SocketNotifier * sn = new SocketNotifier(this, fd, func);
1264         d->socket_notifiers_[fd] = sn;
1265         connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1266 }
1267
1268
1269 void GuiApplication::socketDataReceived(int fd)
1270 {
1271         d->socket_notifiers_[fd]->func_();
1272 }
1273
1274
1275 void GuiApplication::unregisterSocketCallback(int fd)
1276 {
1277         d->socket_notifiers_.take(fd)->setEnabled(false);
1278 }
1279
1280
1281 void GuiApplication::commitData(QSessionManager & sm)
1282 {
1283         /// The implementation is required to avoid an application exit
1284         /// when session state save is triggered by session manager.
1285         /// The default implementation sends a close event to all
1286         /// visible top level widgets when session managment allows
1287         /// interaction.
1288         /// We are changing that to close all wiew one by one.
1289         /// FIXME: verify if the default implementation is enough now.
1290         if (sm.allowsInteraction() && !closeAllViews())
1291                 sm.cancel();
1292 }
1293
1294
1295 void GuiApplication::unregisterView(GuiView * gv)
1296 {
1297         LASSERT(d->views_[gv->id()] == gv, /**/);
1298         d->views_.remove(gv->id());
1299         if (current_view_ == gv) {
1300                 current_view_ = 0;
1301                 theLyXFunc().setLyXView(0);
1302         }
1303 }
1304
1305
1306 bool GuiApplication::closeAllViews()
1307 {
1308         if (d->views_.empty())
1309                 return true;
1310
1311         QList<GuiView *> views = d->views_.values();
1312         foreach (GuiView * view, views) {
1313                 if (!view->close())
1314                         return false;
1315         }
1316
1317         d->views_.clear();
1318         return true;
1319 }
1320
1321
1322 GuiView & GuiApplication::view(int id) const
1323 {
1324         LASSERT(d->views_.contains(id), /**/);
1325         return *d->views_.value(id);
1326 }
1327
1328
1329 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1330 {
1331         QList<GuiView *> views = d->views_.values();
1332         foreach (GuiView * view, views)
1333                 view->hideDialog(name, inset);
1334 }
1335
1336
1337 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1338 {
1339         Buffer const * buffer_ = 0;
1340         QHash<int, GuiView *>::iterator end = d->views_.end();
1341         for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1342                 if (Buffer const * ptr = (*it)->updateInset(inset))
1343                         buffer_ = ptr;
1344         }
1345         return buffer_;
1346 }
1347
1348
1349 bool GuiApplication::searchMenu(FuncRequest const & func,
1350         docstring_list & names) const
1351 {
1352         return d->menus_.searchMenu(func, names);
1353 }
1354
1355
1356 bool GuiApplication::readUIFile(QString const & name, bool include)
1357 {
1358         enum {
1359                 ui_menuset = 1,
1360                 ui_toolbars,
1361                 ui_toolbarset,
1362                 ui_include,
1363                 ui_last
1364         };
1365
1366         LexerKeyword uitags[] = {
1367                 { "include", ui_include },
1368                 { "menuset", ui_menuset },
1369                 { "toolbars", ui_toolbars },
1370                 { "toolbarset", ui_toolbarset }
1371         };
1372
1373         // Ensure that a file is read only once (prevents include loops)
1374         static QStringList uifiles;
1375         if (uifiles.contains(name)) {
1376                 if (!include) {
1377                         // We are reading again the top uifile so reset the safeguard:
1378                         uifiles.clear();
1379                         d->menus_.reset();
1380                         d->toolbars_.reset();
1381                 } else {
1382                         LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1383                                 << "Is this an include loop?");
1384                         return false;
1385                 }
1386         }
1387
1388         LYXERR(Debug::INIT, "About to read " << name << "...");
1389
1390         FileName ui_path;
1391         if (include) {
1392                 ui_path = libFileSearch("ui", name, "inc");
1393                 if (ui_path.empty())
1394                         ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1395         } else {
1396                 ui_path = libFileSearch("ui", name, "ui");
1397         }
1398
1399         if (ui_path.empty()) {
1400                 LYXERR(Debug::INIT, "Could not find " << name);
1401                 Alert::warning(_("Could not find UI definition file"),
1402                                bformat(_("Error while reading the configuration file\n%1$s.\n"
1403                                    "Please check your installation."), qstring_to_ucs4(name)));
1404                 return false;
1405         }
1406
1407         uifiles.push_back(name);
1408
1409         LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1410         Lexer lex(uitags);
1411         lex.setFile(ui_path);
1412         if (!lex.isOK()) {
1413                 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1414                        << endl;
1415         }
1416
1417         if (lyxerr.debugging(Debug::PARSER))
1418                 lex.printTable(lyxerr);
1419
1420         while (lex.isOK()) {
1421                 switch (lex.lex()) {
1422                 case ui_include: {
1423                         lex.next(true);
1424                         QString const file = toqstr(lex.getString());
1425                         if (!readUIFile(file, true))
1426                                 return false;
1427                         break;
1428                 }
1429                 case ui_menuset:
1430                         d->menus_.read(lex);
1431                         break;
1432
1433                 case ui_toolbarset:
1434                         d->toolbars_.readToolbars(lex);
1435                         break;
1436
1437                 case ui_toolbars:
1438                         d->toolbars_.readToolbarSettings(lex);
1439                         break;
1440
1441                 default:
1442                         if (!rtrim(lex.getString()).empty())
1443                                 lex.printError("LyX::ReadUIFile: "
1444                                                "Unknown menu tag: `$$Token'");
1445                         break;
1446                 }
1447         }
1448         return true;
1449 }
1450
1451
1452 void GuiApplication::onLastWindowClosed()
1453 {
1454         if (d->global_menubar_)
1455                 d->global_menubar_->grabKeyboard();
1456 }
1457
1458
1459 ////////////////////////////////////////////////////////////////////////
1460 //
1461 // X11 specific stuff goes here...
1462
1463 #ifdef Q_WS_X11
1464 bool GuiApplication::x11EventFilter(XEvent * xev)
1465 {
1466         if (!current_view_)
1467                 return false;
1468
1469         switch (xev->type) {
1470         case SelectionRequest: {
1471                 if (xev->xselectionrequest.selection != XA_PRIMARY)
1472                         break;
1473                 LYXERR(Debug::SELECTION, "X requested selection.");
1474                 BufferView * bv = current_view_->view();
1475                 if (bv) {
1476                         docstring const sel = bv->requestSelection();
1477                         if (!sel.empty())
1478                                 d->selection_.put(sel);
1479                 }
1480                 break;
1481         }
1482         case SelectionClear: {
1483                 if (xev->xselectionclear.selection != XA_PRIMARY)
1484                         break;
1485                 LYXERR(Debug::SELECTION, "Lost selection.");
1486                 BufferView * bv = current_view_->view();
1487                 if (bv)
1488                         bv->clearSelection();
1489                 break;
1490         }
1491         }
1492         return false;
1493 }
1494 #endif
1495
1496 } // namespace frontend
1497
1498
1499 void hideDialogs(std::string const & name, Inset * inset)
1500 {
1501         if (theApp())
1502                 theApp()->hideDialogs(name, inset);
1503 }
1504
1505
1506 ////////////////////////////////////////////////////////////////////
1507 //
1508 // Font stuff
1509 //
1510 ////////////////////////////////////////////////////////////////////
1511
1512 frontend::FontLoader & theFontLoader()
1513 {
1514         LASSERT(frontend::guiApp, /**/);
1515         return frontend::guiApp->fontLoader();
1516 }
1517
1518
1519 frontend::FontMetrics const & theFontMetrics(Font const & f)
1520 {
1521         return theFontMetrics(f.fontInfo());
1522 }
1523
1524
1525 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1526 {
1527         LASSERT(frontend::guiApp, /**/);
1528         return frontend::guiApp->fontLoader().metrics(f);
1529 }
1530
1531
1532 ////////////////////////////////////////////////////////////////////
1533 //
1534 // Misc stuff
1535 //
1536 ////////////////////////////////////////////////////////////////////
1537
1538 frontend::Clipboard & theClipboard()
1539 {
1540         LASSERT(frontend::guiApp, /**/);
1541         return frontend::guiApp->clipboard();
1542 }
1543
1544
1545 frontend::Selection & theSelection()
1546 {
1547         LASSERT(frontend::guiApp, /**/);
1548         return frontend::guiApp->selection();
1549 }
1550
1551 } // namespace lyx
1552
1553 #include "GuiApplication_moc.cpp"