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"
66 #include <QFileOpenEvent>
70 #include <QLibraryInfo>
72 #include <QMacPasteboardMime>
77 #include <QPixmapCache>
79 #include <QSessionManager>
80 #include <QSocketNotifier>
81 #include <QSortFilterProxyModel>
82 #include <QStandardItemModel>
85 #include <QTranslator>
89 #include <X11/Xatom.h>
96 #include <QWindowsMime>
97 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
103 #include <boost/bind.hpp>
109 using namespace lyx::support;
112 static void initializeResources()
114 static bool initialized = false;
116 Q_INIT_RESOURCE(Resources);
124 frontend::Application * createApplication(int & argc, char * argv[])
126 return new frontend::GuiApplication(argc, argv);
131 ////////////////////////////////////////////////////////////////////////
132 // Icon loading support code.
133 ////////////////////////////////////////////////////////////////////////
143 bool operator<(PngMap const & lhs, PngMap const & rhs)
145 return lhs.key < rhs.key;
151 CompareKey(QString const & name) : name_(name) {}
152 bool operator()(PngMap const & other) const { return other.key == name_; }
158 // this must be sorted alphabetically
159 // Upper case comes before lower case
160 PngMap sorted_png_map[] = {
161 { "Bumpeq", "bumpeq2" },
164 { "Delta", "delta2" },
165 { "Downarrow", "downarrow2" },
166 { "Gamma", "gamma2" },
167 { "Lambda", "lambda2" },
168 { "Leftarrow", "leftarrow2" },
169 { "Leftrightarrow", "leftrightarrow2" },
170 { "Longleftarrow", "longleftarrow2" },
171 { "Longleftrightarrow", "longleftrightarrow2" },
172 { "Longrightarrow", "longrightarrow2" },
173 { "Omega", "omega2" },
177 { "Rightarrow", "rightarrow2" },
178 { "Sigma", "sigma2" },
179 { "Subset", "subset2" },
180 { "Supset", "supset2" },
181 { "Theta", "theta2" },
182 { "Uparrow", "uparrow2" },
183 { "Updownarrow", "updownarrow2" },
184 { "Upsilon", "upsilon2" },
185 { "Vdash", "vdash3" },
188 { "nLeftarrow", "nleftarrow2" },
189 { "nLeftrightarrow", "nleftrightarrow2" },
190 { "nRightarrow", "nrightarrow2" },
191 { "nVDash", "nvdash3" },
192 { "nvDash", "nvdash2" },
193 { "textrm \\AA", "textrm_AA"},
194 { "textrm \\O", "textrm_O"},
195 { "vDash", "vdash2" }
198 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
201 QString findPng(QString const & name)
203 PngMap const * const begin = sorted_png_map;
204 PngMap const * const end = begin + nr_sorted_png_map;
205 LASSERT(sorted(begin, end), /**/);
207 PngMap const * const it = find_if(begin, end, CompareKey(name));
211 png_name = it->value;
214 png_name.replace('_', "underscore");
215 png_name.replace(' ', '_');
217 // This way we can have "math-delim { }" on the toolbar.
218 png_name.replace('(', "lparen");
219 png_name.replace(')', "rparen");
220 png_name.replace('[', "lbracket");
221 png_name.replace(']', "rbracket");
222 png_name.replace('{', "lbrace");
223 png_name.replace('}', "rbrace");
224 png_name.replace('|', "bars");
225 png_name.replace(',', "thinspace");
226 png_name.replace(':', "mediumspace");
227 png_name.replace(';', "thickspace");
228 png_name.replace('!', "negthinspace");
231 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
232 << "Looking for math PNG called \"" << png_name << '"');
239 QString iconName(FuncRequest const & f, bool unknown)
241 initializeResources();
246 case LFUN_MATH_INSERT:
247 if (!f.argument().empty()) {
249 name1 = findPng(toqstr(f.argument()).mid(1));
252 case LFUN_MATH_DELIM:
253 case LFUN_MATH_BIGDELIM:
255 name1 = findPng(toqstr(f.argument()));
259 name1 = toqstr(f.argument());
262 name2 = toqstr(lyxaction.getActionName(f.action));
265 if (!f.argument().empty()) {
266 name1 = name2 + ' ' + toqstr(f.argument());
267 name1.replace(' ', '_');
271 FileName fname = libFileSearch("images/" + path, name1, "png");
273 return toqstr(fname.absFilename());
275 fname = libFileSearch("images/" + path, name2, "png");
277 return toqstr(fname.absFilename());
279 path = ":/images/" + path;
282 LYXERR0("Directory " << path << " not found in resource!");
286 if (res.exists(name1))
290 if (res.exists(name2))
293 LYXERR(Debug::GUI, "Cannot find icon for command \""
294 << lyxaction.getActionName(f.action)
295 << '(' << to_utf8(f.argument()) << ")\"");
298 return QString(":/images/unknown.png");
304 QIcon getIcon(FuncRequest const & f, bool unknown)
306 QString icon = iconName(f, unknown);
310 LYXERR(Debug::GUI, "Found icon: " << icon);
312 if (!pm.load(icon)) {
313 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
321 ////////////////////////////////////////////////////////////////////////
322 // LyX server support code.
323 ////////////////////////////////////////////////////////////////////////
324 class SocketNotifier : public QSocketNotifier
327 /// connect a connection notification from the LyXServerSocket
328 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
329 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
333 /// The callback function
334 Application::SocketCallback func_;
338 ////////////////////////////////////////////////////////////////////////
339 // Mac specific stuff goes here...
340 ////////////////////////////////////////////////////////////////////////
342 class MenuTranslator : public QTranslator
345 MenuTranslator(QObject * parent)
346 : QTranslator(parent)
349 QString translate(const char * /*context*/,
350 const char * sourceText,
351 const char * /*comment*/ = 0)
353 string const s = sourceText;
354 if (s == N_("About %1") || s == N_("Preferences")
355 || s == N_("Reconfigure") || s == N_("Quit %1"))
362 class GlobalMenuBar : public QMenuBar
366 GlobalMenuBar() : QMenuBar(0) {}
369 bool event(QEvent * e)
371 if (e->type() == QEvent::ShortcutOverride) {
372 // && activeWindow() == 0) {
373 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
375 setKeySymbol(&sym, ke);
376 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
385 // QMacPasteboardMimeGraphics can only be compiled on Mac.
387 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
390 QMacPasteboardMimeGraphics()
391 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
394 QString convertorName() { return "Graphics"; }
396 QString flavorFor(QString const & mime)
398 LYXERR(Debug::ACTION, "flavorFor " << mime);
399 if (mime == pdfMimeType())
400 return QLatin1String("com.adobe.pdf");
404 QString mimeFor(QString flav)
406 LYXERR(Debug::ACTION, "mimeFor " << flav);
407 if (flav == QLatin1String("com.adobe.pdf"))
408 return pdfMimeType();
412 bool canConvert(QString const & mime, QString flav)
414 return mimeFor(flav) == mime;
417 QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav)
420 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
424 QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav)
426 QList<QByteArray> ret;
427 ret.append(data.toByteArray());
433 ///////////////////////////////////////////////////////////////
434 // You can find more platform specific stuff
435 // at the end of this file...
436 ///////////////////////////////////////////////////////////////
438 ////////////////////////////////////////////////////////////////////////
439 // Windows specific stuff goes here...
442 // QWindowsMimeMetafile can only be compiled on Windows.
444 static FORMATETC cfFromMime(QString const & mimetype)
447 if (mimetype == emfMimeType()) {
448 formatetc.cfFormat = CF_ENHMETAFILE;
449 formatetc.tymed = TYMED_ENHMF;
450 } else if (mimetype == wmfMimeType()) {
451 formatetc.cfFormat = CF_METAFILEPICT;
452 formatetc.tymed = TYMED_MFPICT;
455 formatetc.dwAspect = DVASPECT_CONTENT;
456 formatetc.lindex = -1;
461 class QWindowsMimeMetafile : public QWindowsMime {
463 QWindowsMimeMetafile() {}
465 bool canConvertFromMime(FORMATETC const & formatetc,
466 QMimeData const * mimedata) const
471 bool canConvertToMime(QString const & mimetype,
472 IDataObject * pDataObj) const
474 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
476 FORMATETC formatetc = cfFromMime(mimetype);
477 return pDataObj->QueryGetData(&formatetc) == S_OK;
480 bool convertFromMime(FORMATETC const & formatetc,
481 const QMimeData * mimedata, STGMEDIUM * pmedium) const
486 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
487 QVariant::Type preferredType) const
490 if (!canConvertToMime(mimetype, pDataObj))
493 FORMATETC formatetc = cfFromMime(mimetype);
495 if (pDataObj->GetData(&formatetc, &s) != S_OK)
499 if (s.tymed == TYMED_ENHMF) {
500 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
501 data.resize(dataSize);
502 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
503 (LPBYTE)data.data());
504 } else if (s.tymed == TYMED_MFPICT) {
505 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
506 data.resize(dataSize);
507 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
508 (LPBYTE)data.data());
511 ReleaseStgMedium(&s);
517 QVector<FORMATETC> formatsForMime(QString const & mimeType,
518 QMimeData const * mimeData) const
520 QVector<FORMATETC> formats;
521 formats += cfFromMime(mimeType);
525 QString mimeForFormat(FORMATETC const & formatetc) const
527 switch (formatetc.cfFormat) {
529 return emfMimeType();
530 case CF_METAFILEPICT:
531 return wmfMimeType();
539 ////////////////////////////////////////////////////////////////////////
540 // GuiApplication::Private definition and implementation.
541 ////////////////////////////////////////////////////////////////////////
543 struct GuiApplication::Private
546 : language_model_(0), global_menubar_(0)
549 // Create the global default menubar which is shown for the dialogs
550 // and if no GuiView is visible.
551 global_menubar_ = new GlobalMenuBar();
556 QSortFilterProxyModel * language_model_;
558 GuiClipboard clipboard_;
560 GuiSelection selection_;
562 FontLoader font_loader_;
564 ColorCache color_cache_;
566 QTranslator qt_trans_;
568 QHash<int, SocketNotifier *> socket_notifiers_;
572 /// The global instance
575 /// this timer is used for any regular events one wants to
576 /// perform. at present it is used to check if forked processes
578 QTimer general_timer_;
580 /// Multiple views container.
582 * Warning: This must not be a smart pointer as the destruction of the
583 * object is handled by Qt when the view is closed
584 * \sa Qt::WA_DeleteOnClose attribute.
586 QHash<int, GuiView *> views_;
588 /// Only used on mac.
589 GlobalMenuBar * global_menubar_;
592 /// Linkback mime handler for MacOSX.
593 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
597 /// WMF Mime handler for Windows clipboard.
598 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
599 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
600 // is something in the clipboard.
601 QWindowsMimeMetafile wmf_mime_;
606 GuiApplication * guiApp;
608 GuiApplication::~GuiApplication()
611 closeAllLinkBackLinks();
617 GuiApplication::GuiApplication(int & argc, char ** argv)
618 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
620 QString app_name = "LyX";
621 QCoreApplication::setOrganizationName(app_name);
622 QCoreApplication::setOrganizationDomain("lyx.org");
623 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
625 // FIXME: quitOnLastWindowClosed is true by default. We should have a
626 // lyxrc setting for this in order to let the application stay resident.
627 // But then we need some kind of dock icon, at least on Windows.
629 if (lyxrc.quit_on_last_window_closed)
630 setQuitOnLastWindowClosed(false);
633 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
634 // seems to be the default case for applications like LyX.
635 setQuitOnLastWindowClosed(false);
639 // doubleClickInterval() is 400 ms on X11 which is just too long.
640 // On Windows and Mac OS X, the operating system's value is used.
641 // On Microsoft Windows, calling this function sets the double
642 // click interval for all applications. So we don't!
643 QApplication::setDoubleClickInterval(300);
646 // install translation file for Qt built-in dialogs
647 QString language_name = QString("qt_") + QLocale::system().name();
649 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
650 // Short-named translator can be loaded from a long name, but not the
651 // opposite. Therefore, long name should be used without truncation.
652 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
653 if (d->qt_trans_.load(language_name,
654 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
656 installTranslator(&d->qt_trans_);
657 // even if the language calls for RtL, don't do that
658 setLayoutDirection(Qt::LeftToRight);
659 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
662 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
666 // This allows to translate the strings that appear in the LyX menu.
667 /// A translator suitable for the entries in the LyX menu.
668 /// Only needed with Qt/Mac.
669 installTranslator(new MenuTranslator(this));
671 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
673 using namespace lyx::graphics;
675 Image::newImage = boost::bind(&GuiImage::newImage);
676 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
678 // needs to be done before reading lyxrc
680 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
684 // Set the cache to 5120 kilobytes which corresponds to screen size of
685 // 1280 by 1024 pixels with a color depth of 32 bits.
686 QPixmapCache::setCacheLimit(5120);
688 // Initialize RC Fonts
689 if (lyxrc.roman_font_name.empty())
690 lyxrc.roman_font_name = fromqstr(romanFontName());
692 if (lyxrc.sans_font_name.empty())
693 lyxrc.sans_font_name = fromqstr(sansFontName());
695 if (lyxrc.typewriter_font_name.empty())
696 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
698 d->general_timer_.setInterval(500);
699 connect(&d->general_timer_, SIGNAL(timeout()),
700 this, SLOT(handleRegularEvents()));
701 d->general_timer_.start();
705 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
707 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
712 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
718 case LFUN_WINDOW_CLOSE:
719 enable = d->views_.size() > 0;
722 case LFUN_BUFFER_NEW:
723 case LFUN_BUFFER_NEW_TEMPLATE:
725 case LFUN_SCREEN_FONT_UPDATE:
727 case LFUN_WINDOW_NEW:
737 flag.setEnabled(false);
743 bool GuiApplication::dispatch(FuncRequest const & cmd)
745 switch (cmd.action) {
747 case LFUN_WINDOW_NEW:
748 createView(toqstr(cmd.argument()));
751 case LFUN_WINDOW_CLOSE:
752 // update bookmark pit of the current buffer before window close
753 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
754 theLyXFunc().gotoBookmark(i+1, false, false);
755 current_view_->close();
759 // quitting is triggered by the gui code
760 // (leaving the event loop).
762 current_view_->message(from_utf8(N_("Exiting.")));
767 case LFUN_SCREEN_FONT_UPDATE: {
768 // handle the screen font changes.
769 d->font_loader_.update();
770 // Backup current_view_
771 GuiView * view = current_view_;
772 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
773 // to skip the refresh.
775 BufferList::iterator it = theBufferList().begin();
776 BufferList::iterator const end = theBufferList().end();
777 for (; it != end; ++it)
779 // Restore current_view_
780 current_view_ = view;
784 case LFUN_BUFFER_NEW:
785 if (d->views_.empty()
786 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
787 createView(QString(), false); // keep hidden
788 current_view_->newDocument(to_utf8(cmd.argument()), false);
789 current_view_->show();
790 setActiveWindow(current_view_);
792 current_view_->newDocument(to_utf8(cmd.argument()), false);
796 case LFUN_BUFFER_NEW_TEMPLATE:
797 if (d->views_.empty()
798 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
800 current_view_->newDocument(to_utf8(cmd.argument()), true);
801 if (!current_view_->buffer())
802 current_view_->close();
804 current_view_->newDocument(to_utf8(cmd.argument()), true);
809 if (d->views_.empty()
810 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
812 current_view_->openDocument(to_utf8(cmd.argument()));
813 if (!current_view_->buffer())
814 current_view_->close();
816 current_view_->openDocument(to_utf8(cmd.argument()));
819 case LFUN_SET_COLOR: {
821 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
822 if (lyx_name.empty() || x11_name.empty()) {
823 current_view_->message(
824 _("Syntax: set-color <lyx_name> <x11_name>"));
828 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
829 bool const graphicsbg_changed = lyx_name == graphicsbg
830 && x11_name != graphicsbg;
831 if (graphicsbg_changed) {
832 // FIXME: The graphics cache no longer has a changeDisplay method.
834 graphics::GCache::get().changeDisplay(true);
838 if (!lcolor.setColor(lyx_name, x11_name)) {
839 current_view_->message(
840 bformat(_("Set-color \"%1$s\" failed "
841 "- color is undefined or "
842 "may not be redefined"),
843 from_utf8(lyx_name)));
846 // Make sure we don't keep old colors in cache.
847 d->color_cache_.clear();
852 // Notify the caller that the action has not been dispatched.
856 // The action has been dispatched.
861 void GuiApplication::resetGui()
863 QHash<int, GuiView *>::iterator it;
864 for (it = d->views_.begin(); it != d->views_.end(); ++it)
865 (*it)->resetDialogs();
867 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
871 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
873 // release the keyboard which might have been grabed by the global
874 // menubar on Mac to catch shortcuts even without any GuiView.
875 if (d->global_menubar_)
876 d->global_menubar_->releaseKeyboard();
880 while (d->views_.find(id) != d->views_.end())
882 GuiView * view = new GuiView(id);
884 // copy the icon size from old view
886 view->setIconSize(current_view_->iconSize());
889 d->views_[id] = view;
893 setActiveWindow(view);
896 if (!geometry_arg.isEmpty()) {
900 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
901 re.indexIn(geometry_arg);
902 w = re.cap(1).toInt();
903 h = re.cap(2).toInt();
904 x = re.cap(3).toInt();
905 y = re.cap(4).toInt();
906 view->setGeometry(x, y, w, h);
910 setCurrentView(view);
914 Clipboard & GuiApplication::clipboard()
916 return d->clipboard_;
920 Selection & GuiApplication::selection()
922 return d->selection_;
926 FontLoader & GuiApplication::fontLoader()
928 return d->font_loader_;
932 Toolbars const & GuiApplication::toolbars() const
938 Toolbars & GuiApplication::toolbars()
944 Menus const & GuiApplication::menus() const
950 Menus & GuiApplication::menus()
956 QList<int> GuiApplication::viewIds() const
958 return d->views_.keys();
962 ColorCache & GuiApplication::colorCache()
964 return d->color_cache_;
968 int GuiApplication::exec()
970 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
971 return QApplication::exec();
975 void GuiApplication::exit(int status)
977 QApplication::exit(status);
981 void GuiApplication::execBatchCommands()
984 if (!readUIFile(toqstr(lyxrc.ui_file)))
985 // Gives some error box here.
988 // init the global menubar on Mac. This must be done after the session
989 // was recovered to know the "last files".
990 if (d->global_menubar_)
991 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
993 LyX::ref().execBatchCommands();
996 QAbstractItemModel * GuiApplication::languageModel()
998 if (d->language_model_)
999 return d->language_model_;
1001 QStandardItemModel * lang_model = new QStandardItemModel(this);
1002 lang_model->insertColumns(0, 1);
1004 Languages::const_iterator it = languages.begin();
1005 Languages::const_iterator end = languages.end();
1006 for (; it != end; ++it) {
1007 current_row = lang_model->rowCount();
1008 lang_model->insertRows(current_row, 1);
1009 QModelIndex item = lang_model->index(current_row, 0);
1010 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1011 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1013 d->language_model_ = new QSortFilterProxyModel(this);
1014 d->language_model_->setSourceModel(lang_model);
1015 #if QT_VERSION >= 0x040300
1016 d->language_model_->setSortLocaleAware(true);
1018 return d->language_model_;
1022 void GuiApplication::restoreGuiSession()
1024 if (!lyxrc.load_session)
1027 Session & session = LyX::ref().session();
1028 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1029 // do not add to the lastfile list since these files are restored from
1030 // last session, and should be already there (regular files), or should
1031 // not be added at all (help files).
1032 for_each(lastopened.begin(), lastopened.end(),
1033 bind(&GuiView::loadDocument, current_view_, _1, false));
1035 // clear this list to save a few bytes of RAM
1036 session.lastOpened().clear();
1040 QString const GuiApplication::romanFontName()
1043 font.setKerning(false);
1044 font.setStyleHint(QFont::Serif);
1045 font.setFamily("serif");
1047 return QFontInfo(font).family();
1051 QString const GuiApplication::sansFontName()
1054 font.setKerning(false);
1055 font.setStyleHint(QFont::SansSerif);
1056 font.setFamily("sans");
1058 return QFontInfo(font).family();
1062 QString const GuiApplication::typewriterFontName()
1065 font.setKerning(false);
1066 font.setStyleHint(QFont::TypeWriter);
1067 font.setFamily("monospace");
1069 return QFontInfo(font).family();
1073 void GuiApplication::handleRegularEvents()
1075 ForkedCallsController::handleCompletedProcesses();
1079 bool GuiApplication::event(QEvent * e)
1082 case QEvent::FileOpen: {
1083 // Open a file; this happens only on Mac OS X for now
1084 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1085 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1086 qstring_to_ucs4(foe->file())));
1091 return QApplication::event(e);
1096 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1099 return QApplication::notify(receiver, event);
1101 catch (ExceptionMessage const & e) {
1103 case ErrorException:
1104 LyX::cref().emergencyCleanup();
1105 setQuitOnLastWindowClosed(false);
1107 Alert::error(e.title_, e.details_);
1109 // Properly crash in debug mode in order to get a useful backtrace.
1112 // In release mode, try to exit gracefully.
1115 case BufferException: {
1116 Buffer * buf = current_view_->buffer();
1117 docstring details = e.details_ + '\n';
1118 details += theBufferList().emergencyWrite(buf);
1119 theBufferList().release(buf);
1120 details += "\n" + _("The current document was closed.");
1121 Alert::error(e.title_, details);
1124 case WarningException:
1125 Alert::warning(e.title_, e.details_);
1129 catch (exception const & e) {
1130 docstring s = _("LyX has caught an exception, it will now "
1131 "attempt to save all unsaved documents and exit."
1133 s += from_ascii(e.what());
1134 Alert::error(_("Software exception Detected"), s);
1135 LyX::cref().exit(1);
1138 docstring s = _("LyX has caught some really weird exception, it will "
1139 "now attempt to save all unsaved documents and exit.");
1140 Alert::error(_("Software exception Detected"), s);
1141 LyX::cref().exit(1);
1148 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1150 QColor const & qcol = d->color_cache_.get(col);
1151 if (!qcol.isValid()) {
1157 rgbcol.r = qcol.red();
1158 rgbcol.g = qcol.green();
1159 rgbcol.b = qcol.blue();
1164 string const GuiApplication::hexName(ColorCode col)
1166 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1170 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1172 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1173 d->socket_notifiers_[fd] = sn;
1174 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1178 void GuiApplication::socketDataReceived(int fd)
1180 d->socket_notifiers_[fd]->func_();
1184 void GuiApplication::unregisterSocketCallback(int fd)
1186 d->socket_notifiers_.take(fd)->setEnabled(false);
1190 void GuiApplication::commitData(QSessionManager & sm)
1192 /// The implementation is required to avoid an application exit
1193 /// when session state save is triggered by session manager.
1194 /// The default implementation sends a close event to all
1195 /// visible top level widgets when session managment allows
1197 /// We are changing that to close all wiew one by one.
1198 /// FIXME: verify if the default implementation is enough now.
1199 if (sm.allowsInteraction() && !closeAllViews())
1204 void GuiApplication::unregisterView(GuiView * gv)
1206 LASSERT(d->views_[gv->id()] == gv, /**/);
1207 d->views_.remove(gv->id());
1208 if (current_view_ == gv) {
1210 theLyXFunc().setLyXView(0);
1215 bool GuiApplication::closeAllViews()
1217 if (d->views_.empty())
1220 QList<GuiView *> views = d->views_.values();
1221 foreach (GuiView * view, views) {
1231 GuiView & GuiApplication::view(int id) const
1233 LASSERT(d->views_.contains(id), /**/);
1234 return *d->views_.value(id);
1238 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1240 QList<GuiView *> views = d->views_.values();
1241 foreach (GuiView * view, views)
1242 view->hideDialog(name, inset);
1246 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1248 Buffer const * buffer_ = 0;
1249 QHash<int, GuiView *>::iterator end = d->views_.end();
1250 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1251 if (Buffer const * ptr = (*it)->updateInset(inset))
1258 bool GuiApplication::searchMenu(FuncRequest const & func,
1259 docstring_list & names) const
1261 return d->menus_.searchMenu(func, names);
1265 bool GuiApplication::readUIFile(QString const & name, bool include)
1275 LexerKeyword uitags[] = {
1276 { "include", ui_include },
1277 { "menuset", ui_menuset },
1278 { "toolbars", ui_toolbars },
1279 { "toolbarset", ui_toolbarset }
1282 // Ensure that a file is read only once (prevents include loops)
1283 static QStringList uifiles;
1284 if (uifiles.contains(name)) {
1285 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1286 << "Is this an include loop?");
1290 LYXERR(Debug::INIT, "About to read " << name << "...");
1294 ui_path = libFileSearch("ui", name, "inc");
1295 if (ui_path.empty())
1296 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1298 ui_path = libFileSearch("ui", name, "ui");
1301 if (ui_path.empty()) {
1302 LYXERR(Debug::INIT, "Could not find " << name);
1303 Alert::warning(_("Could not find UI defintion file"),
1304 bformat(_("Error while reading the configuration file\n%1$s.\n"
1305 "Please check your installation."), qstring_to_ucs4(name)));
1309 uifiles.push_back(name);
1311 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1313 lex.setFile(ui_path);
1315 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1319 if (lyxerr.debugging(Debug::PARSER))
1320 lex.printTable(lyxerr);
1322 while (lex.isOK()) {
1323 switch (lex.lex()) {
1326 QString const file = toqstr(lex.getString());
1327 if (!readUIFile(file, true))
1332 d->menus_.read(lex);
1336 d->toolbars_.readToolbars(lex);
1340 d->toolbars_.readToolbarSettings(lex);
1344 if (!rtrim(lex.getString()).empty())
1345 lex.printError("LyX::ReadUIFile: "
1346 "Unknown menu tag: `$$Token'");
1354 void GuiApplication::onLastWindowClosed()
1356 if (d->global_menubar_)
1357 d->global_menubar_->grabKeyboard();
1361 ////////////////////////////////////////////////////////////////////////
1363 // X11 specific stuff goes here...
1366 bool GuiApplication::x11EventFilter(XEvent * xev)
1371 switch (xev->type) {
1372 case SelectionRequest: {
1373 if (xev->xselectionrequest.selection != XA_PRIMARY)
1375 LYXERR(Debug::GUI, "X requested selection.");
1376 BufferView * bv = current_view_->view();
1378 docstring const sel = bv->requestSelection();
1380 d->selection_.put(sel);
1384 case SelectionClear: {
1385 if (xev->xselectionclear.selection != XA_PRIMARY)
1387 LYXERR(Debug::GUI, "Lost selection.");
1388 BufferView * bv = current_view_->view();
1390 bv->clearSelection();
1398 } // namespace frontend
1401 void hideDialogs(std::string const & name, Inset * inset)
1404 theApp()->hideDialogs(name, inset);
1408 ////////////////////////////////////////////////////////////////////
1412 ////////////////////////////////////////////////////////////////////
1414 frontend::FontLoader & theFontLoader()
1416 LASSERT(frontend::guiApp, /**/);
1417 return frontend::guiApp->fontLoader();
1421 frontend::FontMetrics const & theFontMetrics(Font const & f)
1423 return theFontMetrics(f.fontInfo());
1427 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1429 LASSERT(frontend::guiApp, /**/);
1430 return frontend::guiApp->fontLoader().metrics(f);
1434 ////////////////////////////////////////////////////////////////////
1438 ////////////////////////////////////////////////////////////////////
1440 frontend::Clipboard & theClipboard()
1442 LASSERT(frontend::guiApp, /**/);
1443 return frontend::guiApp->clipboard();
1447 frontend::Selection & theSelection()
1449 LASSERT(frontend::guiApp, /**/);
1450 return frontend::guiApp->selection();
1455 #include "GuiApplication_moc.cpp"