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);
680 // needs to be done before reading lyxrc
682 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
686 // Set the cache to 5120 kilobytes which corresponds to screen size of
687 // 1280 by 1024 pixels with a color depth of 32 bits.
688 QPixmapCache::setCacheLimit(5120);
690 // Initialize RC Fonts
691 if (lyxrc.roman_font_name.empty())
692 lyxrc.roman_font_name = fromqstr(romanFontName());
694 if (lyxrc.sans_font_name.empty())
695 lyxrc.sans_font_name = fromqstr(sansFontName());
697 if (lyxrc.typewriter_font_name.empty())
698 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
700 d->general_timer_.setInterval(500);
701 connect(&d->general_timer_, SIGNAL(timeout()),
702 this, SLOT(handleRegularEvents()));
703 d->general_timer_.start();
707 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
709 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
714 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
720 case LFUN_WINDOW_CLOSE:
721 enable = d->views_.size() > 0;
724 case LFUN_BUFFER_NEW:
725 case LFUN_BUFFER_NEW_TEMPLATE:
727 case LFUN_SCREEN_FONT_UPDATE:
729 case LFUN_WINDOW_NEW:
739 flag.setEnabled(false);
745 bool GuiApplication::dispatch(FuncRequest const & cmd)
747 switch (cmd.action) {
749 case LFUN_WINDOW_NEW:
750 createView(toqstr(cmd.argument()));
753 case LFUN_WINDOW_CLOSE:
754 // update bookmark pit of the current buffer before window close
755 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
756 theLyXFunc().gotoBookmark(i+1, false, false);
757 current_view_->close();
761 // quitting is triggered by the gui code
762 // (leaving the event loop).
764 current_view_->message(from_utf8(N_("Exiting.")));
769 case LFUN_SCREEN_FONT_UPDATE: {
770 // handle the screen font changes.
771 d->font_loader_.update();
772 // Backup current_view_
773 GuiView * view = current_view_;
774 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
775 // to skip the refresh.
777 BufferList::iterator it = theBufferList().begin();
778 BufferList::iterator const end = theBufferList().end();
779 for (; it != end; ++it)
781 // Restore current_view_
782 current_view_ = view;
786 case LFUN_BUFFER_NEW:
787 if (d->views_.empty()
788 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
789 createView(QString(), false); // keep hidden
790 current_view_->newDocument(to_utf8(cmd.argument()), false);
791 current_view_->show();
792 setActiveWindow(current_view_);
794 current_view_->newDocument(to_utf8(cmd.argument()), false);
798 case LFUN_BUFFER_NEW_TEMPLATE:
799 if (d->views_.empty()
800 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
802 current_view_->newDocument(to_utf8(cmd.argument()), true);
803 if (!current_view_->buffer())
804 current_view_->close();
806 current_view_->newDocument(to_utf8(cmd.argument()), true);
811 if (d->views_.empty()
812 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
814 current_view_->openDocument(to_utf8(cmd.argument()));
815 if (!current_view_->buffer())
816 current_view_->close();
818 current_view_->openDocument(to_utf8(cmd.argument()));
821 case LFUN_SET_COLOR: {
823 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
824 if (lyx_name.empty() || x11_name.empty()) {
825 current_view_->message(
826 _("Syntax: set-color <lyx_name> <x11_name>"));
830 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
831 bool const graphicsbg_changed = lyx_name == graphicsbg
832 && x11_name != graphicsbg;
833 if (graphicsbg_changed) {
834 // FIXME: The graphics cache no longer has a changeDisplay method.
836 graphics::GCache::get().changeDisplay(true);
840 if (!lcolor.setColor(lyx_name, x11_name)) {
841 current_view_->message(
842 bformat(_("Set-color \"%1$s\" failed "
843 "- color is undefined or "
844 "may not be redefined"),
845 from_utf8(lyx_name)));
848 // Make sure we don't keep old colors in cache.
849 d->color_cache_.clear();
854 // Notify the caller that the action has not been dispatched.
858 // The action has been dispatched.
863 void GuiApplication::resetGui()
865 QHash<int, GuiView *>::iterator it;
866 for (it = d->views_.begin(); it != d->views_.end(); ++it)
867 (*it)->resetDialogs();
869 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
873 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
875 // release the keyboard which might have been grabed by the global
876 // menubar on Mac to catch shortcuts even without any GuiView.
877 if (d->global_menubar_)
878 d->global_menubar_->releaseKeyboard();
882 while (d->views_.find(id) != d->views_.end())
884 GuiView * view = new GuiView(id);
886 // copy the icon size from old view
888 view->setIconSize(current_view_->iconSize());
891 d->views_[id] = view;
895 setActiveWindow(view);
898 if (!geometry_arg.isEmpty()) {
902 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
903 re.indexIn(geometry_arg);
904 w = re.cap(1).toInt();
905 h = re.cap(2).toInt();
906 x = re.cap(3).toInt();
907 y = re.cap(4).toInt();
908 view->setGeometry(x, y, w, h);
912 setCurrentView(view);
916 Clipboard & GuiApplication::clipboard()
918 return d->clipboard_;
922 Selection & GuiApplication::selection()
924 return d->selection_;
928 FontLoader & GuiApplication::fontLoader()
930 return d->font_loader_;
934 Toolbars const & GuiApplication::toolbars() const
940 Toolbars & GuiApplication::toolbars()
946 Menus const & GuiApplication::menus() const
952 Menus & GuiApplication::menus()
958 QList<int> GuiApplication::viewIds() const
960 return d->views_.keys();
964 ColorCache & GuiApplication::colorCache()
966 return d->color_cache_;
970 int GuiApplication::exec()
972 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
973 return QApplication::exec();
977 void GuiApplication::exit(int status)
979 QApplication::exit(status);
983 void GuiApplication::execBatchCommands()
986 if (!readUIFile(toqstr(lyxrc.ui_file)))
987 // Gives some error box here.
990 // init the global menubar on Mac. This must be done after the session
991 // was recovered to know the "last files".
992 if (d->global_menubar_)
993 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
995 LyX::ref().execBatchCommands();
998 QAbstractItemModel * GuiApplication::languageModel()
1000 if (d->language_model_)
1001 return d->language_model_;
1003 QStandardItemModel * lang_model = new QStandardItemModel(this);
1004 lang_model->insertColumns(0, 1);
1006 Languages::const_iterator it = languages.begin();
1007 Languages::const_iterator end = languages.end();
1008 for (; it != end; ++it) {
1009 current_row = lang_model->rowCount();
1010 lang_model->insertRows(current_row, 1);
1011 QModelIndex item = lang_model->index(current_row, 0);
1012 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1013 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1015 d->language_model_ = new QSortFilterProxyModel(this);
1016 d->language_model_->setSourceModel(lang_model);
1017 #if QT_VERSION >= 0x040300
1018 d->language_model_->setSortLocaleAware(true);
1020 return d->language_model_;
1024 void GuiApplication::restoreGuiSession()
1026 if (!lyxrc.load_session)
1029 Session & session = LyX::ref().session();
1030 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1031 // do not add to the lastfile list since these files are restored from
1032 // last session, and should be already there (regular files), or should
1033 // not be added at all (help files).
1034 for_each(lastopened.begin(), lastopened.end(),
1035 bind(&GuiView::loadDocument, current_view_, _1, false));
1037 // clear this list to save a few bytes of RAM
1038 session.lastOpened().clear();
1042 QString const GuiApplication::romanFontName()
1045 font.setKerning(false);
1046 font.setStyleHint(QFont::Serif);
1047 font.setFamily("serif");
1049 return QFontInfo(font).family();
1053 QString const GuiApplication::sansFontName()
1056 font.setKerning(false);
1057 font.setStyleHint(QFont::SansSerif);
1058 font.setFamily("sans");
1060 return QFontInfo(font).family();
1064 QString const GuiApplication::typewriterFontName()
1067 font.setKerning(false);
1068 font.setStyleHint(QFont::TypeWriter);
1069 font.setFamily("monospace");
1071 return QFontInfo(font).family();
1075 void GuiApplication::handleRegularEvents()
1077 ForkedCallsController::handleCompletedProcesses();
1081 bool GuiApplication::event(QEvent * e)
1084 case QEvent::FileOpen: {
1085 // Open a file; this happens only on Mac OS X for now
1086 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1087 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1088 qstring_to_ucs4(foe->file())));
1093 return QApplication::event(e);
1098 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1101 return QApplication::notify(receiver, event);
1103 catch (ExceptionMessage const & e) {
1105 case ErrorException:
1106 LyX::cref().emergencyCleanup();
1107 setQuitOnLastWindowClosed(false);
1109 Alert::error(e.title_, e.details_);
1111 // Properly crash in debug mode in order to get a useful backtrace.
1114 // In release mode, try to exit gracefully.
1117 case BufferException: {
1118 Buffer * buf = current_view_->buffer();
1119 docstring details = e.details_ + '\n';
1120 details += theBufferList().emergencyWrite(buf);
1121 theBufferList().release(buf);
1122 details += "\n" + _("The current document was closed.");
1123 Alert::error(e.title_, details);
1126 case WarningException:
1127 Alert::warning(e.title_, e.details_);
1131 catch (exception const & e) {
1132 docstring s = _("LyX has caught an exception, it will now "
1133 "attempt to save all unsaved documents and exit."
1135 s += from_ascii(e.what());
1136 Alert::error(_("Software exception Detected"), s);
1137 LyX::cref().exit(1);
1140 docstring s = _("LyX has caught some really weird exception, it will "
1141 "now attempt to save all unsaved documents and exit.");
1142 Alert::error(_("Software exception Detected"), s);
1143 LyX::cref().exit(1);
1150 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1152 QColor const & qcol = d->color_cache_.get(col);
1153 if (!qcol.isValid()) {
1159 rgbcol.r = qcol.red();
1160 rgbcol.g = qcol.green();
1161 rgbcol.b = qcol.blue();
1166 string const GuiApplication::hexName(ColorCode col)
1168 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1172 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1174 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1175 d->socket_notifiers_[fd] = sn;
1176 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1180 void GuiApplication::socketDataReceived(int fd)
1182 d->socket_notifiers_[fd]->func_();
1186 void GuiApplication::unregisterSocketCallback(int fd)
1188 d->socket_notifiers_.take(fd)->setEnabled(false);
1192 void GuiApplication::commitData(QSessionManager & sm)
1194 /// The implementation is required to avoid an application exit
1195 /// when session state save is triggered by session manager.
1196 /// The default implementation sends a close event to all
1197 /// visible top level widgets when session managment allows
1199 /// We are changing that to close all wiew one by one.
1200 /// FIXME: verify if the default implementation is enough now.
1201 if (sm.allowsInteraction() && !closeAllViews())
1206 void GuiApplication::unregisterView(GuiView * gv)
1208 LASSERT(d->views_[gv->id()] == gv, /**/);
1209 d->views_.remove(gv->id());
1210 if (current_view_ == gv) {
1212 theLyXFunc().setLyXView(0);
1217 bool GuiApplication::closeAllViews()
1219 if (d->views_.empty())
1222 QList<GuiView *> views = d->views_.values();
1223 foreach (GuiView * view, views) {
1233 GuiView & GuiApplication::view(int id) const
1235 LASSERT(d->views_.contains(id), /**/);
1236 return *d->views_.value(id);
1240 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1242 QList<GuiView *> views = d->views_.values();
1243 foreach (GuiView * view, views)
1244 view->hideDialog(name, inset);
1248 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1250 Buffer const * buffer_ = 0;
1251 QHash<int, GuiView *>::iterator end = d->views_.end();
1252 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1253 if (Buffer const * ptr = (*it)->updateInset(inset))
1260 bool GuiApplication::searchMenu(FuncRequest const & func,
1261 docstring_list & names) const
1263 return d->menus_.searchMenu(func, names);
1267 bool GuiApplication::readUIFile(QString const & name, bool include)
1277 LexerKeyword uitags[] = {
1278 { "include", ui_include },
1279 { "menuset", ui_menuset },
1280 { "toolbars", ui_toolbars },
1281 { "toolbarset", ui_toolbarset }
1284 // Ensure that a file is read only once (prevents include loops)
1285 static QStringList uifiles;
1286 if (uifiles.contains(name)) {
1287 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1288 << "Is this an include loop?");
1292 LYXERR(Debug::INIT, "About to read " << name << "...");
1296 ui_path = libFileSearch("ui", name, "inc");
1297 if (ui_path.empty())
1298 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1300 ui_path = libFileSearch("ui", name, "ui");
1303 if (ui_path.empty()) {
1304 LYXERR(Debug::INIT, "Could not find " << name);
1305 Alert::warning(_("Could not find UI defintion file"),
1306 bformat(_("Error while reading the configuration file\n%1$s.\n"
1307 "Please check your installation."), qstring_to_ucs4(name)));
1311 uifiles.push_back(name);
1313 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1315 lex.setFile(ui_path);
1317 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1321 if (lyxerr.debugging(Debug::PARSER))
1322 lex.printTable(lyxerr);
1324 while (lex.isOK()) {
1325 switch (lex.lex()) {
1328 QString const file = toqstr(lex.getString());
1329 if (!readUIFile(file, true))
1334 d->menus_.read(lex);
1338 d->toolbars_.readToolbars(lex);
1342 d->toolbars_.readToolbarSettings(lex);
1346 if (!rtrim(lex.getString()).empty())
1347 lex.printError("LyX::ReadUIFile: "
1348 "Unknown menu tag: `$$Token'");
1356 void GuiApplication::onLastWindowClosed()
1358 if (d->global_menubar_)
1359 d->global_menubar_->grabKeyboard();
1363 ////////////////////////////////////////////////////////////////////////
1365 // X11 specific stuff goes here...
1368 bool GuiApplication::x11EventFilter(XEvent * xev)
1373 switch (xev->type) {
1374 case SelectionRequest: {
1375 if (xev->xselectionrequest.selection != XA_PRIMARY)
1377 LYXERR(Debug::GUI, "X requested selection.");
1378 BufferView * bv = current_view_->view();
1380 docstring const sel = bv->requestSelection();
1382 d->selection_.put(sel);
1386 case SelectionClear: {
1387 if (xev->xselectionclear.selection != XA_PRIMARY)
1389 LYXERR(Debug::GUI, "Lost selection.");
1390 BufferView * bv = current_view_->view();
1392 bv->clearSelection();
1400 } // namespace frontend
1403 void hideDialogs(std::string const & name, Inset * inset)
1406 theApp()->hideDialogs(name, inset);
1410 ////////////////////////////////////////////////////////////////////
1414 ////////////////////////////////////////////////////////////////////
1416 frontend::FontLoader & theFontLoader()
1418 LASSERT(frontend::guiApp, /**/);
1419 return frontend::guiApp->fontLoader();
1423 frontend::FontMetrics const & theFontMetrics(Font const & f)
1425 return theFontMetrics(f.fontInfo());
1429 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1431 LASSERT(frontend::guiApp, /**/);
1432 return frontend::guiApp->fontLoader().metrics(f);
1436 ////////////////////////////////////////////////////////////////////
1440 ////////////////////////////////////////////////////////////////////
1442 frontend::Clipboard & theClipboard()
1444 LASSERT(frontend::guiApp, /**/);
1445 return frontend::guiApp->clipboard();
1449 frontend::Selection & theSelection()
1451 LASSERT(frontend::guiApp, /**/);
1452 return frontend::guiApp->selection();
1457 #include "GuiApplication_moc.cpp"