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/Messages.h"
58 #include "support/os.h"
59 #include "support/Package.h"
62 #include "support/linkback/LinkBackProxy.h"
70 #include <QFileOpenEvent>
74 #include <QImageReader>
76 #include <QLibraryInfo>
78 #include <QMacPasteboardMime>
83 #include <QPixmapCache>
85 #include <QSessionManager>
87 #include <QSocketNotifier>
88 #include <QSortFilterProxyModel>
89 #include <QStandardItemModel>
92 #include <QTranslator>
96 #include <X11/Xatom.h>
103 #include <QWindowsMime>
104 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
110 #include <boost/bind.hpp>
111 #include <boost/crc.hpp>
117 using namespace lyx::support;
120 static void initializeResources()
122 static bool initialized = false;
124 Q_INIT_RESOURCE(Resources);
132 frontend::Application * createApplication(int & argc, char * argv[])
134 return new frontend::GuiApplication(argc, argv);
140 /// Return the list of loadable formats.
141 vector<string> loadableImageFormats()
145 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
147 LYXERR(Debug::GRAPHICS,
148 "\nThe image loader can load the following directly:\n");
150 if (qt_formats.empty())
151 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
153 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
155 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
157 string ext = ascii_lowercase((const char *) *it);
167 ////////////////////////////////////////////////////////////////////////
168 // Icon loading support code.
169 ////////////////////////////////////////////////////////////////////////
179 bool operator<(PngMap const & lhs, PngMap const & rhs)
181 return lhs.key < rhs.key;
187 CompareKey(QString const & name) : name_(name) {}
188 bool operator()(PngMap const & other) const { return other.key == name_; }
194 // this must be sorted alphabetically
195 // Upper case comes before lower case
196 PngMap sorted_png_map[] = {
197 { "Bumpeq", "bumpeq2" },
200 { "Delta", "delta2" },
201 { "Downarrow", "downarrow2" },
202 { "Gamma", "gamma2" },
203 { "Lambda", "lambda2" },
204 { "Leftarrow", "leftarrow2" },
205 { "Leftrightarrow", "leftrightarrow2" },
206 { "Longleftarrow", "longleftarrow2" },
207 { "Longleftrightarrow", "longleftrightarrow2" },
208 { "Longrightarrow", "longrightarrow2" },
209 { "Omega", "omega2" },
213 { "Rightarrow", "rightarrow2" },
214 { "Sigma", "sigma2" },
215 { "Subset", "subset2" },
216 { "Supset", "supset2" },
217 { "Theta", "theta2" },
218 { "Uparrow", "uparrow2" },
219 { "Updownarrow", "updownarrow2" },
220 { "Upsilon", "upsilon2" },
221 { "Vdash", "vdash3" },
224 { "nLeftarrow", "nleftarrow2" },
225 { "nLeftrightarrow", "nleftrightarrow2" },
226 { "nRightarrow", "nrightarrow2" },
227 { "nVDash", "nvdash3" },
228 { "nvDash", "nvdash2" },
229 { "textrm \\AA", "textrm_AA"},
230 { "textrm \\O", "textrm_O"},
231 { "vDash", "vdash2" }
234 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
237 QString findPng(QString const & name)
239 PngMap const * const begin = sorted_png_map;
240 PngMap const * const end = begin + nr_sorted_png_map;
241 LASSERT(sorted(begin, end), /**/);
243 PngMap const * const it = find_if(begin, end, CompareKey(name));
247 png_name = it->value;
250 png_name.replace('_', "underscore");
251 png_name.replace(' ', '_');
253 // This way we can have "math-delim { }" on the toolbar.
254 png_name.replace('(', "lparen");
255 png_name.replace(')', "rparen");
256 png_name.replace('[', "lbracket");
257 png_name.replace(']', "rbracket");
258 png_name.replace('{', "lbrace");
259 png_name.replace('}', "rbrace");
260 png_name.replace('|', "bars");
261 png_name.replace(',', "thinspace");
262 png_name.replace(':', "mediumspace");
263 png_name.replace(';', "thickspace");
264 png_name.replace('!', "negthinspace");
267 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
268 << "Looking for math PNG called \"" << png_name << '"');
275 QString iconName(FuncRequest const & f, bool unknown)
277 initializeResources();
282 case LFUN_MATH_INSERT:
283 if (!f.argument().empty()) {
285 name1 = findPng(toqstr(f.argument()).mid(1));
288 case LFUN_MATH_DELIM:
289 case LFUN_MATH_BIGDELIM:
291 name1 = findPng(toqstr(f.argument()));
295 name1 = toqstr(f.argument());
298 name2 = toqstr(lyxaction.getActionName(f.action));
301 if (!f.argument().empty()) {
302 name1 = name2 + ' ' + toqstr(f.argument());
303 name1.replace(' ', '_');
307 FileName fname = libFileSearch("images/" + path, name1, "png");
309 return toqstr(fname.absFilename());
311 fname = libFileSearch("images/" + path, name2, "png");
313 return toqstr(fname.absFilename());
315 path = ":/images/" + path;
318 LYXERR0("Directory " << path << " not found in resource!");
322 if (res.exists(name1))
326 if (res.exists(name2))
329 LYXERR(Debug::GUI, "Cannot find icon for command \""
330 << lyxaction.getActionName(f.action)
331 << '(' << to_utf8(f.argument()) << ")\"");
334 return QString(":/images/unknown.png");
340 QIcon getIcon(FuncRequest const & f, bool unknown)
342 QString icon = iconName(f, unknown);
346 //LYXERR(Debug::GUI, "Found icon: " << icon);
348 if (!pm.load(icon)) {
349 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
357 ////////////////////////////////////////////////////////////////////////
358 // LyX server support code.
359 ////////////////////////////////////////////////////////////////////////
360 class SocketNotifier : public QSocketNotifier
363 /// connect a connection notification from the LyXServerSocket
364 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
365 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
369 /// The callback function
370 Application::SocketCallback func_;
374 ////////////////////////////////////////////////////////////////////////
375 // Mac specific stuff goes here...
376 ////////////////////////////////////////////////////////////////////////
378 class MenuTranslator : public QTranslator
381 MenuTranslator(QObject * parent)
382 : QTranslator(parent)
385 QString translate(const char * /*context*/,
386 const char * sourceText,
387 const char * /*comment*/ = 0)
389 string const s = sourceText;
390 if (s == N_("About %1") || s == N_("Preferences")
391 || s == N_("Reconfigure") || s == N_("Quit %1"))
398 class GlobalMenuBar : public QMenuBar
402 GlobalMenuBar() : QMenuBar(0) {}
405 bool event(QEvent * e)
407 if (e->type() == QEvent::ShortcutOverride) {
408 // && activeWindow() == 0) {
409 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
411 setKeySymbol(&sym, ke);
412 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
421 // QMacPasteboardMimeGraphics can only be compiled on Mac.
423 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
426 QMacPasteboardMimeGraphics()
427 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
430 QString convertorName() { return "Graphics"; }
432 QString flavorFor(QString const & mime)
434 LYXERR(Debug::ACTION, "flavorFor " << mime);
435 if (mime == pdfMimeType())
436 return QLatin1String("com.adobe.pdf");
440 QString mimeFor(QString flav)
442 LYXERR(Debug::ACTION, "mimeFor " << flav);
443 if (flav == QLatin1String("com.adobe.pdf"))
444 return pdfMimeType();
448 bool canConvert(QString const & mime, QString flav)
450 return mimeFor(flav) == mime;
453 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
457 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
461 QList<QByteArray> convertFromMime(QString const & /*mime*/,
462 QVariant data, QString /*flav*/)
464 QList<QByteArray> ret;
465 ret.append(data.toByteArray());
471 ///////////////////////////////////////////////////////////////
472 // You can find more platform specific stuff
473 // at the end of this file...
474 ///////////////////////////////////////////////////////////////
476 ////////////////////////////////////////////////////////////////////////
477 // Windows specific stuff goes here...
480 // QWindowsMimeMetafile can only be compiled on Windows.
482 static FORMATETC cfFromMime(QString const & mimetype)
485 if (mimetype == emfMimeType()) {
486 formatetc.cfFormat = CF_ENHMETAFILE;
487 formatetc.tymed = TYMED_ENHMF;
488 } else if (mimetype == wmfMimeType()) {
489 formatetc.cfFormat = CF_METAFILEPICT;
490 formatetc.tymed = TYMED_MFPICT;
493 formatetc.dwAspect = DVASPECT_CONTENT;
494 formatetc.lindex = -1;
499 class QWindowsMimeMetafile : public QWindowsMime {
501 QWindowsMimeMetafile() {}
503 bool canConvertFromMime(FORMATETC const & formatetc,
504 QMimeData const * mimedata) const
509 bool canConvertToMime(QString const & mimetype,
510 IDataObject * pDataObj) const
512 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
514 FORMATETC formatetc = cfFromMime(mimetype);
515 return pDataObj->QueryGetData(&formatetc) == S_OK;
518 bool convertFromMime(FORMATETC const & formatetc,
519 const QMimeData * mimedata, STGMEDIUM * pmedium) const
524 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
525 QVariant::Type preferredType) const
528 if (!canConvertToMime(mimetype, pDataObj))
531 FORMATETC formatetc = cfFromMime(mimetype);
533 if (pDataObj->GetData(&formatetc, &s) != S_OK)
537 if (s.tymed == TYMED_ENHMF) {
538 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
539 data.resize(dataSize);
540 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
541 (LPBYTE)data.data());
542 } else if (s.tymed == TYMED_MFPICT) {
543 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
544 data.resize(dataSize);
545 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
546 (LPBYTE)data.data());
549 ReleaseStgMedium(&s);
555 QVector<FORMATETC> formatsForMime(QString const & mimeType,
556 QMimeData const * mimeData) const
558 QVector<FORMATETC> formats;
559 formats += cfFromMime(mimeType);
563 QString mimeForFormat(FORMATETC const & formatetc) const
565 switch (formatetc.cfFormat) {
567 return emfMimeType();
568 case CF_METAFILEPICT:
569 return wmfMimeType();
577 ////////////////////////////////////////////////////////////////////////
578 // GuiApplication::Private definition and implementation.
579 ////////////////////////////////////////////////////////////////////////
581 struct GuiApplication::Private
584 : language_model_(0), global_menubar_(0)
587 // Create the global default menubar which is shown for the dialogs
588 // and if no GuiView is visible.
589 global_menubar_ = new GlobalMenuBar();
594 QSortFilterProxyModel * language_model_;
596 GuiClipboard clipboard_;
598 GuiSelection selection_;
600 FontLoader font_loader_;
602 ColorCache color_cache_;
604 QTranslator qt_trans_;
606 QHash<int, SocketNotifier *> socket_notifiers_;
610 /// The global instance
613 /// this timer is used for any regular events one wants to
614 /// perform. at present it is used to check if forked processes
616 QTimer general_timer_;
618 /// Multiple views container.
620 * Warning: This must not be a smart pointer as the destruction of the
621 * object is handled by Qt when the view is closed
622 * \sa Qt::WA_DeleteOnClose attribute.
624 QHash<int, GuiView *> views_;
626 /// Only used on mac.
627 GlobalMenuBar * global_menubar_;
630 /// Linkback mime handler for MacOSX.
631 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
635 /// WMF Mime handler for Windows clipboard.
636 /// \warning: see comment in ~GuiApplication and in bug 4846.
637 QWindowsMimeMetafile wmf_mime_;
642 GuiApplication * guiApp;
644 GuiApplication::~GuiApplication()
647 closeAllLinkBackLinks();
649 // FIXME: Work around bug 4846 for Windows Vista and Qt4
650 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
651 // If the clipboard is not cleared, LyX crashes on exit when it is
652 // compiled in release mode and if there is something in the clipboard.
653 // This is related to QWindowsMimeMetafile which is apparently not
654 // properly destroyed.
655 qApp->clipboard()->clear(QClipboard::Clipboard);
660 GuiApplication::GuiApplication(int & argc, char ** argv)
661 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
663 QString app_name = "LyX";
664 QCoreApplication::setOrganizationName(app_name);
665 QCoreApplication::setOrganizationDomain("lyx.org");
666 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
668 // Install translator for GUI elements.
669 installTranslator(&d->qt_trans_);
671 // FIXME: quitOnLastWindowClosed is true by default. We should have a
672 // lyxrc setting for this in order to let the application stay resident.
673 // But then we need some kind of dock icon, at least on Windows.
675 if (lyxrc.quit_on_last_window_closed)
676 setQuitOnLastWindowClosed(false);
679 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
680 // seems to be the default case for applications like LyX.
681 setQuitOnLastWindowClosed(false);
683 // This allows to translate the strings that appear in the LyX menu.
684 /// A translator suitable for the entries in the LyX menu.
685 /// Only needed with Qt/Mac.
686 installTranslator(new MenuTranslator(this));
690 // doubleClickInterval() is 400 ms on X11 which is just too long.
691 // On Windows and Mac OS X, the operating system's value is used.
692 // On Microsoft Windows, calling this function sets the double
693 // click interval for all applications. So we don't!
694 QApplication::setDoubleClickInterval(300);
697 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
699 // needs to be done before reading lyxrc
701 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
705 // Set the cache to 5120 kilobytes which corresponds to screen size of
706 // 1280 by 1024 pixels with a color depth of 32 bits.
707 QPixmapCache::setCacheLimit(5120);
709 // Initialize RC Fonts
710 if (lyxrc.roman_font_name.empty())
711 lyxrc.roman_font_name = fromqstr(romanFontName());
713 if (lyxrc.sans_font_name.empty())
714 lyxrc.sans_font_name = fromqstr(sansFontName());
716 if (lyxrc.typewriter_font_name.empty())
717 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
719 d->general_timer_.setInterval(500);
720 connect(&d->general_timer_, SIGNAL(timeout()),
721 this, SLOT(handleRegularEvents()));
722 d->general_timer_.start();
726 void GuiApplication::clearSession()
733 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
735 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
740 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
746 case LFUN_WINDOW_CLOSE:
747 enable = d->views_.size() > 0;
750 case LFUN_BUFFER_NEW:
751 case LFUN_BUFFER_NEW_TEMPLATE:
753 case LFUN_SCREEN_FONT_UPDATE:
755 case LFUN_WINDOW_NEW:
765 flag.setEnabled(false);
771 bool GuiApplication::dispatch(FuncRequest const & cmd)
773 switch (cmd.action) {
775 case LFUN_WINDOW_NEW:
776 createView(toqstr(cmd.argument()));
779 case LFUN_WINDOW_CLOSE:
780 // update bookmark pit of the current buffer before window close
781 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
782 theLyXFunc().gotoBookmark(i+1, false, false);
783 current_view_->close();
787 // quitting is triggered by the gui code
788 // (leaving the event loop).
790 current_view_->message(from_utf8(N_("Exiting.")));
795 case LFUN_SCREEN_FONT_UPDATE: {
796 // handle the screen font changes.
797 d->font_loader_.update();
798 // Backup current_view_
799 GuiView * view = current_view_;
800 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
801 // to skip the refresh.
803 BufferList::iterator it = theBufferList().begin();
804 BufferList::iterator const end = theBufferList().end();
805 for (; it != end; ++it)
807 // Restore current_view_
808 current_view_ = view;
812 case LFUN_BUFFER_NEW:
813 if (d->views_.empty()
814 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
815 createView(QString(), false); // keep hidden
816 current_view_->newDocument(to_utf8(cmd.argument()), false);
817 current_view_->show();
818 setActiveWindow(current_view_);
820 current_view_->newDocument(to_utf8(cmd.argument()), false);
824 case LFUN_BUFFER_NEW_TEMPLATE:
825 if (d->views_.empty()
826 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
828 current_view_->newDocument(to_utf8(cmd.argument()), true);
829 if (!current_view_->buffer())
830 current_view_->close();
832 current_view_->newDocument(to_utf8(cmd.argument()), true);
837 if (d->views_.empty()
838 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
839 string const fname = to_utf8(cmd.argument());
840 // We want the ui session to be saved per document and not per
841 // window number. The filename crc is a good enough identifier.
842 boost::crc_32_type crc;
843 crc = for_each(fname.begin(), fname.end(), crc);
844 createView(crc.checksum());
845 current_view_->openDocument(fname);
846 if (!current_view_->buffer())
847 current_view_->close();
849 current_view_->openDocument(to_utf8(cmd.argument()));
852 case LFUN_SET_COLOR: {
854 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
855 if (lyx_name.empty() || x11_name.empty()) {
856 current_view_->message(
857 _("Syntax: set-color <lyx_name> <x11_name>"));
861 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
862 bool const graphicsbg_changed = lyx_name == graphicsbg
863 && x11_name != graphicsbg;
864 if (graphicsbg_changed) {
865 // FIXME: The graphics cache no longer has a changeDisplay method.
867 graphics::GCache::get().changeDisplay(true);
871 if (!lcolor.setColor(lyx_name, x11_name)) {
872 current_view_->message(
873 bformat(_("Set-color \"%1$s\" failed "
874 "- color is undefined or "
875 "may not be redefined"),
876 from_utf8(lyx_name)));
879 // Make sure we don't keep old colors in cache.
880 d->color_cache_.clear();
885 // Notify the caller that the action has not been dispatched.
889 // The action has been dispatched.
894 void GuiApplication::resetGui()
896 // Set the language defined by the user.
900 if (!readUIFile(toqstr(lyxrc.ui_file)))
901 // Gives some error box here.
905 d->global_menubar_->clear();
906 delete d->global_menubar_;
907 // Create the global default menubar which is shown for the dialogs
908 // and if no GuiView is visible.
909 d->global_menubar_ = new GlobalMenuBar();
911 // init the global menubar on Mac. This must be done after the session
912 // was recovered to know the "last files".
913 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
916 QHash<int, GuiView *>::iterator it;
917 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
919 gv->setLayoutDirection(layoutDirection());
923 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
927 void GuiApplication::createView(int view_id)
929 createView(QString(), true, view_id);
933 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
936 // release the keyboard which might have been grabed by the global
937 // menubar on Mac to catch shortcuts even without any GuiView.
938 if (d->global_menubar_)
939 d->global_menubar_->releaseKeyboard();
944 while (d->views_.find(id) != d->views_.end())
947 LYXERR(Debug::GUI, "About to create new window with ID " << id);
948 GuiView * view = new GuiView(id);
950 d->views_[id] = view;
954 setActiveWindow(view);
957 if (!geometry_arg.isEmpty()) {
961 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
962 re.indexIn(geometry_arg);
963 w = re.cap(1).toInt();
964 h = re.cap(2).toInt();
965 x = re.cap(3).toInt();
966 y = re.cap(4).toInt();
967 view->setGeometry(x, y, w, h);
974 Clipboard & GuiApplication::clipboard()
976 return d->clipboard_;
980 Selection & GuiApplication::selection()
982 return d->selection_;
986 FontLoader & GuiApplication::fontLoader()
988 return d->font_loader_;
992 Toolbars const & GuiApplication::toolbars() const
998 Toolbars & GuiApplication::toolbars()
1000 return d->toolbars_;
1004 Menus const & GuiApplication::menus() const
1010 Menus & GuiApplication::menus()
1016 QList<int> GuiApplication::viewIds() const
1018 return d->views_.keys();
1022 ColorCache & GuiApplication::colorCache()
1024 return d->color_cache_;
1028 int GuiApplication::exec()
1030 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1031 return QApplication::exec();
1035 void GuiApplication::exit(int status)
1037 QApplication::exit(status);
1041 void GuiApplication::setGuiLanguage()
1043 // Set the language defined by the user.
1046 QString const default_language = toqstr(Messages::defaultLanguage());
1047 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1048 QLocale const default_locale(default_language);
1049 QLocale::setDefault(default_locale);
1051 // install translation file for Qt built-in dialogs
1052 QString const language_name = QString("qt_") + default_locale.name();
1054 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1055 // Short-named translator can be loaded from a long name, but not the
1056 // opposite. Therefore, long name should be used without truncation.
1057 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1058 if (!d->qt_trans_.load(language_name,
1059 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1060 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1063 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1067 switch (default_locale.language()) {
1068 case QLocale::Arabic :
1069 case QLocale::Hebrew :
1070 case QLocale::Persian :
1071 case QLocale::Urdu :
1072 setLayoutDirection(Qt::RightToLeft);
1075 setLayoutDirection(Qt::LeftToRight);
1080 void GuiApplication::execBatchCommands()
1085 if (!readUIFile(toqstr(lyxrc.ui_file)))
1086 // Gives some error box here.
1089 // init the global menubar on Mac. This must be done after the session
1090 // was recovered to know the "last files".
1091 if (d->global_menubar_)
1092 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1094 lyx::execBatchCommands();
1098 QAbstractItemModel * GuiApplication::languageModel()
1100 if (d->language_model_)
1101 return d->language_model_;
1103 QStandardItemModel * lang_model = new QStandardItemModel(this);
1104 lang_model->insertColumns(0, 1);
1106 Languages::const_iterator it = languages.begin();
1107 Languages::const_iterator end = languages.end();
1108 for (; it != end; ++it) {
1109 current_row = lang_model->rowCount();
1110 lang_model->insertRows(current_row, 1);
1111 QModelIndex item = lang_model->index(current_row, 0);
1112 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1113 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1115 d->language_model_ = new QSortFilterProxyModel(this);
1116 d->language_model_->setSourceModel(lang_model);
1117 #if QT_VERSION >= 0x040300
1118 d->language_model_->setSortLocaleAware(true);
1120 return d->language_model_;
1124 void GuiApplication::restoreGuiSession()
1126 if (!lyxrc.load_session)
1129 Session & session = theSession();
1130 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1131 // do not add to the lastfile list since these files are restored from
1132 // last session, and should be already there (regular files), or should
1133 // not be added at all (help files).
1134 for_each(lastopened.begin(), lastopened.end(),
1135 bind(&GuiView::loadDocument, current_view_, _1, false));
1137 // clear this list to save a few bytes of RAM
1138 session.lastOpened().clear();
1142 QString const GuiApplication::romanFontName()
1145 font.setKerning(false);
1146 font.setStyleHint(QFont::Serif);
1147 font.setFamily("serif");
1149 return QFontInfo(font).family();
1153 QString const GuiApplication::sansFontName()
1156 font.setKerning(false);
1157 font.setStyleHint(QFont::SansSerif);
1158 font.setFamily("sans");
1160 return QFontInfo(font).family();
1164 QString const GuiApplication::typewriterFontName()
1167 font.setKerning(false);
1168 font.setStyleHint(QFont::TypeWriter);
1169 font.setFamily("monospace");
1171 return QFontInfo(font).family();
1175 void GuiApplication::handleRegularEvents()
1177 ForkedCallsController::handleCompletedProcesses();
1181 bool GuiApplication::event(QEvent * e)
1184 case QEvent::FileOpen: {
1185 // Open a file; this happens only on Mac OS X for now
1186 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1187 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1188 qstring_to_ucs4(foe->file())));
1193 return QApplication::event(e);
1198 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1201 return QApplication::notify(receiver, event);
1203 catch (ExceptionMessage const & e) {
1205 case ErrorException:
1207 setQuitOnLastWindowClosed(false);
1209 Alert::error(e.title_, e.details_);
1211 // Properly crash in debug mode in order to get a useful backtrace.
1214 // In release mode, try to exit gracefully.
1217 case BufferException: {
1218 Buffer * buf = current_view_->buffer();
1219 docstring details = e.details_ + '\n';
1220 details += theBufferList().emergencyWrite(buf);
1221 theBufferList().release(buf);
1222 details += "\n" + _("The current document was closed.");
1223 Alert::error(e.title_, details);
1226 case WarningException:
1227 Alert::warning(e.title_, e.details_);
1231 catch (exception const & e) {
1232 docstring s = _("LyX has caught an exception, it will now "
1233 "attempt to save all unsaved documents and exit."
1235 s += from_ascii(e.what());
1236 Alert::error(_("Software exception Detected"), s);
1240 docstring s = _("LyX has caught some really weird exception, it will "
1241 "now attempt to save all unsaved documents and exit.");
1242 Alert::error(_("Software exception Detected"), s);
1250 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1252 QColor const & qcol = d->color_cache_.get(col);
1253 if (!qcol.isValid()) {
1259 rgbcol.r = qcol.red();
1260 rgbcol.g = qcol.green();
1261 rgbcol.b = qcol.blue();
1266 string const GuiApplication::hexName(ColorCode col)
1268 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1272 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1274 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1275 d->socket_notifiers_[fd] = sn;
1276 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1280 void GuiApplication::socketDataReceived(int fd)
1282 d->socket_notifiers_[fd]->func_();
1286 void GuiApplication::unregisterSocketCallback(int fd)
1288 d->socket_notifiers_.take(fd)->setEnabled(false);
1292 void GuiApplication::commitData(QSessionManager & sm)
1294 /// The implementation is required to avoid an application exit
1295 /// when session state save is triggered by session manager.
1296 /// The default implementation sends a close event to all
1297 /// visible top level widgets when session managment allows
1299 /// We are changing that to close all wiew one by one.
1300 /// FIXME: verify if the default implementation is enough now.
1301 if (sm.allowsInteraction() && !closeAllViews())
1306 void GuiApplication::unregisterView(GuiView * gv)
1308 LASSERT(d->views_[gv->id()] == gv, /**/);
1309 d->views_.remove(gv->id());
1310 if (current_view_ == gv) {
1312 theLyXFunc().setLyXView(0);
1317 bool GuiApplication::closeAllViews()
1319 if (d->views_.empty())
1322 QList<GuiView *> views = d->views_.values();
1323 foreach (GuiView * view, views) {
1333 GuiView & GuiApplication::view(int id) const
1335 LASSERT(d->views_.contains(id), /**/);
1336 return *d->views_.value(id);
1340 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1342 QList<GuiView *> views = d->views_.values();
1343 foreach (GuiView * view, views)
1344 view->hideDialog(name, inset);
1348 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1350 Buffer const * buffer_ = 0;
1351 QHash<int, GuiView *>::iterator end = d->views_.end();
1352 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1353 if (Buffer const * ptr = (*it)->updateInset(inset))
1360 bool GuiApplication::searchMenu(FuncRequest const & func,
1361 docstring_list & names) const
1363 return d->menus_.searchMenu(func, names);
1367 bool GuiApplication::readUIFile(QString const & name, bool include)
1377 LexerKeyword uitags[] = {
1378 { "include", ui_include },
1379 { "menuset", ui_menuset },
1380 { "toolbars", ui_toolbars },
1381 { "toolbarset", ui_toolbarset }
1384 LYXERR(Debug::INIT, "About to read " << name << "...");
1388 ui_path = libFileSearch("ui", name, "inc");
1389 if (ui_path.empty())
1390 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1392 ui_path = libFileSearch("ui", name, "ui");
1395 if (ui_path.empty()) {
1396 LYXERR(Debug::INIT, "Could not find " << name);
1397 Alert::warning(_("Could not find UI definition file"),
1398 bformat(_("Error while reading the configuration file\n%1$s.\n"
1399 "Please check your installation."), qstring_to_ucs4(name)));
1404 // Ensure that a file is read only once (prevents include loops)
1405 static QStringList uifiles;
1406 QString const uifile = toqstr(ui_path.absFilename());
1407 if (uifiles.contains(uifile)) {
1409 // We are reading again the top uifile so reset the safeguard:
1412 d->toolbars_.reset();
1414 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1415 << "Is this an include loop?");
1419 uifiles.push_back(uifile);
1421 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1424 lex.setFile(ui_path);
1426 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1430 if (lyxerr.debugging(Debug::PARSER))
1431 lex.printTable(lyxerr);
1433 while (lex.isOK()) {
1434 switch (lex.lex()) {
1437 QString const file = toqstr(lex.getString());
1438 if (!readUIFile(file, true))
1443 d->menus_.read(lex);
1447 d->toolbars_.readToolbars(lex);
1451 d->toolbars_.readToolbarSettings(lex);
1455 if (!rtrim(lex.getString()).empty())
1456 lex.printError("LyX::ReadUIFile: "
1457 "Unknown menu tag: `$$Token'");
1466 settings.beginGroup("ui_files");
1467 bool touched = false;
1468 for (int i = 0; i != uifiles.size(); ++i) {
1469 QFileInfo fi(uifiles[i]);
1470 QDateTime const date_value = fi.lastModified();
1471 QString const name_key = QString::number(i);
1472 if (!settings.contains(name_key)
1473 || settings.value(name_key).toString() != uifiles[i]
1474 || settings.value(name_key + "/date").toDateTime() != date_value) {
1476 settings.setValue(name_key, uifiles[i]);
1477 settings.setValue(name_key + "/date", date_value);
1480 settings.endGroup();
1482 settings.remove("views");
1488 void GuiApplication::onLastWindowClosed()
1490 if (d->global_menubar_)
1491 d->global_menubar_->grabKeyboard();
1495 ////////////////////////////////////////////////////////////////////////
1497 // X11 specific stuff goes here...
1500 bool GuiApplication::x11EventFilter(XEvent * xev)
1505 switch (xev->type) {
1506 case SelectionRequest: {
1507 if (xev->xselectionrequest.selection != XA_PRIMARY)
1509 LYXERR(Debug::SELECTION, "X requested selection.");
1510 BufferView * bv = current_view_->view();
1512 docstring const sel = bv->requestSelection();
1514 d->selection_.put(sel);
1518 case SelectionClear: {
1519 if (xev->xselectionclear.selection != XA_PRIMARY)
1521 LYXERR(Debug::SELECTION, "Lost selection.");
1522 BufferView * bv = current_view_->view();
1524 bv->clearSelection();
1532 } // namespace frontend
1535 void hideDialogs(std::string const & name, Inset * inset)
1538 theApp()->hideDialogs(name, inset);
1542 ////////////////////////////////////////////////////////////////////
1546 ////////////////////////////////////////////////////////////////////
1548 frontend::FontLoader & theFontLoader()
1550 LASSERT(frontend::guiApp, /**/);
1551 return frontend::guiApp->fontLoader();
1555 frontend::FontMetrics const & theFontMetrics(Font const & f)
1557 return theFontMetrics(f.fontInfo());
1561 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1563 LASSERT(frontend::guiApp, /**/);
1564 return frontend::guiApp->fontLoader().metrics(f);
1568 ////////////////////////////////////////////////////////////////////
1572 ////////////////////////////////////////////////////////////////////
1574 frontend::Clipboard & theClipboard()
1576 LASSERT(frontend::guiApp, /**/);
1577 return frontend::guiApp->clipboard();
1581 frontend::Selection & theSelection()
1583 LASSERT(frontend::guiApp, /**/);
1584 return frontend::guiApp->selection();
1589 #include "GuiApplication_moc.cpp"