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/os.h"
58 #include "support/Package.h"
61 #include "support/linkback/LinkBackProxy.h"
67 #include <QFileOpenEvent>
71 #include <QLibraryInfo>
73 #include <QMacPasteboardMime>
78 #include <QPixmapCache>
80 #include <QSessionManager>
81 #include <QSocketNotifier>
82 #include <QSortFilterProxyModel>
83 #include <QStandardItemModel>
86 #include <QTranslator>
90 #include <X11/Xatom.h>
97 #include <QWindowsMime>
98 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
104 #include <boost/bind.hpp>
110 using namespace lyx::support;
113 static void initializeResources()
115 static bool initialized = false;
117 Q_INIT_RESOURCE(Resources);
125 frontend::Application * createApplication(int & argc, char * argv[])
127 return new frontend::GuiApplication(argc, argv);
132 ////////////////////////////////////////////////////////////////////////
133 // Icon loading support code.
134 ////////////////////////////////////////////////////////////////////////
144 bool operator<(PngMap const & lhs, PngMap const & rhs)
146 return lhs.key < rhs.key;
152 CompareKey(QString const & name) : name_(name) {}
153 bool operator()(PngMap const & other) const { return other.key == name_; }
159 // this must be sorted alphabetically
160 // Upper case comes before lower case
161 PngMap sorted_png_map[] = {
162 { "Bumpeq", "bumpeq2" },
165 { "Delta", "delta2" },
166 { "Downarrow", "downarrow2" },
167 { "Gamma", "gamma2" },
168 { "Lambda", "lambda2" },
169 { "Leftarrow", "leftarrow2" },
170 { "Leftrightarrow", "leftrightarrow2" },
171 { "Longleftarrow", "longleftarrow2" },
172 { "Longleftrightarrow", "longleftrightarrow2" },
173 { "Longrightarrow", "longrightarrow2" },
174 { "Omega", "omega2" },
178 { "Rightarrow", "rightarrow2" },
179 { "Sigma", "sigma2" },
180 { "Subset", "subset2" },
181 { "Supset", "supset2" },
182 { "Theta", "theta2" },
183 { "Uparrow", "uparrow2" },
184 { "Updownarrow", "updownarrow2" },
185 { "Upsilon", "upsilon2" },
186 { "Vdash", "vdash3" },
189 { "nLeftarrow", "nleftarrow2" },
190 { "nLeftrightarrow", "nleftrightarrow2" },
191 { "nRightarrow", "nrightarrow2" },
192 { "nVDash", "nvdash3" },
193 { "nvDash", "nvdash2" },
194 { "textrm \\AA", "textrm_AA"},
195 { "textrm \\O", "textrm_O"},
196 { "vDash", "vdash2" }
199 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
202 QString findPng(QString const & name)
204 PngMap const * const begin = sorted_png_map;
205 PngMap const * const end = begin + nr_sorted_png_map;
206 LASSERT(sorted(begin, end), /**/);
208 PngMap const * const it = find_if(begin, end, CompareKey(name));
212 png_name = it->value;
215 png_name.replace('_', "underscore");
216 png_name.replace(' ', '_');
218 // This way we can have "math-delim { }" on the toolbar.
219 png_name.replace('(', "lparen");
220 png_name.replace(')', "rparen");
221 png_name.replace('[', "lbracket");
222 png_name.replace(']', "rbracket");
223 png_name.replace('{', "lbrace");
224 png_name.replace('}', "rbrace");
225 png_name.replace('|', "bars");
226 png_name.replace(',', "thinspace");
227 png_name.replace(':', "mediumspace");
228 png_name.replace(';', "thickspace");
229 png_name.replace('!', "negthinspace");
232 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
233 << "Looking for math PNG called \"" << png_name << '"');
240 QString iconName(FuncRequest const & f, bool unknown)
242 initializeResources();
247 case LFUN_MATH_INSERT:
248 if (!f.argument().empty()) {
250 name1 = findPng(toqstr(f.argument()).mid(1));
253 case LFUN_MATH_DELIM:
254 case LFUN_MATH_BIGDELIM:
256 name1 = findPng(toqstr(f.argument()));
260 name1 = toqstr(f.argument());
263 name2 = toqstr(lyxaction.getActionName(f.action));
266 if (!f.argument().empty()) {
267 name1 = name2 + ' ' + toqstr(f.argument());
268 name1.replace(' ', '_');
272 FileName fname = libFileSearch("images/" + path, name1, "png");
274 return toqstr(fname.absFilename());
276 fname = libFileSearch("images/" + path, name2, "png");
278 return toqstr(fname.absFilename());
280 path = ":/images/" + path;
283 LYXERR0("Directory " << path << " not found in resource!");
287 if (res.exists(name1))
291 if (res.exists(name2))
294 LYXERR(Debug::GUI, "Cannot find icon for command \""
295 << lyxaction.getActionName(f.action)
296 << '(' << to_utf8(f.argument()) << ")\"");
299 return QString(":/images/unknown.png");
305 QIcon getIcon(FuncRequest const & f, bool unknown)
307 QString icon = iconName(f, unknown);
311 LYXERR(Debug::GUI, "Found icon: " << icon);
313 if (!pm.load(icon)) {
314 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
322 ////////////////////////////////////////////////////////////////////////
323 // LyX server support code.
324 ////////////////////////////////////////////////////////////////////////
325 class SocketNotifier : public QSocketNotifier
328 /// connect a connection notification from the LyXServerSocket
329 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
330 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
334 /// The callback function
335 Application::SocketCallback func_;
339 ////////////////////////////////////////////////////////////////////////
340 // Mac specific stuff goes here...
341 ////////////////////////////////////////////////////////////////////////
343 class MenuTranslator : public QTranslator
346 MenuTranslator(QObject * parent)
347 : QTranslator(parent)
350 QString translate(const char * /*context*/,
351 const char * sourceText,
352 const char * /*comment*/ = 0)
354 string const s = sourceText;
355 if (s == N_("About %1") || s == N_("Preferences")
356 || s == N_("Reconfigure") || s == N_("Quit %1"))
363 class GlobalMenuBar : public QMenuBar
367 GlobalMenuBar() : QMenuBar(0) {}
370 bool event(QEvent * e)
372 if (e->type() == QEvent::ShortcutOverride) {
373 // && activeWindow() == 0) {
374 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
376 setKeySymbol(&sym, ke);
377 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
386 // QMacPasteboardMimeGraphics can only be compiled on Mac.
388 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
391 QMacPasteboardMimeGraphics()
392 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
395 QString convertorName() { return "Graphics"; }
397 QString flavorFor(QString const & mime)
399 LYXERR(Debug::ACTION, "flavorFor " << mime);
400 if (mime == pdfMimeType())
401 return QLatin1String("com.adobe.pdf");
405 QString mimeFor(QString flav)
407 LYXERR(Debug::ACTION, "mimeFor " << flav);
408 if (flav == QLatin1String("com.adobe.pdf"))
409 return pdfMimeType();
413 bool canConvert(QString const & mime, QString flav)
415 return mimeFor(flav) == mime;
418 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
422 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
426 QList<QByteArray> convertFromMime(QString const & /*mime*/,
427 QVariant data, QString /*flav*/)
429 QList<QByteArray> ret;
430 ret.append(data.toByteArray());
436 ///////////////////////////////////////////////////////////////
437 // You can find more platform specific stuff
438 // at the end of this file...
439 ///////////////////////////////////////////////////////////////
441 ////////////////////////////////////////////////////////////////////////
442 // Windows specific stuff goes here...
445 // QWindowsMimeMetafile can only be compiled on Windows.
447 static FORMATETC cfFromMime(QString const & mimetype)
450 if (mimetype == emfMimeType()) {
451 formatetc.cfFormat = CF_ENHMETAFILE;
452 formatetc.tymed = TYMED_ENHMF;
453 } else if (mimetype == wmfMimeType()) {
454 formatetc.cfFormat = CF_METAFILEPICT;
455 formatetc.tymed = TYMED_MFPICT;
458 formatetc.dwAspect = DVASPECT_CONTENT;
459 formatetc.lindex = -1;
464 class QWindowsMimeMetafile : public QWindowsMime {
466 QWindowsMimeMetafile() {}
468 bool canConvertFromMime(FORMATETC const & formatetc,
469 QMimeData const * mimedata) const
474 bool canConvertToMime(QString const & mimetype,
475 IDataObject * pDataObj) const
477 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
479 FORMATETC formatetc = cfFromMime(mimetype);
480 return pDataObj->QueryGetData(&formatetc) == S_OK;
483 bool convertFromMime(FORMATETC const & formatetc,
484 const QMimeData * mimedata, STGMEDIUM * pmedium) const
489 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
490 QVariant::Type preferredType) const
493 if (!canConvertToMime(mimetype, pDataObj))
496 FORMATETC formatetc = cfFromMime(mimetype);
498 if (pDataObj->GetData(&formatetc, &s) != S_OK)
502 if (s.tymed == TYMED_ENHMF) {
503 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
504 data.resize(dataSize);
505 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
506 (LPBYTE)data.data());
507 } else if (s.tymed == TYMED_MFPICT) {
508 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
509 data.resize(dataSize);
510 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
511 (LPBYTE)data.data());
514 ReleaseStgMedium(&s);
520 QVector<FORMATETC> formatsForMime(QString const & mimeType,
521 QMimeData const * mimeData) const
523 QVector<FORMATETC> formats;
524 formats += cfFromMime(mimeType);
528 QString mimeForFormat(FORMATETC const & formatetc) const
530 switch (formatetc.cfFormat) {
532 return emfMimeType();
533 case CF_METAFILEPICT:
534 return wmfMimeType();
542 ////////////////////////////////////////////////////////////////////////
543 // GuiApplication::Private definition and implementation.
544 ////////////////////////////////////////////////////////////////////////
546 struct GuiApplication::Private
549 : language_model_(0), global_menubar_(0)
552 // Create the global default menubar which is shown for the dialogs
553 // and if no GuiView is visible.
554 global_menubar_ = new GlobalMenuBar();
559 QSortFilterProxyModel * language_model_;
561 GuiClipboard clipboard_;
563 GuiSelection selection_;
565 FontLoader font_loader_;
567 ColorCache color_cache_;
569 QTranslator qt_trans_;
571 QHash<int, SocketNotifier *> socket_notifiers_;
575 /// The global instance
578 /// this timer is used for any regular events one wants to
579 /// perform. at present it is used to check if forked processes
581 QTimer general_timer_;
583 /// Multiple views container.
585 * Warning: This must not be a smart pointer as the destruction of the
586 * object is handled by Qt when the view is closed
587 * \sa Qt::WA_DeleteOnClose attribute.
589 QHash<int, GuiView *> views_;
591 /// Only used on mac.
592 GlobalMenuBar * global_menubar_;
595 /// Linkback mime handler for MacOSX.
596 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
600 /// WMF Mime handler for Windows clipboard.
601 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
602 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
603 // is something in the clipboard.
604 QWindowsMimeMetafile wmf_mime_;
609 GuiApplication * guiApp;
611 GuiApplication::~GuiApplication()
614 closeAllLinkBackLinks();
620 GuiApplication::GuiApplication(int & argc, char ** argv)
621 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
623 QString app_name = "LyX";
624 QCoreApplication::setOrganizationName(app_name);
625 QCoreApplication::setOrganizationDomain("lyx.org");
626 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
628 // FIXME: quitOnLastWindowClosed is true by default. We should have a
629 // lyxrc setting for this in order to let the application stay resident.
630 // But then we need some kind of dock icon, at least on Windows.
632 if (lyxrc.quit_on_last_window_closed)
633 setQuitOnLastWindowClosed(false);
636 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
637 // seems to be the default case for applications like LyX.
638 setQuitOnLastWindowClosed(false);
642 // doubleClickInterval() is 400 ms on X11 which is just too long.
643 // On Windows and Mac OS X, the operating system's value is used.
644 // On Microsoft Windows, calling this function sets the double
645 // click interval for all applications. So we don't!
646 QApplication::setDoubleClickInterval(300);
649 // install translation file for Qt built-in dialogs
650 QString language_name = QString("qt_") + QLocale::system().name();
652 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
653 // Short-named translator can be loaded from a long name, but not the
654 // opposite. Therefore, long name should be used without truncation.
655 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
656 if (d->qt_trans_.load(language_name,
657 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
659 installTranslator(&d->qt_trans_);
660 // even if the language calls for RtL, don't do that
661 setLayoutDirection(Qt::LeftToRight);
662 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
665 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
669 // This allows to translate the strings that appear in the LyX menu.
670 /// A translator suitable for the entries in the LyX menu.
671 /// Only needed with Qt/Mac.
672 installTranslator(new MenuTranslator(this));
674 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
676 using namespace lyx::graphics;
678 Image::newImage = boost::bind(&GuiImage::newImage);
679 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
681 // needs to be done before reading lyxrc
683 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
687 // Set the cache to 5120 kilobytes which corresponds to screen size of
688 // 1280 by 1024 pixels with a color depth of 32 bits.
689 QPixmapCache::setCacheLimit(5120);
691 // Initialize RC Fonts
692 if (lyxrc.roman_font_name.empty())
693 lyxrc.roman_font_name = fromqstr(romanFontName());
695 if (lyxrc.sans_font_name.empty())
696 lyxrc.sans_font_name = fromqstr(sansFontName());
698 if (lyxrc.typewriter_font_name.empty())
699 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
701 d->general_timer_.setInterval(500);
702 connect(&d->general_timer_, SIGNAL(timeout()),
703 this, SLOT(handleRegularEvents()));
704 d->general_timer_.start();
708 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
710 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
715 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
721 case LFUN_WINDOW_CLOSE:
722 enable = d->views_.size() > 0;
725 case LFUN_BUFFER_NEW:
726 case LFUN_BUFFER_NEW_TEMPLATE:
728 case LFUN_SCREEN_FONT_UPDATE:
730 case LFUN_WINDOW_NEW:
740 flag.setEnabled(false);
746 bool GuiApplication::dispatch(FuncRequest const & cmd)
748 switch (cmd.action) {
750 case LFUN_WINDOW_NEW:
751 createView(toqstr(cmd.argument()));
754 case LFUN_WINDOW_CLOSE:
755 // update bookmark pit of the current buffer before window close
756 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
757 theLyXFunc().gotoBookmark(i+1, false, false);
758 current_view_->close();
762 // quitting is triggered by the gui code
763 // (leaving the event loop).
765 current_view_->message(from_utf8(N_("Exiting.")));
770 case LFUN_SCREEN_FONT_UPDATE: {
771 // handle the screen font changes.
772 d->font_loader_.update();
773 // Backup current_view_
774 GuiView * view = current_view_;
775 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
776 // to skip the refresh.
778 BufferList::iterator it = theBufferList().begin();
779 BufferList::iterator const end = theBufferList().end();
780 for (; it != end; ++it)
782 // Restore current_view_
783 current_view_ = view;
787 case LFUN_BUFFER_NEW:
788 if (d->views_.empty()
789 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
790 createView(QString(), false); // keep hidden
791 current_view_->newDocument(to_utf8(cmd.argument()), false);
792 current_view_->show();
793 setActiveWindow(current_view_);
795 current_view_->newDocument(to_utf8(cmd.argument()), false);
799 case LFUN_BUFFER_NEW_TEMPLATE:
800 if (d->views_.empty()
801 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
803 current_view_->newDocument(to_utf8(cmd.argument()), true);
804 if (!current_view_->buffer())
805 current_view_->close();
807 current_view_->newDocument(to_utf8(cmd.argument()), true);
812 if (d->views_.empty()
813 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
815 current_view_->openDocument(to_utf8(cmd.argument()));
816 if (!current_view_->buffer())
817 current_view_->close();
819 current_view_->openDocument(to_utf8(cmd.argument()));
822 case LFUN_SET_COLOR: {
824 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
825 if (lyx_name.empty() || x11_name.empty()) {
826 current_view_->message(
827 _("Syntax: set-color <lyx_name> <x11_name>"));
831 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
832 bool const graphicsbg_changed = lyx_name == graphicsbg
833 && x11_name != graphicsbg;
834 if (graphicsbg_changed) {
835 // FIXME: The graphics cache no longer has a changeDisplay method.
837 graphics::GCache::get().changeDisplay(true);
841 if (!lcolor.setColor(lyx_name, x11_name)) {
842 current_view_->message(
843 bformat(_("Set-color \"%1$s\" failed "
844 "- color is undefined or "
845 "may not be redefined"),
846 from_utf8(lyx_name)));
849 // Make sure we don't keep old colors in cache.
850 d->color_cache_.clear();
855 // Notify the caller that the action has not been dispatched.
859 // The action has been dispatched.
864 void GuiApplication::resetGui()
866 QHash<int, GuiView *>::iterator it;
867 for (it = d->views_.begin(); it != d->views_.end(); ++it)
868 (*it)->resetDialogs();
870 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
874 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
876 // release the keyboard which might have been grabed by the global
877 // menubar on Mac to catch shortcuts even without any GuiView.
878 if (d->global_menubar_)
879 d->global_menubar_->releaseKeyboard();
883 while (d->views_.find(id) != d->views_.end())
885 GuiView * view = new GuiView(id);
887 // copy the icon size from old view
889 view->setIconSize(current_view_->iconSize());
892 d->views_[id] = view;
896 setActiveWindow(view);
899 if (!geometry_arg.isEmpty()) {
903 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
904 re.indexIn(geometry_arg);
905 w = re.cap(1).toInt();
906 h = re.cap(2).toInt();
907 x = re.cap(3).toInt();
908 y = re.cap(4).toInt();
909 view->setGeometry(x, y, w, h);
913 setCurrentView(view);
917 Clipboard & GuiApplication::clipboard()
919 return d->clipboard_;
923 Selection & GuiApplication::selection()
925 return d->selection_;
929 FontLoader & GuiApplication::fontLoader()
931 return d->font_loader_;
935 Toolbars const & GuiApplication::toolbars() const
941 Toolbars & GuiApplication::toolbars()
947 Menus const & GuiApplication::menus() const
953 Menus & GuiApplication::menus()
959 QList<int> GuiApplication::viewIds() const
961 return d->views_.keys();
965 ColorCache & GuiApplication::colorCache()
967 return d->color_cache_;
971 int GuiApplication::exec()
973 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
974 return QApplication::exec();
978 void GuiApplication::exit(int status)
980 QApplication::exit(status);
984 void GuiApplication::execBatchCommands()
987 if (!readUIFile(toqstr(lyxrc.ui_file)))
988 // Gives some error box here.
991 // init the global menubar on Mac. This must be done after the session
992 // was recovered to know the "last files".
993 if (d->global_menubar_)
994 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
996 LyX::ref().execBatchCommands();
999 QAbstractItemModel * GuiApplication::languageModel()
1001 if (d->language_model_)
1002 return d->language_model_;
1004 QStandardItemModel * lang_model = new QStandardItemModel(this);
1005 lang_model->insertColumns(0, 1);
1007 Languages::const_iterator it = languages.begin();
1008 Languages::const_iterator end = languages.end();
1009 for (; it != end; ++it) {
1010 current_row = lang_model->rowCount();
1011 lang_model->insertRows(current_row, 1);
1012 QModelIndex item = lang_model->index(current_row, 0);
1013 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1014 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1016 d->language_model_ = new QSortFilterProxyModel(this);
1017 d->language_model_->setSourceModel(lang_model);
1018 #if QT_VERSION >= 0x040300
1019 d->language_model_->setSortLocaleAware(true);
1021 return d->language_model_;
1025 void GuiApplication::restoreGuiSession()
1027 if (!lyxrc.load_session)
1030 Session & session = LyX::ref().session();
1031 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1032 // do not add to the lastfile list since these files are restored from
1033 // last session, and should be already there (regular files), or should
1034 // not be added at all (help files).
1035 for_each(lastopened.begin(), lastopened.end(),
1036 bind(&GuiView::loadDocument, current_view_, _1, false));
1038 // clear this list to save a few bytes of RAM
1039 session.lastOpened().clear();
1043 QString const GuiApplication::romanFontName()
1046 font.setKerning(false);
1047 font.setStyleHint(QFont::Serif);
1048 font.setFamily("serif");
1050 return QFontInfo(font).family();
1054 QString const GuiApplication::sansFontName()
1057 font.setKerning(false);
1058 font.setStyleHint(QFont::SansSerif);
1059 font.setFamily("sans");
1061 return QFontInfo(font).family();
1065 QString const GuiApplication::typewriterFontName()
1068 font.setKerning(false);
1069 font.setStyleHint(QFont::TypeWriter);
1070 font.setFamily("monospace");
1072 return QFontInfo(font).family();
1076 void GuiApplication::handleRegularEvents()
1078 ForkedCallsController::handleCompletedProcesses();
1082 bool GuiApplication::event(QEvent * e)
1085 case QEvent::FileOpen: {
1086 // Open a file; this happens only on Mac OS X for now
1087 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1088 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1089 qstring_to_ucs4(foe->file())));
1094 return QApplication::event(e);
1099 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1102 return QApplication::notify(receiver, event);
1104 catch (ExceptionMessage const & e) {
1106 case ErrorException:
1107 LyX::cref().emergencyCleanup();
1108 setQuitOnLastWindowClosed(false);
1110 Alert::error(e.title_, e.details_);
1112 // Properly crash in debug mode in order to get a useful backtrace.
1115 // In release mode, try to exit gracefully.
1118 case BufferException: {
1119 Buffer * buf = current_view_->buffer();
1120 docstring details = e.details_ + '\n';
1121 details += theBufferList().emergencyWrite(buf);
1122 theBufferList().release(buf);
1123 details += "\n" + _("The current document was closed.");
1124 Alert::error(e.title_, details);
1127 case WarningException:
1128 Alert::warning(e.title_, e.details_);
1132 catch (exception const & e) {
1133 docstring s = _("LyX has caught an exception, it will now "
1134 "attempt to save all unsaved documents and exit."
1136 s += from_ascii(e.what());
1137 Alert::error(_("Software exception Detected"), s);
1138 LyX::cref().exit(1);
1141 docstring s = _("LyX has caught some really weird exception, it will "
1142 "now attempt to save all unsaved documents and exit.");
1143 Alert::error(_("Software exception Detected"), s);
1144 LyX::cref().exit(1);
1151 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1153 QColor const & qcol = d->color_cache_.get(col);
1154 if (!qcol.isValid()) {
1160 rgbcol.r = qcol.red();
1161 rgbcol.g = qcol.green();
1162 rgbcol.b = qcol.blue();
1167 string const GuiApplication::hexName(ColorCode col)
1169 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1173 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1175 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1176 d->socket_notifiers_[fd] = sn;
1177 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1181 void GuiApplication::socketDataReceived(int fd)
1183 d->socket_notifiers_[fd]->func_();
1187 void GuiApplication::unregisterSocketCallback(int fd)
1189 d->socket_notifiers_.take(fd)->setEnabled(false);
1193 void GuiApplication::commitData(QSessionManager & sm)
1195 /// The implementation is required to avoid an application exit
1196 /// when session state save is triggered by session manager.
1197 /// The default implementation sends a close event to all
1198 /// visible top level widgets when session managment allows
1200 /// We are changing that to close all wiew one by one.
1201 /// FIXME: verify if the default implementation is enough now.
1202 if (sm.allowsInteraction() && !closeAllViews())
1207 void GuiApplication::unregisterView(GuiView * gv)
1209 LASSERT(d->views_[gv->id()] == gv, /**/);
1210 d->views_.remove(gv->id());
1211 if (current_view_ == gv) {
1213 theLyXFunc().setLyXView(0);
1218 bool GuiApplication::closeAllViews()
1220 if (d->views_.empty())
1223 QList<GuiView *> views = d->views_.values();
1224 foreach (GuiView * view, views) {
1234 GuiView & GuiApplication::view(int id) const
1236 LASSERT(d->views_.contains(id), /**/);
1237 return *d->views_.value(id);
1241 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1243 QList<GuiView *> views = d->views_.values();
1244 foreach (GuiView * view, views)
1245 view->hideDialog(name, inset);
1249 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1251 Buffer const * buffer_ = 0;
1252 QHash<int, GuiView *>::iterator end = d->views_.end();
1253 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1254 if (Buffer const * ptr = (*it)->updateInset(inset))
1261 bool GuiApplication::searchMenu(FuncRequest const & func,
1262 docstring_list & names) const
1264 return d->menus_.searchMenu(func, names);
1268 bool GuiApplication::readUIFile(QString const & name, bool include)
1278 LexerKeyword uitags[] = {
1279 { "include", ui_include },
1280 { "menuset", ui_menuset },
1281 { "toolbars", ui_toolbars },
1282 { "toolbarset", ui_toolbarset }
1285 // Ensure that a file is read only once (prevents include loops)
1286 static QStringList uifiles;
1287 if (uifiles.contains(name)) {
1288 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1289 << "Is this an include loop?");
1293 LYXERR(Debug::INIT, "About to read " << name << "...");
1297 ui_path = libFileSearch("ui", name, "inc");
1298 if (ui_path.empty())
1299 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1301 ui_path = libFileSearch("ui", name, "ui");
1304 if (ui_path.empty()) {
1305 LYXERR(Debug::INIT, "Could not find " << name);
1306 Alert::warning(_("Could not find UI defintion file"),
1307 bformat(_("Error while reading the configuration file\n%1$s.\n"
1308 "Please check your installation."), qstring_to_ucs4(name)));
1312 uifiles.push_back(name);
1314 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1316 lex.setFile(ui_path);
1318 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1322 if (lyxerr.debugging(Debug::PARSER))
1323 lex.printTable(lyxerr);
1325 while (lex.isOK()) {
1326 switch (lex.lex()) {
1329 QString const file = toqstr(lex.getString());
1330 if (!readUIFile(file, true))
1335 d->menus_.read(lex);
1339 d->toolbars_.readToolbars(lex);
1343 d->toolbars_.readToolbarSettings(lex);
1347 if (!rtrim(lex.getString()).empty())
1348 lex.printError("LyX::ReadUIFile: "
1349 "Unknown menu tag: `$$Token'");
1357 void GuiApplication::onLastWindowClosed()
1359 if (d->global_menubar_)
1360 d->global_menubar_->grabKeyboard();
1364 ////////////////////////////////////////////////////////////////////////
1366 // X11 specific stuff goes here...
1369 bool GuiApplication::x11EventFilter(XEvent * xev)
1374 switch (xev->type) {
1375 case SelectionRequest: {
1376 if (xev->xselectionrequest.selection != XA_PRIMARY)
1378 LYXERR(Debug::GUI, "X requested selection.");
1379 BufferView * bv = current_view_->view();
1381 docstring const sel = bv->requestSelection();
1383 d->selection_.put(sel);
1387 case SelectionClear: {
1388 if (xev->xselectionclear.selection != XA_PRIMARY)
1390 LYXERR(Debug::GUI, "Lost selection.");
1391 BufferView * bv = current_view_->view();
1393 bv->clearSelection();
1401 } // namespace frontend
1404 void hideDialogs(std::string const & name, Inset * inset)
1407 theApp()->hideDialogs(name, inset);
1411 ////////////////////////////////////////////////////////////////////
1415 ////////////////////////////////////////////////////////////////////
1417 frontend::FontLoader & theFontLoader()
1419 LASSERT(frontend::guiApp, /**/);
1420 return frontend::guiApp->fontLoader();
1424 frontend::FontMetrics const & theFontMetrics(Font const & f)
1426 return theFontMetrics(f.fontInfo());
1430 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1432 LASSERT(frontend::guiApp, /**/);
1433 return frontend::guiApp->fontLoader().metrics(f);
1437 ////////////////////////////////////////////////////////////////////
1441 ////////////////////////////////////////////////////////////////////
1443 frontend::Clipboard & theClipboard()
1445 LASSERT(frontend::guiApp, /**/);
1446 return frontend::guiApp->clipboard();
1450 frontend::Selection & theSelection()
1452 LASSERT(frontend::guiApp, /**/);
1453 return frontend::guiApp->selection();
1458 #include "GuiApplication_moc.cpp"