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>
107 #include <boost/crc.hpp>
113 using namespace lyx::support;
116 static void initializeResources()
118 static bool initialized = false;
120 Q_INIT_RESOURCE(Resources);
128 frontend::Application * createApplication(int & argc, char * argv[])
130 return new frontend::GuiApplication(argc, argv);
136 /// Return the list of loadable formats.
137 vector<string> loadableImageFormats()
141 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
143 LYXERR(Debug::GRAPHICS,
144 "\nThe image loader can load the following directly:\n");
146 if (qt_formats.empty())
147 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
149 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
151 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
153 string ext = ascii_lowercase((const char *) *it);
163 ////////////////////////////////////////////////////////////////////////
164 // Icon loading support code.
165 ////////////////////////////////////////////////////////////////////////
175 bool operator<(PngMap const & lhs, PngMap const & rhs)
177 return lhs.key < rhs.key;
183 CompareKey(QString const & name) : name_(name) {}
184 bool operator()(PngMap const & other) const { return other.key == name_; }
190 // this must be sorted alphabetically
191 // Upper case comes before lower case
192 PngMap sorted_png_map[] = {
193 { "Bumpeq", "bumpeq2" },
196 { "Delta", "delta2" },
197 { "Downarrow", "downarrow2" },
198 { "Gamma", "gamma2" },
199 { "Lambda", "lambda2" },
200 { "Leftarrow", "leftarrow2" },
201 { "Leftrightarrow", "leftrightarrow2" },
202 { "Longleftarrow", "longleftarrow2" },
203 { "Longleftrightarrow", "longleftrightarrow2" },
204 { "Longrightarrow", "longrightarrow2" },
205 { "Omega", "omega2" },
209 { "Rightarrow", "rightarrow2" },
210 { "Sigma", "sigma2" },
211 { "Subset", "subset2" },
212 { "Supset", "supset2" },
213 { "Theta", "theta2" },
214 { "Uparrow", "uparrow2" },
215 { "Updownarrow", "updownarrow2" },
216 { "Upsilon", "upsilon2" },
217 { "Vdash", "vdash3" },
220 { "nLeftarrow", "nleftarrow2" },
221 { "nLeftrightarrow", "nleftrightarrow2" },
222 { "nRightarrow", "nrightarrow2" },
223 { "nVDash", "nvdash3" },
224 { "nvDash", "nvdash2" },
225 { "textrm \\AA", "textrm_AA"},
226 { "textrm \\O", "textrm_O"},
227 { "vDash", "vdash2" }
230 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
233 QString findPng(QString const & name)
235 PngMap const * const begin = sorted_png_map;
236 PngMap const * const end = begin + nr_sorted_png_map;
237 LASSERT(sorted(begin, end), /**/);
239 PngMap const * const it = find_if(begin, end, CompareKey(name));
243 png_name = it->value;
246 png_name.replace('_', "underscore");
247 png_name.replace(' ', '_');
249 // This way we can have "math-delim { }" on the toolbar.
250 png_name.replace('(', "lparen");
251 png_name.replace(')', "rparen");
252 png_name.replace('[', "lbracket");
253 png_name.replace(']', "rbracket");
254 png_name.replace('{', "lbrace");
255 png_name.replace('}', "rbrace");
256 png_name.replace('|', "bars");
257 png_name.replace(',', "thinspace");
258 png_name.replace(':', "mediumspace");
259 png_name.replace(';', "thickspace");
260 png_name.replace('!', "negthinspace");
263 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
264 << "Looking for math PNG called \"" << png_name << '"');
271 QString iconName(FuncRequest const & f, bool unknown)
273 initializeResources();
278 case LFUN_MATH_INSERT:
279 if (!f.argument().empty()) {
281 name1 = findPng(toqstr(f.argument()).mid(1));
284 case LFUN_MATH_DELIM:
285 case LFUN_MATH_BIGDELIM:
287 name1 = findPng(toqstr(f.argument()));
291 name1 = toqstr(f.argument());
294 name2 = toqstr(lyxaction.getActionName(f.action));
297 if (!f.argument().empty()) {
298 name1 = name2 + ' ' + toqstr(f.argument());
299 name1.replace(' ', '_');
303 FileName fname = libFileSearch("images/" + path, name1, "png");
305 return toqstr(fname.absFilename());
307 fname = libFileSearch("images/" + path, name2, "png");
309 return toqstr(fname.absFilename());
311 path = ":/images/" + path;
314 LYXERR0("Directory " << path << " not found in resource!");
318 if (res.exists(name1))
322 if (res.exists(name2))
325 LYXERR(Debug::GUI, "Cannot find icon for command \""
326 << lyxaction.getActionName(f.action)
327 << '(' << to_utf8(f.argument()) << ")\"");
330 return QString(":/images/unknown.png");
336 QIcon getIcon(FuncRequest const & f, bool unknown)
338 QString icon = iconName(f, unknown);
342 //LYXERR(Debug::GUI, "Found icon: " << icon);
344 if (!pm.load(icon)) {
345 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
353 ////////////////////////////////////////////////////////////////////////
354 // LyX server support code.
355 ////////////////////////////////////////////////////////////////////////
356 class SocketNotifier : public QSocketNotifier
359 /// connect a connection notification from the LyXServerSocket
360 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
361 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
365 /// The callback function
366 Application::SocketCallback func_;
370 ////////////////////////////////////////////////////////////////////////
371 // Mac specific stuff goes here...
372 ////////////////////////////////////////////////////////////////////////
374 class MenuTranslator : public QTranslator
377 MenuTranslator(QObject * parent)
378 : QTranslator(parent)
381 QString translate(const char * /*context*/,
382 const char * sourceText,
383 const char * /*comment*/ = 0)
385 string const s = sourceText;
386 if (s == N_("About %1") || s == N_("Preferences")
387 || s == N_("Reconfigure") || s == N_("Quit %1"))
394 class GlobalMenuBar : public QMenuBar
398 GlobalMenuBar() : QMenuBar(0) {}
401 bool event(QEvent * e)
403 if (e->type() == QEvent::ShortcutOverride) {
404 // && activeWindow() == 0) {
405 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
407 setKeySymbol(&sym, ke);
408 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
417 // QMacPasteboardMimeGraphics can only be compiled on Mac.
419 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
422 QMacPasteboardMimeGraphics()
423 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
426 QString convertorName() { return "Graphics"; }
428 QString flavorFor(QString const & mime)
430 LYXERR(Debug::ACTION, "flavorFor " << mime);
431 if (mime == pdfMimeType())
432 return QLatin1String("com.adobe.pdf");
436 QString mimeFor(QString flav)
438 LYXERR(Debug::ACTION, "mimeFor " << flav);
439 if (flav == QLatin1String("com.adobe.pdf"))
440 return pdfMimeType();
444 bool canConvert(QString const & mime, QString flav)
446 return mimeFor(flav) == mime;
449 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
453 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
457 QList<QByteArray> convertFromMime(QString const & /*mime*/,
458 QVariant data, QString /*flav*/)
460 QList<QByteArray> ret;
461 ret.append(data.toByteArray());
467 ///////////////////////////////////////////////////////////////
468 // You can find more platform specific stuff
469 // at the end of this file...
470 ///////////////////////////////////////////////////////////////
472 ////////////////////////////////////////////////////////////////////////
473 // Windows specific stuff goes here...
476 // QWindowsMimeMetafile can only be compiled on Windows.
478 static FORMATETC cfFromMime(QString const & mimetype)
481 if (mimetype == emfMimeType()) {
482 formatetc.cfFormat = CF_ENHMETAFILE;
483 formatetc.tymed = TYMED_ENHMF;
484 } else if (mimetype == wmfMimeType()) {
485 formatetc.cfFormat = CF_METAFILEPICT;
486 formatetc.tymed = TYMED_MFPICT;
489 formatetc.dwAspect = DVASPECT_CONTENT;
490 formatetc.lindex = -1;
495 class QWindowsMimeMetafile : public QWindowsMime {
497 QWindowsMimeMetafile() {}
499 bool canConvertFromMime(FORMATETC const & formatetc,
500 QMimeData const * mimedata) const
505 bool canConvertToMime(QString const & mimetype,
506 IDataObject * pDataObj) const
508 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
510 FORMATETC formatetc = cfFromMime(mimetype);
511 return pDataObj->QueryGetData(&formatetc) == S_OK;
514 bool convertFromMime(FORMATETC const & formatetc,
515 const QMimeData * mimedata, STGMEDIUM * pmedium) const
520 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
521 QVariant::Type preferredType) const
524 if (!canConvertToMime(mimetype, pDataObj))
527 FORMATETC formatetc = cfFromMime(mimetype);
529 if (pDataObj->GetData(&formatetc, &s) != S_OK)
533 if (s.tymed == TYMED_ENHMF) {
534 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
535 data.resize(dataSize);
536 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
537 (LPBYTE)data.data());
538 } else if (s.tymed == TYMED_MFPICT) {
539 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
540 data.resize(dataSize);
541 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
542 (LPBYTE)data.data());
545 ReleaseStgMedium(&s);
551 QVector<FORMATETC> formatsForMime(QString const & mimeType,
552 QMimeData const * mimeData) const
554 QVector<FORMATETC> formats;
555 formats += cfFromMime(mimeType);
559 QString mimeForFormat(FORMATETC const & formatetc) const
561 switch (formatetc.cfFormat) {
563 return emfMimeType();
564 case CF_METAFILEPICT:
565 return wmfMimeType();
573 ////////////////////////////////////////////////////////////////////////
574 // GuiApplication::Private definition and implementation.
575 ////////////////////////////////////////////////////////////////////////
577 struct GuiApplication::Private
580 : language_model_(0), global_menubar_(0)
583 // Create the global default menubar which is shown for the dialogs
584 // and if no GuiView is visible.
585 global_menubar_ = new GlobalMenuBar();
590 QSortFilterProxyModel * language_model_;
592 GuiClipboard clipboard_;
594 GuiSelection selection_;
596 FontLoader font_loader_;
598 ColorCache color_cache_;
600 QTranslator qt_trans_;
602 QHash<int, SocketNotifier *> socket_notifiers_;
606 /// The global instance
609 /// this timer is used for any regular events one wants to
610 /// perform. at present it is used to check if forked processes
612 QTimer general_timer_;
614 /// Multiple views container.
616 * Warning: This must not be a smart pointer as the destruction of the
617 * object is handled by Qt when the view is closed
618 * \sa Qt::WA_DeleteOnClose attribute.
620 QHash<int, GuiView *> views_;
622 /// Only used on mac.
623 GlobalMenuBar * global_menubar_;
626 /// Linkback mime handler for MacOSX.
627 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
631 /// WMF Mime handler for Windows clipboard.
632 // FIXME for Windows Vista and Qt4 (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
633 // But this makes LyX crash on exit when LyX is compiled in release mode and if there
634 // is something in the clipboard.
635 QWindowsMimeMetafile wmf_mime_;
640 GuiApplication * guiApp;
642 GuiApplication::~GuiApplication()
645 closeAllLinkBackLinks();
651 GuiApplication::GuiApplication(int & argc, char ** argv)
652 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
654 QString app_name = "LyX";
655 QCoreApplication::setOrganizationName(app_name);
656 QCoreApplication::setOrganizationDomain("lyx.org");
657 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
659 // FIXME: quitOnLastWindowClosed is true by default. We should have a
660 // lyxrc setting for this in order to let the application stay resident.
661 // But then we need some kind of dock icon, at least on Windows.
663 if (lyxrc.quit_on_last_window_closed)
664 setQuitOnLastWindowClosed(false);
667 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
668 // seems to be the default case for applications like LyX.
669 setQuitOnLastWindowClosed(false);
673 // doubleClickInterval() is 400 ms on X11 which is just too long.
674 // On Windows and Mac OS X, the operating system's value is used.
675 // On Microsoft Windows, calling this function sets the double
676 // click interval for all applications. So we don't!
677 QApplication::setDoubleClickInterval(300);
680 // install translation file for Qt built-in dialogs
681 QString language_name = QString("qt_") + QLocale::system().name();
683 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
684 // Short-named translator can be loaded from a long name, but not the
685 // opposite. Therefore, long name should be used without truncation.
686 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
687 if (d->qt_trans_.load(language_name,
688 QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
690 installTranslator(&d->qt_trans_);
691 // even if the language calls for RtL, don't do that
692 setLayoutDirection(Qt::LeftToRight);
693 LYXERR(Debug::GUI, "Successfully installed Qt translations for locale "
696 LYXERR(Debug::GUI, "Could not find Qt translations for locale "
700 // This allows to translate the strings that appear in the LyX menu.
701 /// A translator suitable for the entries in the LyX menu.
702 /// Only needed with Qt/Mac.
703 installTranslator(new MenuTranslator(this));
705 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
707 using namespace lyx::graphics;
709 Image::newImage = boost::bind(&GuiImage::newImage);
711 // needs to be done before reading lyxrc
713 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
717 // Set the cache to 5120 kilobytes which corresponds to screen size of
718 // 1280 by 1024 pixels with a color depth of 32 bits.
719 QPixmapCache::setCacheLimit(5120);
721 // Initialize RC Fonts
722 if (lyxrc.roman_font_name.empty())
723 lyxrc.roman_font_name = fromqstr(romanFontName());
725 if (lyxrc.sans_font_name.empty())
726 lyxrc.sans_font_name = fromqstr(sansFontName());
728 if (lyxrc.typewriter_font_name.empty())
729 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
731 d->general_timer_.setInterval(500);
732 connect(&d->general_timer_, SIGNAL(timeout()),
733 this, SLOT(handleRegularEvents()));
734 d->general_timer_.start();
738 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
740 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
745 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
751 case LFUN_WINDOW_CLOSE:
752 enable = d->views_.size() > 0;
755 case LFUN_BUFFER_NEW:
756 case LFUN_BUFFER_NEW_TEMPLATE:
758 case LFUN_SCREEN_FONT_UPDATE:
760 case LFUN_WINDOW_NEW:
770 flag.setEnabled(false);
776 bool GuiApplication::dispatch(FuncRequest const & cmd)
778 switch (cmd.action) {
780 case LFUN_WINDOW_NEW:
781 createView(toqstr(cmd.argument()));
784 case LFUN_WINDOW_CLOSE:
785 // update bookmark pit of the current buffer before window close
786 for (size_t i = 0; i < LyX::ref().session().bookmarks().size(); ++i)
787 theLyXFunc().gotoBookmark(i+1, false, false);
788 current_view_->close();
792 // quitting is triggered by the gui code
793 // (leaving the event loop).
795 current_view_->message(from_utf8(N_("Exiting.")));
800 case LFUN_SCREEN_FONT_UPDATE: {
801 // handle the screen font changes.
802 d->font_loader_.update();
803 // Backup current_view_
804 GuiView * view = current_view_;
805 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
806 // to skip the refresh.
808 BufferList::iterator it = theBufferList().begin();
809 BufferList::iterator const end = theBufferList().end();
810 for (; it != end; ++it)
812 // Restore current_view_
813 current_view_ = view;
817 case LFUN_BUFFER_NEW:
818 if (d->views_.empty()
819 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
820 createView(QString(), false); // keep hidden
821 current_view_->newDocument(to_utf8(cmd.argument()), false);
822 current_view_->show();
823 setActiveWindow(current_view_);
825 current_view_->newDocument(to_utf8(cmd.argument()), false);
829 case LFUN_BUFFER_NEW_TEMPLATE:
830 if (d->views_.empty()
831 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
833 current_view_->newDocument(to_utf8(cmd.argument()), true);
834 if (!current_view_->buffer())
835 current_view_->close();
837 current_view_->newDocument(to_utf8(cmd.argument()), true);
842 if (d->views_.empty()
843 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
844 string const fname = to_utf8(cmd.argument());
845 // We want the ui session to be saved per document and not per
846 // window number. The filename crc is a good enough identifier.
847 boost::crc_32_type crc;
848 crc = for_each(fname.begin(), fname.end(), crc);
849 createView(crc.checksum());
850 current_view_->openDocument(fname);
851 if (!current_view_->buffer())
852 current_view_->close();
854 current_view_->openDocument(to_utf8(cmd.argument()));
857 case LFUN_SET_COLOR: {
859 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
860 if (lyx_name.empty() || x11_name.empty()) {
861 current_view_->message(
862 _("Syntax: set-color <lyx_name> <x11_name>"));
866 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
867 bool const graphicsbg_changed = lyx_name == graphicsbg
868 && x11_name != graphicsbg;
869 if (graphicsbg_changed) {
870 // FIXME: The graphics cache no longer has a changeDisplay method.
872 graphics::GCache::get().changeDisplay(true);
876 if (!lcolor.setColor(lyx_name, x11_name)) {
877 current_view_->message(
878 bformat(_("Set-color \"%1$s\" failed "
879 "- color is undefined or "
880 "may not be redefined"),
881 from_utf8(lyx_name)));
884 // Make sure we don't keep old colors in cache.
885 d->color_cache_.clear();
890 // Notify the caller that the action has not been dispatched.
894 // The action has been dispatched.
899 void GuiApplication::resetGui()
901 QHash<int, GuiView *>::iterator it;
902 for (it = d->views_.begin(); it != d->views_.end(); ++it)
903 (*it)->resetDialogs();
905 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
909 void GuiApplication::createView(int view_id)
911 createView(QString(), true, view_id);
915 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
918 // release the keyboard which might have been grabed by the global
919 // menubar on Mac to catch shortcuts even without any GuiView.
920 if (d->global_menubar_)
921 d->global_menubar_->releaseKeyboard();
926 while (d->views_.find(id) != d->views_.end())
929 LYXERR(Debug::GUI, "About to create new window with ID " << id);
930 GuiView * view = new GuiView(id);
932 d->views_[id] = view;
936 setActiveWindow(view);
939 if (!geometry_arg.isEmpty()) {
943 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
944 re.indexIn(geometry_arg);
945 w = re.cap(1).toInt();
946 h = re.cap(2).toInt();
947 x = re.cap(3).toInt();
948 y = re.cap(4).toInt();
949 view->setGeometry(x, y, w, h);
953 setCurrentView(view);
957 Clipboard & GuiApplication::clipboard()
959 return d->clipboard_;
963 Selection & GuiApplication::selection()
965 return d->selection_;
969 FontLoader & GuiApplication::fontLoader()
971 return d->font_loader_;
975 Toolbars const & GuiApplication::toolbars() const
981 Toolbars & GuiApplication::toolbars()
987 Menus const & GuiApplication::menus() const
993 Menus & GuiApplication::menus()
999 QList<int> GuiApplication::viewIds() const
1001 return d->views_.keys();
1005 ColorCache & GuiApplication::colorCache()
1007 return d->color_cache_;
1011 int GuiApplication::exec()
1013 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1014 return QApplication::exec();
1018 void GuiApplication::exit(int status)
1020 QApplication::exit(status);
1024 void GuiApplication::execBatchCommands()
1026 // Set the language defined by the user.
1027 LyX::ref().setRcGuiLanguage();
1030 if (!readUIFile(toqstr(lyxrc.ui_file)))
1031 // Gives some error box here.
1034 // init the global menubar on Mac. This must be done after the session
1035 // was recovered to know the "last files".
1036 if (d->global_menubar_)
1037 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1039 LyX::ref().execBatchCommands();
1042 QAbstractItemModel * GuiApplication::languageModel()
1044 if (d->language_model_)
1045 return d->language_model_;
1047 QStandardItemModel * lang_model = new QStandardItemModel(this);
1048 lang_model->insertColumns(0, 1);
1050 Languages::const_iterator it = languages.begin();
1051 Languages::const_iterator end = languages.end();
1052 for (; it != end; ++it) {
1053 current_row = lang_model->rowCount();
1054 lang_model->insertRows(current_row, 1);
1055 QModelIndex item = lang_model->index(current_row, 0);
1056 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1057 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1059 d->language_model_ = new QSortFilterProxyModel(this);
1060 d->language_model_->setSourceModel(lang_model);
1061 #if QT_VERSION >= 0x040300
1062 d->language_model_->setSortLocaleAware(true);
1064 return d->language_model_;
1068 void GuiApplication::restoreGuiSession()
1070 if (!lyxrc.load_session)
1073 Session & session = LyX::ref().session();
1074 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1075 // do not add to the lastfile list since these files are restored from
1076 // last session, and should be already there (regular files), or should
1077 // not be added at all (help files).
1078 for_each(lastopened.begin(), lastopened.end(),
1079 bind(&GuiView::loadDocument, current_view_, _1, false));
1081 // clear this list to save a few bytes of RAM
1082 session.lastOpened().clear();
1086 QString const GuiApplication::romanFontName()
1089 font.setKerning(false);
1090 font.setStyleHint(QFont::Serif);
1091 font.setFamily("serif");
1093 return QFontInfo(font).family();
1097 QString const GuiApplication::sansFontName()
1100 font.setKerning(false);
1101 font.setStyleHint(QFont::SansSerif);
1102 font.setFamily("sans");
1104 return QFontInfo(font).family();
1108 QString const GuiApplication::typewriterFontName()
1111 font.setKerning(false);
1112 font.setStyleHint(QFont::TypeWriter);
1113 font.setFamily("monospace");
1115 return QFontInfo(font).family();
1119 void GuiApplication::handleRegularEvents()
1121 ForkedCallsController::handleCompletedProcesses();
1125 bool GuiApplication::event(QEvent * e)
1128 case QEvent::FileOpen: {
1129 // Open a file; this happens only on Mac OS X for now
1130 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1131 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1132 qstring_to_ucs4(foe->file())));
1137 return QApplication::event(e);
1142 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1145 return QApplication::notify(receiver, event);
1147 catch (ExceptionMessage const & e) {
1149 case ErrorException:
1150 LyX::cref().emergencyCleanup();
1151 setQuitOnLastWindowClosed(false);
1153 Alert::error(e.title_, e.details_);
1155 // Properly crash in debug mode in order to get a useful backtrace.
1158 // In release mode, try to exit gracefully.
1161 case BufferException: {
1162 Buffer * buf = current_view_->buffer();
1163 docstring details = e.details_ + '\n';
1164 details += theBufferList().emergencyWrite(buf);
1165 theBufferList().release(buf);
1166 details += "\n" + _("The current document was closed.");
1167 Alert::error(e.title_, details);
1170 case WarningException:
1171 Alert::warning(e.title_, e.details_);
1175 catch (exception const & e) {
1176 docstring s = _("LyX has caught an exception, it will now "
1177 "attempt to save all unsaved documents and exit."
1179 s += from_ascii(e.what());
1180 Alert::error(_("Software exception Detected"), s);
1181 LyX::cref().exit(1);
1184 docstring s = _("LyX has caught some really weird exception, it will "
1185 "now attempt to save all unsaved documents and exit.");
1186 Alert::error(_("Software exception Detected"), s);
1187 LyX::cref().exit(1);
1194 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1196 QColor const & qcol = d->color_cache_.get(col);
1197 if (!qcol.isValid()) {
1203 rgbcol.r = qcol.red();
1204 rgbcol.g = qcol.green();
1205 rgbcol.b = qcol.blue();
1210 string const GuiApplication::hexName(ColorCode col)
1212 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1216 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1218 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1219 d->socket_notifiers_[fd] = sn;
1220 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1224 void GuiApplication::socketDataReceived(int fd)
1226 d->socket_notifiers_[fd]->func_();
1230 void GuiApplication::unregisterSocketCallback(int fd)
1232 d->socket_notifiers_.take(fd)->setEnabled(false);
1236 void GuiApplication::commitData(QSessionManager & sm)
1238 /// The implementation is required to avoid an application exit
1239 /// when session state save is triggered by session manager.
1240 /// The default implementation sends a close event to all
1241 /// visible top level widgets when session managment allows
1243 /// We are changing that to close all wiew one by one.
1244 /// FIXME: verify if the default implementation is enough now.
1245 if (sm.allowsInteraction() && !closeAllViews())
1250 void GuiApplication::unregisterView(GuiView * gv)
1252 LASSERT(d->views_[gv->id()] == gv, /**/);
1253 d->views_.remove(gv->id());
1254 if (current_view_ == gv) {
1256 theLyXFunc().setLyXView(0);
1261 bool GuiApplication::closeAllViews()
1263 if (d->views_.empty())
1266 QList<GuiView *> views = d->views_.values();
1267 foreach (GuiView * view, views) {
1277 GuiView & GuiApplication::view(int id) const
1279 LASSERT(d->views_.contains(id), /**/);
1280 return *d->views_.value(id);
1284 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1286 QList<GuiView *> views = d->views_.values();
1287 foreach (GuiView * view, views)
1288 view->hideDialog(name, inset);
1292 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1294 Buffer const * buffer_ = 0;
1295 QHash<int, GuiView *>::iterator end = d->views_.end();
1296 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1297 if (Buffer const * ptr = (*it)->updateInset(inset))
1304 bool GuiApplication::searchMenu(FuncRequest const & func,
1305 docstring_list & names) const
1307 return d->menus_.searchMenu(func, names);
1311 bool GuiApplication::readUIFile(QString const & name, bool include)
1321 LexerKeyword uitags[] = {
1322 { "include", ui_include },
1323 { "menuset", ui_menuset },
1324 { "toolbars", ui_toolbars },
1325 { "toolbarset", ui_toolbarset }
1328 // Ensure that a file is read only once (prevents include loops)
1329 static QStringList uifiles;
1330 if (uifiles.contains(name)) {
1331 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1332 << "Is this an include loop?");
1336 LYXERR(Debug::INIT, "About to read " << name << "...");
1340 ui_path = libFileSearch("ui", name, "inc");
1341 if (ui_path.empty())
1342 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1344 ui_path = libFileSearch("ui", name, "ui");
1347 if (ui_path.empty()) {
1348 LYXERR(Debug::INIT, "Could not find " << name);
1349 Alert::warning(_("Could not find UI definition file"),
1350 bformat(_("Error while reading the configuration file\n%1$s.\n"
1351 "Please check your installation."), qstring_to_ucs4(name)));
1355 uifiles.push_back(name);
1357 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1359 lex.setFile(ui_path);
1361 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1365 if (lyxerr.debugging(Debug::PARSER))
1366 lex.printTable(lyxerr);
1368 while (lex.isOK()) {
1369 switch (lex.lex()) {
1372 QString const file = toqstr(lex.getString());
1373 if (!readUIFile(file, true))
1378 d->menus_.read(lex);
1382 d->toolbars_.readToolbars(lex);
1386 d->toolbars_.readToolbarSettings(lex);
1390 if (!rtrim(lex.getString()).empty())
1391 lex.printError("LyX::ReadUIFile: "
1392 "Unknown menu tag: `$$Token'");
1400 void GuiApplication::onLastWindowClosed()
1402 if (d->global_menubar_)
1403 d->global_menubar_->grabKeyboard();
1407 ////////////////////////////////////////////////////////////////////////
1409 // X11 specific stuff goes here...
1412 bool GuiApplication::x11EventFilter(XEvent * xev)
1417 switch (xev->type) {
1418 case SelectionRequest: {
1419 if (xev->xselectionrequest.selection != XA_PRIMARY)
1421 LYXERR(Debug::GUI, "X requested selection.");
1422 BufferView * bv = current_view_->view();
1424 docstring const sel = bv->requestSelection();
1426 d->selection_.put(sel);
1430 case SelectionClear: {
1431 if (xev->xselectionclear.selection != XA_PRIMARY)
1433 LYXERR(Debug::GUI, "Lost selection.");
1434 BufferView * bv = current_view_->view();
1436 bv->clearSelection();
1444 } // namespace frontend
1447 void hideDialogs(std::string const & name, Inset * inset)
1450 theApp()->hideDialogs(name, inset);
1454 ////////////////////////////////////////////////////////////////////
1458 ////////////////////////////////////////////////////////////////////
1460 frontend::FontLoader & theFontLoader()
1462 LASSERT(frontend::guiApp, /**/);
1463 return frontend::guiApp->fontLoader();
1467 frontend::FontMetrics const & theFontMetrics(Font const & f)
1469 return theFontMetrics(f.fontInfo());
1473 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1475 LASSERT(frontend::guiApp, /**/);
1476 return frontend::guiApp->fontLoader().metrics(f);
1480 ////////////////////////////////////////////////////////////////////
1484 ////////////////////////////////////////////////////////////////////
1486 frontend::Clipboard & theClipboard()
1488 LASSERT(frontend::guiApp, /**/);
1489 return frontend::guiApp->clipboard();
1493 frontend::Selection & theSelection()
1495 LASSERT(frontend::guiApp, /**/);
1496 return frontend::guiApp->selection();
1501 #include "GuiApplication_moc.cpp"