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"
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 frontend::Application * createApplication(int & argc, char * argv[])
110 return new frontend::GuiApplication(argc, argv);
115 class SocketNotifier : public QSocketNotifier
118 /// connect a connection notification from the LyXServerSocket
119 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
120 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
124 /// The callback function
125 Application::SocketCallback func_;
129 ////////////////////////////////////////////////////////////////////////
130 // Mac specific stuff goes here...
132 class MenuTranslator : public QTranslator
135 MenuTranslator(QObject * parent)
136 : QTranslator(parent)
139 QString translate(const char * /*context*/,
140 const char * sourceText,
141 const char * /*comment*/ = 0)
143 string const s = sourceText;
144 if (s == N_("About %1") || s == N_("Preferences")
145 || s == N_("Reconfigure") || s == N_("Quit %1"))
152 class GlobalMenuBar : public QMenuBar
156 GlobalMenuBar() : QMenuBar(0) {}
159 bool event(QEvent * e)
161 if (e->type() == QEvent::ShortcutOverride) {
162 // && activeWindow() == 0) {
163 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
165 setKeySymbol(&sym, ke);
166 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
175 // QMacPasteboardMimeGraphics can only be compiled on Mac.
177 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
180 QMacPasteboardMimeGraphics()
181 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
184 QString convertorName() { return "Graphics"; }
186 QString flavorFor(QString const & mime)
188 LYXERR(Debug::ACTION, "flavorFor " << mime);
189 if (mime == pdfMimeType())
190 return QLatin1String("com.adobe.pdf");
194 QString mimeFor(QString flav)
196 LYXERR(Debug::ACTION, "mimeFor " << flav);
197 if (flav == QLatin1String("com.adobe.pdf"))
198 return pdfMimeType();
202 bool canConvert(QString const & mime, QString flav)
204 return mimeFor(flav) == mime;
207 QVariant convertToMime(QString const & mime, QList<QByteArray> data, QString flav)
210 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
214 QList<QByteArray> convertFromMime(QString const & mime, QVariant data, QString flav)
216 QList<QByteArray> ret;
217 ret.append(data.toByteArray());
223 ///////////////////////////////////////////////////////////////
224 // You can find more platform specific stuff
225 // at the end of this file...
226 ///////////////////////////////////////////////////////////////
228 ////////////////////////////////////////////////////////////////////////
229 // Windows specific stuff goes here...
232 // QWindowsMimeMetafile can only be compiled on Windows.
234 static FORMATETC cfFromMime(QString const & mimetype)
237 if (mimetype == emfMimeType()) {
238 formatetc.cfFormat = CF_ENHMETAFILE;
239 formatetc.tymed = TYMED_ENHMF;
240 } else if (mimetype == wmfMimeType()) {
241 formatetc.cfFormat = CF_METAFILEPICT;
242 formatetc.tymed = TYMED_MFPICT;
245 formatetc.dwAspect = DVASPECT_CONTENT;
246 formatetc.lindex = -1;
251 class QWindowsMimeMetafile : public QWindowsMime {
253 QWindowsMimeMetafile() {}
255 bool canConvertFromMime(FORMATETC const & formatetc,
256 QMimeData const * mimedata) const
261 bool canConvertToMime(QString const & mimetype,
262 IDataObject * pDataObj) const
264 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
266 FORMATETC formatetc = cfFromMime(mimetype);
267 return pDataObj->QueryGetData(&formatetc) == S_OK;
270 bool convertFromMime(FORMATETC const & formatetc,
271 const QMimeData * mimedata, STGMEDIUM * pmedium) const
276 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
277 QVariant::Type preferredType) const
280 if (!canConvertToMime(mimetype, pDataObj))
283 FORMATETC formatetc = cfFromMime(mimetype);
285 if (pDataObj->GetData(&formatetc, &s) != S_OK)
289 if (s.tymed == TYMED_ENHMF) {
290 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
291 data.resize(dataSize);
292 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
293 (LPBYTE)data.data());
294 } else if (s.tymed == TYMED_MFPICT) {
295 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
296 data.resize(dataSize);
297 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
298 (LPBYTE)data.data());
301 ReleaseStgMedium(&s);
307 QVector<FORMATETC> formatsForMime(QString const & mimeType,
308 QMimeData const * mimeData) const
310 QVector<FORMATETC> formats;
311 formats += cfFromMime(mimeType);
315 QString mimeForFormat(FORMATETC const & formatetc) const
317 switch (formatetc.cfFormat) {
319 return emfMimeType();
320 case CF_METAFILEPICT:
321 return wmfMimeType();
329 ////////////////////////////////////////////////////////////////////////
330 // GuiApplication::Private definition and implementation.
331 ////////////////////////////////////////////////////////////////////////
333 struct GuiApplication::Private
336 : language_model_(0), global_menubar_(0)
339 // Create the global default menubar which is shown for the dialogs
340 // and if no GuiView is visible.
341 global_menubar_ = new GlobalMenuBar();
346 QSortFilterProxyModel * language_model_;
348 GuiClipboard clipboard_;
350 GuiSelection selection_;
352 FontLoader font_loader_;
354 ColorCache color_cache_;
356 QTranslator qt_trans_;
358 QHash<int, SocketNotifier *> socket_notifiers_;
362 /// The global instance
365 /// this timer is used for any regular events one wants to
366 /// perform. at present it is used to check if forked processes
368 QTimer general_timer_;
370 /// Multiple views container.
372 * Warning: This must not be a smart pointer as the destruction of the
373 * object is handled by Qt when the view is closed
374 * \sa Qt::WA_DeleteOnClose attribute.
376 QHash<int, GuiView *> views_;
378 /// Only used on mac.
379 GlobalMenuBar * global_menubar_;
382 /// Linkback mime handler for MacOSX.
383 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
387 /// WMF Mime handler for Windows clipboard.
388 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
389 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
390 // is something in the clipboard.
391 QWindowsMimeMetafile wmf_mime_;
396 GuiApplication * guiApp;
398 GuiApplication::~GuiApplication()
401 closeAllLinkBackLinks();
407 GuiApplication::GuiApplication(int & argc, char ** argv)
408 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
410 QString app_name = "LyX";
411 QCoreApplication::setOrganizationName(app_name);
412 QCoreApplication::setOrganizationDomain("lyx.org");
413 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
415 // FIXME: quitOnLastWindowClosed is true by default. We should have a
416 // lyxrc setting for this in order to let the application stay resident.
417 // But then we need some kind of dock icon, at least on Windows.
419 if (lyxrc.quit_on_last_window_closed)
420 setQuitOnLastWindowClosed(false);
423 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
424 // seems to be the default case for applications like LyX.
425 setQuitOnLastWindowClosed(false);
429 // doubleClickInterval() is 400 ms on X11 which is just too long.
430 // On Windows and Mac OS X, the operating system's value is used.
431 // On Microsoft Windows, calling this function sets the double
432 // click interval for all applications. So we don't!
433 QApplication::setDoubleClickInterval(300);
436 // install translation file for Qt built-in dialogs
437 QString language_name = QString("qt_") + QLocale::system().name();
439 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
440 // Short-named translator can be loaded from a long name, but not the
441 // opposite. Therefore, long name should be used without truncation.
442 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
443 if (d->qt_trans_.load(language_name,
444 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
446 installTranslator(&d->qt_trans_);
447 // even if the language calls for RtL, don't do that
448 setLayoutDirection(Qt::LeftToRight);
449 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
452 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
456 // This allows to translate the strings that appear in the LyX menu.
457 /// A translator suitable for the entries in the LyX menu.
458 /// Only needed with Qt/Mac.
459 installTranslator(new MenuTranslator(this));
461 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
463 using namespace lyx::graphics;
465 Image::newImage = boost::bind(&GuiImage::newImage);
466 Image::loadableFormats = boost::bind(&GuiImage::loadableFormats);
468 // needs to be done before reading lyxrc
470 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
474 // Set the cache to 5120 kilobytes which corresponds to screen size of
475 // 1280 by 1024 pixels with a color depth of 32 bits.
476 QPixmapCache::setCacheLimit(5120);
478 // Initialize RC Fonts
479 if (lyxrc.roman_font_name.empty())
480 lyxrc.roman_font_name = fromqstr(romanFontName());
482 if (lyxrc.sans_font_name.empty())
483 lyxrc.sans_font_name = fromqstr(sansFontName());
485 if (lyxrc.typewriter_font_name.empty())
486 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
488 d->general_timer_.setInterval(500);
489 connect(&d->general_timer_, SIGNAL(timeout()),
490 this, SLOT(handleRegularEvents()));
491 d->general_timer_.start();
495 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
501 case LFUN_WINDOW_CLOSE:
502 enable = d->views_.size() > 0;
505 case LFUN_BUFFER_NEW:
506 case LFUN_BUFFER_NEW_TEMPLATE:
508 case LFUN_SCREEN_FONT_UPDATE:
510 case LFUN_WINDOW_NEW:
520 flag.setEnabled(false);
526 bool GuiApplication::dispatch(FuncRequest const & cmd)
528 switch (cmd.action) {
530 case LFUN_WINDOW_NEW:
531 createView(toqstr(cmd.argument()));
534 case LFUN_WINDOW_CLOSE:
535 // update bookmark pit of the current buffer before window close
536 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
537 theLyXFunc().gotoBookmark(i+1, false, false);
538 current_view_->close();
542 // quitting is triggered by the gui code
543 // (leaving the event loop).
545 current_view_->message(from_utf8(N_("Exiting.")));
550 case LFUN_SCREEN_FONT_UPDATE: {
551 // handle the screen font changes.
552 d->font_loader_.update();
553 // Backup current_view_
554 GuiView * view = current_view_;
555 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
556 // to skip the refresh.
558 BufferList::iterator it = theBufferList().begin();
559 BufferList::iterator const end = theBufferList().end();
560 for (; it != end; ++it)
562 // Restore current_view_
563 current_view_ = view;
567 case LFUN_BUFFER_NEW:
568 if (d->views_.empty()
569 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
570 createView(QString(), false); // keep hidden
571 current_view_->newDocument(to_utf8(cmd.argument()), false);
572 current_view_->show();
573 setActiveWindow(current_view_);
575 current_view_->newDocument(to_utf8(cmd.argument()), false);
579 case LFUN_BUFFER_NEW_TEMPLATE:
580 if (d->views_.empty()
581 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
583 current_view_->newDocument(to_utf8(cmd.argument()), true);
584 if (!current_view_->buffer())
585 current_view_->close();
587 current_view_->newDocument(to_utf8(cmd.argument()), true);
592 if (d->views_.empty()
593 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
595 current_view_->openDocument(to_utf8(cmd.argument()));
596 if (!current_view_->buffer())
597 current_view_->close();
599 current_view_->openDocument(to_utf8(cmd.argument()));
602 case LFUN_SET_COLOR: {
604 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
605 if (lyx_name.empty() || x11_name.empty()) {
606 current_view_->message(
607 _("Syntax: set-color <lyx_name> <x11_name>"));
611 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
612 bool const graphicsbg_changed = lyx_name == graphicsbg
613 && x11_name != graphicsbg;
614 if (graphicsbg_changed) {
615 // FIXME: The graphics cache no longer has a changeDisplay method.
617 graphics::GCache::get().changeDisplay(true);
621 if (!lcolor.setColor(lyx_name, x11_name)) {
622 current_view_->message(
623 bformat(_("Set-color \"%1$s\" failed "
624 "- color is undefined or "
625 "may not be redefined"),
626 from_utf8(lyx_name)));
629 // Make sure we don't keep old colors in cache.
630 d->color_cache_.clear();
635 // Notify the caller that the action has not been dispatched.
639 // The action has been dispatched.
644 void GuiApplication::resetGui()
646 QHash<int, GuiView *>::iterator it;
647 for (it = d->views_.begin(); it != d->views_.end(); ++it)
648 (*it)->resetDialogs();
650 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
654 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
656 // release the keyboard which might have been grabed by the global
657 // menubar on Mac to catch shortcuts even without any GuiView.
658 if (d->global_menubar_)
659 d->global_menubar_->releaseKeyboard();
663 while (d->views_.find(id) != d->views_.end())
665 GuiView * view = new GuiView(id);
667 // copy the icon size from old view
669 view->setIconSize(current_view_->iconSize());
672 d->views_[id] = view;
676 setActiveWindow(view);
679 if (!geometry_arg.isEmpty()) {
683 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
684 re.indexIn(geometry_arg);
685 w = re.cap(1).toInt();
686 h = re.cap(2).toInt();
687 x = re.cap(3).toInt();
688 y = re.cap(4).toInt();
689 view->setGeometry(x, y, w, h);
693 setCurrentView(view);
697 Clipboard & GuiApplication::clipboard()
699 return d->clipboard_;
703 Selection & GuiApplication::selection()
705 return d->selection_;
709 FontLoader & GuiApplication::fontLoader()
711 return d->font_loader_;
715 Toolbars const & GuiApplication::toolbars() const
721 Toolbars & GuiApplication::toolbars()
727 Menus const & GuiApplication::menus() const
733 Menus & GuiApplication::menus()
739 QList<int> GuiApplication::viewIds() const
741 return d->views_.keys();
745 ColorCache & GuiApplication::colorCache()
747 return d->color_cache_;
751 int GuiApplication::exec()
753 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
754 return QApplication::exec();
758 void GuiApplication::exit(int status)
760 QApplication::exit(status);
764 void GuiApplication::execBatchCommands()
767 if (!readUIFile(toqstr(lyxrc.ui_file)))
768 // Gives some error box here.
771 // init the global menubar on Mac. This must be done after the session
772 // was recovered to know the "last files".
773 if (d->global_menubar_)
774 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
776 LyX::ref().execBatchCommands();
779 QAbstractItemModel * GuiApplication::languageModel()
781 if (d->language_model_)
782 return d->language_model_;
784 QStandardItemModel * lang_model = new QStandardItemModel(this);
785 lang_model->insertColumns(0, 1);
787 Languages::const_iterator it = languages.begin();
788 Languages::const_iterator end = languages.end();
789 for (; it != end; ++it) {
790 current_row = lang_model->rowCount();
791 lang_model->insertRows(current_row, 1);
792 QModelIndex item = lang_model->index(current_row, 0);
793 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
794 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
796 d->language_model_ = new QSortFilterProxyModel(this);
797 d->language_model_->setSourceModel(lang_model);
798 #if QT_VERSION >= 0x040300
799 d->language_model_->setSortLocaleAware(true);
801 return d->language_model_;
805 void GuiApplication::restoreGuiSession()
807 if (!lyxrc.load_session)
810 Session & session = LyX::ref().session();
811 vector<FileName> const & lastopened = session.lastOpened().getfiles();
812 // do not add to the lastfile list since these files are restored from
813 // last session, and should be already there (regular files), or should
814 // not be added at all (help files).
815 for_each(lastopened.begin(), lastopened.end(),
816 bind(&GuiView::loadDocument, current_view_, _1, false));
818 // clear this list to save a few bytes of RAM
819 session.lastOpened().clear();
823 QString const GuiApplication::romanFontName()
826 font.setKerning(false);
827 font.setStyleHint(QFont::Serif);
828 font.setFamily("serif");
830 return QFontInfo(font).family();
834 QString const GuiApplication::sansFontName()
837 font.setKerning(false);
838 font.setStyleHint(QFont::SansSerif);
839 font.setFamily("sans");
841 return QFontInfo(font).family();
845 QString const GuiApplication::typewriterFontName()
848 font.setKerning(false);
849 font.setStyleHint(QFont::TypeWriter);
850 font.setFamily("monospace");
852 return QFontInfo(font).family();
856 void GuiApplication::handleRegularEvents()
858 ForkedCallsController::handleCompletedProcesses();
862 bool GuiApplication::event(QEvent * e)
865 case QEvent::FileOpen: {
866 // Open a file; this happens only on Mac OS X for now
867 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
868 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
869 qstring_to_ucs4(foe->file())));
874 return QApplication::event(e);
879 bool GuiApplication::notify(QObject * receiver, QEvent * event)
882 return QApplication::notify(receiver, event);
884 catch (ExceptionMessage const & e) {
887 LyX::cref().emergencyCleanup();
888 setQuitOnLastWindowClosed(false);
890 Alert::error(e.title_, e.details_);
892 // Properly crash in debug mode in order to get a useful backtrace.
895 // In release mode, try to exit gracefully.
898 case BufferException: {
899 Buffer * buf = current_view_->buffer();
900 docstring details = e.details_ + '\n';
901 details += theBufferList().emergencyWrite(buf);
902 theBufferList().release(buf);
903 details += "\n" + _("The current document was closed.");
904 Alert::error(e.title_, details);
907 case WarningException:
908 Alert::warning(e.title_, e.details_);
912 catch (exception const & e) {
913 docstring s = _("LyX has caught an exception, it will now "
914 "attempt to save all unsaved documents and exit."
916 s += from_ascii(e.what());
917 Alert::error(_("Software exception Detected"), s);
921 docstring s = _("LyX has caught some really weird exception, it will "
922 "now attempt to save all unsaved documents and exit.");
923 Alert::error(_("Software exception Detected"), s);
931 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
933 QColor const & qcol = d->color_cache_.get(col);
934 if (!qcol.isValid()) {
940 rgbcol.r = qcol.red();
941 rgbcol.g = qcol.green();
942 rgbcol.b = qcol.blue();
947 string const GuiApplication::hexName(ColorCode col)
949 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
953 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
955 SocketNotifier * sn = new SocketNotifier(this, fd, func);
956 d->socket_notifiers_[fd] = sn;
957 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
961 void GuiApplication::socketDataReceived(int fd)
963 d->socket_notifiers_[fd]->func_();
967 void GuiApplication::unregisterSocketCallback(int fd)
969 d->socket_notifiers_.take(fd)->setEnabled(false);
973 void GuiApplication::commitData(QSessionManager & sm)
975 /// The implementation is required to avoid an application exit
976 /// when session state save is triggered by session manager.
977 /// The default implementation sends a close event to all
978 /// visible top level widgets when session managment allows
980 /// We are changing that to close all wiew one by one.
981 /// FIXME: verify if the default implementation is enough now.
982 if (sm.allowsInteraction() && !closeAllViews())
987 void GuiApplication::unregisterView(GuiView * gv)
989 LASSERT(d->views_[gv->id()] == gv, /**/);
990 d->views_.remove(gv->id());
991 if (current_view_ == gv) {
993 theLyXFunc().setLyXView(0);
998 bool GuiApplication::closeAllViews()
1000 if (d->views_.empty())
1003 QList<GuiView *> views = d->views_.values();
1004 foreach (GuiView * view, views) {
1014 GuiView & GuiApplication::view(int id) const
1016 LASSERT(d->views_.contains(id), /**/);
1017 return *d->views_.value(id);
1021 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1023 QList<GuiView *> views = d->views_.values();
1024 foreach (GuiView * view, views)
1025 view->hideDialog(name, inset);
1029 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1031 Buffer const * buffer_ = 0;
1032 QHash<int, GuiView *>::iterator end = d->views_.end();
1033 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1034 if (Buffer const * ptr = (*it)->updateInset(inset))
1041 bool GuiApplication::searchMenu(FuncRequest const & func,
1042 docstring_list & names) const
1044 return d->menus_.searchMenu(func, names);
1048 bool GuiApplication::readUIFile(QString const & name, bool include)
1058 LexerKeyword uitags[] = {
1059 { "include", ui_include },
1060 { "menuset", ui_menuset },
1061 { "toolbars", ui_toolbars },
1062 { "toolbarset", ui_toolbarset }
1065 // Ensure that a file is read only once (prevents include loops)
1066 static QStringList uifiles;
1067 if (uifiles.contains(name)) {
1068 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1069 << "Is this an include loop?");
1073 LYXERR(Debug::INIT, "About to read " << name << "...");
1077 ui_path = libFileSearch("ui", name, "inc");
1078 if (ui_path.empty())
1079 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1081 ui_path = libFileSearch("ui", name, "ui");
1084 if (ui_path.empty()) {
1085 LYXERR(Debug::INIT, "Could not find " << name);
1086 Alert::warning(_("Could not find UI defintion file"),
1087 bformat(_("Error while reading the configuration file\n%1$s.\n"
1088 "Please check your installation."), qstring_to_ucs4(name)));
1092 uifiles.push_back(name);
1094 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1096 lex.setFile(ui_path);
1098 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1102 if (lyxerr.debugging(Debug::PARSER))
1103 lex.printTable(lyxerr);
1105 while (lex.isOK()) {
1106 switch (lex.lex()) {
1109 QString const file = toqstr(lex.getString());
1110 if (!readUIFile(file, true))
1115 d->menus_.read(lex);
1119 d->toolbars_.readToolbars(lex);
1123 d->toolbars_.readToolbarSettings(lex);
1127 if (!rtrim(lex.getString()).empty())
1128 lex.printError("LyX::ReadUIFile: "
1129 "Unknown menu tag: `$$Token'");
1137 void GuiApplication::onLastWindowClosed()
1139 if (d->global_menubar_)
1140 d->global_menubar_->grabKeyboard();
1144 ////////////////////////////////////////////////////////////////////////
1146 // X11 specific stuff goes here...
1149 bool GuiApplication::x11EventFilter(XEvent * xev)
1154 switch (xev->type) {
1155 case SelectionRequest: {
1156 if (xev->xselectionrequest.selection != XA_PRIMARY)
1158 LYXERR(Debug::GUI, "X requested selection.");
1159 BufferView * bv = current_view_->view();
1161 docstring const sel = bv->requestSelection();
1163 d->selection_.put(sel);
1167 case SelectionClear: {
1168 if (xev->xselectionclear.selection != XA_PRIMARY)
1170 LYXERR(Debug::GUI, "Lost selection.");
1171 BufferView * bv = current_view_->view();
1173 bv->clearSelection();
1181 } // namespace frontend
1184 void hideDialogs(std::string const & name, Inset * inset)
1187 theApp()->hideDialogs(name, inset);
1191 ////////////////////////////////////////////////////////////////////
1195 ////////////////////////////////////////////////////////////////////
1197 frontend::FontLoader & theFontLoader()
1199 LASSERT(frontend::guiApp, /**/);
1200 return frontend::guiApp->fontLoader();
1204 frontend::FontMetrics const & theFontMetrics(Font const & f)
1206 return theFontMetrics(f.fontInfo());
1210 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1212 LASSERT(frontend::guiApp, /**/);
1213 return frontend::guiApp->fontLoader().metrics(f);
1217 ////////////////////////////////////////////////////////////////////
1221 ////////////////////////////////////////////////////////////////////
1223 frontend::Clipboard & theClipboard()
1225 LASSERT(frontend::guiApp, /**/);
1226 return frontend::guiApp->clipboard();
1230 frontend::Selection & theSelection()
1232 LASSERT(frontend::guiApp, /**/);
1233 return frontend::guiApp->selection();
1238 #include "GuiApplication_moc.cpp"