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"
25 #include "ToolbarBackend.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"
47 #include "support/lassert.h"
48 #include "support/debug.h"
49 #include "support/ExceptionMessage.h"
50 #include "support/FileName.h"
51 #include "support/foreach.h"
52 #include "support/ForkedCalls.h"
53 #include "support/gettext.h"
54 #include "support/lstrings.h"
55 #include "support/os.h"
56 #include "support/Package.h"
59 #include "support/linkback/LinkBackProxy.h"
64 #include <QFileOpenEvent>
67 #include <QLibraryInfo>
68 #include <QMacPasteboardMime>
71 #include <QPixmapCache>
73 #include <QSessionManager>
74 #include <QSocketNotifier>
75 #include <QSortFilterProxyModel>
76 #include <QStandardItemModel>
79 #include <QTranslator>
83 #include <X11/Xatom.h>
91 #include <QWindowsMime>
92 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
98 #include <boost/bind.hpp>
103 using namespace lyx::support;
108 // defined in GuiClipboard.cpp.
109 extern char const * const lyx_mime_type;
110 extern char const * const pdf_mime_type;
111 extern char const * const emf_mime_type;
112 extern char const * const wmf_mime_type;
114 frontend::Application * createApplication(int & argc, char * argv[])
116 return new frontend::GuiApplication(argc, argv);
122 class SocketNotifier : public QSocketNotifier
125 /// connect a connection notification from the LyXServerSocket
126 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
127 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
131 /// The callback function
132 Application::SocketCallback func_;
136 ////////////////////////////////////////////////////////////////////////
137 // Mac specific stuff goes here...
139 class MenuTranslator : public QTranslator
142 MenuTranslator(QObject * parent)
143 : QTranslator(parent)
146 QString translate(const char * /*context*/,
147 const char * sourceText,
148 const char * /*comment*/ = 0)
150 string const s = sourceText;
151 if (s == N_("About %1") || s == N_("Preferences")
152 || s == N_("Reconfigure") || s == N_("Quit %1"))
159 class GlobalMenuBar : public QMenuBar
163 GlobalMenuBar() : QMenuBar(0) {}
166 bool event(QEvent * e)
168 if (e->type() == QEvent::ShortcutOverride) {
169 // && activeWindow() == 0) {
170 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
172 setKeySymbol(&sym, ke);
173 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
182 // QMacPasteboardMimeGraphics can only be compiled on Mac.
184 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
187 QMacPasteboardMimeGraphics()
188 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
191 QString convertorName() { return "Graphics"; }
193 QString flavorFor(QString const & mime)
195 LYXERR(Debug::ACTION, "flavorFor " << mime);
196 if (mime == QLatin1String(pdf_mime_type))
197 return QLatin1String("com.adobe.pdf");
201 QString mimeFor(QString flav)
203 LYXERR(Debug::ACTION, "mimeFor " << flav);
204 if (flav == QLatin1String("com.adobe.pdf"))
205 return QLatin1String(pdf_mime_type);
209 bool canConvert(QString const & mime, QString flav)
210 { return mimeFor(flav) == mime; }
212 QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav)
215 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
219 QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav)
221 QList<QByteArray> ret;
222 ret.append(data.toByteArray());
228 ///////////////////////////////////////////////////////////////
229 // You can find more platform specific stuff
230 // at the end of this file...
231 ///////////////////////////////////////////////////////////////
233 ////////////////////////////////////////////////////////////////////////
234 // Windows specific stuff goes here...
237 // QWindowsMimeMetafile can only be compiled on Windows.
239 static FORMATETC cfFromMime(QString const & mimetype)
242 if (mimetype == emf_mime_type) {
243 formatetc.cfFormat = CF_ENHMETAFILE;
244 formatetc.tymed = TYMED_ENHMF;
245 } else if (mimetype == wmf_mime_type) {
246 formatetc.cfFormat = CF_METAFILEPICT;
247 formatetc.tymed = TYMED_MFPICT;
250 formatetc.dwAspect = DVASPECT_CONTENT;
251 formatetc.lindex = -1;
256 class QWindowsMimeMetafile : public QWindowsMime {
258 QWindowsMimeMetafile() {}
260 bool canConvertFromMime(FORMATETC const & formatetc,
261 QMimeData const * mimedata) const
266 bool canConvertToMime(QString const & mimetype,
267 IDataObject * pDataObj) const
269 if (mimetype != emf_mime_type && mimetype != wmf_mime_type)
271 FORMATETC formatetc = cfFromMime(mimetype);
272 return pDataObj->QueryGetData(&formatetc) == S_OK;
275 bool convertFromMime(FORMATETC const & formatetc,
276 const QMimeData * mimedata, STGMEDIUM * pmedium) const
281 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
282 QVariant::Type preferredType) const
285 if (!canConvertToMime(mimetype, pDataObj))
288 FORMATETC formatetc = cfFromMime(mimetype);
290 if (pDataObj->GetData(&formatetc, &s) != S_OK)
294 if (s.tymed == TYMED_ENHMF) {
295 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
296 data.resize(dataSize);
297 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
298 (LPBYTE)data.data());
299 } else if (s.tymed == TYMED_MFPICT) {
300 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
301 data.resize(dataSize);
302 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
303 (LPBYTE)data.data());
306 ReleaseStgMedium(&s);
312 QVector<FORMATETC> formatsForMime(QString const & mimeType,
313 QMimeData const * mimeData) const
315 QVector<FORMATETC> formats;
316 formats += cfFromMime(mimeType);
320 QString mimeForFormat(FORMATETC const & formatetc) const
322 switch (formatetc.cfFormat) {
324 return emf_mime_type;
325 case CF_METAFILEPICT:
326 return wmf_mime_type;
334 ////////////////////////////////////////////////////////////////////////
335 // GuiApplication::Private definition and implementation.
336 ////////////////////////////////////////////////////////////////////////
338 struct GuiApplication::Private
341 : language_model_(0), global_menubar_(0)
344 // Create the global default menubar which is shown for the dialogs
345 // and if no GuiView is visible.
346 global_menubar_ = new GlobalMenuBar();
351 QSortFilterProxyModel * language_model_;
353 GuiClipboard clipboard_;
355 GuiSelection selection_;
357 FontLoader font_loader_;
359 ColorCache color_cache_;
361 QTranslator qt_trans_;
363 QHash<int, SocketNotifier *> socket_notifiers_;
366 /// this timer is used for any regular events one wants to
367 /// perform. at present it is used to check if forked processes
369 QTimer general_timer_;
371 /// Multiple views container.
373 * Warning: This must not be a smart pointer as the destruction of the
374 * object is handled by Qt when the view is closed
375 * \sa Qt::WA_DeleteOnClose attribute.
377 QHash<int, GuiView *> views_;
379 /// Only used on mac.
380 GlobalMenuBar * global_menubar_;
383 /// Linkback mime handler for MacOSX.
384 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
388 /// WMF Mime handler for Windows clipboard.
389 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
390 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
391 // is something in the clipboard.
392 QWindowsMimeMetafile wmf_mime_;
397 GuiApplication * guiApp;
399 GuiApplication::~GuiApplication()
402 closeAllLinkBackLinks();
408 GuiApplication::GuiApplication(int & argc, char ** argv)
409 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
411 QString app_name = "LyX";
412 QCoreApplication::setOrganizationName(app_name);
413 QCoreApplication::setOrganizationDomain("lyx.org");
414 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
416 // FIXME: quitOnLastWindowClosed is true by default. We should have a
417 // lyxrc setting for this in order to let the application stay resident.
418 // But then we need some kind of dock icon, at least on Windows.
420 if (lyxrc.quit_on_last_window_closed)
421 setQuitOnLastWindowClosed(false);
424 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
425 // seems to be the default case for applications like LyX.
426 setQuitOnLastWindowClosed(false);
430 // doubleClickInterval() is 400 ms on X11 which is just too long.
431 // On Windows and Mac OS X, the operating system's value is used.
432 // On Microsoft Windows, calling this function sets the double
433 // click interval for all applications. So we don't!
434 QApplication::setDoubleClickInterval(300);
437 // install translation file for Qt built-in dialogs
438 QString language_name = QString("qt_") + QLocale::system().name();
440 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
441 // Short-named translator can be loaded from a long name, but not the
442 // opposite. Therefore, long name should be used without truncation.
443 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
444 if (d->qt_trans_.load(language_name,
445 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
447 installTranslator(&d->qt_trans_);
448 // even if the language calls for RtL, don't do that
449 setLayoutDirection(Qt::LeftToRight);
450 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
453 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
457 // This allows to translate the strings that appear in the LyX menu.
458 /// A translator suitable for the entries in the LyX menu.
459 /// Only needed with Qt/Mac.
460 installTranslator(new MenuTranslator(this));
462 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
464 using namespace lyx::graphics;
466 Image::newImage = boost::bind(&GuiImage::newImage);
467 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
469 // needs to be done before reading lyxrc
471 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
475 // Set the cache to 5120 kilobytes which corresponds to screen size of
476 // 1280 by 1024 pixels with a color depth of 32 bits.
477 QPixmapCache::setCacheLimit(5120);
479 // Initialize RC Fonts
480 if (lyxrc.roman_font_name.empty())
481 lyxrc.roman_font_name = fromqstr(romanFontName());
483 if (lyxrc.sans_font_name.empty())
484 lyxrc.sans_font_name = fromqstr(sansFontName());
486 if (lyxrc.typewriter_font_name.empty())
487 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
489 d->general_timer_.setInterval(500);
490 connect(&d->general_timer_, SIGNAL(timeout()),
491 this, SLOT(handleRegularEvents()));
492 d->general_timer_.start();
496 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
502 case LFUN_WINDOW_CLOSE:
503 enable = d->views_.size() > 0;
506 case LFUN_BUFFER_NEW:
507 case LFUN_BUFFER_NEW_TEMPLATE:
509 case LFUN_SCREEN_FONT_UPDATE:
511 case LFUN_WINDOW_NEW:
527 bool GuiApplication::dispatch(FuncRequest const & cmd)
529 switch (cmd.action) {
531 case LFUN_WINDOW_NEW:
532 createView(toqstr(cmd.argument()));
535 case LFUN_WINDOW_CLOSE:
536 // update bookmark pit of the current buffer before window close
537 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
538 theLyXFunc().gotoBookmark(i+1, false, false);
539 current_view_->close();
543 // quitting is triggered by the gui code
544 // (leaving the event loop).
546 current_view_->message(from_utf8(N_("Exiting.")));
551 case LFUN_SCREEN_FONT_UPDATE: {
552 // handle the screen font changes.
553 d->font_loader_.update();
554 // Backup current_view_
555 GuiView * view = current_view_;
556 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
557 // to skip the refresh.
559 BufferList::iterator it = theBufferList().begin();
560 BufferList::iterator const end = theBufferList().end();
561 for (; it != end; ++it)
563 // Restore current_view_
564 current_view_ = view;
568 case LFUN_BUFFER_NEW:
569 if (d->views_.empty()
570 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
571 createView(QString(), false); // keep hidden
572 current_view_->newDocument(to_utf8(cmd.argument()), false);
573 current_view_->show();
574 setActiveWindow(current_view_);
576 current_view_->newDocument(to_utf8(cmd.argument()), false);
580 case LFUN_BUFFER_NEW_TEMPLATE:
581 if (d->views_.empty()
582 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
584 current_view_->newDocument(to_utf8(cmd.argument()), true);
585 if (!current_view_->buffer())
586 current_view_->close();
588 current_view_->newDocument(to_utf8(cmd.argument()), true);
593 if (d->views_.empty()
594 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
596 current_view_->openDocument(to_utf8(cmd.argument()));
597 if (!current_view_->buffer())
598 current_view_->close();
600 current_view_->openDocument(to_utf8(cmd.argument()));
603 case LFUN_SET_COLOR: {
605 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
606 if (lyx_name.empty() || x11_name.empty()) {
607 current_view_->message(
608 _("Syntax: set-color <lyx_name> <x11_name>"));
612 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
613 bool const graphicsbg_changed = lyx_name == graphicsbg
614 && x11_name != graphicsbg;
615 if (graphicsbg_changed) {
616 // FIXME: The graphics cache no longer has a changeDisplay method.
618 graphics::GCache::get().changeDisplay(true);
622 if (!lcolor.setColor(lyx_name, x11_name)) {
623 current_view_->message(
624 bformat(_("Set-color \"%1$s\" failed "
625 "- color is undefined or "
626 "may not be redefined"),
627 from_utf8(lyx_name)));
630 // Make sure we don't keep old colors in cache.
631 d->color_cache_.clear();
636 // Notify the caller that the action has not been dispatched.
640 // The action has been dispatched.
645 void GuiApplication::resetGui()
647 QHash<int, GuiView *>::iterator it;
648 for (it = d->views_.begin(); it != d->views_.end(); ++it)
649 (*it)->resetDialogs();
651 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
655 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
657 // release the keyboard which might have been grabed by the global
658 // menubar on Mac to catch shortcuts even without any GuiView.
659 if (d->global_menubar_)
660 d->global_menubar_->releaseKeyboard();
664 while (d->views_.find(id) != d->views_.end())
666 GuiView * view = new GuiView(id);
668 // copy the icon size from old view
670 view->setIconSize(current_view_->iconSize());
673 d->views_[id] = view;
677 setActiveWindow(view);
680 if (!geometry_arg.isEmpty()) {
684 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
685 re.indexIn(geometry_arg);
686 w = re.cap(1).toInt();
687 h = re.cap(2).toInt();
688 x = re.cap(3).toInt();
689 y = re.cap(4).toInt();
690 view->setGeometry(x, y, w, h);
694 setCurrentView(view);
698 Clipboard & GuiApplication::clipboard()
700 return d->clipboard_;
704 Selection & GuiApplication::selection()
706 return d->selection_;
710 FontLoader & GuiApplication::fontLoader()
712 return d->font_loader_;
716 Menus const & GuiApplication::menus() const
722 Menus & GuiApplication::menus()
728 QList<int> GuiApplication::viewIds() const
730 return d->views_.keys();
734 ColorCache & GuiApplication::colorCache()
736 return d->color_cache_;
740 int GuiApplication::exec()
742 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
743 return QApplication::exec();
747 void GuiApplication::exit(int status)
749 QApplication::exit(status);
753 void GuiApplication::execBatchCommands()
756 if (!readUIFile(toqstr(lyxrc.ui_file)))
757 // Gives some error box here.
760 // init the global menubar on Mac. This must be done after the session
761 // was recovered to know the "last files".
762 if (d->global_menubar_)
763 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
765 LyX::ref().execBatchCommands();
768 QAbstractItemModel * GuiApplication::languageModel()
770 if (d->language_model_)
771 return d->language_model_;
773 QStandardItemModel * lang_model = new QStandardItemModel(this);
774 lang_model->insertColumns(0, 1);
776 Languages::const_iterator it = languages.begin();
777 Languages::const_iterator end = languages.end();
778 for (; it != end; ++it) {
779 current_row = lang_model->rowCount();
780 lang_model->insertRows(current_row, 1);
781 QModelIndex item = lang_model->index(current_row, 0);
782 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
783 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
785 d->language_model_ = new QSortFilterProxyModel(this);
786 d->language_model_->setSourceModel(lang_model);
787 #if QT_VERSION >= 0x040300
788 d->language_model_->setSortLocaleAware(true);
790 return d->language_model_;
794 void GuiApplication::restoreGuiSession()
796 if (!lyxrc.load_session)
799 Session & session = LyX::ref().session();
800 vector<FileName> const & lastopened = session.lastOpened().getfiles();
801 // do not add to the lastfile list since these files are restored from
802 // last session, and should be already there (regular files), or should
803 // not be added at all (help files).
804 for_each(lastopened.begin(), lastopened.end(),
805 bind(&GuiView::loadDocument, current_view_, _1, false));
807 // clear this list to save a few bytes of RAM
808 session.lastOpened().clear();
812 QString const GuiApplication::romanFontName()
815 font.setKerning(false);
816 font.setStyleHint(QFont::Serif);
817 font.setFamily("serif");
819 return QFontInfo(font).family();
823 QString const GuiApplication::sansFontName()
826 font.setKerning(false);
827 font.setStyleHint(QFont::SansSerif);
828 font.setFamily("sans");
830 return QFontInfo(font).family();
834 QString const GuiApplication::typewriterFontName()
837 font.setKerning(false);
838 font.setStyleHint(QFont::TypeWriter);
839 font.setFamily("monospace");
841 return QFontInfo(font).family();
845 void GuiApplication::handleRegularEvents()
847 ForkedCallsController::handleCompletedProcesses();
851 bool GuiApplication::event(QEvent * e)
854 case QEvent::FileOpen: {
855 // Open a file; this happens only on Mac OS X for now
856 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
858 if (!current_view_ || !current_view_->view())
859 // The application is not properly initialized yet.
860 // So we acknowledge the event and delay the file opening
861 // until LyX is ready.
862 // FIXME UNICODE: FileName accept an utf8 encoded string.
863 LyX::ref().addFileToLoad(fromqstr(foe->file()));
865 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
866 qstring_to_ucs4(foe->file())));
872 return QApplication::event(e);
877 bool GuiApplication::notify(QObject * receiver, QEvent * event)
880 return QApplication::notify(receiver, event);
882 catch (ExceptionMessage const & e) {
885 LyX::cref().emergencyCleanup();
886 setQuitOnLastWindowClosed(false);
888 Alert::error(e.title_, e.details_);
890 // Properly crash in debug mode in order to get a useful backtrace.
893 // In release mode, try to exit gracefully.
896 case BufferException: {
897 Buffer * buf = current_view_->buffer();
898 docstring details = e.details_ + '\n';
899 details += theBufferList().emergencyWrite(buf);
900 theBufferList().release(buf);
901 details += "\n" + _("The current document was closed.");
902 Alert::error(e.title_, details);
905 case WarningException:
906 Alert::warning(e.title_, e.details_);
910 catch (exception const & e) {
911 docstring s = _("LyX has caught an exception, it will now "
912 "attempt to save all unsaved documents and exit."
914 s += from_ascii(e.what());
915 Alert::error(_("Software exception Detected"), s);
919 docstring s = _("LyX has caught some really weird exception, it will "
920 "now attempt to save all unsaved documents and exit.");
921 Alert::error(_("Software exception Detected"), s);
929 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
931 QColor const & qcol = d->color_cache_.get(col);
932 if (!qcol.isValid()) {
938 rgbcol.r = qcol.red();
939 rgbcol.g = qcol.green();
940 rgbcol.b = qcol.blue();
945 string const GuiApplication::hexName(ColorCode col)
947 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
951 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
953 SocketNotifier * sn = new SocketNotifier(this, fd, func);
954 d->socket_notifiers_[fd] = sn;
955 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
959 void GuiApplication::socketDataReceived(int fd)
961 d->socket_notifiers_[fd]->func_();
965 void GuiApplication::unregisterSocketCallback(int fd)
967 d->socket_notifiers_.take(fd)->setEnabled(false);
971 void GuiApplication::commitData(QSessionManager & sm)
973 /// The implementation is required to avoid an application exit
974 /// when session state save is triggered by session manager.
975 /// The default implementation sends a close event to all
976 /// visible top level widgets when session managment allows
978 /// We are changing that to close all wiew one by one.
979 /// FIXME: verify if the default implementation is enough now.
980 if (sm.allowsInteraction() && !closeAllViews())
985 void GuiApplication::unregisterView(GuiView * gv)
987 LASSERT(d->views_[gv->id()] == gv, /**/);
988 d->views_.remove(gv->id());
989 if (current_view_ == gv) {
991 theLyXFunc().setLyXView(0);
996 bool GuiApplication::closeAllViews()
998 if (d->views_.empty())
1001 QList<GuiView *> views = d->views_.values();
1002 foreach (GuiView * view, views) {
1012 GuiView & GuiApplication::view(int id) const
1014 LASSERT(d->views_.contains(id), /**/);
1015 return *d->views_.value(id);
1019 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1021 QList<GuiView *> views = d->views_.values();
1022 foreach (GuiView * view, views)
1023 view->hideDialog(name, inset);
1027 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1029 Buffer const * buffer_ = 0;
1030 QHash<int, GuiView *>::iterator end = d->views_.end();
1031 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1032 if (Buffer const * ptr = (*it)->updateInset(inset))
1039 bool GuiApplication::searchMenu(FuncRequest const & func,
1040 docstring_list & names) const
1042 return d->menus_.searchMenu(func, names);
1046 bool GuiApplication::readUIFile(QString const & name, bool include)
1056 LexerKeyword uitags[] = {
1057 { "include", ui_include },
1058 { "menuset", ui_menuset },
1059 { "toolbars", ui_toolbars },
1060 { "toolbarset", ui_toolbarset }
1063 // Ensure that a file is read only once (prevents include loops)
1064 static QStringList uifiles;
1065 if (uifiles.contains(name)) {
1066 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1067 << "Is this an include loop?");
1071 LYXERR(Debug::INIT, "About to read " << name << "...");
1075 ui_path = libFileSearch("ui", name, "inc");
1076 if (ui_path.empty())
1077 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1079 ui_path = libFileSearch("ui", name, "ui");
1082 if (ui_path.empty()) {
1083 LYXERR(Debug::INIT, "Could not find " << name);
1084 Alert::warning(_("Could not find UI defintion file"),
1085 bformat(_("Error while reading the configuration file\n%1$s.\n"
1086 "Please check your installation."), qstring_to_ucs4(name)));
1090 uifiles.push_back(name);
1092 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1094 lex.setFile(ui_path);
1096 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1100 if (lyxerr.debugging(Debug::PARSER))
1101 lex.printTable(lyxerr);
1103 while (lex.isOK()) {
1104 switch (lex.lex()) {
1107 QString const file = toqstr(lex.getString());
1108 if (!readUIFile(file, true))
1113 d->menus_.read(lex);
1117 toolbarbackend.readToolbars(lex);
1121 toolbarbackend.readToolbarSettings(lex);
1125 if (!rtrim(lex.getString()).empty())
1126 lex.printError("LyX::ReadUIFile: "
1127 "Unknown menu tag: `$$Token'");
1135 void GuiApplication::onLastWindowClosed()
1137 if (d->global_menubar_)
1138 d->global_menubar_->grabKeyboard();
1142 ////////////////////////////////////////////////////////////////////////
1144 // X11 specific stuff goes here...
1147 bool GuiApplication::x11EventFilter(XEvent * xev)
1152 switch (xev->type) {
1153 case SelectionRequest: {
1154 if (xev->xselectionrequest.selection != XA_PRIMARY)
1156 LYXERR(Debug::GUI, "X requested selection.");
1157 BufferView * bv = current_view_->view();
1159 docstring const sel = bv->requestSelection();
1161 d->selection_.put(sel);
1165 case SelectionClear: {
1166 if (xev->xselectionclear.selection != XA_PRIMARY)
1168 LYXERR(Debug::GUI, "Lost selection.");
1169 BufferView * bv = current_view_->view();
1171 bv->clearSelection();
1179 } // namespace frontend
1182 void hideDialogs(std::string const & name, Inset * inset)
1185 theApp()->hideDialogs(name, inset);
1189 ////////////////////////////////////////////////////////////////////
1193 ////////////////////////////////////////////////////////////////////
1195 frontend::FontLoader & theFontLoader()
1197 LASSERT(frontend::guiApp, /**/);
1198 return frontend::guiApp->fontLoader();
1202 frontend::FontMetrics const & theFontMetrics(Font const & f)
1204 return theFontMetrics(f.fontInfo());
1208 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1210 LASSERT(frontend::guiApp, /**/);
1211 return frontend::guiApp->fontLoader().metrics(f);
1215 ////////////////////////////////////////////////////////////////////
1219 ////////////////////////////////////////////////////////////////////
1221 frontend::Clipboard & theClipboard()
1223 LASSERT(frontend::guiApp, /**/);
1224 return frontend::guiApp->clipboard();
1228 frontend::Selection & theSelection()
1230 LASSERT(frontend::guiApp, /**/);
1231 return frontend::guiApp->selection();
1236 #include "GuiApplication_moc.cpp"