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(' ', '_');
322 name1.replace('\\', "backslash");
326 FileName fname = libFileSearch("images/" + path, name1, "png");
328 return toqstr(fname.absFilename());
330 fname = libFileSearch("images/" + path, name2, "png");
332 return toqstr(fname.absFilename());
334 path = ":/images/" + path;
337 LYXERR0("Directory " << path << " not found in resource!");
341 if (res.exists(name1))
345 if (res.exists(name2))
348 LYXERR(Debug::GUI, "Cannot find icon with filename "
349 << "\"" << name1 << "\""
351 << "\"" << name2 << "\""
353 << lyxaction.getActionName(f.action)
354 << '(' << to_utf8(f.argument()) << ")\"");
357 return QString(":/images/unknown.png");
363 QIcon getIcon(FuncRequest const & f, bool unknown)
365 QString icon = iconName(f, unknown);
369 //LYXERR(Debug::GUI, "Found icon: " << icon);
371 if (!pm.load(icon)) {
372 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
380 ////////////////////////////////////////////////////////////////////////
382 // LyX server support code.
384 ////////////////////////////////////////////////////////////////////////
386 class SocketNotifier : public QSocketNotifier
389 /// connect a connection notification from the LyXServerSocket
390 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
391 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
395 /// The callback function
396 Application::SocketCallback func_;
400 ////////////////////////////////////////////////////////////////////////
402 // Mac specific stuff goes here...
404 ////////////////////////////////////////////////////////////////////////
406 class MenuTranslator : public QTranslator
409 MenuTranslator(QObject * parent)
410 : QTranslator(parent)
413 QString translate(const char * /*context*/,
414 const char * sourceText,
415 const char * /*comment*/ = 0)
417 string const s = sourceText;
418 if (s == N_("About %1") || s == N_("Preferences")
419 || s == N_("Reconfigure") || s == N_("Quit %1"))
426 class GlobalMenuBar : public QMenuBar
430 GlobalMenuBar() : QMenuBar(0) {}
433 bool event(QEvent * e)
435 if (e->type() == QEvent::ShortcutOverride) {
436 // && activeWindow() == 0) {
437 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
439 setKeySymbol(&sym, ke);
440 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
449 // QMacPasteboardMimeGraphics can only be compiled on Mac.
451 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
454 QMacPasteboardMimeGraphics()
455 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
458 QString convertorName() { return "Graphics"; }
460 QString flavorFor(QString const & mime)
462 LYXERR(Debug::ACTION, "flavorFor " << mime);
463 if (mime == pdfMimeType())
464 return QLatin1String("com.adobe.pdf");
468 QString mimeFor(QString flav)
470 LYXERR(Debug::ACTION, "mimeFor " << flav);
471 if (flav == QLatin1String("com.adobe.pdf"))
472 return pdfMimeType();
476 bool canConvert(QString const & mime, QString flav)
478 return mimeFor(flav) == mime;
481 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
485 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
489 QList<QByteArray> convertFromMime(QString const & /*mime*/,
490 QVariant data, QString /*flav*/)
492 QList<QByteArray> ret;
493 ret.append(data.toByteArray());
499 ///////////////////////////////////////////////////////////////
501 // You can find more platform specific stuff at the end of this file...
503 ///////////////////////////////////////////////////////////////
505 ////////////////////////////////////////////////////////////////////////
506 // Windows specific stuff goes here...
509 // QWindowsMimeMetafile can only be compiled on Windows.
511 static FORMATETC cfFromMime(QString const & mimetype)
514 if (mimetype == emfMimeType()) {
515 formatetc.cfFormat = CF_ENHMETAFILE;
516 formatetc.tymed = TYMED_ENHMF;
517 } else if (mimetype == wmfMimeType()) {
518 formatetc.cfFormat = CF_METAFILEPICT;
519 formatetc.tymed = TYMED_MFPICT;
522 formatetc.dwAspect = DVASPECT_CONTENT;
523 formatetc.lindex = -1;
528 class QWindowsMimeMetafile : public QWindowsMime {
530 QWindowsMimeMetafile() {}
532 bool canConvertFromMime(FORMATETC const & formatetc,
533 QMimeData const * mimedata) const
538 bool canConvertToMime(QString const & mimetype,
539 IDataObject * pDataObj) const
541 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
543 FORMATETC formatetc = cfFromMime(mimetype);
544 return pDataObj->QueryGetData(&formatetc) == S_OK;
547 bool convertFromMime(FORMATETC const & formatetc,
548 const QMimeData * mimedata, STGMEDIUM * pmedium) const
553 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
554 QVariant::Type preferredType) const
557 if (!canConvertToMime(mimetype, pDataObj))
560 FORMATETC formatetc = cfFromMime(mimetype);
562 if (pDataObj->GetData(&formatetc, &s) != S_OK)
566 if (s.tymed == TYMED_ENHMF) {
567 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
568 data.resize(dataSize);
569 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
570 (LPBYTE)data.data());
571 } else if (s.tymed == TYMED_MFPICT) {
572 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
573 data.resize(dataSize);
574 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
575 (LPBYTE)data.data());
578 ReleaseStgMedium(&s);
584 QVector<FORMATETC> formatsForMime(QString const & mimetype,
585 QMimeData const * mimedata) const
587 QVector<FORMATETC> formats;
588 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
589 formats += cfFromMime(mimetype);
593 QString mimeForFormat(FORMATETC const & formatetc) const
595 switch (formatetc.cfFormat) {
597 return emfMimeType();
598 case CF_METAFILEPICT:
599 return wmfMimeType();
607 ////////////////////////////////////////////////////////////////////////
608 // GuiApplication::Private definition and implementation.
609 ////////////////////////////////////////////////////////////////////////
611 struct GuiApplication::Private
613 Private(): language_model_(0), global_menubar_(0) {}
616 QSortFilterProxyModel * language_model_;
618 GuiClipboard clipboard_;
620 GuiSelection selection_;
622 FontLoader font_loader_;
624 ColorCache color_cache_;
626 QTranslator qt_trans_;
628 QHash<int, SocketNotifier *> socket_notifiers_;
632 /// The global instance
635 /// this timer is used for any regular events one wants to
636 /// perform. at present it is used to check if forked processes
638 QTimer general_timer_;
640 /// delayed FuncRequests
641 std::queue<FuncRequest> func_request_queue_;
643 /// Multiple views container.
645 * Warning: This must not be a smart pointer as the destruction of the
646 * object is handled by Qt when the view is closed
647 * \sa Qt::WA_DeleteOnClose attribute.
649 QHash<int, GuiView *> views_;
651 /// Only used on mac.
652 GlobalMenuBar * global_menubar_;
655 /// Linkback mime handler for MacOSX.
656 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
660 /// WMF Mime handler for Windows clipboard.
661 /// \warning: see comment in ~GuiApplication and in bug 4846.
662 QWindowsMimeMetafile wmf_mime_;
667 GuiApplication * guiApp;
669 GuiApplication::~GuiApplication()
672 closeAllLinkBackLinks();
674 // FIXME: Work around bug 4846 for Windows Vista and Qt4
675 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
676 // If the clipboard is not cleared, LyX crashes on exit when it is
677 // compiled in release mode and if there is something in the clipboard.
678 // This is related to QWindowsMimeMetafile which is apparently not
679 // properly destroyed.
680 qApp->clipboard()->clear(QClipboard::Clipboard);
685 GuiApplication::GuiApplication(int & argc, char ** argv)
686 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
688 QString app_name = "LyX";
689 QCoreApplication::setOrganizationName(app_name);
690 QCoreApplication::setOrganizationDomain("lyx.org");
691 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
693 // Install translator for GUI elements.
694 installTranslator(&d->qt_trans_);
696 // FIXME: quitOnLastWindowClosed is true by default. We should have a
697 // lyxrc setting for this in order to let the application stay resident.
698 // But then we need some kind of dock icon, at least on Windows.
700 if (lyxrc.quit_on_last_window_closed)
701 setQuitOnLastWindowClosed(false);
704 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
705 // seems to be the default case for applications like LyX.
706 setQuitOnLastWindowClosed(false);
708 // This allows to translate the strings that appear in the LyX menu.
709 /// A translator suitable for the entries in the LyX menu.
710 /// Only needed with Qt/Mac.
711 installTranslator(new MenuTranslator(this));
715 // doubleClickInterval() is 400 ms on X11 which is just too long.
716 // On Windows and Mac OS X, the operating system's value is used.
717 // On Microsoft Windows, calling this function sets the double
718 // click interval for all applications. So we don't!
719 QApplication::setDoubleClickInterval(300);
722 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
724 // needs to be done before reading lyxrc
726 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
730 // Set the cache to 5120 kilobytes which corresponds to screen size of
731 // 1280 by 1024 pixels with a color depth of 32 bits.
732 QPixmapCache::setCacheLimit(5120);
734 // Initialize RC Fonts
735 if (lyxrc.roman_font_name.empty())
736 lyxrc.roman_font_name = fromqstr(romanFontName());
738 if (lyxrc.sans_font_name.empty())
739 lyxrc.sans_font_name = fromqstr(sansFontName());
741 if (lyxrc.typewriter_font_name.empty())
742 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
744 d->general_timer_.setInterval(500);
745 connect(&d->general_timer_, SIGNAL(timeout()),
746 this, SLOT(handleRegularEvents()));
747 d->general_timer_.start();
751 GuiApplication * theGuiApp()
753 return dynamic_cast<GuiApplication *>(theApp());
757 void GuiApplication::clearSession()
764 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
766 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
771 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
777 case LFUN_WINDOW_CLOSE:
778 enable = d->views_.size() > 0;
781 case LFUN_BUFFER_NEW:
782 case LFUN_BUFFER_NEW_TEMPLATE:
784 case LFUN_SCREEN_FONT_UPDATE:
786 case LFUN_WINDOW_NEW:
796 flag.setEnabled(false);
802 bool GuiApplication::dispatch(FuncRequest const & cmd)
804 switch (cmd.action) {
806 case LFUN_WINDOW_NEW:
807 createView(toqstr(cmd.argument()));
810 case LFUN_WINDOW_CLOSE:
811 // update bookmark pit of the current buffer before window close
812 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
813 theLyXFunc().gotoBookmark(i+1, false, false);
814 current_view_->close();
818 // quitting is triggered by the gui code
819 // (leaving the event loop).
821 current_view_->message(from_utf8(N_("Exiting.")));
826 case LFUN_SCREEN_FONT_UPDATE: {
827 // handle the screen font changes.
828 d->font_loader_.update();
829 // Backup current_view_
830 GuiView * view = current_view_;
831 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
832 // to skip the refresh.
834 BufferList::iterator it = theBufferList().begin();
835 BufferList::iterator const end = theBufferList().end();
836 for (; it != end; ++it)
838 // Restore current_view_
839 current_view_ = view;
843 case LFUN_BUFFER_NEW:
844 if (d->views_.empty()
845 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
846 createView(QString(), false); // keep hidden
847 current_view_->newDocument(to_utf8(cmd.argument()), false);
848 current_view_->show();
849 setActiveWindow(current_view_);
851 current_view_->newDocument(to_utf8(cmd.argument()), false);
855 case LFUN_BUFFER_NEW_TEMPLATE:
856 if (d->views_.empty()
857 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
859 current_view_->newDocument(to_utf8(cmd.argument()), true);
860 if (!current_view_->buffer())
861 current_view_->close();
863 current_view_->newDocument(to_utf8(cmd.argument()), true);
868 if (d->views_.empty()
869 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
870 string const fname = to_utf8(cmd.argument());
871 // We want the ui session to be saved per document and not per
872 // window number. The filename crc is a good enough identifier.
873 boost::crc_32_type crc;
874 crc = for_each(fname.begin(), fname.end(), crc);
875 createView(crc.checksum());
876 current_view_->openDocument(fname);
877 if (current_view_ && !current_view_->buffer())
878 current_view_->close();
880 current_view_->openDocument(to_utf8(cmd.argument()));
883 case LFUN_SET_COLOR: {
885 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
886 if (lyx_name.empty() || x11_name.empty()) {
887 current_view_->message(
888 _("Syntax: set-color <lyx_name> <x11_name>"));
892 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
893 bool const graphicsbg_changed = lyx_name == graphicsbg
894 && x11_name != graphicsbg;
895 if (graphicsbg_changed) {
896 // FIXME: The graphics cache no longer has a changeDisplay method.
898 graphics::GCache::get().changeDisplay(true);
902 if (!lcolor.setColor(lyx_name, x11_name)) {
903 current_view_->message(
904 bformat(_("Set-color \"%1$s\" failed "
905 "- color is undefined or "
906 "may not be redefined"),
907 from_utf8(lyx_name)));
910 // Make sure we don't keep old colors in cache.
911 d->color_cache_.clear();
916 // Notify the caller that the action has not been dispatched.
920 // The action has been dispatched.
925 void GuiApplication::dispatchDelayed(FuncRequest const & func)
927 d->func_request_queue_.push(func);
928 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
932 void GuiApplication::resetGui()
934 // Set the language defined by the user.
938 if (!readUIFile(toqstr(lyxrc.ui_file)))
939 // Gives some error box here.
942 if (d->global_menubar_)
943 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
945 QHash<int, GuiView *>::iterator it;
946 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
948 gv->setLayoutDirection(layoutDirection());
952 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
956 void GuiApplication::createView(int view_id)
958 createView(QString(), true, view_id);
962 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
965 // release the keyboard which might have been grabed by the global
966 // menubar on Mac to catch shortcuts even without any GuiView.
967 if (d->global_menubar_)
968 d->global_menubar_->releaseKeyboard();
973 while (d->views_.find(id) != d->views_.end())
976 LYXERR(Debug::GUI, "About to create new window with ID " << id);
977 GuiView * view = new GuiView(id);
979 d->views_[id] = view;
983 setActiveWindow(view);
986 if (!geometry_arg.isEmpty()) {
990 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
991 re.indexIn(geometry_arg);
992 w = re.cap(1).toInt();
993 h = re.cap(2).toInt();
994 x = re.cap(3).toInt();
995 y = re.cap(4).toInt();
996 view->setGeometry(x, y, w, h);
1003 Clipboard & GuiApplication::clipboard()
1005 return d->clipboard_;
1009 Selection & GuiApplication::selection()
1011 return d->selection_;
1015 FontLoader & GuiApplication::fontLoader()
1017 return d->font_loader_;
1021 Toolbars const & GuiApplication::toolbars() const
1023 return d->toolbars_;
1027 Toolbars & GuiApplication::toolbars()
1029 return d->toolbars_;
1033 Menus const & GuiApplication::menus() const
1039 Menus & GuiApplication::menus()
1045 QList<int> GuiApplication::viewIds() const
1047 return d->views_.keys();
1051 ColorCache & GuiApplication::colorCache()
1053 return d->color_cache_;
1057 int GuiApplication::exec()
1059 // asynchronously handle batch commands. This event will be in
1060 // the event queue in front of other asynchronous events. Hence,
1061 // we can assume in the latter that the gui is setup already.
1062 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1064 return QApplication::exec();
1068 void GuiApplication::exit(int status)
1070 QApplication::exit(status);
1074 void GuiApplication::setGuiLanguage()
1076 // Set the language defined by the user.
1079 QString const default_language = toqstr(Messages::defaultLanguage());
1080 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1081 QLocale const default_locale(default_language);
1082 QLocale::setDefault(default_locale);
1084 // install translation file for Qt built-in dialogs
1085 QString const language_name = QString("qt_") + default_locale.name();
1087 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1088 // Short-named translator can be loaded from a long name, but not the
1089 // opposite. Therefore, long name should be used without truncation.
1090 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1091 if (!d->qt_trans_.load(language_name,
1092 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1093 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1096 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1100 switch (default_locale.language()) {
1101 case QLocale::Arabic :
1102 case QLocale::Hebrew :
1103 case QLocale::Persian :
1104 case QLocale::Urdu :
1105 setLayoutDirection(Qt::RightToLeft);
1108 setLayoutDirection(Qt::LeftToRight);
1113 void GuiApplication::processFuncRequestQueue()
1115 while (!d->func_request_queue_.empty()) {
1116 lyx::dispatch(d->func_request_queue_.back());
1117 d->func_request_queue_.pop();
1122 void GuiApplication::execBatchCommands()
1127 if (!readUIFile(toqstr(lyxrc.ui_file)))
1128 // Gives some error box here.
1132 // Create the global default menubar which is shown for the dialogs
1133 // and if no GuiView is visible.
1134 // This must be done after the session was recovered to know the "last files".
1135 d->global_menubar_ = new GlobalMenuBar();
1136 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1139 lyx::execBatchCommands();
1143 QAbstractItemModel * GuiApplication::languageModel()
1145 if (d->language_model_)
1146 return d->language_model_;
1148 QStandardItemModel * lang_model = new QStandardItemModel(this);
1149 lang_model->insertColumns(0, 1);
1151 Languages::const_iterator it = languages.begin();
1152 Languages::const_iterator end = languages.end();
1153 for (; it != end; ++it) {
1154 current_row = lang_model->rowCount();
1155 lang_model->insertRows(current_row, 1);
1156 QModelIndex item = lang_model->index(current_row, 0);
1157 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1158 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1160 d->language_model_ = new QSortFilterProxyModel(this);
1161 d->language_model_->setSourceModel(lang_model);
1162 #if QT_VERSION >= 0x040300
1163 d->language_model_->setSortLocaleAware(true);
1165 return d->language_model_;
1169 void GuiApplication::restoreGuiSession()
1171 if (!lyxrc.load_session)
1174 Session & session = theSession();
1175 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1176 // do not add to the lastfile list since these files are restored from
1177 // last session, and should be already there (regular files), or should
1178 // not be added at all (help files).
1179 for_each(lastopened.begin(), lastopened.end(),
1180 bind(&GuiView::loadDocument, current_view_, _1, false));
1182 // clear this list to save a few bytes of RAM
1183 session.lastOpened().clear();
1187 QString const GuiApplication::romanFontName()
1190 font.setKerning(false);
1191 font.setStyleHint(QFont::Serif);
1192 font.setFamily("serif");
1194 return QFontInfo(font).family();
1198 QString const GuiApplication::sansFontName()
1201 font.setKerning(false);
1202 font.setStyleHint(QFont::SansSerif);
1203 font.setFamily("sans");
1205 return QFontInfo(font).family();
1209 QString const GuiApplication::typewriterFontName()
1212 font.setKerning(false);
1213 font.setStyleHint(QFont::TypeWriter);
1214 font.setFamily("monospace");
1216 return QFontInfo(font).family();
1220 void GuiApplication::handleRegularEvents()
1222 ForkedCallsController::handleCompletedProcesses();
1226 bool GuiApplication::event(QEvent * e)
1229 case QEvent::FileOpen: {
1230 // Open a file; this happens only on Mac OS X for now.
1232 // We do this asynchronously because on startup the batch
1233 // commands are not executed here yet and the gui is not ready
1235 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1236 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1241 return QApplication::event(e);
1246 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1249 return QApplication::notify(receiver, event);
1251 catch (ExceptionMessage const & e) {
1253 case ErrorException:
1255 setQuitOnLastWindowClosed(false);
1257 Alert::error(e.title_, e.details_);
1259 // Properly crash in debug mode in order to get a useful backtrace.
1262 // In release mode, try to exit gracefully.
1265 case BufferException: {
1266 Buffer * buf = current_view_->buffer();
1267 docstring details = e.details_ + '\n';
1268 details += theBufferList().emergencyWrite(buf);
1269 theBufferList().release(buf);
1270 details += "\n" + _("The current document was closed.");
1271 Alert::error(e.title_, details);
1274 case WarningException:
1275 Alert::warning(e.title_, e.details_);
1279 catch (exception const & e) {
1280 docstring s = _("LyX has caught an exception, it will now "
1281 "attempt to save all unsaved documents and exit."
1283 s += from_ascii(e.what());
1284 Alert::error(_("Software exception Detected"), s);
1288 docstring s = _("LyX has caught some really weird exception, it will "
1289 "now attempt to save all unsaved documents and exit.");
1290 Alert::error(_("Software exception Detected"), s);
1298 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1300 QColor const & qcol = d->color_cache_.get(col);
1301 if (!qcol.isValid()) {
1307 rgbcol.r = qcol.red();
1308 rgbcol.g = qcol.green();
1309 rgbcol.b = qcol.blue();
1314 string const GuiApplication::hexName(ColorCode col)
1316 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1320 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1322 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1323 d->socket_notifiers_[fd] = sn;
1324 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1328 void GuiApplication::socketDataReceived(int fd)
1330 d->socket_notifiers_[fd]->func_();
1334 void GuiApplication::unregisterSocketCallback(int fd)
1336 d->socket_notifiers_.take(fd)->setEnabled(false);
1340 void GuiApplication::commitData(QSessionManager & sm)
1342 /// The implementation is required to avoid an application exit
1343 /// when session state save is triggered by session manager.
1344 /// The default implementation sends a close event to all
1345 /// visible top level widgets when session managment allows
1347 /// We are changing that to close all wiew one by one.
1348 /// FIXME: verify if the default implementation is enough now.
1349 if (sm.allowsInteraction() && !closeAllViews())
1354 void GuiApplication::unregisterView(GuiView * gv)
1356 LASSERT(d->views_[gv->id()] == gv, /**/);
1357 d->views_.remove(gv->id());
1358 if (current_view_ == gv) {
1360 theLyXFunc().setLyXView(0);
1365 bool GuiApplication::closeAllViews()
1367 if (d->views_.empty())
1370 QList<GuiView *> views = d->views_.values();
1371 foreach (GuiView * view, views) {
1381 GuiView & GuiApplication::view(int id) const
1383 LASSERT(d->views_.contains(id), /**/);
1384 return *d->views_.value(id);
1388 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1390 QList<GuiView *> views = d->views_.values();
1391 foreach (GuiView * view, views)
1392 view->hideDialog(name, inset);
1396 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1398 Buffer const * buffer_ = 0;
1399 QHash<int, GuiView *>::iterator end = d->views_.end();
1400 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1401 if (Buffer const * ptr = (*it)->updateInset(inset))
1408 bool GuiApplication::searchMenu(FuncRequest const & func,
1409 docstring_list & names) const
1411 return d->menus_.searchMenu(func, names);
1415 bool GuiApplication::readUIFile(QString const & name, bool include)
1425 LexerKeyword uitags[] = {
1426 { "include", ui_include },
1427 { "menuset", ui_menuset },
1428 { "toolbars", ui_toolbars },
1429 { "toolbarset", ui_toolbarset }
1432 LYXERR(Debug::INIT, "About to read " << name << "...");
1436 ui_path = libFileSearch("ui", name, "inc");
1437 if (ui_path.empty())
1438 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1440 ui_path = libFileSearch("ui", name, "ui");
1443 if (ui_path.empty()) {
1444 LYXERR(Debug::INIT, "Could not find " << name);
1445 Alert::warning(_("Could not find UI definition file"),
1446 bformat(_("Error while reading the configuration file\n%1$s.\n"
1447 "Please check your installation."), qstring_to_ucs4(name)));
1452 // Ensure that a file is read only once (prevents include loops)
1453 static QStringList uifiles;
1454 QString const uifile = toqstr(ui_path.absFilename());
1455 if (uifiles.contains(uifile)) {
1457 // We are reading again the top uifile so reset the safeguard:
1460 d->toolbars_.reset();
1462 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1463 << "Is this an include loop?");
1467 uifiles.push_back(uifile);
1469 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1472 lex.setFile(ui_path);
1474 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1478 if (lyxerr.debugging(Debug::PARSER))
1479 lex.printTable(lyxerr);
1481 while (lex.isOK()) {
1482 switch (lex.lex()) {
1485 QString const file = toqstr(lex.getString());
1486 if (!readUIFile(file, true))
1491 d->menus_.read(lex);
1495 d->toolbars_.readToolbars(lex);
1499 d->toolbars_.readToolbarSettings(lex);
1503 if (!rtrim(lex.getString()).empty())
1504 lex.printError("LyX::ReadUIFile: "
1505 "Unknown menu tag: `$$Token'");
1514 settings.beginGroup("ui_files");
1515 bool touched = false;
1516 for (int i = 0; i != uifiles.size(); ++i) {
1517 QFileInfo fi(uifiles[i]);
1518 QDateTime const date_value = fi.lastModified();
1519 QString const name_key = QString::number(i);
1520 if (!settings.contains(name_key)
1521 || settings.value(name_key).toString() != uifiles[i]
1522 || settings.value(name_key + "/date").toDateTime() != date_value) {
1524 settings.setValue(name_key, uifiles[i]);
1525 settings.setValue(name_key + "/date", date_value);
1528 settings.endGroup();
1530 settings.remove("views");
1536 void GuiApplication::onLastWindowClosed()
1538 if (d->global_menubar_)
1539 d->global_menubar_->grabKeyboard();
1543 ////////////////////////////////////////////////////////////////////////
1545 // X11 specific stuff goes here...
1548 bool GuiApplication::x11EventFilter(XEvent * xev)
1553 switch (xev->type) {
1554 case SelectionRequest: {
1555 if (xev->xselectionrequest.selection != XA_PRIMARY)
1557 LYXERR(Debug::SELECTION, "X requested selection.");
1558 BufferView * bv = current_view_->view();
1560 docstring const sel = bv->requestSelection();
1562 d->selection_.put(sel);
1566 case SelectionClear: {
1567 if (xev->xselectionclear.selection != XA_PRIMARY)
1569 LYXERR(Debug::SELECTION, "Lost selection.");
1570 BufferView * bv = current_view_->view();
1572 bv->clearSelection();
1580 } // namespace frontend
1583 void hideDialogs(std::string const & name, Inset * inset)
1586 theApp()->hideDialogs(name, inset);
1590 ////////////////////////////////////////////////////////////////////
1594 ////////////////////////////////////////////////////////////////////
1596 frontend::FontLoader & theFontLoader()
1598 LASSERT(frontend::guiApp, /**/);
1599 return frontend::guiApp->fontLoader();
1603 frontend::FontMetrics const & theFontMetrics(Font const & f)
1605 return theFontMetrics(f.fontInfo());
1609 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1611 LASSERT(frontend::guiApp, /**/);
1612 return frontend::guiApp->fontLoader().metrics(f);
1616 ////////////////////////////////////////////////////////////////////
1620 ////////////////////////////////////////////////////////////////////
1622 frontend::Clipboard & theClipboard()
1624 LASSERT(frontend::guiApp, /**/);
1625 return frontend::guiApp->clipboard();
1629 frontend::Selection & theSelection()
1631 LASSERT(frontend::guiApp, /**/);
1632 return frontend::guiApp->selection();
1638 #include "moc_GuiApplication.cpp"