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"
69 #include <QFileOpenEvent>
73 #include <QImageReader>
75 #include <QLibraryInfo>
77 #include <QMacPasteboardMime>
82 #include <QPixmapCache>
84 #include <QSessionManager>
86 #include <QSocketNotifier>
87 #include <QSortFilterProxyModel>
88 #include <QStandardItemModel>
91 #include <QTranslator>
95 #include <X11/Xatom.h>
102 #include <QWindowsMime>
103 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
109 #include <boost/bind.hpp>
110 #include <boost/crc.hpp>
116 using namespace lyx::support;
119 static void initializeResources()
121 static bool initialized = false;
123 Q_INIT_RESOURCE(Resources);
131 frontend::Application * createApplication(int & argc, char * argv[])
133 return new frontend::GuiApplication(argc, argv);
139 /// Return the list of loadable formats.
140 vector<string> loadableImageFormats()
144 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
146 LYXERR(Debug::GRAPHICS,
147 "\nThe image loader can load the following directly:\n");
149 if (qt_formats.empty())
150 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
152 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
154 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
156 string ext = ascii_lowercase((const char *) *it);
166 ////////////////////////////////////////////////////////////////////////
167 // Icon loading support code.
168 ////////////////////////////////////////////////////////////////////////
178 bool operator<(PngMap const & lhs, PngMap const & rhs)
180 return lhs.key < rhs.key;
186 CompareKey(QString const & name) : name_(name) {}
187 bool operator()(PngMap const & other) const { return other.key == name_; }
193 // this must be sorted alphabetically
194 // Upper case comes before lower case
195 PngMap sorted_png_map[] = {
196 { "Bumpeq", "bumpeq2" },
199 { "Delta", "delta2" },
200 { "Downarrow", "downarrow2" },
201 { "Gamma", "gamma2" },
202 { "Lambda", "lambda2" },
203 { "Leftarrow", "leftarrow2" },
204 { "Leftrightarrow", "leftrightarrow2" },
205 { "Longleftarrow", "longleftarrow2" },
206 { "Longleftrightarrow", "longleftrightarrow2" },
207 { "Longrightarrow", "longrightarrow2" },
208 { "Omega", "omega2" },
212 { "Rightarrow", "rightarrow2" },
213 { "Sigma", "sigma2" },
214 { "Subset", "subset2" },
215 { "Supset", "supset2" },
216 { "Theta", "theta2" },
217 { "Uparrow", "uparrow2" },
218 { "Updownarrow", "updownarrow2" },
219 { "Upsilon", "upsilon2" },
220 { "Vdash", "vdash3" },
223 { "nLeftarrow", "nleftarrow2" },
224 { "nLeftrightarrow", "nleftrightarrow2" },
225 { "nRightarrow", "nrightarrow2" },
226 { "nVDash", "nvdash3" },
227 { "nvDash", "nvdash2" },
228 { "textrm \\AA", "textrm_AA"},
229 { "textrm \\O", "textrm_O"},
230 { "vDash", "vdash2" }
233 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
236 QString findPng(QString const & name)
238 PngMap const * const begin = sorted_png_map;
239 PngMap const * const end = begin + nr_sorted_png_map;
240 LASSERT(sorted(begin, end), /**/);
242 PngMap const * const it = find_if(begin, end, CompareKey(name));
246 png_name = it->value;
249 png_name.replace('_', "underscore");
250 png_name.replace(' ', '_');
252 // This way we can have "math-delim { }" on the toolbar.
253 png_name.replace('(', "lparen");
254 png_name.replace(')', "rparen");
255 png_name.replace('[', "lbracket");
256 png_name.replace(']', "rbracket");
257 png_name.replace('{', "lbrace");
258 png_name.replace('}', "rbrace");
259 png_name.replace('|', "bars");
260 png_name.replace(',', "thinspace");
261 png_name.replace(':', "mediumspace");
262 png_name.replace(';', "thickspace");
263 png_name.replace('!', "negthinspace");
266 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
267 << "Looking for math PNG called \"" << png_name << '"');
274 QString iconName(FuncRequest const & f, bool unknown)
276 initializeResources();
281 case LFUN_MATH_INSERT:
282 if (!f.argument().empty()) {
284 name1 = findPng(toqstr(f.argument()).mid(1));
287 case LFUN_MATH_DELIM:
288 case LFUN_MATH_BIGDELIM:
290 name1 = findPng(toqstr(f.argument()));
294 name1 = toqstr(f.argument());
297 name2 = toqstr(lyxaction.getActionName(f.action));
300 if (!f.argument().empty()) {
301 name1 = name2 + ' ' + toqstr(f.argument());
302 name1.replace(' ', '_');
306 FileName fname = libFileSearch("images/" + path, name1, "png");
308 return toqstr(fname.absFilename());
310 fname = libFileSearch("images/" + path, name2, "png");
312 return toqstr(fname.absFilename());
314 path = ":/images/" + path;
317 LYXERR0("Directory " << path << " not found in resource!");
321 if (res.exists(name1))
325 if (res.exists(name2))
328 LYXERR(Debug::GUI, "Cannot find icon for command \""
329 << lyxaction.getActionName(f.action)
330 << '(' << to_utf8(f.argument()) << ")\"");
333 return QString(":/images/unknown.png");
339 QIcon getIcon(FuncRequest const & f, bool unknown)
341 QString icon = iconName(f, unknown);
345 //LYXERR(Debug::GUI, "Found icon: " << icon);
347 if (!pm.load(icon)) {
348 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
356 ////////////////////////////////////////////////////////////////////////
357 // LyX server support code.
358 ////////////////////////////////////////////////////////////////////////
359 class SocketNotifier : public QSocketNotifier
362 /// connect a connection notification from the LyXServerSocket
363 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
364 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
368 /// The callback function
369 Application::SocketCallback func_;
373 ////////////////////////////////////////////////////////////////////////
374 // Mac specific stuff goes here...
375 ////////////////////////////////////////////////////////////////////////
377 class MenuTranslator : public QTranslator
380 MenuTranslator(QObject * parent)
381 : QTranslator(parent)
384 QString translate(const char * /*context*/,
385 const char * sourceText,
386 const char * /*comment*/ = 0)
388 string const s = sourceText;
389 if (s == N_("About %1") || s == N_("Preferences")
390 || s == N_("Reconfigure") || s == N_("Quit %1"))
397 class GlobalMenuBar : public QMenuBar
401 GlobalMenuBar() : QMenuBar(0) {}
404 bool event(QEvent * e)
406 if (e->type() == QEvent::ShortcutOverride) {
407 // && activeWindow() == 0) {
408 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
410 setKeySymbol(&sym, ke);
411 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
420 // QMacPasteboardMimeGraphics can only be compiled on Mac.
422 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
425 QMacPasteboardMimeGraphics()
426 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
429 QString convertorName() { return "Graphics"; }
431 QString flavorFor(QString const & mime)
433 LYXERR(Debug::ACTION, "flavorFor " << mime);
434 if (mime == pdfMimeType())
435 return QLatin1String("com.adobe.pdf");
439 QString mimeFor(QString flav)
441 LYXERR(Debug::ACTION, "mimeFor " << flav);
442 if (flav == QLatin1String("com.adobe.pdf"))
443 return pdfMimeType();
447 bool canConvert(QString const & mime, QString flav)
449 return mimeFor(flav) == mime;
452 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
456 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
460 QList<QByteArray> convertFromMime(QString const & /*mime*/,
461 QVariant data, QString /*flav*/)
463 QList<QByteArray> ret;
464 ret.append(data.toByteArray());
470 ///////////////////////////////////////////////////////////////
471 // You can find more platform specific stuff
472 // at the end of this file...
473 ///////////////////////////////////////////////////////////////
475 ////////////////////////////////////////////////////////////////////////
476 // Windows specific stuff goes here...
479 // QWindowsMimeMetafile can only be compiled on Windows.
481 static FORMATETC cfFromMime(QString const & mimetype)
484 if (mimetype == emfMimeType()) {
485 formatetc.cfFormat = CF_ENHMETAFILE;
486 formatetc.tymed = TYMED_ENHMF;
487 } else if (mimetype == wmfMimeType()) {
488 formatetc.cfFormat = CF_METAFILEPICT;
489 formatetc.tymed = TYMED_MFPICT;
492 formatetc.dwAspect = DVASPECT_CONTENT;
493 formatetc.lindex = -1;
498 class QWindowsMimeMetafile : public QWindowsMime {
500 QWindowsMimeMetafile() {}
502 bool canConvertFromMime(FORMATETC const & formatetc,
503 QMimeData const * mimedata) const
508 bool canConvertToMime(QString const & mimetype,
509 IDataObject * pDataObj) const
511 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
513 FORMATETC formatetc = cfFromMime(mimetype);
514 return pDataObj->QueryGetData(&formatetc) == S_OK;
517 bool convertFromMime(FORMATETC const & formatetc,
518 const QMimeData * mimedata, STGMEDIUM * pmedium) const
523 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
524 QVariant::Type preferredType) const
527 if (!canConvertToMime(mimetype, pDataObj))
530 FORMATETC formatetc = cfFromMime(mimetype);
532 if (pDataObj->GetData(&formatetc, &s) != S_OK)
536 if (s.tymed == TYMED_ENHMF) {
537 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
538 data.resize(dataSize);
539 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
540 (LPBYTE)data.data());
541 } else if (s.tymed == TYMED_MFPICT) {
542 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
543 data.resize(dataSize);
544 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
545 (LPBYTE)data.data());
548 ReleaseStgMedium(&s);
554 QVector<FORMATETC> formatsForMime(QString const & mimeType,
555 QMimeData const * mimeData) const
557 QVector<FORMATETC> formats;
558 formats += cfFromMime(mimeType);
562 QString mimeForFormat(FORMATETC const & formatetc) const
564 switch (formatetc.cfFormat) {
566 return emfMimeType();
567 case CF_METAFILEPICT:
568 return wmfMimeType();
576 ////////////////////////////////////////////////////////////////////////
577 // GuiApplication::Private definition and implementation.
578 ////////////////////////////////////////////////////////////////////////
580 struct GuiApplication::Private
583 : language_model_(0), global_menubar_(0)
586 // Create the global default menubar which is shown for the dialogs
587 // and if no GuiView is visible.
588 global_menubar_ = new GlobalMenuBar();
593 QSortFilterProxyModel * language_model_;
595 GuiClipboard clipboard_;
597 GuiSelection selection_;
599 FontLoader font_loader_;
601 ColorCache color_cache_;
603 QTranslator qt_trans_;
605 QHash<int, SocketNotifier *> socket_notifiers_;
609 /// The global instance
612 /// this timer is used for any regular events one wants to
613 /// perform. at present it is used to check if forked processes
615 QTimer general_timer_;
617 /// Multiple views container.
619 * Warning: This must not be a smart pointer as the destruction of the
620 * object is handled by Qt when the view is closed
621 * \sa Qt::WA_DeleteOnClose attribute.
623 QHash<int, GuiView *> views_;
625 /// Only used on mac.
626 GlobalMenuBar * global_menubar_;
629 /// Linkback mime handler for MacOSX.
630 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
634 /// WMF Mime handler for Windows clipboard.
635 /// \warning: see comment in ~GuiApplication and in bug 4846.
636 QWindowsMimeMetafile wmf_mime_;
641 GuiApplication * guiApp;
643 GuiApplication::~GuiApplication()
646 closeAllLinkBackLinks();
648 // FIXME: Work around bug 4846 for Windows Vista and Qt4
649 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
650 // If the clipboard is not cleared, LyX crashes on exit when it is
651 // compiled in release mode and if there is something in the clipboard.
652 // This is related to QWindowsMimeMetafile which is apparently not
653 // properly destroyed.
654 qApp->clipboard()->clear(QClipboard::Clipboard);
659 GuiApplication::GuiApplication(int & argc, char ** argv)
660 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
662 QString app_name = "LyX";
663 QCoreApplication::setOrganizationName(app_name);
664 QCoreApplication::setOrganizationDomain("lyx.org");
665 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
667 // Install translator for GUI elements.
668 installTranslator(&d->qt_trans_);
670 // FIXME: quitOnLastWindowClosed is true by default. We should have a
671 // lyxrc setting for this in order to let the application stay resident.
672 // But then we need some kind of dock icon, at least on Windows.
674 if (lyxrc.quit_on_last_window_closed)
675 setQuitOnLastWindowClosed(false);
678 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
679 // seems to be the default case for applications like LyX.
680 setQuitOnLastWindowClosed(false);
682 // This allows to translate the strings that appear in the LyX menu.
683 /// A translator suitable for the entries in the LyX menu.
684 /// Only needed with Qt/Mac.
685 installTranslator(new MenuTranslator(this));
689 // doubleClickInterval() is 400 ms on X11 which is just too long.
690 // On Windows and Mac OS X, the operating system's value is used.
691 // On Microsoft Windows, calling this function sets the double
692 // click interval for all applications. So we don't!
693 QApplication::setDoubleClickInterval(300);
696 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
698 // needs to be done before reading lyxrc
700 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
704 // Set the cache to 5120 kilobytes which corresponds to screen size of
705 // 1280 by 1024 pixels with a color depth of 32 bits.
706 QPixmapCache::setCacheLimit(5120);
708 // Initialize RC Fonts
709 if (lyxrc.roman_font_name.empty())
710 lyxrc.roman_font_name = fromqstr(romanFontName());
712 if (lyxrc.sans_font_name.empty())
713 lyxrc.sans_font_name = fromqstr(sansFontName());
715 if (lyxrc.typewriter_font_name.empty())
716 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
718 d->general_timer_.setInterval(500);
719 connect(&d->general_timer_, SIGNAL(timeout()),
720 this, SLOT(handleRegularEvents()));
721 d->general_timer_.start();
725 void GuiApplication::clearSession()
732 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
734 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
739 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
745 case LFUN_WINDOW_CLOSE:
746 enable = d->views_.size() > 0;
749 case LFUN_BUFFER_NEW:
750 case LFUN_BUFFER_NEW_TEMPLATE:
752 case LFUN_SCREEN_FONT_UPDATE:
754 case LFUN_WINDOW_NEW:
764 flag.setEnabled(false);
770 bool GuiApplication::dispatch(FuncRequest const & cmd)
772 switch (cmd.action) {
774 case LFUN_WINDOW_NEW:
775 createView(toqstr(cmd.argument()));
778 case LFUN_WINDOW_CLOSE:
779 // update bookmark pit of the current buffer before window close
780 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
781 theLyXFunc().gotoBookmark(i+1, false, false);
782 current_view_->close();
786 // quitting is triggered by the gui code
787 // (leaving the event loop).
789 current_view_->message(from_utf8(N_("Exiting.")));
794 case LFUN_SCREEN_FONT_UPDATE: {
795 // handle the screen font changes.
796 d->font_loader_.update();
797 // Backup current_view_
798 GuiView * view = current_view_;
799 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
800 // to skip the refresh.
802 BufferList::iterator it = theBufferList().begin();
803 BufferList::iterator const end = theBufferList().end();
804 for (; it != end; ++it)
806 // Restore current_view_
807 current_view_ = view;
811 case LFUN_BUFFER_NEW:
812 if (d->views_.empty()
813 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
814 createView(QString(), false); // keep hidden
815 current_view_->newDocument(to_utf8(cmd.argument()), false);
816 current_view_->show();
817 setActiveWindow(current_view_);
819 current_view_->newDocument(to_utf8(cmd.argument()), false);
823 case LFUN_BUFFER_NEW_TEMPLATE:
824 if (d->views_.empty()
825 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
827 current_view_->newDocument(to_utf8(cmd.argument()), true);
828 if (!current_view_->buffer())
829 current_view_->close();
831 current_view_->newDocument(to_utf8(cmd.argument()), true);
836 if (d->views_.empty()
837 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
838 string const fname = to_utf8(cmd.argument());
839 // We want the ui session to be saved per document and not per
840 // window number. The filename crc is a good enough identifier.
841 boost::crc_32_type crc;
842 crc = for_each(fname.begin(), fname.end(), crc);
843 createView(crc.checksum());
844 current_view_->openDocument(fname);
845 if (!current_view_->buffer())
846 current_view_->close();
848 current_view_->openDocument(to_utf8(cmd.argument()));
851 case LFUN_SET_COLOR: {
853 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
854 if (lyx_name.empty() || x11_name.empty()) {
855 current_view_->message(
856 _("Syntax: set-color <lyx_name> <x11_name>"));
860 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
861 bool const graphicsbg_changed = lyx_name == graphicsbg
862 && x11_name != graphicsbg;
863 if (graphicsbg_changed) {
864 // FIXME: The graphics cache no longer has a changeDisplay method.
866 graphics::GCache::get().changeDisplay(true);
870 if (!lcolor.setColor(lyx_name, x11_name)) {
871 current_view_->message(
872 bformat(_("Set-color \"%1$s\" failed "
873 "- color is undefined or "
874 "may not be redefined"),
875 from_utf8(lyx_name)));
878 // Make sure we don't keep old colors in cache.
879 d->color_cache_.clear();
884 // Notify the caller that the action has not been dispatched.
888 // The action has been dispatched.
893 void GuiApplication::resetGui()
895 // Set the language defined by the user.
899 if (!readUIFile(toqstr(lyxrc.ui_file)))
900 // Gives some error box here.
904 d->global_menubar_->clear();
905 delete d->global_menubar_;
906 // Create the global default menubar which is shown for the dialogs
907 // and if no GuiView is visible.
908 d->global_menubar_ = new GlobalMenuBar();
910 // init the global menubar on Mac. This must be done after the session
911 // was recovered to know the "last files".
912 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
915 QHash<int, GuiView *>::iterator it;
916 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
918 gv->setLayoutDirection(layoutDirection());
922 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
926 void GuiApplication::createView(int view_id)
928 createView(QString(), true, view_id);
932 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
935 // release the keyboard which might have been grabed by the global
936 // menubar on Mac to catch shortcuts even without any GuiView.
937 if (d->global_menubar_)
938 d->global_menubar_->releaseKeyboard();
943 while (d->views_.find(id) != d->views_.end())
946 LYXERR(Debug::GUI, "About to create new window with ID " << id);
947 GuiView * view = new GuiView(id);
949 d->views_[id] = view;
953 setActiveWindow(view);
956 if (!geometry_arg.isEmpty()) {
960 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
961 re.indexIn(geometry_arg);
962 w = re.cap(1).toInt();
963 h = re.cap(2).toInt();
964 x = re.cap(3).toInt();
965 y = re.cap(4).toInt();
966 view->setGeometry(x, y, w, h);
970 setCurrentView(view);
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 qDebug() << "File read " << i << " " << uifiles[i] << " " << date_value.toString("hh:mm:ss.zzz");
1473 qDebug() << "File saved " << name_key << " " << settings.value(name_key).toString()
1474 << " " << settings.value(name_key + "/date").toDateTime().toString("hh:mm:ss.zzz");
1476 if (!settings.contains(name_key)
1477 || settings.value(name_key).toString() != uifiles[i]
1478 || settings.value(name_key + "/date").toDateTime() != date_value) {
1480 settings.setValue(name_key, uifiles[i]);
1481 settings.setValue(name_key + "/date", date_value);
1484 settings.endGroup();
1486 settings.remove("views");
1492 void GuiApplication::onLastWindowClosed()
1494 if (d->global_menubar_)
1495 d->global_menubar_->grabKeyboard();
1499 ////////////////////////////////////////////////////////////////////////
1501 // X11 specific stuff goes here...
1504 bool GuiApplication::x11EventFilter(XEvent * xev)
1509 switch (xev->type) {
1510 case SelectionRequest: {
1511 if (xev->xselectionrequest.selection != XA_PRIMARY)
1513 LYXERR(Debug::SELECTION, "X requested selection.");
1514 BufferView * bv = current_view_->view();
1516 docstring const sel = bv->requestSelection();
1518 d->selection_.put(sel);
1522 case SelectionClear: {
1523 if (xev->xselectionclear.selection != XA_PRIMARY)
1525 LYXERR(Debug::SELECTION, "Lost selection.");
1526 BufferView * bv = current_view_->view();
1528 bv->clearSelection();
1536 } // namespace frontend
1539 void hideDialogs(std::string const & name, Inset * inset)
1542 theApp()->hideDialogs(name, inset);
1546 ////////////////////////////////////////////////////////////////////
1550 ////////////////////////////////////////////////////////////////////
1552 frontend::FontLoader & theFontLoader()
1554 LASSERT(frontend::guiApp, /**/);
1555 return frontend::guiApp->fontLoader();
1559 frontend::FontMetrics const & theFontMetrics(Font const & f)
1561 return theFontMetrics(f.fontInfo());
1565 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1567 LASSERT(frontend::guiApp, /**/);
1568 return frontend::guiApp->fontLoader().metrics(f);
1572 ////////////////////////////////////////////////////////////////////
1576 ////////////////////////////////////////////////////////////////////
1578 frontend::Clipboard & theClipboard()
1580 LASSERT(frontend::guiApp, /**/);
1581 return frontend::guiApp->clipboard();
1585 frontend::Selection & theSelection()
1587 LASSERT(frontend::guiApp, /**/);
1588 return frontend::guiApp->selection();
1593 #include "GuiApplication_moc.cpp"