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"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
43 #include "LyXAction.h"
49 #include "support/lassert.h"
50 #include "support/debug.h"
51 #include "support/ExceptionMessage.h"
52 #include "support/FileName.h"
53 #include "support/foreach.h"
54 #include "support/ForkedCalls.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/lyxalgo.h" // sorted
58 #include "support/Messages.h"
59 #include "support/os.h"
60 #include "support/Package.h"
63 #include "support/linkback/LinkBackProxy.h"
73 #include <QFileOpenEvent>
77 #include <QImageReader>
79 #include <QLibraryInfo>
81 #include <QMacPasteboardMime>
86 #include <QPixmapCache>
88 #include <QSessionManager>
90 #include <QSocketNotifier>
91 #include <QSortFilterProxyModel>
92 #include <QStandardItemModel>
95 #include <QTranslator>
99 #include <X11/Xatom.h>
100 #include <X11/Xlib.h>
106 #include <QWindowsMime>
113 #include <boost/bind.hpp>
114 #include <boost/crc.hpp>
120 using namespace lyx::support;
123 static void initializeResources()
125 static bool initialized = false;
127 Q_INIT_RESOURCE(Resources);
135 frontend::Application * createApplication(int & argc, char * argv[])
138 // prune -geometry argument(s) by shifting
139 // the following ones 2 places down.
140 for (int i = 0 ; i < argc ; ++i) {
141 if (strcmp(argv[i], "-geometry") == 0) {
142 int const remove = (i+1) < argc ? 2 : 1;
144 for (int j = i; j < argc; ++j)
145 argv[j] = argv[j + remove];
150 return new frontend::GuiApplication(argc, argv);
156 /// Return the list of loadable formats.
157 vector<string> loadableImageFormats()
161 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
163 LYXERR(Debug::GRAPHICS,
164 "\nThe image loader can load the following directly:\n");
166 if (qt_formats.empty())
167 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
169 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
171 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
173 string ext = ascii_lowercase((const char *) *it);
184 ////////////////////////////////////////////////////////////////////////
186 // Icon loading support code
188 ////////////////////////////////////////////////////////////////////////
198 bool operator<(PngMap const & lhs, PngMap const & rhs)
200 return lhs.key < rhs.key;
206 CompareKey(QString const & name) : name_(name) {}
207 bool operator()(PngMap const & other) const { return other.key == name_; }
213 // this must be sorted alphabetically
214 // Upper case comes before lower case
215 PngMap sorted_png_map[] = {
216 { "Bumpeq", "bumpeq2" },
219 { "Delta", "delta2" },
220 { "Downarrow", "downarrow2" },
221 { "Gamma", "gamma2" },
222 { "Lambda", "lambda2" },
223 { "Leftarrow", "leftarrow2" },
224 { "Leftrightarrow", "leftrightarrow2" },
225 { "Longleftarrow", "longleftarrow2" },
226 { "Longleftrightarrow", "longleftrightarrow2" },
227 { "Longrightarrow", "longrightarrow2" },
228 { "Omega", "omega2" },
232 { "Rightarrow", "rightarrow2" },
233 { "Sigma", "sigma2" },
234 { "Subset", "subset2" },
235 { "Supset", "supset2" },
236 { "Theta", "theta2" },
237 { "Uparrow", "uparrow2" },
238 { "Updownarrow", "updownarrow2" },
239 { "Upsilon", "upsilon2" },
240 { "Vdash", "vdash3" },
243 { "nLeftarrow", "nleftarrow2" },
244 { "nLeftrightarrow", "nleftrightarrow2" },
245 { "nRightarrow", "nrightarrow2" },
246 { "nVDash", "nvdash3" },
247 { "nvDash", "nvdash2" },
248 { "textrm \\AA", "textrm_AA"},
249 { "textrm \\O", "textrm_O"},
250 { "vDash", "vdash2" }
253 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
256 QString findPng(QString const & name)
258 PngMap const * const begin = sorted_png_map;
259 PngMap const * const end = begin + nr_sorted_png_map;
260 LASSERT(sorted(begin, end), /**/);
262 PngMap const * const it = find_if(begin, end, CompareKey(name));
266 png_name = it->value;
269 png_name.replace('_', "underscore");
270 png_name.replace(' ', '_');
272 // This way we can have "math-delim { }" on the toolbar.
273 png_name.replace('(', "lparen");
274 png_name.replace(')', "rparen");
275 png_name.replace('[', "lbracket");
276 png_name.replace(']', "rbracket");
277 png_name.replace('{', "lbrace");
278 png_name.replace('}', "rbrace");
279 png_name.replace('|', "bars");
280 png_name.replace(',', "thinspace");
281 png_name.replace(':', "mediumspace");
282 png_name.replace(';', "thickspace");
283 png_name.replace('!', "negthinspace");
286 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
287 << "Looking for math PNG called \"" << png_name << '"');
294 QString iconName(FuncRequest const & f, bool unknown)
296 initializeResources();
301 case LFUN_MATH_INSERT:
302 if (!f.argument().empty()) {
304 name1 = findPng(toqstr(f.argument()).mid(1));
307 case LFUN_MATH_DELIM:
308 case LFUN_MATH_BIGDELIM:
310 name1 = findPng(toqstr(f.argument()));
314 name1 = toqstr(f.argument());
316 case LFUN_COMMAND_ALTERNATIVES: {
317 // use the first of the alternative commands
319 docstring dummy = split(f.argument(), firstcom, ';');
320 name1 = toqstr(firstcom);
321 name1.replace(' ', '_');
325 name2 = toqstr(lyxaction.getActionName(f.action));
328 if (!f.argument().empty()) {
329 name1 = name2 + ' ' + toqstr(f.argument());
330 name1.replace(' ', '_');
331 name1.replace('\\', "backslash");
335 FileName fname = libFileSearch("images/" + path, name1, "png");
337 return toqstr(fname.absFilename());
339 fname = libFileSearch("images/" + path, name2, "png");
341 return toqstr(fname.absFilename());
343 path = ":/images/" + path;
346 LYXERR0("Directory " << path << " not found in resource!");
350 if (res.exists(name1))
354 if (res.exists(name2))
357 LYXERR(Debug::GUI, "Cannot find icon with filename "
358 << "\"" << name1 << "\""
360 << "\"" << name2 << "\""
362 << lyxaction.getActionName(f.action)
363 << '(' << to_utf8(f.argument()) << ")\"");
366 return QString(":/images/unknown.png");
372 QIcon getIcon(FuncRequest const & f, bool unknown)
374 QString icon = iconName(f, unknown);
378 //LYXERR(Debug::GUI, "Found icon: " << icon);
380 if (!pm.load(icon)) {
381 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
389 ////////////////////////////////////////////////////////////////////////
391 // LyX server support code.
393 ////////////////////////////////////////////////////////////////////////
395 class SocketNotifier : public QSocketNotifier
398 /// connect a connection notification from the LyXServerSocket
399 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
400 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
404 /// The callback function
405 Application::SocketCallback func_;
409 ////////////////////////////////////////////////////////////////////////
411 // Mac specific stuff goes here...
413 ////////////////////////////////////////////////////////////////////////
415 class MenuTranslator : public QTranslator
418 MenuTranslator(QObject * parent)
419 : QTranslator(parent)
422 QString translate(const char * /*context*/,
423 const char * sourceText,
424 const char * /*comment*/ = 0)
426 string const s = sourceText;
427 if (s == N_("About %1") || s == N_("Preferences")
428 || s == N_("Reconfigure") || s == N_("Quit %1"))
435 class GlobalMenuBar : public QMenuBar
439 GlobalMenuBar() : QMenuBar(0) {}
442 bool event(QEvent * e)
444 if (e->type() == QEvent::ShortcutOverride) {
445 // && activeWindow() == 0) {
446 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
448 setKeySymbol(&sym, ke);
449 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
458 // QMacPasteboardMimeGraphics can only be compiled on Mac.
460 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
463 QMacPasteboardMimeGraphics()
464 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
467 QString convertorName() { return "Graphics"; }
469 QString flavorFor(QString const & mime)
471 LYXERR(Debug::ACTION, "flavorFor " << mime);
472 if (mime == pdfMimeType())
473 return QLatin1String("com.adobe.pdf");
477 QString mimeFor(QString flav)
479 LYXERR(Debug::ACTION, "mimeFor " << flav);
480 if (flav == QLatin1String("com.adobe.pdf"))
481 return pdfMimeType();
485 bool canConvert(QString const & mime, QString flav)
487 return mimeFor(flav) == mime;
490 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
494 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
498 QList<QByteArray> convertFromMime(QString const & /*mime*/,
499 QVariant data, QString /*flav*/)
501 QList<QByteArray> ret;
502 ret.append(data.toByteArray());
508 ///////////////////////////////////////////////////////////////
510 // You can find more platform specific stuff at the end of this file...
512 ///////////////////////////////////////////////////////////////
514 ////////////////////////////////////////////////////////////////////////
515 // Windows specific stuff goes here...
518 // QWindowsMimeMetafile can only be compiled on Windows.
520 static FORMATETC cfFromMime(QString const & mimetype)
523 if (mimetype == emfMimeType()) {
524 formatetc.cfFormat = CF_ENHMETAFILE;
525 formatetc.tymed = TYMED_ENHMF;
526 } else if (mimetype == wmfMimeType()) {
527 formatetc.cfFormat = CF_METAFILEPICT;
528 formatetc.tymed = TYMED_MFPICT;
531 formatetc.dwAspect = DVASPECT_CONTENT;
532 formatetc.lindex = -1;
537 class QWindowsMimeMetafile : public QWindowsMime {
539 QWindowsMimeMetafile() {}
541 bool canConvertFromMime(FORMATETC const & formatetc,
542 QMimeData const * mimedata) const
547 bool canConvertToMime(QString const & mimetype,
548 IDataObject * pDataObj) const
550 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
552 FORMATETC formatetc = cfFromMime(mimetype);
553 return pDataObj->QueryGetData(&formatetc) == S_OK;
556 bool convertFromMime(FORMATETC const & formatetc,
557 const QMimeData * mimedata, STGMEDIUM * pmedium) const
562 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
563 QVariant::Type preferredType) const
566 if (!canConvertToMime(mimetype, pDataObj))
569 FORMATETC formatetc = cfFromMime(mimetype);
571 if (pDataObj->GetData(&formatetc, &s) != S_OK)
575 if (s.tymed == TYMED_ENHMF) {
576 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
577 data.resize(dataSize);
578 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
579 (LPBYTE)data.data());
580 } else if (s.tymed == TYMED_MFPICT) {
581 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
582 data.resize(dataSize);
583 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
584 (LPBYTE)data.data());
587 ReleaseStgMedium(&s);
593 QVector<FORMATETC> formatsForMime(QString const & mimetype,
594 QMimeData const * mimedata) const
596 QVector<FORMATETC> formats;
597 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
598 formats += cfFromMime(mimetype);
602 QString mimeForFormat(FORMATETC const & formatetc) const
604 switch (formatetc.cfFormat) {
606 return emfMimeType();
607 case CF_METAFILEPICT:
608 return wmfMimeType();
616 ////////////////////////////////////////////////////////////////////////
617 // GuiApplication::Private definition and implementation.
618 ////////////////////////////////////////////////////////////////////////
620 struct GuiApplication::Private
622 Private(): language_model_(0), global_menubar_(0) {}
625 QSortFilterProxyModel * language_model_;
627 GuiClipboard clipboard_;
629 GuiSelection selection_;
631 FontLoader font_loader_;
633 ColorCache color_cache_;
635 QTranslator qt_trans_;
637 QHash<int, SocketNotifier *> socket_notifiers_;
641 /// The global instance
644 /// this timer is used for any regular events one wants to
645 /// perform. at present it is used to check if forked processes
647 QTimer general_timer_;
649 /// delayed FuncRequests
650 std::queue<FuncRequest> func_request_queue_;
652 /// Multiple views container.
654 * Warning: This must not be a smart pointer as the destruction of the
655 * object is handled by Qt when the view is closed
656 * \sa Qt::WA_DeleteOnClose attribute.
658 QHash<int, GuiView *> views_;
660 /// Only used on mac.
661 GlobalMenuBar * global_menubar_;
664 /// Linkback mime handler for MacOSX.
665 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
669 /// WMF Mime handler for Windows clipboard.
670 QWindowsMimeMetafile wmf_mime_;
675 GuiApplication * guiApp;
677 GuiApplication::~GuiApplication()
680 closeAllLinkBackLinks();
686 GuiApplication::GuiApplication(int & argc, char ** argv)
687 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
689 QString app_name = "LyX";
690 QCoreApplication::setOrganizationName(app_name);
691 QCoreApplication::setOrganizationDomain("lyx.org");
692 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
694 // Install translator for GUI elements.
695 installTranslator(&d->qt_trans_);
697 // FIXME: quitOnLastWindowClosed is true by default. We should have a
698 // lyxrc setting for this in order to let the application stay resident.
699 // But then we need some kind of dock icon, at least on Windows.
701 if (lyxrc.quit_on_last_window_closed)
702 setQuitOnLastWindowClosed(false);
705 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
706 // seems to be the default case for applications like LyX.
707 setQuitOnLastWindowClosed(false);
709 // This allows to translate the strings that appear in the LyX menu.
710 /// A translator suitable for the entries in the LyX menu.
711 /// Only needed with Qt/Mac.
712 installTranslator(new MenuTranslator(this));
716 // doubleClickInterval() is 400 ms on X11 which is just too long.
717 // On Windows and Mac OS X, the operating system's value is used.
718 // On Microsoft Windows, calling this function sets the double
719 // click interval for all applications. So we don't!
720 QApplication::setDoubleClickInterval(300);
723 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
725 // needs to be done before reading lyxrc
727 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
731 // Set the cache to 5120 kilobytes which corresponds to screen size of
732 // 1280 by 1024 pixels with a color depth of 32 bits.
733 QPixmapCache::setCacheLimit(5120);
735 // Initialize RC Fonts
736 if (lyxrc.roman_font_name.empty())
737 lyxrc.roman_font_name = fromqstr(romanFontName());
739 if (lyxrc.sans_font_name.empty())
740 lyxrc.sans_font_name = fromqstr(sansFontName());
742 if (lyxrc.typewriter_font_name.empty())
743 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
745 d->general_timer_.setInterval(500);
746 connect(&d->general_timer_, SIGNAL(timeout()),
747 this, SLOT(handleRegularEvents()));
748 d->general_timer_.start();
752 GuiApplication * theGuiApp()
754 return dynamic_cast<GuiApplication *>(theApp());
758 void GuiApplication::clearSession()
765 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
767 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
772 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
778 case LFUN_WINDOW_CLOSE:
779 enable = d->views_.size() > 0;
782 case LFUN_BUFFER_NEW:
783 case LFUN_BUFFER_NEW_TEMPLATE:
785 case LFUN_SCREEN_FONT_UPDATE:
787 case LFUN_WINDOW_NEW:
797 flag.setEnabled(false);
803 bool GuiApplication::dispatch(FuncRequest const & cmd)
805 switch (cmd.action) {
807 case LFUN_WINDOW_NEW:
808 createView(toqstr(cmd.argument()));
811 case LFUN_WINDOW_CLOSE:
812 // update bookmark pit of the current buffer before window close
813 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
814 theLyXFunc().gotoBookmark(i+1, false, false);
815 current_view_->close();
819 // quitting is triggered by the gui code
820 // (leaving the event loop).
822 current_view_->message(from_utf8(N_("Exiting.")));
827 case LFUN_SCREEN_FONT_UPDATE: {
828 // handle the screen font changes.
829 d->font_loader_.update();
830 // Backup current_view_
831 GuiView * view = current_view_;
832 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
833 // to skip the refresh.
835 BufferList::iterator it = theBufferList().begin();
836 BufferList::iterator const end = theBufferList().end();
837 for (; it != end; ++it)
839 // Restore current_view_
840 current_view_ = view;
844 case LFUN_BUFFER_NEW:
845 if (d->views_.empty()
846 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
847 createView(QString(), false); // keep hidden
848 current_view_->newDocument(to_utf8(cmd.argument()), false);
849 current_view_->show();
850 setActiveWindow(current_view_);
852 current_view_->newDocument(to_utf8(cmd.argument()), false);
856 case LFUN_BUFFER_NEW_TEMPLATE:
857 if (d->views_.empty()
858 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
860 current_view_->newDocument(to_utf8(cmd.argument()), true);
861 if (!current_view_->buffer())
862 current_view_->close();
864 current_view_->newDocument(to_utf8(cmd.argument()), true);
869 if (d->views_.empty()
870 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
871 string const fname = to_utf8(cmd.argument());
872 // We want the ui session to be saved per document and not per
873 // window number. The filename crc is a good enough identifier.
874 boost::crc_32_type crc;
875 crc = for_each(fname.begin(), fname.end(), crc);
876 createView(crc.checksum());
877 current_view_->openDocument(fname);
878 if (current_view_ && !current_view_->buffer())
879 current_view_->close();
881 current_view_->openDocument(to_utf8(cmd.argument()));
884 case LFUN_SET_COLOR: {
886 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
887 if (lyx_name.empty() || x11_name.empty()) {
888 current_view_->message(
889 _("Syntax: set-color <lyx_name> <x11_name>"));
893 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
894 bool const graphicsbg_changed = lyx_name == graphicsbg
895 && x11_name != graphicsbg;
896 if (graphicsbg_changed) {
897 // FIXME: The graphics cache no longer has a changeDisplay method.
899 graphics::GCache::get().changeDisplay(true);
903 if (!lcolor.setColor(lyx_name, x11_name)) {
904 current_view_->message(
905 bformat(_("Set-color \"%1$s\" failed "
906 "- color is undefined or "
907 "may not be redefined"),
908 from_utf8(lyx_name)));
911 // Make sure we don't keep old colors in cache.
912 d->color_cache_.clear();
917 // Notify the caller that the action has not been dispatched.
921 // The action has been dispatched.
926 void GuiApplication::dispatchDelayed(FuncRequest const & func)
928 d->func_request_queue_.push(func);
929 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
933 void GuiApplication::resetGui()
935 // Set the language defined by the user.
939 if (!readUIFile(toqstr(lyxrc.ui_file)))
940 // Gives some error box here.
943 if (d->global_menubar_)
944 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
946 QHash<int, GuiView *>::iterator it;
947 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
949 gv->setLayoutDirection(layoutDirection());
953 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
957 void GuiApplication::createView(int view_id)
959 createView(QString(), true, view_id);
963 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
966 // release the keyboard which might have been grabed by the global
967 // menubar on Mac to catch shortcuts even without any GuiView.
968 if (d->global_menubar_)
969 d->global_menubar_->releaseKeyboard();
974 while (d->views_.find(id) != d->views_.end())
977 LYXERR(Debug::GUI, "About to create new window with ID " << id);
978 GuiView * view = new GuiView(id);
980 d->views_[id] = view;
984 setActiveWindow(view);
987 if (!geometry_arg.isEmpty()) {
991 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
992 re.indexIn(geometry_arg);
993 w = re.cap(1).toInt();
994 h = re.cap(2).toInt();
995 x = re.cap(3).toInt();
996 y = re.cap(4).toInt();
997 view->setGeometry(x, y, w, h);
1004 Clipboard & GuiApplication::clipboard()
1006 return d->clipboard_;
1010 Selection & GuiApplication::selection()
1012 return d->selection_;
1016 FontLoader & GuiApplication::fontLoader()
1018 return d->font_loader_;
1022 Toolbars const & GuiApplication::toolbars() const
1024 return d->toolbars_;
1028 Toolbars & GuiApplication::toolbars()
1030 return d->toolbars_;
1034 Menus const & GuiApplication::menus() const
1040 Menus & GuiApplication::menus()
1046 QList<int> GuiApplication::viewIds() const
1048 return d->views_.keys();
1052 ColorCache & GuiApplication::colorCache()
1054 return d->color_cache_;
1058 int GuiApplication::exec()
1060 // asynchronously handle batch commands. This event will be in
1061 // the event queue in front of other asynchronous events. Hence,
1062 // we can assume in the latter that the gui is setup already.
1063 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1065 return QApplication::exec();
1069 void GuiApplication::exit(int status)
1071 QApplication::exit(status);
1075 void GuiApplication::setGuiLanguage()
1077 // Set the language defined by the user.
1080 QString const default_language = toqstr(Messages::defaultLanguage());
1081 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1082 QLocale const default_locale(default_language);
1083 QLocale::setDefault(default_locale);
1085 // install translation file for Qt built-in dialogs
1086 QString const language_name = QString("qt_") + default_locale.name();
1088 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1089 // Short-named translator can be loaded from a long name, but not the
1090 // opposite. Therefore, long name should be used without truncation.
1091 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1092 if (!d->qt_trans_.load(language_name,
1093 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1094 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1097 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1101 switch (default_locale.language()) {
1102 case QLocale::Arabic :
1103 case QLocale::Hebrew :
1104 case QLocale::Persian :
1105 case QLocale::Urdu :
1106 setLayoutDirection(Qt::RightToLeft);
1109 setLayoutDirection(Qt::LeftToRight);
1114 void GuiApplication::processFuncRequestQueue()
1116 while (!d->func_request_queue_.empty()) {
1117 lyx::dispatch(d->func_request_queue_.back());
1118 d->func_request_queue_.pop();
1123 void GuiApplication::execBatchCommands()
1128 if (!readUIFile(toqstr(lyxrc.ui_file)))
1129 // Gives some error box here.
1133 // Create the global default menubar which is shown for the dialogs
1134 // and if no GuiView is visible.
1135 // This must be done after the session was recovered to know the "last files".
1136 d->global_menubar_ = new GlobalMenuBar();
1137 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1140 lyx::execBatchCommands();
1144 QAbstractItemModel * GuiApplication::languageModel()
1146 if (d->language_model_)
1147 return d->language_model_;
1149 QStandardItemModel * lang_model = new QStandardItemModel(this);
1150 lang_model->insertColumns(0, 1);
1152 Languages::const_iterator it = languages.begin();
1153 Languages::const_iterator end = languages.end();
1154 for (; it != end; ++it) {
1155 current_row = lang_model->rowCount();
1156 lang_model->insertRows(current_row, 1);
1157 QModelIndex item = lang_model->index(current_row, 0);
1158 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1159 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1161 d->language_model_ = new QSortFilterProxyModel(this);
1162 d->language_model_->setSourceModel(lang_model);
1163 #if QT_VERSION >= 0x040300
1164 d->language_model_->setSortLocaleAware(true);
1166 return d->language_model_;
1170 void GuiApplication::restoreGuiSession()
1172 if (!lyxrc.load_session)
1175 Session & session = theSession();
1176 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1177 // do not add to the lastfile list since these files are restored from
1178 // last session, and should be already there (regular files), or should
1179 // not be added at all (help files).
1180 for_each(lastopened.begin(), lastopened.end(),
1181 bind(&GuiView::loadDocument, current_view_, _1, false));
1183 // clear this list to save a few bytes of RAM
1184 session.lastOpened().clear();
1188 QString const GuiApplication::romanFontName()
1191 font.setKerning(false);
1192 font.setStyleHint(QFont::Serif);
1193 font.setFamily("serif");
1195 return QFontInfo(font).family();
1199 QString const GuiApplication::sansFontName()
1202 font.setKerning(false);
1203 font.setStyleHint(QFont::SansSerif);
1204 font.setFamily("sans");
1206 return QFontInfo(font).family();
1210 QString const GuiApplication::typewriterFontName()
1213 font.setKerning(false);
1214 font.setStyleHint(QFont::TypeWriter);
1215 font.setFamily("monospace");
1217 return QFontInfo(font).family();
1221 void GuiApplication::handleRegularEvents()
1223 ForkedCallsController::handleCompletedProcesses();
1227 bool GuiApplication::event(QEvent * e)
1230 case QEvent::FileOpen: {
1231 // Open a file; this happens only on Mac OS X for now.
1233 // We do this asynchronously because on startup the batch
1234 // commands are not executed here yet and the gui is not ready
1236 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1237 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1242 return QApplication::event(e);
1247 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1250 return QApplication::notify(receiver, event);
1252 catch (ExceptionMessage const & e) {
1254 case ErrorException:
1256 setQuitOnLastWindowClosed(false);
1258 Alert::error(e.title_, e.details_);
1260 // Properly crash in debug mode in order to get a useful backtrace.
1263 // In release mode, try to exit gracefully.
1266 case BufferException: {
1267 Buffer * buf = current_view_->buffer();
1268 docstring details = e.details_ + '\n';
1269 details += theBufferList().emergencyWrite(buf);
1270 theBufferList().release(buf);
1271 details += "\n" + _("The current document was closed.");
1272 Alert::error(e.title_, details);
1275 case WarningException:
1276 Alert::warning(e.title_, e.details_);
1280 catch (exception const & e) {
1281 docstring s = _("LyX has caught an exception, it will now "
1282 "attempt to save all unsaved documents and exit."
1284 s += from_ascii(e.what());
1285 Alert::error(_("Software exception Detected"), s);
1289 docstring s = _("LyX has caught some really weird exception, it will "
1290 "now attempt to save all unsaved documents and exit.");
1291 Alert::error(_("Software exception Detected"), s);
1299 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1301 QColor const & qcol = d->color_cache_.get(col);
1302 if (!qcol.isValid()) {
1308 rgbcol.r = qcol.red();
1309 rgbcol.g = qcol.green();
1310 rgbcol.b = qcol.blue();
1315 string const GuiApplication::hexName(ColorCode col)
1317 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1321 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1323 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1324 d->socket_notifiers_[fd] = sn;
1325 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1329 void GuiApplication::socketDataReceived(int fd)
1331 d->socket_notifiers_[fd]->func_();
1335 void GuiApplication::unregisterSocketCallback(int fd)
1337 d->socket_notifiers_.take(fd)->setEnabled(false);
1341 void GuiApplication::commitData(QSessionManager & sm)
1343 /// The implementation is required to avoid an application exit
1344 /// when session state save is triggered by session manager.
1345 /// The default implementation sends a close event to all
1346 /// visible top level widgets when session managment allows
1348 /// We are changing that to close all wiew one by one.
1349 /// FIXME: verify if the default implementation is enough now.
1350 if (sm.allowsInteraction() && !closeAllViews())
1355 void GuiApplication::unregisterView(GuiView * gv)
1357 LASSERT(d->views_[gv->id()] == gv, /**/);
1358 d->views_.remove(gv->id());
1359 if (current_view_ == gv) {
1361 theLyXFunc().setLyXView(0);
1366 bool GuiApplication::closeAllViews()
1368 if (d->views_.empty())
1371 QList<GuiView *> views = d->views_.values();
1372 foreach (GuiView * view, views) {
1382 GuiView & GuiApplication::view(int id) const
1384 LASSERT(d->views_.contains(id), /**/);
1385 return *d->views_.value(id);
1389 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1391 QList<GuiView *> views = d->views_.values();
1392 foreach (GuiView * view, views)
1393 view->hideDialog(name, inset);
1397 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1399 Buffer const * buffer_ = 0;
1400 QHash<int, GuiView *>::iterator end = d->views_.end();
1401 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1402 if (Buffer const * ptr = (*it)->updateInset(inset))
1409 bool GuiApplication::searchMenu(FuncRequest const & func,
1410 docstring_list & names) const
1412 return d->menus_.searchMenu(func, names);
1416 bool GuiApplication::readUIFile(QString const & name, bool include)
1426 LexerKeyword uitags[] = {
1427 { "include", ui_include },
1428 { "menuset", ui_menuset },
1429 { "toolbars", ui_toolbars },
1430 { "toolbarset", ui_toolbarset }
1433 LYXERR(Debug::INIT, "About to read " << name << "...");
1437 ui_path = libFileSearch("ui", name, "inc");
1438 if (ui_path.empty())
1439 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1441 ui_path = libFileSearch("ui", name, "ui");
1444 if (ui_path.empty()) {
1445 LYXERR(Debug::INIT, "Could not find " << name);
1446 Alert::warning(_("Could not find UI definition file"),
1447 bformat(_("Error while reading the configuration file\n%1$s.\n"
1448 "Please check your installation."), qstring_to_ucs4(name)));
1453 // Ensure that a file is read only once (prevents include loops)
1454 static QStringList uifiles;
1455 QString const uifile = toqstr(ui_path.absFilename());
1456 if (uifiles.contains(uifile)) {
1458 // We are reading again the top uifile so reset the safeguard:
1461 d->toolbars_.reset();
1463 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1464 << "Is this an include loop?");
1468 uifiles.push_back(uifile);
1470 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1473 lex.setFile(ui_path);
1475 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1479 if (lyxerr.debugging(Debug::PARSER))
1480 lex.printTable(lyxerr);
1482 while (lex.isOK()) {
1483 switch (lex.lex()) {
1486 QString const file = toqstr(lex.getString());
1487 if (!readUIFile(file, true))
1492 d->menus_.read(lex);
1496 d->toolbars_.readToolbars(lex);
1500 d->toolbars_.readToolbarSettings(lex);
1504 if (!rtrim(lex.getString()).empty())
1505 lex.printError("LyX::ReadUIFile: "
1506 "Unknown menu tag: `$$Token'");
1515 settings.beginGroup("ui_files");
1516 bool touched = false;
1517 for (int i = 0; i != uifiles.size(); ++i) {
1518 QFileInfo fi(uifiles[i]);
1519 QDateTime const date_value = fi.lastModified();
1520 QString const name_key = QString::number(i);
1521 if (!settings.contains(name_key)
1522 || settings.value(name_key).toString() != uifiles[i]
1523 || settings.value(name_key + "/date").toDateTime() != date_value) {
1525 settings.setValue(name_key, uifiles[i]);
1526 settings.setValue(name_key + "/date", date_value);
1529 settings.endGroup();
1531 settings.remove("views");
1537 void GuiApplication::onLastWindowClosed()
1539 if (d->global_menubar_)
1540 d->global_menubar_->grabKeyboard();
1544 ////////////////////////////////////////////////////////////////////////
1546 // X11 specific stuff goes here...
1549 bool GuiApplication::x11EventFilter(XEvent * xev)
1554 switch (xev->type) {
1555 case SelectionRequest: {
1556 if (xev->xselectionrequest.selection != XA_PRIMARY)
1558 LYXERR(Debug::SELECTION, "X requested selection.");
1559 BufferView * bv = current_view_->view();
1561 docstring const sel = bv->requestSelection();
1563 d->selection_.put(sel);
1567 case SelectionClear: {
1568 if (xev->xselectionclear.selection != XA_PRIMARY)
1570 LYXERR(Debug::SELECTION, "Lost selection.");
1571 BufferView * bv = current_view_->view();
1573 bv->clearSelection();
1581 } // namespace frontend
1584 void hideDialogs(std::string const & name, Inset * inset)
1587 theApp()->hideDialogs(name, inset);
1591 ////////////////////////////////////////////////////////////////////
1595 ////////////////////////////////////////////////////////////////////
1597 frontend::FontLoader & theFontLoader()
1599 LASSERT(frontend::guiApp, /**/);
1600 return frontend::guiApp->fontLoader();
1604 frontend::FontMetrics const & theFontMetrics(Font const & f)
1606 return theFontMetrics(f.fontInfo());
1610 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1612 LASSERT(frontend::guiApp, /**/);
1613 return frontend::guiApp->fontLoader().metrics(f);
1617 ////////////////////////////////////////////////////////////////////
1621 ////////////////////////////////////////////////////////////////////
1623 frontend::Clipboard & theClipboard()
1625 LASSERT(frontend::guiApp, /**/);
1626 return frontend::guiApp->clipboard();
1630 frontend::Selection & theSelection()
1632 LASSERT(frontend::guiApp, /**/);
1633 return frontend::guiApp->selection();
1639 #include "moc_GuiApplication.cpp"