2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
42 #include "LyXAction.h"
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"
62 #include "support/linkback/LinkBackProxy.h"
72 #include <QFileOpenEvent>
76 #include <QImageReader>
78 #include <QLibraryInfo>
80 #include <QMacPasteboardMime>
85 #include <QPixmapCache>
87 #include <QSessionManager>
89 #include <QSocketNotifier>
90 #include <QSortFilterProxyModel>
91 #include <QStandardItemModel>
94 #include <QTranslator>
98 #include <X11/Xatom.h>
105 #include <QWindowsMime>
112 #include <boost/bind.hpp>
113 #include <boost/crc.hpp>
119 using namespace lyx::support;
122 static void initializeResources()
124 static bool initialized = false;
126 Q_INIT_RESOURCE(Resources);
134 frontend::Application * createApplication(int & argc, char * argv[])
137 // prune -geometry argument(s) by shifting
138 // the following ones 2 places down.
139 for (int i = 0 ; i < argc ; ++i) {
140 if (strcmp(argv[i], "-geometry") == 0) {
141 int const remove = (i+1) < argc ? 2 : 1;
143 for (int j = i; j < argc; ++j)
144 argv[j] = argv[j + remove];
149 return new frontend::GuiApplication(argc, argv);
155 /// Return the list of loadable formats.
156 vector<string> loadableImageFormats()
160 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
162 LYXERR(Debug::GRAPHICS,
163 "\nThe image loader can load the following directly:\n");
165 if (qt_formats.empty())
166 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
168 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
170 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
172 string ext = ascii_lowercase((const char *) *it);
183 ////////////////////////////////////////////////////////////////////////
184 // Icon loading support code.
185 ////////////////////////////////////////////////////////////////////////
195 bool operator<(PngMap const & lhs, PngMap const & rhs)
197 return lhs.key < rhs.key;
203 CompareKey(QString const & name) : name_(name) {}
204 bool operator()(PngMap const & other) const { return other.key == name_; }
210 // this must be sorted alphabetically
211 // Upper case comes before lower case
212 PngMap sorted_png_map[] = {
213 { "Bumpeq", "bumpeq2" },
216 { "Delta", "delta2" },
217 { "Downarrow", "downarrow2" },
218 { "Gamma", "gamma2" },
219 { "Lambda", "lambda2" },
220 { "Leftarrow", "leftarrow2" },
221 { "Leftrightarrow", "leftrightarrow2" },
222 { "Longleftarrow", "longleftarrow2" },
223 { "Longleftrightarrow", "longleftrightarrow2" },
224 { "Longrightarrow", "longrightarrow2" },
225 { "Omega", "omega2" },
229 { "Rightarrow", "rightarrow2" },
230 { "Sigma", "sigma2" },
231 { "Subset", "subset2" },
232 { "Supset", "supset2" },
233 { "Theta", "theta2" },
234 { "Uparrow", "uparrow2" },
235 { "Updownarrow", "updownarrow2" },
236 { "Upsilon", "upsilon2" },
237 { "Vdash", "vdash3" },
240 { "nLeftarrow", "nleftarrow2" },
241 { "nLeftrightarrow", "nleftrightarrow2" },
242 { "nRightarrow", "nrightarrow2" },
243 { "nVDash", "nvdash3" },
244 { "nvDash", "nvdash2" },
245 { "textrm \\AA", "textrm_AA"},
246 { "textrm \\O", "textrm_O"},
247 { "vDash", "vdash2" }
250 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
253 QString findPng(QString const & name)
255 PngMap const * const begin = sorted_png_map;
256 PngMap const * const end = begin + nr_sorted_png_map;
257 LASSERT(sorted(begin, end), /**/);
259 PngMap const * const it = find_if(begin, end, CompareKey(name));
263 png_name = it->value;
266 png_name.replace('_', "underscore");
267 png_name.replace(' ', '_');
269 // This way we can have "math-delim { }" on the toolbar.
270 png_name.replace('(', "lparen");
271 png_name.replace(')', "rparen");
272 png_name.replace('[', "lbracket");
273 png_name.replace(']', "rbracket");
274 png_name.replace('{', "lbrace");
275 png_name.replace('}', "rbrace");
276 png_name.replace('|', "bars");
277 png_name.replace(',', "thinspace");
278 png_name.replace(':', "mediumspace");
279 png_name.replace(';', "thickspace");
280 png_name.replace('!', "negthinspace");
283 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
284 << "Looking for math PNG called \"" << png_name << '"');
291 QString iconName(FuncRequest const & f, bool unknown)
293 initializeResources();
298 case LFUN_MATH_INSERT:
299 if (!f.argument().empty()) {
301 name1 = findPng(toqstr(f.argument()).mid(1));
304 case LFUN_MATH_DELIM:
305 case LFUN_MATH_BIGDELIM:
307 name1 = findPng(toqstr(f.argument()));
311 name1 = toqstr(f.argument());
314 name2 = toqstr(lyxaction.getActionName(f.action));
317 if (!f.argument().empty()) {
318 name1 = name2 + ' ' + toqstr(f.argument());
319 name1.replace(' ', '_');
323 FileName fname = libFileSearch("images/" + path, name1, "png");
325 return toqstr(fname.absFilename());
327 fname = libFileSearch("images/" + path, name2, "png");
329 return toqstr(fname.absFilename());
331 path = ":/images/" + path;
334 LYXERR0("Directory " << path << " not found in resource!");
338 if (res.exists(name1))
342 if (res.exists(name2))
345 LYXERR(Debug::GUI, "Cannot find icon for command \""
346 << lyxaction.getActionName(f.action)
347 << '(' << to_utf8(f.argument()) << ")\"");
350 return QString(":/images/unknown.png");
356 QIcon getIcon(FuncRequest const & f, bool unknown)
358 QString icon = iconName(f, unknown);
362 //LYXERR(Debug::GUI, "Found icon: " << icon);
364 if (!pm.load(icon)) {
365 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
373 ////////////////////////////////////////////////////////////////////////
374 // LyX server support code.
375 ////////////////////////////////////////////////////////////////////////
376 class SocketNotifier : public QSocketNotifier
379 /// connect a connection notification from the LyXServerSocket
380 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
381 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
385 /// The callback function
386 Application::SocketCallback func_;
390 ////////////////////////////////////////////////////////////////////////
391 // Mac specific stuff goes here...
392 ////////////////////////////////////////////////////////////////////////
394 class MenuTranslator : public QTranslator
397 MenuTranslator(QObject * parent)
398 : QTranslator(parent)
401 QString translate(const char * /*context*/,
402 const char * sourceText,
403 const char * /*comment*/ = 0)
405 string const s = sourceText;
406 if (s == N_("About %1") || s == N_("Preferences")
407 || s == N_("Reconfigure") || s == N_("Quit %1"))
414 class GlobalMenuBar : public QMenuBar
418 GlobalMenuBar() : QMenuBar(0) {}
421 bool event(QEvent * e)
423 if (e->type() == QEvent::ShortcutOverride) {
424 // && activeWindow() == 0) {
425 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
427 setKeySymbol(&sym, ke);
428 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
437 // QMacPasteboardMimeGraphics can only be compiled on Mac.
439 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
442 QMacPasteboardMimeGraphics()
443 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
446 QString convertorName() { return "Graphics"; }
448 QString flavorFor(QString const & mime)
450 LYXERR(Debug::ACTION, "flavorFor " << mime);
451 if (mime == pdfMimeType())
452 return QLatin1String("com.adobe.pdf");
456 QString mimeFor(QString flav)
458 LYXERR(Debug::ACTION, "mimeFor " << flav);
459 if (flav == QLatin1String("com.adobe.pdf"))
460 return pdfMimeType();
464 bool canConvert(QString const & mime, QString flav)
466 return mimeFor(flav) == mime;
469 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
473 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
477 QList<QByteArray> convertFromMime(QString const & /*mime*/,
478 QVariant data, QString /*flav*/)
480 QList<QByteArray> ret;
481 ret.append(data.toByteArray());
487 ///////////////////////////////////////////////////////////////
488 // You can find more platform specific stuff
489 // at the end of this file...
490 ///////////////////////////////////////////////////////////////
492 ////////////////////////////////////////////////////////////////////////
493 // Windows specific stuff goes here...
496 // QWindowsMimeMetafile can only be compiled on Windows.
498 static FORMATETC cfFromMime(QString const & mimetype)
501 if (mimetype == emfMimeType()) {
502 formatetc.cfFormat = CF_ENHMETAFILE;
503 formatetc.tymed = TYMED_ENHMF;
504 } else if (mimetype == wmfMimeType()) {
505 formatetc.cfFormat = CF_METAFILEPICT;
506 formatetc.tymed = TYMED_MFPICT;
509 formatetc.dwAspect = DVASPECT_CONTENT;
510 formatetc.lindex = -1;
515 class QWindowsMimeMetafile : public QWindowsMime {
517 QWindowsMimeMetafile() {}
519 bool canConvertFromMime(FORMATETC const & formatetc,
520 QMimeData const * mimedata) const
525 bool canConvertToMime(QString const & mimetype,
526 IDataObject * pDataObj) const
528 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
530 FORMATETC formatetc = cfFromMime(mimetype);
531 return pDataObj->QueryGetData(&formatetc) == S_OK;
534 bool convertFromMime(FORMATETC const & formatetc,
535 const QMimeData * mimedata, STGMEDIUM * pmedium) const
540 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
541 QVariant::Type preferredType) const
544 if (!canConvertToMime(mimetype, pDataObj))
547 FORMATETC formatetc = cfFromMime(mimetype);
549 if (pDataObj->GetData(&formatetc, &s) != S_OK)
553 if (s.tymed == TYMED_ENHMF) {
554 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
555 data.resize(dataSize);
556 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
557 (LPBYTE)data.data());
558 } else if (s.tymed == TYMED_MFPICT) {
559 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
560 data.resize(dataSize);
561 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
562 (LPBYTE)data.data());
565 ReleaseStgMedium(&s);
571 QVector<FORMATETC> formatsForMime(QString const & mimeType,
572 QMimeData const * mimeData) const
574 QVector<FORMATETC> formats;
575 formats += cfFromMime(mimeType);
579 QString mimeForFormat(FORMATETC const & formatetc) const
581 switch (formatetc.cfFormat) {
583 return emfMimeType();
584 case CF_METAFILEPICT:
585 return wmfMimeType();
593 ////////////////////////////////////////////////////////////////////////
594 // GuiApplication::Private definition and implementation.
595 ////////////////////////////////////////////////////////////////////////
597 struct GuiApplication::Private
599 Private(): language_model_(0), global_menubar_(0) {}
602 QSortFilterProxyModel * language_model_;
604 GuiClipboard clipboard_;
606 GuiSelection selection_;
608 FontLoader font_loader_;
610 ColorCache color_cache_;
612 QTranslator qt_trans_;
614 QHash<int, SocketNotifier *> socket_notifiers_;
618 /// The global instance
621 /// this timer is used for any regular events one wants to
622 /// perform. at present it is used to check if forked processes
624 QTimer general_timer_;
626 /// delayed FuncRequests
627 std::queue<FuncRequest> func_request_queue_;
629 /// Multiple views container.
631 * Warning: This must not be a smart pointer as the destruction of the
632 * object is handled by Qt when the view is closed
633 * \sa Qt::WA_DeleteOnClose attribute.
635 QHash<int, GuiView *> views_;
637 /// Only used on mac.
638 GlobalMenuBar * global_menubar_;
641 /// Linkback mime handler for MacOSX.
642 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
646 /// WMF Mime handler for Windows clipboard.
647 /// \warning: see comment in ~GuiApplication and in bug 4846.
648 QWindowsMimeMetafile wmf_mime_;
653 GuiApplication * guiApp;
655 GuiApplication::~GuiApplication()
658 closeAllLinkBackLinks();
660 // FIXME: Work around bug 4846 for Windows Vista and Qt4
661 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
662 // If the clipboard is not cleared, LyX crashes on exit when it is
663 // compiled in release mode and if there is something in the clipboard.
664 // This is related to QWindowsMimeMetafile which is apparently not
665 // properly destroyed.
666 qApp->clipboard()->clear(QClipboard::Clipboard);
671 GuiApplication::GuiApplication(int & argc, char ** argv)
672 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
674 QString app_name = "LyX";
675 QCoreApplication::setOrganizationName(app_name);
676 QCoreApplication::setOrganizationDomain("lyx.org");
677 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
679 // Install translator for GUI elements.
680 installTranslator(&d->qt_trans_);
682 // FIXME: quitOnLastWindowClosed is true by default. We should have a
683 // lyxrc setting for this in order to let the application stay resident.
684 // But then we need some kind of dock icon, at least on Windows.
686 if (lyxrc.quit_on_last_window_closed)
687 setQuitOnLastWindowClosed(false);
690 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
691 // seems to be the default case for applications like LyX.
692 setQuitOnLastWindowClosed(false);
694 // This allows to translate the strings that appear in the LyX menu.
695 /// A translator suitable for the entries in the LyX menu.
696 /// Only needed with Qt/Mac.
697 installTranslator(new MenuTranslator(this));
701 // doubleClickInterval() is 400 ms on X11 which is just too long.
702 // On Windows and Mac OS X, the operating system's value is used.
703 // On Microsoft Windows, calling this function sets the double
704 // click interval for all applications. So we don't!
705 QApplication::setDoubleClickInterval(300);
708 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
710 // needs to be done before reading lyxrc
712 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
716 // Set the cache to 5120 kilobytes which corresponds to screen size of
717 // 1280 by 1024 pixels with a color depth of 32 bits.
718 QPixmapCache::setCacheLimit(5120);
720 // Initialize RC Fonts
721 if (lyxrc.roman_font_name.empty())
722 lyxrc.roman_font_name = fromqstr(romanFontName());
724 if (lyxrc.sans_font_name.empty())
725 lyxrc.sans_font_name = fromqstr(sansFontName());
727 if (lyxrc.typewriter_font_name.empty())
728 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
730 d->general_timer_.setInterval(500);
731 connect(&d->general_timer_, SIGNAL(timeout()),
732 this, SLOT(handleRegularEvents()));
733 d->general_timer_.start();
737 void GuiApplication::clearSession()
744 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
746 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
751 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
757 case LFUN_WINDOW_CLOSE:
758 enable = d->views_.size() > 0;
761 case LFUN_BUFFER_NEW:
762 case LFUN_BUFFER_NEW_TEMPLATE:
764 case LFUN_SCREEN_FONT_UPDATE:
766 case LFUN_WINDOW_NEW:
776 flag.setEnabled(false);
782 bool GuiApplication::dispatch(FuncRequest const & cmd)
784 switch (cmd.action) {
786 case LFUN_WINDOW_NEW:
787 createView(toqstr(cmd.argument()));
790 case LFUN_WINDOW_CLOSE:
791 // update bookmark pit of the current buffer before window close
792 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
793 theLyXFunc().gotoBookmark(i+1, false, false);
794 current_view_->close();
798 // quitting is triggered by the gui code
799 // (leaving the event loop).
801 current_view_->message(from_utf8(N_("Exiting.")));
806 case LFUN_SCREEN_FONT_UPDATE: {
807 // handle the screen font changes.
808 d->font_loader_.update();
809 // Backup current_view_
810 GuiView * view = current_view_;
811 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
812 // to skip the refresh.
814 BufferList::iterator it = theBufferList().begin();
815 BufferList::iterator const end = theBufferList().end();
816 for (; it != end; ++it)
818 // Restore current_view_
819 current_view_ = view;
823 case LFUN_BUFFER_NEW:
824 if (d->views_.empty()
825 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
826 createView(QString(), false); // keep hidden
827 current_view_->newDocument(to_utf8(cmd.argument()), false);
828 current_view_->show();
829 setActiveWindow(current_view_);
831 current_view_->newDocument(to_utf8(cmd.argument()), false);
835 case LFUN_BUFFER_NEW_TEMPLATE:
836 if (d->views_.empty()
837 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
839 current_view_->newDocument(to_utf8(cmd.argument()), true);
840 if (!current_view_->buffer())
841 current_view_->close();
843 current_view_->newDocument(to_utf8(cmd.argument()), true);
848 if (d->views_.empty()
849 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
850 string const fname = to_utf8(cmd.argument());
851 // We want the ui session to be saved per document and not per
852 // window number. The filename crc is a good enough identifier.
853 boost::crc_32_type crc;
854 crc = for_each(fname.begin(), fname.end(), crc);
855 createView(crc.checksum());
856 current_view_->openDocument(fname);
857 if (current_view_ && !current_view_->buffer())
858 current_view_->close();
860 current_view_->openDocument(to_utf8(cmd.argument()));
863 case LFUN_SET_COLOR: {
865 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
866 if (lyx_name.empty() || x11_name.empty()) {
867 current_view_->message(
868 _("Syntax: set-color <lyx_name> <x11_name>"));
872 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
873 bool const graphicsbg_changed = lyx_name == graphicsbg
874 && x11_name != graphicsbg;
875 if (graphicsbg_changed) {
876 // FIXME: The graphics cache no longer has a changeDisplay method.
878 graphics::GCache::get().changeDisplay(true);
882 if (!lcolor.setColor(lyx_name, x11_name)) {
883 current_view_->message(
884 bformat(_("Set-color \"%1$s\" failed "
885 "- color is undefined or "
886 "may not be redefined"),
887 from_utf8(lyx_name)));
890 // Make sure we don't keep old colors in cache.
891 d->color_cache_.clear();
896 // Notify the caller that the action has not been dispatched.
900 // The action has been dispatched.
905 void GuiApplication::dispatchDelayed(FuncRequest const & func)
907 d->func_request_queue_.push(func);
908 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
912 void GuiApplication::resetGui()
914 // Set the language defined by the user.
918 if (!readUIFile(toqstr(lyxrc.ui_file)))
919 // Gives some error box here.
922 if (d->global_menubar_)
923 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
925 QHash<int, GuiView *>::iterator it;
926 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
928 gv->setLayoutDirection(layoutDirection());
932 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
936 void GuiApplication::createView(int view_id)
938 createView(QString(), true, view_id);
942 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
945 // release the keyboard which might have been grabed by the global
946 // menubar on Mac to catch shortcuts even without any GuiView.
947 if (d->global_menubar_)
948 d->global_menubar_->releaseKeyboard();
953 while (d->views_.find(id) != d->views_.end())
956 LYXERR(Debug::GUI, "About to create new window with ID " << id);
957 GuiView * view = new GuiView(id);
959 d->views_[id] = view;
963 setActiveWindow(view);
966 if (!geometry_arg.isEmpty()) {
970 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
971 re.indexIn(geometry_arg);
972 w = re.cap(1).toInt();
973 h = re.cap(2).toInt();
974 x = re.cap(3).toInt();
975 y = re.cap(4).toInt();
976 view->setGeometry(x, y, w, h);
983 Clipboard & GuiApplication::clipboard()
985 return d->clipboard_;
989 Selection & GuiApplication::selection()
991 return d->selection_;
995 FontLoader & GuiApplication::fontLoader()
997 return d->font_loader_;
1001 Toolbars const & GuiApplication::toolbars() const
1003 return d->toolbars_;
1007 Toolbars & GuiApplication::toolbars()
1009 return d->toolbars_;
1013 Menus const & GuiApplication::menus() const
1019 Menus & GuiApplication::menus()
1025 QList<int> GuiApplication::viewIds() const
1027 return d->views_.keys();
1031 ColorCache & GuiApplication::colorCache()
1033 return d->color_cache_;
1037 int GuiApplication::exec()
1039 // asynchronously handle batch commands. This event will be in
1040 // the event queue in front of other asynchronous events. Hence,
1041 // we can assume in the latter that the gui is setup already.
1042 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1044 return QApplication::exec();
1048 void GuiApplication::exit(int status)
1050 QApplication::exit(status);
1054 void GuiApplication::setGuiLanguage()
1056 // Set the language defined by the user.
1059 QString const default_language = toqstr(Messages::defaultLanguage());
1060 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1061 QLocale const default_locale(default_language);
1062 QLocale::setDefault(default_locale);
1064 // install translation file for Qt built-in dialogs
1065 QString const language_name = QString("qt_") + default_locale.name();
1067 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1068 // Short-named translator can be loaded from a long name, but not the
1069 // opposite. Therefore, long name should be used without truncation.
1070 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1071 if (!d->qt_trans_.load(language_name,
1072 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1073 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1076 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1080 switch (default_locale.language()) {
1081 case QLocale::Arabic :
1082 case QLocale::Hebrew :
1083 case QLocale::Persian :
1084 case QLocale::Urdu :
1085 setLayoutDirection(Qt::RightToLeft);
1088 setLayoutDirection(Qt::LeftToRight);
1093 void GuiApplication::processFuncRequestQueue()
1095 while (!d->func_request_queue_.empty()) {
1096 lyx::dispatch(d->func_request_queue_.back());
1097 d->func_request_queue_.pop();
1102 void GuiApplication::execBatchCommands()
1107 if (!readUIFile(toqstr(lyxrc.ui_file)))
1108 // Gives some error box here.
1112 // Create the global default menubar which is shown for the dialogs
1113 // and if no GuiView is visible.
1114 // This must be done after the session was recovered to know the "last files".
1115 d->global_menubar_ = new GlobalMenuBar();
1116 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1119 lyx::execBatchCommands();
1123 QAbstractItemModel * GuiApplication::languageModel()
1125 if (d->language_model_)
1126 return d->language_model_;
1128 QStandardItemModel * lang_model = new QStandardItemModel(this);
1129 lang_model->insertColumns(0, 1);
1131 Languages::const_iterator it = languages.begin();
1132 Languages::const_iterator end = languages.end();
1133 for (; it != end; ++it) {
1134 current_row = lang_model->rowCount();
1135 lang_model->insertRows(current_row, 1);
1136 QModelIndex item = lang_model->index(current_row, 0);
1137 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1138 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1140 d->language_model_ = new QSortFilterProxyModel(this);
1141 d->language_model_->setSourceModel(lang_model);
1142 #if QT_VERSION >= 0x040300
1143 d->language_model_->setSortLocaleAware(true);
1145 return d->language_model_;
1149 void GuiApplication::restoreGuiSession()
1151 if (!lyxrc.load_session)
1154 Session & session = theSession();
1155 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1156 // do not add to the lastfile list since these files are restored from
1157 // last session, and should be already there (regular files), or should
1158 // not be added at all (help files).
1159 for_each(lastopened.begin(), lastopened.end(),
1160 bind(&GuiView::loadDocument, current_view_, _1, false));
1162 // clear this list to save a few bytes of RAM
1163 session.lastOpened().clear();
1167 QString const GuiApplication::romanFontName()
1170 font.setKerning(false);
1171 font.setStyleHint(QFont::Serif);
1172 font.setFamily("serif");
1174 return QFontInfo(font).family();
1178 QString const GuiApplication::sansFontName()
1181 font.setKerning(false);
1182 font.setStyleHint(QFont::SansSerif);
1183 font.setFamily("sans");
1185 return QFontInfo(font).family();
1189 QString const GuiApplication::typewriterFontName()
1192 font.setKerning(false);
1193 font.setStyleHint(QFont::TypeWriter);
1194 font.setFamily("monospace");
1196 return QFontInfo(font).family();
1200 void GuiApplication::handleRegularEvents()
1202 ForkedCallsController::handleCompletedProcesses();
1206 bool GuiApplication::event(QEvent * e)
1209 case QEvent::FileOpen: {
1210 // Open a file; this happens only on Mac OS X for now.
1212 // We do this asynchronously because on startup the batch
1213 // commands are not executed here yet and the gui is not ready
1215 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1216 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1221 return QApplication::event(e);
1226 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1229 return QApplication::notify(receiver, event);
1231 catch (ExceptionMessage const & e) {
1233 case ErrorException:
1235 setQuitOnLastWindowClosed(false);
1237 Alert::error(e.title_, e.details_);
1239 // Properly crash in debug mode in order to get a useful backtrace.
1242 // In release mode, try to exit gracefully.
1245 case BufferException: {
1246 Buffer * buf = current_view_->buffer();
1247 docstring details = e.details_ + '\n';
1248 details += theBufferList().emergencyWrite(buf);
1249 theBufferList().release(buf);
1250 details += "\n" + _("The current document was closed.");
1251 Alert::error(e.title_, details);
1254 case WarningException:
1255 Alert::warning(e.title_, e.details_);
1259 catch (exception const & e) {
1260 docstring s = _("LyX has caught an exception, it will now "
1261 "attempt to save all unsaved documents and exit."
1263 s += from_ascii(e.what());
1264 Alert::error(_("Software exception Detected"), s);
1268 docstring s = _("LyX has caught some really weird exception, it will "
1269 "now attempt to save all unsaved documents and exit.");
1270 Alert::error(_("Software exception Detected"), s);
1278 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1280 QColor const & qcol = d->color_cache_.get(col);
1281 if (!qcol.isValid()) {
1287 rgbcol.r = qcol.red();
1288 rgbcol.g = qcol.green();
1289 rgbcol.b = qcol.blue();
1294 string const GuiApplication::hexName(ColorCode col)
1296 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1300 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1302 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1303 d->socket_notifiers_[fd] = sn;
1304 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1308 void GuiApplication::socketDataReceived(int fd)
1310 d->socket_notifiers_[fd]->func_();
1314 void GuiApplication::unregisterSocketCallback(int fd)
1316 d->socket_notifiers_.take(fd)->setEnabled(false);
1320 void GuiApplication::commitData(QSessionManager & sm)
1322 /// The implementation is required to avoid an application exit
1323 /// when session state save is triggered by session manager.
1324 /// The default implementation sends a close event to all
1325 /// visible top level widgets when session managment allows
1327 /// We are changing that to close all wiew one by one.
1328 /// FIXME: verify if the default implementation is enough now.
1329 if (sm.allowsInteraction() && !closeAllViews())
1334 void GuiApplication::unregisterView(GuiView * gv)
1336 LASSERT(d->views_[gv->id()] == gv, /**/);
1337 d->views_.remove(gv->id());
1338 if (current_view_ == gv) {
1340 theLyXFunc().setLyXView(0);
1345 bool GuiApplication::closeAllViews()
1347 if (d->views_.empty())
1350 QList<GuiView *> views = d->views_.values();
1351 foreach (GuiView * view, views) {
1361 GuiView & GuiApplication::view(int id) const
1363 LASSERT(d->views_.contains(id), /**/);
1364 return *d->views_.value(id);
1368 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1370 QList<GuiView *> views = d->views_.values();
1371 foreach (GuiView * view, views)
1372 view->hideDialog(name, inset);
1376 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1378 Buffer const * buffer_ = 0;
1379 QHash<int, GuiView *>::iterator end = d->views_.end();
1380 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1381 if (Buffer const * ptr = (*it)->updateInset(inset))
1388 bool GuiApplication::searchMenu(FuncRequest const & func,
1389 docstring_list & names) const
1391 return d->menus_.searchMenu(func, names);
1395 bool GuiApplication::readUIFile(QString const & name, bool include)
1405 LexerKeyword uitags[] = {
1406 { "include", ui_include },
1407 { "menuset", ui_menuset },
1408 { "toolbars", ui_toolbars },
1409 { "toolbarset", ui_toolbarset }
1412 LYXERR(Debug::INIT, "About to read " << name << "...");
1416 ui_path = libFileSearch("ui", name, "inc");
1417 if (ui_path.empty())
1418 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1420 ui_path = libFileSearch("ui", name, "ui");
1423 if (ui_path.empty()) {
1424 LYXERR(Debug::INIT, "Could not find " << name);
1425 Alert::warning(_("Could not find UI definition file"),
1426 bformat(_("Error while reading the configuration file\n%1$s.\n"
1427 "Please check your installation."), qstring_to_ucs4(name)));
1432 // Ensure that a file is read only once (prevents include loops)
1433 static QStringList uifiles;
1434 QString const uifile = toqstr(ui_path.absFilename());
1435 if (uifiles.contains(uifile)) {
1437 // We are reading again the top uifile so reset the safeguard:
1440 d->toolbars_.reset();
1442 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1443 << "Is this an include loop?");
1447 uifiles.push_back(uifile);
1449 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1452 lex.setFile(ui_path);
1454 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1458 if (lyxerr.debugging(Debug::PARSER))
1459 lex.printTable(lyxerr);
1461 while (lex.isOK()) {
1462 switch (lex.lex()) {
1465 QString const file = toqstr(lex.getString());
1466 if (!readUIFile(file, true))
1471 d->menus_.read(lex);
1475 d->toolbars_.readToolbars(lex);
1479 d->toolbars_.readToolbarSettings(lex);
1483 if (!rtrim(lex.getString()).empty())
1484 lex.printError("LyX::ReadUIFile: "
1485 "Unknown menu tag: `$$Token'");
1494 settings.beginGroup("ui_files");
1495 bool touched = false;
1496 for (int i = 0; i != uifiles.size(); ++i) {
1497 QFileInfo fi(uifiles[i]);
1498 QDateTime const date_value = fi.lastModified();
1499 QString const name_key = QString::number(i);
1500 if (!settings.contains(name_key)
1501 || settings.value(name_key).toString() != uifiles[i]
1502 || settings.value(name_key + "/date").toDateTime() != date_value) {
1504 settings.setValue(name_key, uifiles[i]);
1505 settings.setValue(name_key + "/date", date_value);
1508 settings.endGroup();
1510 settings.remove("views");
1516 void GuiApplication::onLastWindowClosed()
1518 if (d->global_menubar_)
1519 d->global_menubar_->grabKeyboard();
1523 ////////////////////////////////////////////////////////////////////////
1525 // X11 specific stuff goes here...
1528 bool GuiApplication::x11EventFilter(XEvent * xev)
1533 switch (xev->type) {
1534 case SelectionRequest: {
1535 if (xev->xselectionrequest.selection != XA_PRIMARY)
1537 LYXERR(Debug::SELECTION, "X requested selection.");
1538 BufferView * bv = current_view_->view();
1540 docstring const sel = bv->requestSelection();
1542 d->selection_.put(sel);
1546 case SelectionClear: {
1547 if (xev->xselectionclear.selection != XA_PRIMARY)
1549 LYXERR(Debug::SELECTION, "Lost selection.");
1550 BufferView * bv = current_view_->view();
1552 bv->clearSelection();
1560 } // namespace frontend
1563 void hideDialogs(std::string const & name, Inset * inset)
1566 theApp()->hideDialogs(name, inset);
1570 ////////////////////////////////////////////////////////////////////
1574 ////////////////////////////////////////////////////////////////////
1576 frontend::FontLoader & theFontLoader()
1578 LASSERT(frontend::guiApp, /**/);
1579 return frontend::guiApp->fontLoader();
1583 frontend::FontMetrics const & theFontMetrics(Font const & f)
1585 return theFontMetrics(f.fontInfo());
1589 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1591 LASSERT(frontend::guiApp, /**/);
1592 return frontend::guiApp->fontLoader().metrics(f);
1596 ////////////////////////////////////////////////////////////////////
1600 ////////////////////////////////////////////////////////////////////
1602 frontend::Clipboard & theClipboard()
1604 LASSERT(frontend::guiApp, /**/);
1605 return frontend::guiApp->clipboard();
1609 frontend::Selection & theSelection()
1611 LASSERT(frontend::guiApp, /**/);
1612 return frontend::guiApp->selection();
1617 #include "moc_GuiApplication.cpp"