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);
971 setCurrentView(view);
975 Clipboard & GuiApplication::clipboard()
977 return d->clipboard_;
981 Selection & GuiApplication::selection()
983 return d->selection_;
987 FontLoader & GuiApplication::fontLoader()
989 return d->font_loader_;
993 Toolbars const & GuiApplication::toolbars() const
999 Toolbars & GuiApplication::toolbars()
1001 return d->toolbars_;
1005 Menus const & GuiApplication::menus() const
1011 Menus & GuiApplication::menus()
1017 QList<int> GuiApplication::viewIds() const
1019 return d->views_.keys();
1023 ColorCache & GuiApplication::colorCache()
1025 return d->color_cache_;
1029 int GuiApplication::exec()
1031 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1032 return QApplication::exec();
1036 void GuiApplication::exit(int status)
1038 QApplication::exit(status);
1042 void GuiApplication::setGuiLanguage()
1044 // Set the language defined by the user.
1047 QString const default_language = toqstr(Messages::defaultLanguage());
1048 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1049 QLocale const default_locale(default_language);
1050 QLocale::setDefault(default_locale);
1052 // install translation file for Qt built-in dialogs
1053 QString const language_name = QString("qt_") + default_locale.name();
1055 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1056 // Short-named translator can be loaded from a long name, but not the
1057 // opposite. Therefore, long name should be used without truncation.
1058 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1059 if (!d->qt_trans_.load(language_name,
1060 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1061 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1064 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1068 switch (default_locale.language()) {
1069 case QLocale::Arabic :
1070 case QLocale::Hebrew :
1071 case QLocale::Persian :
1072 case QLocale::Urdu :
1073 setLayoutDirection(Qt::RightToLeft);
1076 setLayoutDirection(Qt::LeftToRight);
1081 void GuiApplication::execBatchCommands()
1086 if (!readUIFile(toqstr(lyxrc.ui_file)))
1087 // Gives some error box here.
1090 // init the global menubar on Mac. This must be done after the session
1091 // was recovered to know the "last files".
1092 if (d->global_menubar_)
1093 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1095 lyx::execBatchCommands();
1099 QAbstractItemModel * GuiApplication::languageModel()
1101 if (d->language_model_)
1102 return d->language_model_;
1104 QStandardItemModel * lang_model = new QStandardItemModel(this);
1105 lang_model->insertColumns(0, 1);
1107 Languages::const_iterator it = languages.begin();
1108 Languages::const_iterator end = languages.end();
1109 for (; it != end; ++it) {
1110 current_row = lang_model->rowCount();
1111 lang_model->insertRows(current_row, 1);
1112 QModelIndex item = lang_model->index(current_row, 0);
1113 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1114 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1116 d->language_model_ = new QSortFilterProxyModel(this);
1117 d->language_model_->setSourceModel(lang_model);
1118 #if QT_VERSION >= 0x040300
1119 d->language_model_->setSortLocaleAware(true);
1121 return d->language_model_;
1125 void GuiApplication::restoreGuiSession()
1127 if (!lyxrc.load_session)
1130 Session & session = theSession();
1131 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1132 // do not add to the lastfile list since these files are restored from
1133 // last session, and should be already there (regular files), or should
1134 // not be added at all (help files).
1135 for_each(lastopened.begin(), lastopened.end(),
1136 bind(&GuiView::loadDocument, current_view_, _1, false));
1138 // clear this list to save a few bytes of RAM
1139 session.lastOpened().clear();
1143 QString const GuiApplication::romanFontName()
1146 font.setKerning(false);
1147 font.setStyleHint(QFont::Serif);
1148 font.setFamily("serif");
1150 return QFontInfo(font).family();
1154 QString const GuiApplication::sansFontName()
1157 font.setKerning(false);
1158 font.setStyleHint(QFont::SansSerif);
1159 font.setFamily("sans");
1161 return QFontInfo(font).family();
1165 QString const GuiApplication::typewriterFontName()
1168 font.setKerning(false);
1169 font.setStyleHint(QFont::TypeWriter);
1170 font.setFamily("monospace");
1172 return QFontInfo(font).family();
1176 void GuiApplication::handleRegularEvents()
1178 ForkedCallsController::handleCompletedProcesses();
1182 bool GuiApplication::event(QEvent * e)
1185 case QEvent::FileOpen: {
1186 // Open a file; this happens only on Mac OS X for now
1187 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1188 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1189 qstring_to_ucs4(foe->file())));
1194 return QApplication::event(e);
1199 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1202 return QApplication::notify(receiver, event);
1204 catch (ExceptionMessage const & e) {
1206 case ErrorException:
1208 setQuitOnLastWindowClosed(false);
1210 Alert::error(e.title_, e.details_);
1212 // Properly crash in debug mode in order to get a useful backtrace.
1215 // In release mode, try to exit gracefully.
1218 case BufferException: {
1219 Buffer * buf = current_view_->buffer();
1220 docstring details = e.details_ + '\n';
1221 details += theBufferList().emergencyWrite(buf);
1222 theBufferList().release(buf);
1223 details += "\n" + _("The current document was closed.");
1224 Alert::error(e.title_, details);
1227 case WarningException:
1228 Alert::warning(e.title_, e.details_);
1232 catch (exception const & e) {
1233 docstring s = _("LyX has caught an exception, it will now "
1234 "attempt to save all unsaved documents and exit."
1236 s += from_ascii(e.what());
1237 Alert::error(_("Software exception Detected"), s);
1241 docstring s = _("LyX has caught some really weird exception, it will "
1242 "now attempt to save all unsaved documents and exit.");
1243 Alert::error(_("Software exception Detected"), s);
1251 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1253 QColor const & qcol = d->color_cache_.get(col);
1254 if (!qcol.isValid()) {
1260 rgbcol.r = qcol.red();
1261 rgbcol.g = qcol.green();
1262 rgbcol.b = qcol.blue();
1267 string const GuiApplication::hexName(ColorCode col)
1269 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1273 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1275 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1276 d->socket_notifiers_[fd] = sn;
1277 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1281 void GuiApplication::socketDataReceived(int fd)
1283 d->socket_notifiers_[fd]->func_();
1287 void GuiApplication::unregisterSocketCallback(int fd)
1289 d->socket_notifiers_.take(fd)->setEnabled(false);
1293 void GuiApplication::commitData(QSessionManager & sm)
1295 /// The implementation is required to avoid an application exit
1296 /// when session state save is triggered by session manager.
1297 /// The default implementation sends a close event to all
1298 /// visible top level widgets when session managment allows
1300 /// We are changing that to close all wiew one by one.
1301 /// FIXME: verify if the default implementation is enough now.
1302 if (sm.allowsInteraction() && !closeAllViews())
1307 void GuiApplication::unregisterView(GuiView * gv)
1309 LASSERT(d->views_[gv->id()] == gv, /**/);
1310 d->views_.remove(gv->id());
1311 if (current_view_ == gv) {
1313 theLyXFunc().setLyXView(0);
1318 bool GuiApplication::closeAllViews()
1320 if (d->views_.empty())
1323 QList<GuiView *> views = d->views_.values();
1324 foreach (GuiView * view, views) {
1334 GuiView & GuiApplication::view(int id) const
1336 LASSERT(d->views_.contains(id), /**/);
1337 return *d->views_.value(id);
1341 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1343 QList<GuiView *> views = d->views_.values();
1344 foreach (GuiView * view, views)
1345 view->hideDialog(name, inset);
1349 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1351 Buffer const * buffer_ = 0;
1352 QHash<int, GuiView *>::iterator end = d->views_.end();
1353 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1354 if (Buffer const * ptr = (*it)->updateInset(inset))
1361 bool GuiApplication::searchMenu(FuncRequest const & func,
1362 docstring_list & names) const
1364 return d->menus_.searchMenu(func, names);
1368 bool GuiApplication::readUIFile(QString const & name, bool include)
1378 LexerKeyword uitags[] = {
1379 { "include", ui_include },
1380 { "menuset", ui_menuset },
1381 { "toolbars", ui_toolbars },
1382 { "toolbarset", ui_toolbarset }
1385 LYXERR(Debug::INIT, "About to read " << name << "...");
1389 ui_path = libFileSearch("ui", name, "inc");
1390 if (ui_path.empty())
1391 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1393 ui_path = libFileSearch("ui", name, "ui");
1396 if (ui_path.empty()) {
1397 LYXERR(Debug::INIT, "Could not find " << name);
1398 Alert::warning(_("Could not find UI definition file"),
1399 bformat(_("Error while reading the configuration file\n%1$s.\n"
1400 "Please check your installation."), qstring_to_ucs4(name)));
1405 // Ensure that a file is read only once (prevents include loops)
1406 static QStringList uifiles;
1407 QString const uifile = toqstr(ui_path.absFilename());
1408 if (uifiles.contains(uifile)) {
1410 // We are reading again the top uifile so reset the safeguard:
1413 d->toolbars_.reset();
1415 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1416 << "Is this an include loop?");
1420 uifiles.push_back(uifile);
1422 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1425 lex.setFile(ui_path);
1427 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1431 if (lyxerr.debugging(Debug::PARSER))
1432 lex.printTable(lyxerr);
1434 while (lex.isOK()) {
1435 switch (lex.lex()) {
1438 QString const file = toqstr(lex.getString());
1439 if (!readUIFile(file, true))
1444 d->menus_.read(lex);
1448 d->toolbars_.readToolbars(lex);
1452 d->toolbars_.readToolbarSettings(lex);
1456 if (!rtrim(lex.getString()).empty())
1457 lex.printError("LyX::ReadUIFile: "
1458 "Unknown menu tag: `$$Token'");
1467 settings.beginGroup("ui_files");
1468 bool touched = false;
1469 for (int i = 0; i != uifiles.size(); ++i) {
1470 QFileInfo fi(uifiles[i]);
1471 QDateTime const date_value = fi.lastModified();
1472 QString const name_key = QString::number(i);
1473 if (!settings.contains(name_key)
1474 || settings.value(name_key).toString() != uifiles[i]
1475 || settings.value(name_key + "/date").toDateTime() != date_value) {
1477 settings.setValue(name_key, uifiles[i]);
1478 settings.setValue(name_key + "/date", date_value);
1481 settings.endGroup();
1483 settings.remove("views");
1489 void GuiApplication::onLastWindowClosed()
1491 if (d->global_menubar_)
1492 d->global_menubar_->grabKeyboard();
1496 ////////////////////////////////////////////////////////////////////////
1498 // X11 specific stuff goes here...
1501 bool GuiApplication::x11EventFilter(XEvent * xev)
1506 switch (xev->type) {
1507 case SelectionRequest: {
1508 if (xev->xselectionrequest.selection != XA_PRIMARY)
1510 LYXERR(Debug::SELECTION, "X requested selection.");
1511 BufferView * bv = current_view_->view();
1513 docstring const sel = bv->requestSelection();
1515 d->selection_.put(sel);
1519 case SelectionClear: {
1520 if (xev->xselectionclear.selection != XA_PRIMARY)
1522 LYXERR(Debug::SELECTION, "Lost selection.");
1523 BufferView * bv = current_view_->view();
1525 bv->clearSelection();
1533 } // namespace frontend
1536 void hideDialogs(std::string const & name, Inset * inset)
1539 theApp()->hideDialogs(name, inset);
1543 ////////////////////////////////////////////////////////////////////
1547 ////////////////////////////////////////////////////////////////////
1549 frontend::FontLoader & theFontLoader()
1551 LASSERT(frontend::guiApp, /**/);
1552 return frontend::guiApp->fontLoader();
1556 frontend::FontMetrics const & theFontMetrics(Font const & f)
1558 return theFontMetrics(f.fontInfo());
1562 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1564 LASSERT(frontend::guiApp, /**/);
1565 return frontend::guiApp->fontLoader().metrics(f);
1569 ////////////////////////////////////////////////////////////////////
1573 ////////////////////////////////////////////////////////////////////
1575 frontend::Clipboard & theClipboard()
1577 LASSERT(frontend::guiApp, /**/);
1578 return frontend::guiApp->clipboard();
1582 frontend::Selection & theSelection()
1584 LASSERT(frontend::guiApp, /**/);
1585 return frontend::guiApp->selection();
1590 #include "GuiApplication_moc.cpp"