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"
68 #include <QFileOpenEvent>
71 #include <QImageReader>
73 #include <QLibraryInfo>
75 #include <QMacPasteboardMime>
80 #include <QPixmapCache>
82 #include <QSessionManager>
83 #include <QSocketNotifier>
84 #include <QSortFilterProxyModel>
85 #include <QStandardItemModel>
88 #include <QTranslator>
92 #include <X11/Xatom.h>
99 #include <QWindowsMime>
100 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
106 #include <boost/bind.hpp>
112 using namespace lyx::support;
115 static void initializeResources()
117 static bool initialized = false;
119 Q_INIT_RESOURCE(Resources);
127 frontend::Application * createApplication(int & argc, char * argv[])
129 return new frontend::GuiApplication(argc, argv);
135 /// Return the list of loadable formats.
136 vector<string> loadableImageFormats()
140 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
142 LYXERR(Debug::GRAPHICS,
143 "\nThe image loader can load the following directly:\n");
145 if (qt_formats.empty())
146 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
148 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
150 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
152 string ext = ascii_lowercase((const char *) *it);
162 ////////////////////////////////////////////////////////////////////////
163 // Icon loading support code.
164 ////////////////////////////////////////////////////////////////////////
174 bool operator<(PngMap const & lhs, PngMap const & rhs)
176 return lhs.key < rhs.key;
182 CompareKey(QString const & name) : name_(name) {}
183 bool operator()(PngMap const & other) const { return other.key == name_; }
189 // this must be sorted alphabetically
190 // Upper case comes before lower case
191 PngMap sorted_png_map[] = {
192 { "Bumpeq", "bumpeq2" },
195 { "Delta", "delta2" },
196 { "Downarrow", "downarrow2" },
197 { "Gamma", "gamma2" },
198 { "Lambda", "lambda2" },
199 { "Leftarrow", "leftarrow2" },
200 { "Leftrightarrow", "leftrightarrow2" },
201 { "Longleftarrow", "longleftarrow2" },
202 { "Longleftrightarrow", "longleftrightarrow2" },
203 { "Longrightarrow", "longrightarrow2" },
204 { "Omega", "omega2" },
208 { "Rightarrow", "rightarrow2" },
209 { "Sigma", "sigma2" },
210 { "Subset", "subset2" },
211 { "Supset", "supset2" },
212 { "Theta", "theta2" },
213 { "Uparrow", "uparrow2" },
214 { "Updownarrow", "updownarrow2" },
215 { "Upsilon", "upsilon2" },
216 { "Vdash", "vdash3" },
219 { "nLeftarrow", "nleftarrow2" },
220 { "nLeftrightarrow", "nleftrightarrow2" },
221 { "nRightarrow", "nrightarrow2" },
222 { "nVDash", "nvdash3" },
223 { "nvDash", "nvdash2" },
224 { "textrm \\AA", "textrm_AA"},
225 { "textrm \\O", "textrm_O"},
226 { "vDash", "vdash2" }
229 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
232 QString findPng(QString const & name)
234 PngMap const * const begin = sorted_png_map;
235 PngMap const * const end = begin + nr_sorted_png_map;
236 LASSERT(sorted(begin, end), /**/);
238 PngMap const * const it = find_if(begin, end, CompareKey(name));
242 png_name = it->value;
245 png_name.replace('_', "underscore");
246 png_name.replace(' ', '_');
248 // This way we can have "math-delim { }" on the toolbar.
249 png_name.replace('(', "lparen");
250 png_name.replace(')', "rparen");
251 png_name.replace('[', "lbracket");
252 png_name.replace(']', "rbracket");
253 png_name.replace('{', "lbrace");
254 png_name.replace('}', "rbrace");
255 png_name.replace('|', "bars");
256 png_name.replace(',', "thinspace");
257 png_name.replace(':', "mediumspace");
258 png_name.replace(';', "thickspace");
259 png_name.replace('!', "negthinspace");
262 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
263 << "Looking for math PNG called \"" << png_name << '"');
270 QString iconName(FuncRequest const & f, bool unknown)
272 initializeResources();
277 case LFUN_MATH_INSERT:
278 if (!f.argument().empty()) {
280 name1 = findPng(toqstr(f.argument()).mid(1));
283 case LFUN_MATH_DELIM:
284 case LFUN_MATH_BIGDELIM:
286 name1 = findPng(toqstr(f.argument()));
290 name1 = toqstr(f.argument());
293 name2 = toqstr(lyxaction.getActionName(f.action));
296 if (!f.argument().empty()) {
297 name1 = name2 + ' ' + toqstr(f.argument());
298 name1.replace(' ', '_');
302 FileName fname = libFileSearch("images/" + path, name1, "png");
304 return toqstr(fname.absFilename());
306 fname = libFileSearch("images/" + path, name2, "png");
308 return toqstr(fname.absFilename());
310 path = ":/images/" + path;
313 LYXERR0("Directory " << path << " not found in resource!");
317 if (res.exists(name1))
321 if (res.exists(name2))
324 LYXERR(Debug::GUI, "Cannot find icon for command \""
325 << lyxaction.getActionName(f.action)
326 << '(' << to_utf8(f.argument()) << ")\"");
329 return QString(":/images/unknown.png");
335 QIcon getIcon(FuncRequest const & f, bool unknown)
337 QString icon = iconName(f, unknown);
341 LYXERR(Debug::GUI, "Found icon: " << icon);
343 if (!pm.load(icon)) {
344 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
352 ////////////////////////////////////////////////////////////////////////
353 // LyX server support code.
354 ////////////////////////////////////////////////////////////////////////
355 class SocketNotifier : public QSocketNotifier
358 /// connect a connection notification from the LyXServerSocket
359 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
360 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
364 /// The callback function
365 Application::SocketCallback func_;
369 ////////////////////////////////////////////////////////////////////////
370 // Mac specific stuff goes here...
371 ////////////////////////////////////////////////////////////////////////
373 class MenuTranslator : public QTranslator
376 MenuTranslator(QObject * parent)
377 : QTranslator(parent)
380 QString translate(const char * /*context*/,
381 const char * sourceText,
382 const char * /*comment*/ = 0)
384 string const s = sourceText;
385 if (s == N_("About %1") || s == N_("Preferences")
386 || s == N_("Reconfigure") || s == N_("Quit %1"))
393 class GlobalMenuBar : public QMenuBar
397 GlobalMenuBar() : QMenuBar(0) {}
400 bool event(QEvent * e)
402 if (e->type() == QEvent::ShortcutOverride) {
403 // && activeWindow() == 0) {
404 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
406 setKeySymbol(&sym, ke);
407 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
416 // QMacPasteboardMimeGraphics can only be compiled on Mac.
418 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
421 QMacPasteboardMimeGraphics()
422 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
425 QString convertorName() { return "Graphics"; }
427 QString flavorFor(QString const & mime)
429 LYXERR(Debug::ACTION, "flavorFor " << mime);
430 if (mime == pdfMimeType())
431 return QLatin1String("com.adobe.pdf");
435 QString mimeFor(QString flav)
437 LYXERR(Debug::ACTION, "mimeFor " << flav);
438 if (flav == QLatin1String("com.adobe.pdf"))
439 return pdfMimeType();
443 bool canConvert(QString const & mime, QString flav)
445 return mimeFor(flav) == mime;
448 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
452 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
456 QList<QByteArray> convertFromMime(QString const & /*mime*/,
457 QVariant data, QString /*flav*/)
459 QList<QByteArray> ret;
460 ret.append(data.toByteArray());
466 ///////////////////////////////////////////////////////////////
467 // You can find more platform specific stuff
468 // at the end of this file...
469 ///////////////////////////////////////////////////////////////
471 ////////////////////////////////////////////////////////////////////////
472 // Windows specific stuff goes here...
475 // QWindowsMimeMetafile can only be compiled on Windows.
477 static FORMATETC cfFromMime(QString const & mimetype)
480 if (mimetype == emfMimeType()) {
481 formatetc.cfFormat = CF_ENHMETAFILE;
482 formatetc.tymed = TYMED_ENHMF;
483 } else if (mimetype == wmfMimeType()) {
484 formatetc.cfFormat = CF_METAFILEPICT;
485 formatetc.tymed = TYMED_MFPICT;
488 formatetc.dwAspect = DVASPECT_CONTENT;
489 formatetc.lindex = -1;
494 class QWindowsMimeMetafile : public QWindowsMime {
496 QWindowsMimeMetafile() {}
498 bool canConvertFromMime(FORMATETC const & formatetc,
499 QMimeData const * mimedata) const
504 bool canConvertToMime(QString const & mimetype,
505 IDataObject * pDataObj) const
507 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
509 FORMATETC formatetc = cfFromMime(mimetype);
510 return pDataObj->QueryGetData(&formatetc) == S_OK;
513 bool convertFromMime(FORMATETC const & formatetc,
514 const QMimeData * mimedata, STGMEDIUM * pmedium) const
519 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
520 QVariant::Type preferredType) const
523 if (!canConvertToMime(mimetype, pDataObj))
526 FORMATETC formatetc = cfFromMime(mimetype);
528 if (pDataObj->GetData(&formatetc, &s) != S_OK)
532 if (s.tymed == TYMED_ENHMF) {
533 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
534 data.resize(dataSize);
535 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
536 (LPBYTE)data.data());
537 } else if (s.tymed == TYMED_MFPICT) {
538 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
539 data.resize(dataSize);
540 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
541 (LPBYTE)data.data());
544 ReleaseStgMedium(&s);
550 QVector<FORMATETC> formatsForMime(QString const & mimeType,
551 QMimeData const * mimeData) const
553 QVector<FORMATETC> formats;
554 formats += cfFromMime(mimeType);
558 QString mimeForFormat(FORMATETC const & formatetc) const
560 switch (formatetc.cfFormat) {
562 return emfMimeType();
563 case CF_METAFILEPICT:
564 return wmfMimeType();
572 ////////////////////////////////////////////////////////////////////////
573 // GuiApplication::Private definition and implementation.
574 ////////////////////////////////////////////////////////////////////////
576 struct GuiApplication::Private
579 : language_model_(0), global_menubar_(0)
582 // Create the global default menubar which is shown for the dialogs
583 // and if no GuiView is visible.
584 global_menubar_ = new GlobalMenuBar();
589 QSortFilterProxyModel * language_model_;
591 GuiClipboard clipboard_;
593 GuiSelection selection_;
595 FontLoader font_loader_;
597 ColorCache color_cache_;
599 QTranslator qt_trans_;
601 QHash<int, SocketNotifier *> socket_notifiers_;
605 /// The global instance
608 /// this timer is used for any regular events one wants to
609 /// perform. at present it is used to check if forked processes
611 QTimer general_timer_;
613 /// Multiple views container.
615 * Warning: This must not be a smart pointer as the destruction of the
616 * object is handled by Qt when the view is closed
617 * \sa Qt::WA_DeleteOnClose attribute.
619 QHash<int, GuiView *> views_;
621 /// Only used on mac.
622 GlobalMenuBar * global_menubar_;
625 /// Linkback mime handler for MacOSX.
626 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
630 /// WMF Mime handler for Windows clipboard.
631 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
632 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
633 // is something in the clipboard.
634 QWindowsMimeMetafile wmf_mime_;
639 GuiApplication * guiApp;
641 GuiApplication::~GuiApplication()
644 closeAllLinkBackLinks();
650 GuiApplication::GuiApplication(int & argc, char ** argv)
651 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
653 QString app_name = "LyX";
654 QCoreApplication::setOrganizationName(app_name);
655 QCoreApplication::setOrganizationDomain("lyx.org");
656 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
658 // FIXME: quitOnLastWindowClosed is true by default. We should have a
659 // lyxrc setting for this in order to let the application stay resident.
660 // But then we need some kind of dock icon, at least on Windows.
662 if (lyxrc.quit_on_last_window_closed)
663 setQuitOnLastWindowClosed(false);
666 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
667 // seems to be the default case for applications like LyX.
668 setQuitOnLastWindowClosed(false);
672 // doubleClickInterval() is 400 ms on X11 which is just too long.
673 // On Windows and Mac OS X, the operating system's value is used.
674 // On Microsoft Windows, calling this function sets the double
675 // click interval for all applications. So we don't!
676 QApplication::setDoubleClickInterval(300);
679 // install translation file for Qt built-in dialogs
680 QString language_name = QString("qt_") + QLocale::system().name();
682 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
683 // Short-named translator can be loaded from a long name, but not the
684 // opposite. Therefore, long name should be used without truncation.
685 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
686 if (d->qt_trans_.load(language_name,
687 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
689 installTranslator(&d->qt_trans_);
690 // even if the language calls for RtL, don't do that
691 setLayoutDirection(Qt::LeftToRight);
692 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
695 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
699 // This allows to translate the strings that appear in the LyX menu.
700 /// A translator suitable for the entries in the LyX menu.
701 /// Only needed with Qt/Mac.
702 installTranslator(new MenuTranslator(this));
704 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
706 using namespace lyx::graphics;
708 Image::newImage = boost::bind(&GuiImage::newImage);
710 // needs to be done before reading lyxrc
712 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
716 // Set the cache to 5120 kilobytes which corresponds to screen size of
717 // 1280 by 1024 pixels with a color depth of 32 bits.
718 QPixmapCache::setCacheLimit(5120);
720 // Initialize RC Fonts
721 if (lyxrc.roman_font_name.empty())
722 lyxrc.roman_font_name = fromqstr(romanFontName());
724 if (lyxrc.sans_font_name.empty())
725 lyxrc.sans_font_name = fromqstr(sansFontName());
727 if (lyxrc.typewriter_font_name.empty())
728 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
730 d->general_timer_.setInterval(500);
731 connect(&d->general_timer_, SIGNAL(timeout()),
732 this, SLOT(handleRegularEvents()));
733 d->general_timer_.start();
737 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
739 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
744 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
750 case LFUN_WINDOW_CLOSE:
751 enable = d->views_.size() > 0;
754 case LFUN_BUFFER_NEW:
755 case LFUN_BUFFER_NEW_TEMPLATE:
757 case LFUN_SCREEN_FONT_UPDATE:
759 case LFUN_WINDOW_NEW:
769 flag.setEnabled(false);
775 bool GuiApplication::dispatch(FuncRequest const & cmd)
777 switch (cmd.action) {
779 case LFUN_WINDOW_NEW:
780 createView(toqstr(cmd.argument()));
783 case LFUN_WINDOW_CLOSE:
784 // update bookmark pit of the current buffer before window close
785 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
786 theLyXFunc().gotoBookmark(i+1, false, false);
787 current_view_->close();
791 // quitting is triggered by the gui code
792 // (leaving the event loop).
794 current_view_->message(from_utf8(N_("Exiting.")));
799 case LFUN_SCREEN_FONT_UPDATE: {
800 // handle the screen font changes.
801 d->font_loader_.update();
802 // Backup current_view_
803 GuiView * view = current_view_;
804 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
805 // to skip the refresh.
807 BufferList::iterator it = theBufferList().begin();
808 BufferList::iterator const end = theBufferList().end();
809 for (; it != end; ++it)
811 // Restore current_view_
812 current_view_ = view;
816 case LFUN_BUFFER_NEW:
817 if (d->views_.empty()
818 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
819 createView(QString(), false); // keep hidden
820 current_view_->newDocument(to_utf8(cmd.argument()), false);
821 current_view_->show();
822 setActiveWindow(current_view_);
824 current_view_->newDocument(to_utf8(cmd.argument()), false);
828 case LFUN_BUFFER_NEW_TEMPLATE:
829 if (d->views_.empty()
830 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
832 current_view_->newDocument(to_utf8(cmd.argument()), true);
833 if (!current_view_->buffer())
834 current_view_->close();
836 current_view_->newDocument(to_utf8(cmd.argument()), true);
841 if (d->views_.empty()
842 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
844 current_view_->openDocument(to_utf8(cmd.argument()));
845 if (!current_view_->buffer())
846 current_view_->close();
848 current_view_->openDocument(to_utf8(cmd.argument()));
851 case LFUN_SET_COLOR: {
853 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
854 if (lyx_name.empty() || x11_name.empty()) {
855 current_view_->message(
856 _("Syntax: set-color <lyx_name> <x11_name>"));
860 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
861 bool const graphicsbg_changed = lyx_name == graphicsbg
862 && x11_name != graphicsbg;
863 if (graphicsbg_changed) {
864 // FIXME: The graphics cache no longer has a changeDisplay method.
866 graphics::GCache::get().changeDisplay(true);
870 if (!lcolor.setColor(lyx_name, x11_name)) {
871 current_view_->message(
872 bformat(_("Set-color \"%1$s\" failed "
873 "- color is undefined or "
874 "may not be redefined"),
875 from_utf8(lyx_name)));
878 // Make sure we don't keep old colors in cache.
879 d->color_cache_.clear();
884 // Notify the caller that the action has not been dispatched.
888 // The action has been dispatched.
893 void GuiApplication::resetGui()
895 QHash<int, GuiView *>::iterator it;
896 for (it = d->views_.begin(); it != d->views_.end(); ++it)
897 (*it)->resetDialogs();
899 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
903 void GuiApplication::createView(QString const & geometry_arg, bool autoShow)
905 // release the keyboard which might have been grabed by the global
906 // menubar on Mac to catch shortcuts even without any GuiView.
907 if (d->global_menubar_)
908 d->global_menubar_->releaseKeyboard();
912 while (d->views_.find(id) != d->views_.end())
914 GuiView * view = new GuiView(id);
916 // copy the icon size from old view
918 view->setIconSize(current_view_->iconSize());
921 d->views_[id] = view;
925 setActiveWindow(view);
928 if (!geometry_arg.isEmpty()) {
932 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
933 re.indexIn(geometry_arg);
934 w = re.cap(1).toInt();
935 h = re.cap(2).toInt();
936 x = re.cap(3).toInt();
937 y = re.cap(4).toInt();
938 view->setGeometry(x, y, w, h);
942 setCurrentView(view);
946 Clipboard & GuiApplication::clipboard()
948 return d->clipboard_;
952 Selection & GuiApplication::selection()
954 return d->selection_;
958 FontLoader & GuiApplication::fontLoader()
960 return d->font_loader_;
964 Toolbars const & GuiApplication::toolbars() const
970 Toolbars & GuiApplication::toolbars()
976 Menus const & GuiApplication::menus() const
982 Menus & GuiApplication::menus()
988 QList<int> GuiApplication::viewIds() const
990 return d->views_.keys();
994 ColorCache & GuiApplication::colorCache()
996 return d->color_cache_;
1000 int GuiApplication::exec()
1002 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1003 return QApplication::exec();
1007 void GuiApplication::exit(int status)
1009 QApplication::exit(status);
1013 void GuiApplication::execBatchCommands()
1016 if (!readUIFile(toqstr(lyxrc.ui_file)))
1017 // Gives some error box here.
1020 // init the global menubar on Mac. This must be done after the session
1021 // was recovered to know the "last files".
1022 if (d->global_menubar_)
1023 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1025 LyX::ref().execBatchCommands();
1028 QAbstractItemModel * GuiApplication::languageModel()
1030 if (d->language_model_)
1031 return d->language_model_;
1033 QStandardItemModel * lang_model = new QStandardItemModel(this);
1034 lang_model->insertColumns(0, 1);
1036 Languages::const_iterator it = languages.begin();
1037 Languages::const_iterator end = languages.end();
1038 for (; it != end; ++it) {
1039 current_row = lang_model->rowCount();
1040 lang_model->insertRows(current_row, 1);
1041 QModelIndex item = lang_model->index(current_row, 0);
1042 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1043 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1045 d->language_model_ = new QSortFilterProxyModel(this);
1046 d->language_model_->setSourceModel(lang_model);
1047 #if QT_VERSION >= 0x040300
1048 d->language_model_->setSortLocaleAware(true);
1050 return d->language_model_;
1054 void GuiApplication::restoreGuiSession()
1056 if (!lyxrc.load_session)
1059 Session & session = LyX::ref().session();
1060 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1061 // do not add to the lastfile list since these files are restored from
1062 // last session, and should be already there (regular files), or should
1063 // not be added at all (help files).
1064 for_each(lastopened.begin(), lastopened.end(),
1065 bind(&GuiView::loadDocument, current_view_, _1, false));
1067 // clear this list to save a few bytes of RAM
1068 session.lastOpened().clear();
1072 QString const GuiApplication::romanFontName()
1075 font.setKerning(false);
1076 font.setStyleHint(QFont::Serif);
1077 font.setFamily("serif");
1079 return QFontInfo(font).family();
1083 QString const GuiApplication::sansFontName()
1086 font.setKerning(false);
1087 font.setStyleHint(QFont::SansSerif);
1088 font.setFamily("sans");
1090 return QFontInfo(font).family();
1094 QString const GuiApplication::typewriterFontName()
1097 font.setKerning(false);
1098 font.setStyleHint(QFont::TypeWriter);
1099 font.setFamily("monospace");
1101 return QFontInfo(font).family();
1105 void GuiApplication::handleRegularEvents()
1107 ForkedCallsController::handleCompletedProcesses();
1111 bool GuiApplication::event(QEvent * e)
1114 case QEvent::FileOpen: {
1115 // Open a file; this happens only on Mac OS X for now
1116 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1117 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1118 qstring_to_ucs4(foe->file())));
1123 return QApplication::event(e);
1128 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1131 return QApplication::notify(receiver, event);
1133 catch (ExceptionMessage const & e) {
1135 case ErrorException:
1136 LyX::cref().emergencyCleanup();
1137 setQuitOnLastWindowClosed(false);
1139 Alert::error(e.title_, e.details_);
1141 // Properly crash in debug mode in order to get a useful backtrace.
1144 // In release mode, try to exit gracefully.
1147 case BufferException: {
1148 Buffer * buf = current_view_->buffer();
1149 docstring details = e.details_ + '\n';
1150 details += theBufferList().emergencyWrite(buf);
1151 theBufferList().release(buf);
1152 details += "\n" + _("The current document was closed.");
1153 Alert::error(e.title_, details);
1156 case WarningException:
1157 Alert::warning(e.title_, e.details_);
1161 catch (exception const & e) {
1162 docstring s = _("LyX has caught an exception, it will now "
1163 "attempt to save all unsaved documents and exit."
1165 s += from_ascii(e.what());
1166 Alert::error(_("Software exception Detected"), s);
1167 LyX::cref().exit(1);
1170 docstring s = _("LyX has caught some really weird exception, it will "
1171 "now attempt to save all unsaved documents and exit.");
1172 Alert::error(_("Software exception Detected"), s);
1173 LyX::cref().exit(1);
1180 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1182 QColor const & qcol = d->color_cache_.get(col);
1183 if (!qcol.isValid()) {
1189 rgbcol.r = qcol.red();
1190 rgbcol.g = qcol.green();
1191 rgbcol.b = qcol.blue();
1196 string const GuiApplication::hexName(ColorCode col)
1198 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1202 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1204 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1205 d->socket_notifiers_[fd] = sn;
1206 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1210 void GuiApplication::socketDataReceived(int fd)
1212 d->socket_notifiers_[fd]->func_();
1216 void GuiApplication::unregisterSocketCallback(int fd)
1218 d->socket_notifiers_.take(fd)->setEnabled(false);
1222 void GuiApplication::commitData(QSessionManager & sm)
1224 /// The implementation is required to avoid an application exit
1225 /// when session state save is triggered by session manager.
1226 /// The default implementation sends a close event to all
1227 /// visible top level widgets when session managment allows
1229 /// We are changing that to close all wiew one by one.
1230 /// FIXME: verify if the default implementation is enough now.
1231 if (sm.allowsInteraction() && !closeAllViews())
1236 void GuiApplication::unregisterView(GuiView * gv)
1238 LASSERT(d->views_[gv->id()] == gv, /**/);
1239 d->views_.remove(gv->id());
1240 if (current_view_ == gv) {
1242 theLyXFunc().setLyXView(0);
1247 bool GuiApplication::closeAllViews()
1249 if (d->views_.empty())
1252 QList<GuiView *> views = d->views_.values();
1253 foreach (GuiView * view, views) {
1263 GuiView & GuiApplication::view(int id) const
1265 LASSERT(d->views_.contains(id), /**/);
1266 return *d->views_.value(id);
1270 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1272 QList<GuiView *> views = d->views_.values();
1273 foreach (GuiView * view, views)
1274 view->hideDialog(name, inset);
1278 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1280 Buffer const * buffer_ = 0;
1281 QHash<int, GuiView *>::iterator end = d->views_.end();
1282 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1283 if (Buffer const * ptr = (*it)->updateInset(inset))
1290 bool GuiApplication::searchMenu(FuncRequest const & func,
1291 docstring_list & names) const
1293 return d->menus_.searchMenu(func, names);
1297 bool GuiApplication::readUIFile(QString const & name, bool include)
1307 LexerKeyword uitags[] = {
1308 { "include", ui_include },
1309 { "menuset", ui_menuset },
1310 { "toolbars", ui_toolbars },
1311 { "toolbarset", ui_toolbarset }
1314 // Ensure that a file is read only once (prevents include loops)
1315 static QStringList uifiles;
1316 if (uifiles.contains(name)) {
1317 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1318 << "Is this an include loop?");
1322 LYXERR(Debug::INIT, "About to read " << name << "...");
1326 ui_path = libFileSearch("ui", name, "inc");
1327 if (ui_path.empty())
1328 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1330 ui_path = libFileSearch("ui", name, "ui");
1333 if (ui_path.empty()) {
1334 LYXERR(Debug::INIT, "Could not find " << name);
1335 Alert::warning(_("Could not find UI defintion file"),
1336 bformat(_("Error while reading the configuration file\n%1$s.\n"
1337 "Please check your installation."), qstring_to_ucs4(name)));
1341 uifiles.push_back(name);
1343 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1345 lex.setFile(ui_path);
1347 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1351 if (lyxerr.debugging(Debug::PARSER))
1352 lex.printTable(lyxerr);
1354 while (lex.isOK()) {
1355 switch (lex.lex()) {
1358 QString const file = toqstr(lex.getString());
1359 if (!readUIFile(file, true))
1364 d->menus_.read(lex);
1368 d->toolbars_.readToolbars(lex);
1372 d->toolbars_.readToolbarSettings(lex);
1376 if (!rtrim(lex.getString()).empty())
1377 lex.printError("LyX::ReadUIFile: "
1378 "Unknown menu tag: `$$Token'");
1386 void GuiApplication::onLastWindowClosed()
1388 if (d->global_menubar_)
1389 d->global_menubar_->grabKeyboard();
1393 ////////////////////////////////////////////////////////////////////////
1395 // X11 specific stuff goes here...
1398 bool GuiApplication::x11EventFilter(XEvent * xev)
1403 switch (xev->type) {
1404 case SelectionRequest: {
1405 if (xev->xselectionrequest.selection != XA_PRIMARY)
1407 LYXERR(Debug::GUI, "X requested selection.");
1408 BufferView * bv = current_view_->view();
1410 docstring const sel = bv->requestSelection();
1412 d->selection_.put(sel);
1416 case SelectionClear: {
1417 if (xev->xselectionclear.selection != XA_PRIMARY)
1419 LYXERR(Debug::GUI, "Lost selection.");
1420 BufferView * bv = current_view_->view();
1422 bv->clearSelection();
1430 } // namespace frontend
1433 void hideDialogs(std::string const & name, Inset * inset)
1436 theApp()->hideDialogs(name, inset);
1440 ////////////////////////////////////////////////////////////////////
1444 ////////////////////////////////////////////////////////////////////
1446 frontend::FontLoader & theFontLoader()
1448 LASSERT(frontend::guiApp, /**/);
1449 return frontend::guiApp->fontLoader();
1453 frontend::FontMetrics const & theFontMetrics(Font const & f)
1455 return theFontMetrics(f.fontInfo());
1459 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1461 LASSERT(frontend::guiApp, /**/);
1462 return frontend::guiApp->fontLoader().metrics(f);
1466 ////////////////////////////////////////////////////////////////////
1470 ////////////////////////////////////////////////////////////////////
1472 frontend::Clipboard & theClipboard()
1474 LASSERT(frontend::guiApp, /**/);
1475 return frontend::guiApp->clipboard();
1479 frontend::Selection & theSelection()
1481 LASSERT(frontend::guiApp, /**/);
1482 return frontend::guiApp->selection();
1487 #include "GuiApplication_moc.cpp"