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"
72 #include <QFileOpenEvent>
76 #include <QImageReader>
78 #include <QLibraryInfo>
80 #include <QMacPasteboardMime>
85 #include <QPixmapCache>
87 #include <QSessionManager>
89 #include <QSocketNotifier>
90 #include <QSortFilterProxyModel>
91 #include <QStandardItemModel>
94 #include <QTranslator>
98 #include <X11/Xatom.h>
105 #include <QWindowsMime>
112 #include <boost/bind.hpp>
113 #include <boost/crc.hpp>
119 using namespace lyx::support;
122 static void initializeResources()
124 static bool initialized = false;
126 Q_INIT_RESOURCE(Resources);
134 frontend::Application * createApplication(int & argc, char * argv[])
137 // prune -geometry argument(s) by shifting
138 // the following ones 2 places down.
139 for (int i = 0 ; i < argc ; ++i) {
140 if (strcmp(argv[i], "-geometry") == 0) {
141 int const remove = (i+1) < argc ? 2 : 1;
143 for (int j = i; j < argc; ++j)
144 argv[j] = argv[j + remove];
149 return new frontend::GuiApplication(argc, argv);
155 /// Return the list of loadable formats.
156 vector<string> loadableImageFormats()
160 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
162 LYXERR(Debug::GRAPHICS,
163 "\nThe image loader can load the following directly:\n");
165 if (qt_formats.empty())
166 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
168 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
170 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
172 string ext = ascii_lowercase((const char *) *it);
183 ////////////////////////////////////////////////////////////////////////
185 // Icon loading support code
187 ////////////////////////////////////////////////////////////////////////
197 bool operator<(PngMap const & lhs, PngMap const & rhs)
199 return lhs.key < rhs.key;
205 CompareKey(QString const & name) : name_(name) {}
206 bool operator()(PngMap const & other) const { return other.key == name_; }
212 // this must be sorted alphabetically
213 // Upper case comes before lower case
214 PngMap sorted_png_map[] = {
215 { "Bumpeq", "bumpeq2" },
218 { "Delta", "delta2" },
219 { "Downarrow", "downarrow2" },
220 { "Gamma", "gamma2" },
221 { "Lambda", "lambda2" },
222 { "Leftarrow", "leftarrow2" },
223 { "Leftrightarrow", "leftrightarrow2" },
224 { "Longleftarrow", "longleftarrow2" },
225 { "Longleftrightarrow", "longleftrightarrow2" },
226 { "Longrightarrow", "longrightarrow2" },
227 { "Omega", "omega2" },
231 { "Rightarrow", "rightarrow2" },
232 { "Sigma", "sigma2" },
233 { "Subset", "subset2" },
234 { "Supset", "supset2" },
235 { "Theta", "theta2" },
236 { "Uparrow", "uparrow2" },
237 { "Updownarrow", "updownarrow2" },
238 { "Upsilon", "upsilon2" },
239 { "Vdash", "vdash3" },
242 { "nLeftarrow", "nleftarrow2" },
243 { "nLeftrightarrow", "nleftrightarrow2" },
244 { "nRightarrow", "nrightarrow2" },
245 { "nVDash", "nvdash3" },
246 { "nvDash", "nvdash2" },
247 { "textrm \\AA", "textrm_AA"},
248 { "textrm \\O", "textrm_O"},
249 { "vDash", "vdash2" }
252 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
255 QString findPng(QString const & name)
257 PngMap const * const begin = sorted_png_map;
258 PngMap const * const end = begin + nr_sorted_png_map;
259 LASSERT(sorted(begin, end), /**/);
261 PngMap const * const it = find_if(begin, end, CompareKey(name));
265 png_name = it->value;
268 png_name.replace('_', "underscore");
269 png_name.replace(' ', '_');
271 // This way we can have "math-delim { }" on the toolbar.
272 png_name.replace('(', "lparen");
273 png_name.replace(')', "rparen");
274 png_name.replace('[', "lbracket");
275 png_name.replace(']', "rbracket");
276 png_name.replace('{', "lbrace");
277 png_name.replace('}', "rbrace");
278 png_name.replace('|', "bars");
279 png_name.replace(',', "thinspace");
280 png_name.replace(':', "mediumspace");
281 png_name.replace(';', "thickspace");
282 png_name.replace('!', "negthinspace");
285 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
286 << "Looking for math PNG called \"" << png_name << '"');
293 QString iconName(FuncRequest const & f, bool unknown)
295 initializeResources();
300 case LFUN_MATH_INSERT:
301 if (!f.argument().empty()) {
303 name1 = findPng(toqstr(f.argument()).mid(1));
306 case LFUN_MATH_DELIM:
307 case LFUN_MATH_BIGDELIM:
309 name1 = findPng(toqstr(f.argument()));
313 name1 = toqstr(f.argument());
316 name2 = toqstr(lyxaction.getActionName(f.action));
319 if (!f.argument().empty()) {
320 name1 = name2 + ' ' + toqstr(f.argument());
321 name1.replace(' ', '_');
325 FileName fname = libFileSearch("images/" + path, name1, "png");
327 return toqstr(fname.absFilename());
329 fname = libFileSearch("images/" + path, name2, "png");
331 return toqstr(fname.absFilename());
333 path = ":/images/" + path;
336 LYXERR0("Directory " << path << " not found in resource!");
340 if (res.exists(name1))
344 if (res.exists(name2))
347 LYXERR(Debug::GUI, "Cannot find icon for command \""
348 << lyxaction.getActionName(f.action)
349 << '(' << to_utf8(f.argument()) << ")\"");
352 return QString(":/images/unknown.png");
358 QIcon getIcon(FuncRequest const & f, bool unknown)
360 QString icon = iconName(f, unknown);
364 //LYXERR(Debug::GUI, "Found icon: " << icon);
366 if (!pm.load(icon)) {
367 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
375 ////////////////////////////////////////////////////////////////////////
377 // LyX server support code.
379 ////////////////////////////////////////////////////////////////////////
381 class SocketNotifier : public QSocketNotifier
384 /// connect a connection notification from the LyXServerSocket
385 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
386 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
390 /// The callback function
391 Application::SocketCallback func_;
395 ////////////////////////////////////////////////////////////////////////
397 // Mac specific stuff goes here...
399 ////////////////////////////////////////////////////////////////////////
401 class MenuTranslator : public QTranslator
404 MenuTranslator(QObject * parent)
405 : QTranslator(parent)
408 QString translate(const char * /*context*/,
409 const char * sourceText,
410 const char * /*comment*/ = 0)
412 string const s = sourceText;
413 if (s == N_("About %1") || s == N_("Preferences")
414 || s == N_("Reconfigure") || s == N_("Quit %1"))
421 class GlobalMenuBar : public QMenuBar
425 GlobalMenuBar() : QMenuBar(0) {}
428 bool event(QEvent * e)
430 if (e->type() == QEvent::ShortcutOverride) {
431 // && activeWindow() == 0) {
432 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
434 setKeySymbol(&sym, ke);
435 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
444 // QMacPasteboardMimeGraphics can only be compiled on Mac.
446 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
449 QMacPasteboardMimeGraphics()
450 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
453 QString convertorName() { return "Graphics"; }
455 QString flavorFor(QString const & mime)
457 LYXERR(Debug::ACTION, "flavorFor " << mime);
458 if (mime == pdfMimeType())
459 return QLatin1String("com.adobe.pdf");
463 QString mimeFor(QString flav)
465 LYXERR(Debug::ACTION, "mimeFor " << flav);
466 if (flav == QLatin1String("com.adobe.pdf"))
467 return pdfMimeType();
471 bool canConvert(QString const & mime, QString flav)
473 return mimeFor(flav) == mime;
476 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
480 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
484 QList<QByteArray> convertFromMime(QString const & /*mime*/,
485 QVariant data, QString /*flav*/)
487 QList<QByteArray> ret;
488 ret.append(data.toByteArray());
494 ///////////////////////////////////////////////////////////////
496 // You can find more platform specific stuff at the end of this file...
498 ///////////////////////////////////////////////////////////////
500 ////////////////////////////////////////////////////////////////////////
501 // Windows specific stuff goes here...
504 // QWindowsMimeMetafile can only be compiled on Windows.
506 static FORMATETC cfFromMime(QString const & mimetype)
509 if (mimetype == emfMimeType()) {
510 formatetc.cfFormat = CF_ENHMETAFILE;
511 formatetc.tymed = TYMED_ENHMF;
512 } else if (mimetype == wmfMimeType()) {
513 formatetc.cfFormat = CF_METAFILEPICT;
514 formatetc.tymed = TYMED_MFPICT;
517 formatetc.dwAspect = DVASPECT_CONTENT;
518 formatetc.lindex = -1;
523 class QWindowsMimeMetafile : public QWindowsMime {
525 QWindowsMimeMetafile() {}
527 bool canConvertFromMime(FORMATETC const & formatetc,
528 QMimeData const * mimedata) const
533 bool canConvertToMime(QString const & mimetype,
534 IDataObject * pDataObj) const
536 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
538 FORMATETC formatetc = cfFromMime(mimetype);
539 return pDataObj->QueryGetData(&formatetc) == S_OK;
542 bool convertFromMime(FORMATETC const & formatetc,
543 const QMimeData * mimedata, STGMEDIUM * pmedium) const
548 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
549 QVariant::Type preferredType) const
552 if (!canConvertToMime(mimetype, pDataObj))
555 FORMATETC formatetc = cfFromMime(mimetype);
557 if (pDataObj->GetData(&formatetc, &s) != S_OK)
561 if (s.tymed == TYMED_ENHMF) {
562 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
563 data.resize(dataSize);
564 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
565 (LPBYTE)data.data());
566 } else if (s.tymed == TYMED_MFPICT) {
567 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
568 data.resize(dataSize);
569 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
570 (LPBYTE)data.data());
573 ReleaseStgMedium(&s);
579 QVector<FORMATETC> formatsForMime(QString const & mimetype,
580 QMimeData const * mimedata) const
582 QVector<FORMATETC> formats;
583 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
584 formats += cfFromMime(mimetype);
588 QString mimeForFormat(FORMATETC const & formatetc) const
590 switch (formatetc.cfFormat) {
592 return emfMimeType();
593 case CF_METAFILEPICT:
594 return wmfMimeType();
602 ////////////////////////////////////////////////////////////////////////
603 // GuiApplication::Private definition and implementation.
604 ////////////////////////////////////////////////////////////////////////
606 struct GuiApplication::Private
608 Private(): language_model_(0), global_menubar_(0) {}
611 QSortFilterProxyModel * language_model_;
613 GuiClipboard clipboard_;
615 GuiSelection selection_;
617 FontLoader font_loader_;
619 ColorCache color_cache_;
621 QTranslator qt_trans_;
623 QHash<int, SocketNotifier *> socket_notifiers_;
627 /// The global instance
630 /// this timer is used for any regular events one wants to
631 /// perform. at present it is used to check if forked processes
633 QTimer general_timer_;
635 /// delayed FuncRequests
636 std::queue<FuncRequest> func_request_queue_;
638 /// Multiple views container.
640 * Warning: This must not be a smart pointer as the destruction of the
641 * object is handled by Qt when the view is closed
642 * \sa Qt::WA_DeleteOnClose attribute.
644 QHash<int, GuiView *> views_;
646 /// Only used on mac.
647 GlobalMenuBar * global_menubar_;
650 /// Linkback mime handler for MacOSX.
651 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
655 /// WMF Mime handler for Windows clipboard.
656 /// \warning: see comment in ~GuiApplication and in bug 4846.
657 QWindowsMimeMetafile wmf_mime_;
662 GuiApplication * guiApp;
664 GuiApplication::~GuiApplication()
667 closeAllLinkBackLinks();
669 // FIXME: Work around bug 4846 for Windows Vista and Qt4
670 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
671 // If the clipboard is not cleared, LyX crashes on exit when it is
672 // compiled in release mode and if there is something in the clipboard.
673 // This is related to QWindowsMimeMetafile which is apparently not
674 // properly destroyed.
675 qApp->clipboard()->clear(QClipboard::Clipboard);
680 GuiApplication::GuiApplication(int & argc, char ** argv)
681 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
683 QString app_name = "LyX";
684 QCoreApplication::setOrganizationName(app_name);
685 QCoreApplication::setOrganizationDomain("lyx.org");
686 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
688 // Install translator for GUI elements.
689 installTranslator(&d->qt_trans_);
691 // FIXME: quitOnLastWindowClosed is true by default. We should have a
692 // lyxrc setting for this in order to let the application stay resident.
693 // But then we need some kind of dock icon, at least on Windows.
695 if (lyxrc.quit_on_last_window_closed)
696 setQuitOnLastWindowClosed(false);
699 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
700 // seems to be the default case for applications like LyX.
701 setQuitOnLastWindowClosed(false);
703 // This allows to translate the strings that appear in the LyX menu.
704 /// A translator suitable for the entries in the LyX menu.
705 /// Only needed with Qt/Mac.
706 installTranslator(new MenuTranslator(this));
710 // doubleClickInterval() is 400 ms on X11 which is just too long.
711 // On Windows and Mac OS X, the operating system's value is used.
712 // On Microsoft Windows, calling this function sets the double
713 // click interval for all applications. So we don't!
714 QApplication::setDoubleClickInterval(300);
717 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
719 // needs to be done before reading lyxrc
721 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
725 // Set the cache to 5120 kilobytes which corresponds to screen size of
726 // 1280 by 1024 pixels with a color depth of 32 bits.
727 QPixmapCache::setCacheLimit(5120);
729 // Initialize RC Fonts
730 if (lyxrc.roman_font_name.empty())
731 lyxrc.roman_font_name = fromqstr(romanFontName());
733 if (lyxrc.sans_font_name.empty())
734 lyxrc.sans_font_name = fromqstr(sansFontName());
736 if (lyxrc.typewriter_font_name.empty())
737 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
739 d->general_timer_.setInterval(500);
740 connect(&d->general_timer_, SIGNAL(timeout()),
741 this, SLOT(handleRegularEvents()));
742 d->general_timer_.start();
746 GuiApplication * theGuiApp()
748 return dynamic_cast<GuiApplication *>(theApp());
752 void GuiApplication::clearSession()
759 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
761 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
766 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
772 case LFUN_WINDOW_CLOSE:
773 enable = d->views_.size() > 0;
776 case LFUN_BUFFER_NEW:
777 case LFUN_BUFFER_NEW_TEMPLATE:
779 case LFUN_SCREEN_FONT_UPDATE:
781 case LFUN_WINDOW_NEW:
791 flag.setEnabled(false);
797 bool GuiApplication::dispatch(FuncRequest const & cmd)
799 switch (cmd.action) {
801 case LFUN_WINDOW_NEW:
802 createView(toqstr(cmd.argument()));
805 case LFUN_WINDOW_CLOSE:
806 // update bookmark pit of the current buffer before window close
807 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
808 theLyXFunc().gotoBookmark(i+1, false, false);
809 current_view_->close();
813 // quitting is triggered by the gui code
814 // (leaving the event loop).
816 current_view_->message(from_utf8(N_("Exiting.")));
821 case LFUN_SCREEN_FONT_UPDATE: {
822 // handle the screen font changes.
823 d->font_loader_.update();
824 // Backup current_view_
825 GuiView * view = current_view_;
826 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
827 // to skip the refresh.
829 BufferList::iterator it = theBufferList().begin();
830 BufferList::iterator const end = theBufferList().end();
831 for (; it != end; ++it)
833 // Restore current_view_
834 current_view_ = view;
838 case LFUN_BUFFER_NEW:
839 if (d->views_.empty()
840 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
841 createView(QString(), false); // keep hidden
842 current_view_->newDocument(to_utf8(cmd.argument()), false);
843 current_view_->show();
844 setActiveWindow(current_view_);
846 current_view_->newDocument(to_utf8(cmd.argument()), false);
850 case LFUN_BUFFER_NEW_TEMPLATE:
851 if (d->views_.empty()
852 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
854 current_view_->newDocument(to_utf8(cmd.argument()), true);
855 if (!current_view_->buffer())
856 current_view_->close();
858 current_view_->newDocument(to_utf8(cmd.argument()), true);
863 if (d->views_.empty()
864 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
865 string const fname = to_utf8(cmd.argument());
866 // We want the ui session to be saved per document and not per
867 // window number. The filename crc is a good enough identifier.
868 boost::crc_32_type crc;
869 crc = for_each(fname.begin(), fname.end(), crc);
870 createView(crc.checksum());
871 current_view_->openDocument(fname);
872 if (current_view_ && !current_view_->buffer())
873 current_view_->close();
875 current_view_->openDocument(to_utf8(cmd.argument()));
878 case LFUN_SET_COLOR: {
880 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
881 if (lyx_name.empty() || x11_name.empty()) {
882 current_view_->message(
883 _("Syntax: set-color <lyx_name> <x11_name>"));
887 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
888 bool const graphicsbg_changed = lyx_name == graphicsbg
889 && x11_name != graphicsbg;
890 if (graphicsbg_changed) {
891 // FIXME: The graphics cache no longer has a changeDisplay method.
893 graphics::GCache::get().changeDisplay(true);
897 if (!lcolor.setColor(lyx_name, x11_name)) {
898 current_view_->message(
899 bformat(_("Set-color \"%1$s\" failed "
900 "- color is undefined or "
901 "may not be redefined"),
902 from_utf8(lyx_name)));
905 // Make sure we don't keep old colors in cache.
906 d->color_cache_.clear();
911 // Notify the caller that the action has not been dispatched.
915 // The action has been dispatched.
920 void GuiApplication::dispatchDelayed(FuncRequest const & func)
922 d->func_request_queue_.push(func);
923 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
927 void GuiApplication::resetGui()
929 // Set the language defined by the user.
933 if (!readUIFile(toqstr(lyxrc.ui_file)))
934 // Gives some error box here.
937 if (d->global_menubar_)
938 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
940 QHash<int, GuiView *>::iterator it;
941 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
943 gv->setLayoutDirection(layoutDirection());
947 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
951 void GuiApplication::createView(int view_id)
953 createView(QString(), true, view_id);
957 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
960 // release the keyboard which might have been grabed by the global
961 // menubar on Mac to catch shortcuts even without any GuiView.
962 if (d->global_menubar_)
963 d->global_menubar_->releaseKeyboard();
968 while (d->views_.find(id) != d->views_.end())
971 LYXERR(Debug::GUI, "About to create new window with ID " << id);
972 GuiView * view = new GuiView(id);
974 d->views_[id] = view;
978 setActiveWindow(view);
981 if (!geometry_arg.isEmpty()) {
985 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
986 re.indexIn(geometry_arg);
987 w = re.cap(1).toInt();
988 h = re.cap(2).toInt();
989 x = re.cap(3).toInt();
990 y = re.cap(4).toInt();
991 view->setGeometry(x, y, w, h);
998 Clipboard & GuiApplication::clipboard()
1000 return d->clipboard_;
1004 Selection & GuiApplication::selection()
1006 return d->selection_;
1010 FontLoader & GuiApplication::fontLoader()
1012 return d->font_loader_;
1016 Toolbars const & GuiApplication::toolbars() const
1018 return d->toolbars_;
1022 Toolbars & GuiApplication::toolbars()
1024 return d->toolbars_;
1028 Menus const & GuiApplication::menus() const
1034 Menus & GuiApplication::menus()
1040 QList<int> GuiApplication::viewIds() const
1042 return d->views_.keys();
1046 ColorCache & GuiApplication::colorCache()
1048 return d->color_cache_;
1052 int GuiApplication::exec()
1054 // asynchronously handle batch commands. This event will be in
1055 // the event queue in front of other asynchronous events. Hence,
1056 // we can assume in the latter that the gui is setup already.
1057 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1059 return QApplication::exec();
1063 void GuiApplication::exit(int status)
1065 QApplication::exit(status);
1069 void GuiApplication::setGuiLanguage()
1071 // Set the language defined by the user.
1074 QString const default_language = toqstr(Messages::defaultLanguage());
1075 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1076 QLocale const default_locale(default_language);
1077 QLocale::setDefault(default_locale);
1079 // install translation file for Qt built-in dialogs
1080 QString const language_name = QString("qt_") + default_locale.name();
1082 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1083 // Short-named translator can be loaded from a long name, but not the
1084 // opposite. Therefore, long name should be used without truncation.
1085 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1086 if (!d->qt_trans_.load(language_name,
1087 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1088 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1091 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1095 switch (default_locale.language()) {
1096 case QLocale::Arabic :
1097 case QLocale::Hebrew :
1098 case QLocale::Persian :
1099 case QLocale::Urdu :
1100 setLayoutDirection(Qt::RightToLeft);
1103 setLayoutDirection(Qt::LeftToRight);
1108 void GuiApplication::processFuncRequestQueue()
1110 while (!d->func_request_queue_.empty()) {
1111 lyx::dispatch(d->func_request_queue_.back());
1112 d->func_request_queue_.pop();
1117 void GuiApplication::execBatchCommands()
1122 if (!readUIFile(toqstr(lyxrc.ui_file)))
1123 // Gives some error box here.
1127 // Create the global default menubar which is shown for the dialogs
1128 // and if no GuiView is visible.
1129 // This must be done after the session was recovered to know the "last files".
1130 d->global_menubar_ = new GlobalMenuBar();
1131 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1134 lyx::execBatchCommands();
1138 QAbstractItemModel * GuiApplication::languageModel()
1140 if (d->language_model_)
1141 return d->language_model_;
1143 QStandardItemModel * lang_model = new QStandardItemModel(this);
1144 lang_model->insertColumns(0, 1);
1146 Languages::const_iterator it = languages.begin();
1147 Languages::const_iterator end = languages.end();
1148 for (; it != end; ++it) {
1149 current_row = lang_model->rowCount();
1150 lang_model->insertRows(current_row, 1);
1151 QModelIndex item = lang_model->index(current_row, 0);
1152 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1153 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1155 d->language_model_ = new QSortFilterProxyModel(this);
1156 d->language_model_->setSourceModel(lang_model);
1157 #if QT_VERSION >= 0x040300
1158 d->language_model_->setSortLocaleAware(true);
1160 return d->language_model_;
1164 void GuiApplication::restoreGuiSession()
1166 if (!lyxrc.load_session)
1169 Session & session = theSession();
1170 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1171 // do not add to the lastfile list since these files are restored from
1172 // last session, and should be already there (regular files), or should
1173 // not be added at all (help files).
1174 for_each(lastopened.begin(), lastopened.end(),
1175 bind(&GuiView::loadDocument, current_view_, _1, false));
1177 // clear this list to save a few bytes of RAM
1178 session.lastOpened().clear();
1182 QString const GuiApplication::romanFontName()
1185 font.setKerning(false);
1186 font.setStyleHint(QFont::Serif);
1187 font.setFamily("serif");
1189 return QFontInfo(font).family();
1193 QString const GuiApplication::sansFontName()
1196 font.setKerning(false);
1197 font.setStyleHint(QFont::SansSerif);
1198 font.setFamily("sans");
1200 return QFontInfo(font).family();
1204 QString const GuiApplication::typewriterFontName()
1207 font.setKerning(false);
1208 font.setStyleHint(QFont::TypeWriter);
1209 font.setFamily("monospace");
1211 return QFontInfo(font).family();
1215 void GuiApplication::handleRegularEvents()
1217 ForkedCallsController::handleCompletedProcesses();
1221 bool GuiApplication::event(QEvent * e)
1224 case QEvent::FileOpen: {
1225 // Open a file; this happens only on Mac OS X for now.
1227 // We do this asynchronously because on startup the batch
1228 // commands are not executed here yet and the gui is not ready
1230 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1231 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1236 return QApplication::event(e);
1241 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1244 return QApplication::notify(receiver, event);
1246 catch (ExceptionMessage const & e) {
1248 case ErrorException:
1250 setQuitOnLastWindowClosed(false);
1252 Alert::error(e.title_, e.details_);
1254 // Properly crash in debug mode in order to get a useful backtrace.
1257 // In release mode, try to exit gracefully.
1260 case BufferException: {
1261 Buffer * buf = current_view_->buffer();
1262 docstring details = e.details_ + '\n';
1263 details += theBufferList().emergencyWrite(buf);
1264 theBufferList().release(buf);
1265 details += "\n" + _("The current document was closed.");
1266 Alert::error(e.title_, details);
1269 case WarningException:
1270 Alert::warning(e.title_, e.details_);
1274 catch (exception const & e) {
1275 docstring s = _("LyX has caught an exception, it will now "
1276 "attempt to save all unsaved documents and exit."
1278 s += from_ascii(e.what());
1279 Alert::error(_("Software exception Detected"), s);
1283 docstring s = _("LyX has caught some really weird exception, it will "
1284 "now attempt to save all unsaved documents and exit.");
1285 Alert::error(_("Software exception Detected"), s);
1293 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1295 QColor const & qcol = d->color_cache_.get(col);
1296 if (!qcol.isValid()) {
1302 rgbcol.r = qcol.red();
1303 rgbcol.g = qcol.green();
1304 rgbcol.b = qcol.blue();
1309 string const GuiApplication::hexName(ColorCode col)
1311 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1315 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1317 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1318 d->socket_notifiers_[fd] = sn;
1319 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1323 void GuiApplication::socketDataReceived(int fd)
1325 d->socket_notifiers_[fd]->func_();
1329 void GuiApplication::unregisterSocketCallback(int fd)
1331 d->socket_notifiers_.take(fd)->setEnabled(false);
1335 void GuiApplication::commitData(QSessionManager & sm)
1337 /// The implementation is required to avoid an application exit
1338 /// when session state save is triggered by session manager.
1339 /// The default implementation sends a close event to all
1340 /// visible top level widgets when session managment allows
1342 /// We are changing that to close all wiew one by one.
1343 /// FIXME: verify if the default implementation is enough now.
1344 if (sm.allowsInteraction() && !closeAllViews())
1349 void GuiApplication::unregisterView(GuiView * gv)
1351 LASSERT(d->views_[gv->id()] == gv, /**/);
1352 d->views_.remove(gv->id());
1353 if (current_view_ == gv) {
1355 theLyXFunc().setLyXView(0);
1360 bool GuiApplication::closeAllViews()
1362 if (d->views_.empty())
1365 QList<GuiView *> views = d->views_.values();
1366 foreach (GuiView * view, views) {
1376 GuiView & GuiApplication::view(int id) const
1378 LASSERT(d->views_.contains(id), /**/);
1379 return *d->views_.value(id);
1383 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1385 QList<GuiView *> views = d->views_.values();
1386 foreach (GuiView * view, views)
1387 view->hideDialog(name, inset);
1391 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1393 Buffer const * buffer_ = 0;
1394 QHash<int, GuiView *>::iterator end = d->views_.end();
1395 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1396 if (Buffer const * ptr = (*it)->updateInset(inset))
1403 bool GuiApplication::searchMenu(FuncRequest const & func,
1404 docstring_list & names) const
1406 return d->menus_.searchMenu(func, names);
1410 bool GuiApplication::readUIFile(QString const & name, bool include)
1420 LexerKeyword uitags[] = {
1421 { "include", ui_include },
1422 { "menuset", ui_menuset },
1423 { "toolbars", ui_toolbars },
1424 { "toolbarset", ui_toolbarset }
1427 LYXERR(Debug::INIT, "About to read " << name << "...");
1431 ui_path = libFileSearch("ui", name, "inc");
1432 if (ui_path.empty())
1433 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1435 ui_path = libFileSearch("ui", name, "ui");
1438 if (ui_path.empty()) {
1439 LYXERR(Debug::INIT, "Could not find " << name);
1440 Alert::warning(_("Could not find UI definition file"),
1441 bformat(_("Error while reading the configuration file\n%1$s.\n"
1442 "Please check your installation."), qstring_to_ucs4(name)));
1447 // Ensure that a file is read only once (prevents include loops)
1448 static QStringList uifiles;
1449 QString const uifile = toqstr(ui_path.absFilename());
1450 if (uifiles.contains(uifile)) {
1452 // We are reading again the top uifile so reset the safeguard:
1455 d->toolbars_.reset();
1457 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1458 << "Is this an include loop?");
1462 uifiles.push_back(uifile);
1464 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1467 lex.setFile(ui_path);
1469 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1473 if (lyxerr.debugging(Debug::PARSER))
1474 lex.printTable(lyxerr);
1476 while (lex.isOK()) {
1477 switch (lex.lex()) {
1480 QString const file = toqstr(lex.getString());
1481 if (!readUIFile(file, true))
1486 d->menus_.read(lex);
1490 d->toolbars_.readToolbars(lex);
1494 d->toolbars_.readToolbarSettings(lex);
1498 if (!rtrim(lex.getString()).empty())
1499 lex.printError("LyX::ReadUIFile: "
1500 "Unknown menu tag: `$$Token'");
1509 settings.beginGroup("ui_files");
1510 bool touched = false;
1511 for (int i = 0; i != uifiles.size(); ++i) {
1512 QFileInfo fi(uifiles[i]);
1513 QDateTime const date_value = fi.lastModified();
1514 QString const name_key = QString::number(i);
1515 if (!settings.contains(name_key)
1516 || settings.value(name_key).toString() != uifiles[i]
1517 || settings.value(name_key + "/date").toDateTime() != date_value) {
1519 settings.setValue(name_key, uifiles[i]);
1520 settings.setValue(name_key + "/date", date_value);
1523 settings.endGroup();
1525 settings.remove("views");
1531 void GuiApplication::onLastWindowClosed()
1533 if (d->global_menubar_)
1534 d->global_menubar_->grabKeyboard();
1538 ////////////////////////////////////////////////////////////////////////
1540 // X11 specific stuff goes here...
1543 bool GuiApplication::x11EventFilter(XEvent * xev)
1548 switch (xev->type) {
1549 case SelectionRequest: {
1550 if (xev->xselectionrequest.selection != XA_PRIMARY)
1552 LYXERR(Debug::SELECTION, "X requested selection.");
1553 BufferView * bv = current_view_->view();
1555 docstring const sel = bv->requestSelection();
1557 d->selection_.put(sel);
1561 case SelectionClear: {
1562 if (xev->xselectionclear.selection != XA_PRIMARY)
1564 LYXERR(Debug::SELECTION, "Lost selection.");
1565 BufferView * bv = current_view_->view();
1567 bv->clearSelection();
1575 } // namespace frontend
1578 void hideDialogs(std::string const & name, Inset * inset)
1581 theApp()->hideDialogs(name, inset);
1585 ////////////////////////////////////////////////////////////////////
1589 ////////////////////////////////////////////////////////////////////
1591 frontend::FontLoader & theFontLoader()
1593 LASSERT(frontend::guiApp, /**/);
1594 return frontend::guiApp->fontLoader();
1598 frontend::FontMetrics const & theFontMetrics(Font const & f)
1600 return theFontMetrics(f.fontInfo());
1604 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1606 LASSERT(frontend::guiApp, /**/);
1607 return frontend::guiApp->fontLoader().metrics(f);
1611 ////////////////////////////////////////////////////////////////////
1615 ////////////////////////////////////////////////////////////////////
1617 frontend::Clipboard & theClipboard()
1619 LASSERT(frontend::guiApp, /**/);
1620 return frontend::guiApp->clipboard();
1624 frontend::Selection & theSelection()
1626 LASSERT(frontend::guiApp, /**/);
1627 return frontend::guiApp->selection();
1633 #include "moc_GuiApplication.cpp"