2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
42 #include "LyXAction.h"
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/ExceptionMessage.h"
51 #include "support/FileName.h"
52 #include "support/foreach.h"
53 #include "support/ForkedCalls.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // sorted
57 #include "support/Messages.h"
58 #include "support/os.h"
59 #include "support/Package.h"
62 #include "support/linkback/LinkBackProxy.h"
70 #include <QFileOpenEvent>
74 #include <QImageReader>
76 #include <QLibraryInfo>
78 #include <QMacPasteboardMime>
83 #include <QPixmapCache>
85 #include <QSessionManager>
87 #include <QSocketNotifier>
88 #include <QSortFilterProxyModel>
89 #include <QStandardItemModel>
92 #include <QTranslator>
96 #include <X11/Xatom.h>
103 #include <QWindowsMime>
110 #include <boost/bind.hpp>
111 #include <boost/crc.hpp>
117 using namespace lyx::support;
120 static void initializeResources()
122 static bool initialized = false;
124 Q_INIT_RESOURCE(Resources);
132 frontend::Application * createApplication(int & argc, char * argv[])
135 // prune -geometry argument(s) by shifting
136 // the following ones 2 places down.
137 for (int i = 0 ; i < argc ; ++i) {
138 if (argv[i] == "-geometry") {
139 int const remove = (i+1) < argc ? 2 : 1;
141 for (int j = i; j < argc; ++j)
142 argv[j] = argv[j + remove];
147 return new frontend::GuiApplication(argc, argv);
153 /// Return the list of loadable formats.
154 vector<string> loadableImageFormats()
158 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
160 LYXERR(Debug::GRAPHICS,
161 "\nThe image loader can load the following directly:\n");
163 if (qt_formats.empty())
164 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
166 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
168 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
170 string ext = ascii_lowercase((const char *) *it);
180 ////////////////////////////////////////////////////////////////////////
181 // Icon loading support code.
182 ////////////////////////////////////////////////////////////////////////
192 bool operator<(PngMap const & lhs, PngMap const & rhs)
194 return lhs.key < rhs.key;
200 CompareKey(QString const & name) : name_(name) {}
201 bool operator()(PngMap const & other) const { return other.key == name_; }
207 // this must be sorted alphabetically
208 // Upper case comes before lower case
209 PngMap sorted_png_map[] = {
210 { "Bumpeq", "bumpeq2" },
213 { "Delta", "delta2" },
214 { "Downarrow", "downarrow2" },
215 { "Gamma", "gamma2" },
216 { "Lambda", "lambda2" },
217 { "Leftarrow", "leftarrow2" },
218 { "Leftrightarrow", "leftrightarrow2" },
219 { "Longleftarrow", "longleftarrow2" },
220 { "Longleftrightarrow", "longleftrightarrow2" },
221 { "Longrightarrow", "longrightarrow2" },
222 { "Omega", "omega2" },
226 { "Rightarrow", "rightarrow2" },
227 { "Sigma", "sigma2" },
228 { "Subset", "subset2" },
229 { "Supset", "supset2" },
230 { "Theta", "theta2" },
231 { "Uparrow", "uparrow2" },
232 { "Updownarrow", "updownarrow2" },
233 { "Upsilon", "upsilon2" },
234 { "Vdash", "vdash3" },
237 { "nLeftarrow", "nleftarrow2" },
238 { "nLeftrightarrow", "nleftrightarrow2" },
239 { "nRightarrow", "nrightarrow2" },
240 { "nVDash", "nvdash3" },
241 { "nvDash", "nvdash2" },
242 { "textrm \\AA", "textrm_AA"},
243 { "textrm \\O", "textrm_O"},
244 { "vDash", "vdash2" }
247 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
250 QString findPng(QString const & name)
252 PngMap const * const begin = sorted_png_map;
253 PngMap const * const end = begin + nr_sorted_png_map;
254 LASSERT(sorted(begin, end), /**/);
256 PngMap const * const it = find_if(begin, end, CompareKey(name));
260 png_name = it->value;
263 png_name.replace('_', "underscore");
264 png_name.replace(' ', '_');
266 // This way we can have "math-delim { }" on the toolbar.
267 png_name.replace('(', "lparen");
268 png_name.replace(')', "rparen");
269 png_name.replace('[', "lbracket");
270 png_name.replace(']', "rbracket");
271 png_name.replace('{', "lbrace");
272 png_name.replace('}', "rbrace");
273 png_name.replace('|', "bars");
274 png_name.replace(',', "thinspace");
275 png_name.replace(':', "mediumspace");
276 png_name.replace(';', "thickspace");
277 png_name.replace('!', "negthinspace");
280 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
281 << "Looking for math PNG called \"" << png_name << '"');
288 QString iconName(FuncRequest const & f, bool unknown)
290 initializeResources();
295 case LFUN_MATH_INSERT:
296 if (!f.argument().empty()) {
298 name1 = findPng(toqstr(f.argument()).mid(1));
301 case LFUN_MATH_DELIM:
302 case LFUN_MATH_BIGDELIM:
304 name1 = findPng(toqstr(f.argument()));
308 name1 = toqstr(f.argument());
311 name2 = toqstr(lyxaction.getActionName(f.action));
314 if (!f.argument().empty()) {
315 name1 = name2 + ' ' + toqstr(f.argument());
316 name1.replace(' ', '_');
320 FileName fname = libFileSearch("images/" + path, name1, "png");
322 return toqstr(fname.absFilename());
324 fname = libFileSearch("images/" + path, name2, "png");
326 return toqstr(fname.absFilename());
328 path = ":/images/" + path;
331 LYXERR0("Directory " << path << " not found in resource!");
335 if (res.exists(name1))
339 if (res.exists(name2))
342 LYXERR(Debug::GUI, "Cannot find icon for command \""
343 << lyxaction.getActionName(f.action)
344 << '(' << to_utf8(f.argument()) << ")\"");
347 return QString(":/images/unknown.png");
353 QIcon getIcon(FuncRequest const & f, bool unknown)
355 QString icon = iconName(f, unknown);
359 //LYXERR(Debug::GUI, "Found icon: " << icon);
361 if (!pm.load(icon)) {
362 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
370 ////////////////////////////////////////////////////////////////////////
371 // LyX server support code.
372 ////////////////////////////////////////////////////////////////////////
373 class SocketNotifier : public QSocketNotifier
376 /// connect a connection notification from the LyXServerSocket
377 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
378 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
382 /// The callback function
383 Application::SocketCallback func_;
387 ////////////////////////////////////////////////////////////////////////
388 // Mac specific stuff goes here...
389 ////////////////////////////////////////////////////////////////////////
391 class MenuTranslator : public QTranslator
394 MenuTranslator(QObject * parent)
395 : QTranslator(parent)
398 QString translate(const char * /*context*/,
399 const char * sourceText,
400 const char * /*comment*/ = 0)
402 string const s = sourceText;
403 if (s == N_("About %1") || s == N_("Preferences")
404 || s == N_("Reconfigure") || s == N_("Quit %1"))
411 class GlobalMenuBar : public QMenuBar
415 GlobalMenuBar() : QMenuBar(0) {}
418 bool event(QEvent * e)
420 if (e->type() == QEvent::ShortcutOverride) {
421 // && activeWindow() == 0) {
422 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
424 setKeySymbol(&sym, ke);
425 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
434 // QMacPasteboardMimeGraphics can only be compiled on Mac.
436 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
439 QMacPasteboardMimeGraphics()
440 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
443 QString convertorName() { return "Graphics"; }
445 QString flavorFor(QString const & mime)
447 LYXERR(Debug::ACTION, "flavorFor " << mime);
448 if (mime == pdfMimeType())
449 return QLatin1String("com.adobe.pdf");
453 QString mimeFor(QString flav)
455 LYXERR(Debug::ACTION, "mimeFor " << flav);
456 if (flav == QLatin1String("com.adobe.pdf"))
457 return pdfMimeType();
461 bool canConvert(QString const & mime, QString flav)
463 return mimeFor(flav) == mime;
466 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
470 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
474 QList<QByteArray> convertFromMime(QString const & /*mime*/,
475 QVariant data, QString /*flav*/)
477 QList<QByteArray> ret;
478 ret.append(data.toByteArray());
484 ///////////////////////////////////////////////////////////////
485 // You can find more platform specific stuff
486 // at the end of this file...
487 ///////////////////////////////////////////////////////////////
489 ////////////////////////////////////////////////////////////////////////
490 // Windows specific stuff goes here...
493 // QWindowsMimeMetafile can only be compiled on Windows.
495 static FORMATETC cfFromMime(QString const & mimetype)
498 if (mimetype == emfMimeType()) {
499 formatetc.cfFormat = CF_ENHMETAFILE;
500 formatetc.tymed = TYMED_ENHMF;
501 } else if (mimetype == wmfMimeType()) {
502 formatetc.cfFormat = CF_METAFILEPICT;
503 formatetc.tymed = TYMED_MFPICT;
506 formatetc.dwAspect = DVASPECT_CONTENT;
507 formatetc.lindex = -1;
512 class QWindowsMimeMetafile : public QWindowsMime {
514 QWindowsMimeMetafile() {}
516 bool canConvertFromMime(FORMATETC const & formatetc,
517 QMimeData const * mimedata) const
522 bool canConvertToMime(QString const & mimetype,
523 IDataObject * pDataObj) const
525 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
527 FORMATETC formatetc = cfFromMime(mimetype);
528 return pDataObj->QueryGetData(&formatetc) == S_OK;
531 bool convertFromMime(FORMATETC const & formatetc,
532 const QMimeData * mimedata, STGMEDIUM * pmedium) const
537 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
538 QVariant::Type preferredType) const
541 if (!canConvertToMime(mimetype, pDataObj))
544 FORMATETC formatetc = cfFromMime(mimetype);
546 if (pDataObj->GetData(&formatetc, &s) != S_OK)
550 if (s.tymed == TYMED_ENHMF) {
551 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
552 data.resize(dataSize);
553 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
554 (LPBYTE)data.data());
555 } else if (s.tymed == TYMED_MFPICT) {
556 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
557 data.resize(dataSize);
558 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
559 (LPBYTE)data.data());
562 ReleaseStgMedium(&s);
568 QVector<FORMATETC> formatsForMime(QString const & mimeType,
569 QMimeData const * mimeData) const
571 QVector<FORMATETC> formats;
572 formats += cfFromMime(mimeType);
576 QString mimeForFormat(FORMATETC const & formatetc) const
578 switch (formatetc.cfFormat) {
580 return emfMimeType();
581 case CF_METAFILEPICT:
582 return wmfMimeType();
590 ////////////////////////////////////////////////////////////////////////
591 // GuiApplication::Private definition and implementation.
592 ////////////////////////////////////////////////////////////////////////
594 struct GuiApplication::Private
597 : language_model_(0), global_menubar_(0)
600 // Create the global default menubar which is shown for the dialogs
601 // and if no GuiView is visible.
602 global_menubar_ = new GlobalMenuBar();
607 QSortFilterProxyModel * language_model_;
609 GuiClipboard clipboard_;
611 GuiSelection selection_;
613 FontLoader font_loader_;
615 ColorCache color_cache_;
617 QTranslator qt_trans_;
619 QHash<int, SocketNotifier *> socket_notifiers_;
623 /// The global instance
626 /// this timer is used for any regular events one wants to
627 /// perform. at present it is used to check if forked processes
629 QTimer general_timer_;
631 /// Multiple views container.
633 * Warning: This must not be a smart pointer as the destruction of the
634 * object is handled by Qt when the view is closed
635 * \sa Qt::WA_DeleteOnClose attribute.
637 QHash<int, GuiView *> views_;
639 /// Only used on mac.
640 GlobalMenuBar * global_menubar_;
643 /// Linkback mime handler for MacOSX.
644 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
648 /// WMF Mime handler for Windows clipboard.
649 /// \warning: see comment in ~GuiApplication and in bug 4846.
650 QWindowsMimeMetafile wmf_mime_;
655 GuiApplication * guiApp;
657 GuiApplication::~GuiApplication()
660 closeAllLinkBackLinks();
662 // FIXME: Work around bug 4846 for Windows Vista and Qt4
663 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
664 // If the clipboard is not cleared, LyX crashes on exit when it is
665 // compiled in release mode and if there is something in the clipboard.
666 // This is related to QWindowsMimeMetafile which is apparently not
667 // properly destroyed.
668 qApp->clipboard()->clear(QClipboard::Clipboard);
673 GuiApplication::GuiApplication(int & argc, char ** argv)
674 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
676 QString app_name = "LyX";
677 QCoreApplication::setOrganizationName(app_name);
678 QCoreApplication::setOrganizationDomain("lyx.org");
679 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
681 // Install translator for GUI elements.
682 installTranslator(&d->qt_trans_);
684 // FIXME: quitOnLastWindowClosed is true by default. We should have a
685 // lyxrc setting for this in order to let the application stay resident.
686 // But then we need some kind of dock icon, at least on Windows.
688 if (lyxrc.quit_on_last_window_closed)
689 setQuitOnLastWindowClosed(false);
692 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
693 // seems to be the default case for applications like LyX.
694 setQuitOnLastWindowClosed(false);
696 // This allows to translate the strings that appear in the LyX menu.
697 /// A translator suitable for the entries in the LyX menu.
698 /// Only needed with Qt/Mac.
699 installTranslator(new MenuTranslator(this));
703 // doubleClickInterval() is 400 ms on X11 which is just too long.
704 // On Windows and Mac OS X, the operating system's value is used.
705 // On Microsoft Windows, calling this function sets the double
706 // click interval for all applications. So we don't!
707 QApplication::setDoubleClickInterval(300);
710 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
712 // needs to be done before reading lyxrc
714 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
718 // Set the cache to 5120 kilobytes which corresponds to screen size of
719 // 1280 by 1024 pixels with a color depth of 32 bits.
720 QPixmapCache::setCacheLimit(5120);
722 // Initialize RC Fonts
723 if (lyxrc.roman_font_name.empty())
724 lyxrc.roman_font_name = fromqstr(romanFontName());
726 if (lyxrc.sans_font_name.empty())
727 lyxrc.sans_font_name = fromqstr(sansFontName());
729 if (lyxrc.typewriter_font_name.empty())
730 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
732 d->general_timer_.setInterval(500);
733 connect(&d->general_timer_, SIGNAL(timeout()),
734 this, SLOT(handleRegularEvents()));
735 d->general_timer_.start();
739 void GuiApplication::clearSession()
746 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
748 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
753 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
759 case LFUN_WINDOW_CLOSE:
760 enable = d->views_.size() > 0;
763 case LFUN_BUFFER_NEW:
764 case LFUN_BUFFER_NEW_TEMPLATE:
766 case LFUN_SCREEN_FONT_UPDATE:
768 case LFUN_WINDOW_NEW:
778 flag.setEnabled(false);
784 bool GuiApplication::dispatch(FuncRequest const & cmd)
786 switch (cmd.action) {
788 case LFUN_WINDOW_NEW:
789 createView(toqstr(cmd.argument()));
792 case LFUN_WINDOW_CLOSE:
793 // update bookmark pit of the current buffer before window close
794 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
795 theLyXFunc().gotoBookmark(i+1, false, false);
796 current_view_->close();
800 // quitting is triggered by the gui code
801 // (leaving the event loop).
803 current_view_->message(from_utf8(N_("Exiting.")));
808 case LFUN_SCREEN_FONT_UPDATE: {
809 // handle the screen font changes.
810 d->font_loader_.update();
811 // Backup current_view_
812 GuiView * view = current_view_;
813 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
814 // to skip the refresh.
816 BufferList::iterator it = theBufferList().begin();
817 BufferList::iterator const end = theBufferList().end();
818 for (; it != end; ++it)
820 // Restore current_view_
821 current_view_ = view;
825 case LFUN_BUFFER_NEW:
826 if (d->views_.empty()
827 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
828 createView(QString(), false); // keep hidden
829 current_view_->newDocument(to_utf8(cmd.argument()), false);
830 current_view_->show();
831 setActiveWindow(current_view_);
833 current_view_->newDocument(to_utf8(cmd.argument()), false);
837 case LFUN_BUFFER_NEW_TEMPLATE:
838 if (d->views_.empty()
839 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
841 current_view_->newDocument(to_utf8(cmd.argument()), true);
842 if (!current_view_->buffer())
843 current_view_->close();
845 current_view_->newDocument(to_utf8(cmd.argument()), true);
850 if (d->views_.empty()
851 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
852 string const fname = to_utf8(cmd.argument());
853 // We want the ui session to be saved per document and not per
854 // window number. The filename crc is a good enough identifier.
855 boost::crc_32_type crc;
856 crc = for_each(fname.begin(), fname.end(), crc);
857 createView(crc.checksum());
858 current_view_->openDocument(fname);
859 if (!current_view_->buffer())
860 current_view_->close();
862 current_view_->openDocument(to_utf8(cmd.argument()));
865 case LFUN_SET_COLOR: {
867 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
868 if (lyx_name.empty() || x11_name.empty()) {
869 current_view_->message(
870 _("Syntax: set-color <lyx_name> <x11_name>"));
874 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
875 bool const graphicsbg_changed = lyx_name == graphicsbg
876 && x11_name != graphicsbg;
877 if (graphicsbg_changed) {
878 // FIXME: The graphics cache no longer has a changeDisplay method.
880 graphics::GCache::get().changeDisplay(true);
884 if (!lcolor.setColor(lyx_name, x11_name)) {
885 current_view_->message(
886 bformat(_("Set-color \"%1$s\" failed "
887 "- color is undefined or "
888 "may not be redefined"),
889 from_utf8(lyx_name)));
892 // Make sure we don't keep old colors in cache.
893 d->color_cache_.clear();
898 // Notify the caller that the action has not been dispatched.
902 // The action has been dispatched.
907 void GuiApplication::resetGui()
909 // Set the language defined by the user.
913 if (!readUIFile(toqstr(lyxrc.ui_file)))
914 // Gives some error box here.
917 if (d->global_menubar_)
918 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
920 QHash<int, GuiView *>::iterator it;
921 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
923 gv->setLayoutDirection(layoutDirection());
927 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
931 void GuiApplication::createView(int view_id)
933 createView(QString(), true, view_id);
937 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
940 // release the keyboard which might have been grabed by the global
941 // menubar on Mac to catch shortcuts even without any GuiView.
942 if (d->global_menubar_)
943 d->global_menubar_->releaseKeyboard();
948 while (d->views_.find(id) != d->views_.end())
951 LYXERR(Debug::GUI, "About to create new window with ID " << id);
952 GuiView * view = new GuiView(id);
954 d->views_[id] = view;
958 setActiveWindow(view);
961 if (!geometry_arg.isEmpty()) {
965 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
966 re.indexIn(geometry_arg);
967 w = re.cap(1).toInt();
968 h = re.cap(2).toInt();
969 x = re.cap(3).toInt();
970 y = re.cap(4).toInt();
971 view->setGeometry(x, y, w, h);
978 Clipboard & GuiApplication::clipboard()
980 return d->clipboard_;
984 Selection & GuiApplication::selection()
986 return d->selection_;
990 FontLoader & GuiApplication::fontLoader()
992 return d->font_loader_;
996 Toolbars const & GuiApplication::toolbars() const
1002 Toolbars & GuiApplication::toolbars()
1004 return d->toolbars_;
1008 Menus const & GuiApplication::menus() const
1014 Menus & GuiApplication::menus()
1020 QList<int> GuiApplication::viewIds() const
1022 return d->views_.keys();
1026 ColorCache & GuiApplication::colorCache()
1028 return d->color_cache_;
1032 int GuiApplication::exec()
1034 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1035 return QApplication::exec();
1039 void GuiApplication::exit(int status)
1041 QApplication::exit(status);
1045 void GuiApplication::setGuiLanguage()
1047 // Set the language defined by the user.
1050 QString const default_language = toqstr(Messages::defaultLanguage());
1051 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1052 QLocale const default_locale(default_language);
1053 QLocale::setDefault(default_locale);
1055 // install translation file for Qt built-in dialogs
1056 QString const language_name = QString("qt_") + default_locale.name();
1058 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1059 // Short-named translator can be loaded from a long name, but not the
1060 // opposite. Therefore, long name should be used without truncation.
1061 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1062 if (!d->qt_trans_.load(language_name,
1063 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1064 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1067 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1071 switch (default_locale.language()) {
1072 case QLocale::Arabic :
1073 case QLocale::Hebrew :
1074 case QLocale::Persian :
1075 case QLocale::Urdu :
1076 setLayoutDirection(Qt::RightToLeft);
1079 setLayoutDirection(Qt::LeftToRight);
1084 void GuiApplication::execBatchCommands()
1089 if (!readUIFile(toqstr(lyxrc.ui_file)))
1090 // Gives some error box here.
1093 // init the global menubar on Mac. This must be done after the session
1094 // was recovered to know the "last files".
1095 if (d->global_menubar_)
1096 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1098 lyx::execBatchCommands();
1102 QAbstractItemModel * GuiApplication::languageModel()
1104 if (d->language_model_)
1105 return d->language_model_;
1107 QStandardItemModel * lang_model = new QStandardItemModel(this);
1108 lang_model->insertColumns(0, 1);
1110 Languages::const_iterator it = languages.begin();
1111 Languages::const_iterator end = languages.end();
1112 for (; it != end; ++it) {
1113 current_row = lang_model->rowCount();
1114 lang_model->insertRows(current_row, 1);
1115 QModelIndex item = lang_model->index(current_row, 0);
1116 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1117 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1119 d->language_model_ = new QSortFilterProxyModel(this);
1120 d->language_model_->setSourceModel(lang_model);
1121 #if QT_VERSION >= 0x040300
1122 d->language_model_->setSortLocaleAware(true);
1124 return d->language_model_;
1128 void GuiApplication::restoreGuiSession()
1130 if (!lyxrc.load_session)
1133 Session & session = theSession();
1134 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1135 // do not add to the lastfile list since these files are restored from
1136 // last session, and should be already there (regular files), or should
1137 // not be added at all (help files).
1138 for_each(lastopened.begin(), lastopened.end(),
1139 bind(&GuiView::loadDocument, current_view_, _1, false));
1141 // clear this list to save a few bytes of RAM
1142 session.lastOpened().clear();
1146 QString const GuiApplication::romanFontName()
1149 font.setKerning(false);
1150 font.setStyleHint(QFont::Serif);
1151 font.setFamily("serif");
1153 return QFontInfo(font).family();
1157 QString const GuiApplication::sansFontName()
1160 font.setKerning(false);
1161 font.setStyleHint(QFont::SansSerif);
1162 font.setFamily("sans");
1164 return QFontInfo(font).family();
1168 QString const GuiApplication::typewriterFontName()
1171 font.setKerning(false);
1172 font.setStyleHint(QFont::TypeWriter);
1173 font.setFamily("monospace");
1175 return QFontInfo(font).family();
1179 void GuiApplication::handleRegularEvents()
1181 ForkedCallsController::handleCompletedProcesses();
1185 bool GuiApplication::event(QEvent * e)
1188 case QEvent::FileOpen: {
1189 // Open a file; this happens only on Mac OS X for now
1190 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1191 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1192 qstring_to_ucs4(foe->file())));
1197 return QApplication::event(e);
1202 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1205 return QApplication::notify(receiver, event);
1207 catch (ExceptionMessage const & e) {
1209 case ErrorException:
1211 setQuitOnLastWindowClosed(false);
1213 Alert::error(e.title_, e.details_);
1215 // Properly crash in debug mode in order to get a useful backtrace.
1218 // In release mode, try to exit gracefully.
1221 case BufferException: {
1222 Buffer * buf = current_view_->buffer();
1223 docstring details = e.details_ + '\n';
1224 details += theBufferList().emergencyWrite(buf);
1225 theBufferList().release(buf);
1226 details += "\n" + _("The current document was closed.");
1227 Alert::error(e.title_, details);
1230 case WarningException:
1231 Alert::warning(e.title_, e.details_);
1235 catch (exception const & e) {
1236 docstring s = _("LyX has caught an exception, it will now "
1237 "attempt to save all unsaved documents and exit."
1239 s += from_ascii(e.what());
1240 Alert::error(_("Software exception Detected"), s);
1244 docstring s = _("LyX has caught some really weird exception, it will "
1245 "now attempt to save all unsaved documents and exit.");
1246 Alert::error(_("Software exception Detected"), s);
1254 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1256 QColor const & qcol = d->color_cache_.get(col);
1257 if (!qcol.isValid()) {
1263 rgbcol.r = qcol.red();
1264 rgbcol.g = qcol.green();
1265 rgbcol.b = qcol.blue();
1270 string const GuiApplication::hexName(ColorCode col)
1272 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1276 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1278 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1279 d->socket_notifiers_[fd] = sn;
1280 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1284 void GuiApplication::socketDataReceived(int fd)
1286 d->socket_notifiers_[fd]->func_();
1290 void GuiApplication::unregisterSocketCallback(int fd)
1292 d->socket_notifiers_.take(fd)->setEnabled(false);
1296 void GuiApplication::commitData(QSessionManager & sm)
1298 /// The implementation is required to avoid an application exit
1299 /// when session state save is triggered by session manager.
1300 /// The default implementation sends a close event to all
1301 /// visible top level widgets when session managment allows
1303 /// We are changing that to close all wiew one by one.
1304 /// FIXME: verify if the default implementation is enough now.
1305 if (sm.allowsInteraction() && !closeAllViews())
1310 void GuiApplication::unregisterView(GuiView * gv)
1312 LASSERT(d->views_[gv->id()] == gv, /**/);
1313 d->views_.remove(gv->id());
1314 if (current_view_ == gv) {
1316 theLyXFunc().setLyXView(0);
1321 bool GuiApplication::closeAllViews()
1323 if (d->views_.empty())
1326 QList<GuiView *> views = d->views_.values();
1327 foreach (GuiView * view, views) {
1337 GuiView & GuiApplication::view(int id) const
1339 LASSERT(d->views_.contains(id), /**/);
1340 return *d->views_.value(id);
1344 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1346 QList<GuiView *> views = d->views_.values();
1347 foreach (GuiView * view, views)
1348 view->hideDialog(name, inset);
1352 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1354 Buffer const * buffer_ = 0;
1355 QHash<int, GuiView *>::iterator end = d->views_.end();
1356 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1357 if (Buffer const * ptr = (*it)->updateInset(inset))
1364 bool GuiApplication::searchMenu(FuncRequest const & func,
1365 docstring_list & names) const
1367 return d->menus_.searchMenu(func, names);
1371 bool GuiApplication::readUIFile(QString const & name, bool include)
1381 LexerKeyword uitags[] = {
1382 { "include", ui_include },
1383 { "menuset", ui_menuset },
1384 { "toolbars", ui_toolbars },
1385 { "toolbarset", ui_toolbarset }
1388 LYXERR(Debug::INIT, "About to read " << name << "...");
1392 ui_path = libFileSearch("ui", name, "inc");
1393 if (ui_path.empty())
1394 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1396 ui_path = libFileSearch("ui", name, "ui");
1399 if (ui_path.empty()) {
1400 LYXERR(Debug::INIT, "Could not find " << name);
1401 Alert::warning(_("Could not find UI definition file"),
1402 bformat(_("Error while reading the configuration file\n%1$s.\n"
1403 "Please check your installation."), qstring_to_ucs4(name)));
1408 // Ensure that a file is read only once (prevents include loops)
1409 static QStringList uifiles;
1410 QString const uifile = toqstr(ui_path.absFilename());
1411 if (uifiles.contains(uifile)) {
1413 // We are reading again the top uifile so reset the safeguard:
1416 d->toolbars_.reset();
1418 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1419 << "Is this an include loop?");
1423 uifiles.push_back(uifile);
1425 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1428 lex.setFile(ui_path);
1430 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1434 if (lyxerr.debugging(Debug::PARSER))
1435 lex.printTable(lyxerr);
1437 while (lex.isOK()) {
1438 switch (lex.lex()) {
1441 QString const file = toqstr(lex.getString());
1442 if (!readUIFile(file, true))
1447 d->menus_.read(lex);
1451 d->toolbars_.readToolbars(lex);
1455 d->toolbars_.readToolbarSettings(lex);
1459 if (!rtrim(lex.getString()).empty())
1460 lex.printError("LyX::ReadUIFile: "
1461 "Unknown menu tag: `$$Token'");
1470 settings.beginGroup("ui_files");
1471 bool touched = false;
1472 for (int i = 0; i != uifiles.size(); ++i) {
1473 QFileInfo fi(uifiles[i]);
1474 QDateTime const date_value = fi.lastModified();
1475 QString const name_key = QString::number(i);
1476 if (!settings.contains(name_key)
1477 || settings.value(name_key).toString() != uifiles[i]
1478 || settings.value(name_key + "/date").toDateTime() != date_value) {
1480 settings.setValue(name_key, uifiles[i]);
1481 settings.setValue(name_key + "/date", date_value);
1484 settings.endGroup();
1486 settings.remove("views");
1492 void GuiApplication::onLastWindowClosed()
1494 if (d->global_menubar_)
1495 d->global_menubar_->grabKeyboard();
1499 ////////////////////////////////////////////////////////////////////////
1501 // X11 specific stuff goes here...
1504 bool GuiApplication::x11EventFilter(XEvent * xev)
1509 switch (xev->type) {
1510 case SelectionRequest: {
1511 if (xev->xselectionrequest.selection != XA_PRIMARY)
1513 LYXERR(Debug::SELECTION, "X requested selection.");
1514 BufferView * bv = current_view_->view();
1516 docstring const sel = bv->requestSelection();
1518 d->selection_.put(sel);
1522 case SelectionClear: {
1523 if (xev->xselectionclear.selection != XA_PRIMARY)
1525 LYXERR(Debug::SELECTION, "Lost selection.");
1526 BufferView * bv = current_view_->view();
1528 bv->clearSelection();
1536 } // namespace frontend
1539 void hideDialogs(std::string const & name, Inset * inset)
1542 theApp()->hideDialogs(name, inset);
1546 ////////////////////////////////////////////////////////////////////
1550 ////////////////////////////////////////////////////////////////////
1552 frontend::FontLoader & theFontLoader()
1554 LASSERT(frontend::guiApp, /**/);
1555 return frontend::guiApp->fontLoader();
1559 frontend::FontMetrics const & theFontMetrics(Font const & f)
1561 return theFontMetrics(f.fontInfo());
1565 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1567 LASSERT(frontend::guiApp, /**/);
1568 return frontend::guiApp->fontLoader().metrics(f);
1572 ////////////////////////////////////////////////////////////////////
1576 ////////////////////////////////////////////////////////////////////
1578 frontend::Clipboard & theClipboard()
1580 LASSERT(frontend::guiApp, /**/);
1581 return frontend::guiApp->clipboard();
1585 frontend::Selection & theSelection()
1587 LASSERT(frontend::guiApp, /**/);
1588 return frontend::guiApp->selection();
1593 #include "GuiApplication_moc.cpp"