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>
104 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
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.
918 d->global_menubar_->clear();
919 delete d->global_menubar_;
920 // Create the global default menubar which is shown for the dialogs
921 // and if no GuiView is visible.
922 d->global_menubar_ = new GlobalMenuBar();
924 // init the global menubar on Mac. This must be done after the session
925 // was recovered to know the "last files".
926 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
929 QHash<int, GuiView *>::iterator it;
930 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
932 gv->setLayoutDirection(layoutDirection());
936 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
940 void GuiApplication::createView(int view_id)
942 createView(QString(), true, view_id);
946 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
949 // release the keyboard which might have been grabed by the global
950 // menubar on Mac to catch shortcuts even without any GuiView.
951 if (d->global_menubar_)
952 d->global_menubar_->releaseKeyboard();
957 while (d->views_.find(id) != d->views_.end())
960 LYXERR(Debug::GUI, "About to create new window with ID " << id);
961 GuiView * view = new GuiView(id);
963 d->views_[id] = view;
967 setActiveWindow(view);
970 if (!geometry_arg.isEmpty()) {
974 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
975 re.indexIn(geometry_arg);
976 w = re.cap(1).toInt();
977 h = re.cap(2).toInt();
978 x = re.cap(3).toInt();
979 y = re.cap(4).toInt();
980 view->setGeometry(x, y, w, h);
987 Clipboard & GuiApplication::clipboard()
989 return d->clipboard_;
993 Selection & GuiApplication::selection()
995 return d->selection_;
999 FontLoader & GuiApplication::fontLoader()
1001 return d->font_loader_;
1005 Toolbars const & GuiApplication::toolbars() const
1007 return d->toolbars_;
1011 Toolbars & GuiApplication::toolbars()
1013 return d->toolbars_;
1017 Menus const & GuiApplication::menus() const
1023 Menus & GuiApplication::menus()
1029 QList<int> GuiApplication::viewIds() const
1031 return d->views_.keys();
1035 ColorCache & GuiApplication::colorCache()
1037 return d->color_cache_;
1041 int GuiApplication::exec()
1043 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1044 return QApplication::exec();
1048 void GuiApplication::exit(int status)
1050 QApplication::exit(status);
1054 void GuiApplication::setGuiLanguage()
1056 // Set the language defined by the user.
1059 QString const default_language = toqstr(Messages::defaultLanguage());
1060 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1061 QLocale const default_locale(default_language);
1062 QLocale::setDefault(default_locale);
1064 // install translation file for Qt built-in dialogs
1065 QString const language_name = QString("qt_") + default_locale.name();
1067 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1068 // Short-named translator can be loaded from a long name, but not the
1069 // opposite. Therefore, long name should be used without truncation.
1070 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1071 if (!d->qt_trans_.load(language_name,
1072 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1073 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1076 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1080 switch (default_locale.language()) {
1081 case QLocale::Arabic :
1082 case QLocale::Hebrew :
1083 case QLocale::Persian :
1084 case QLocale::Urdu :
1085 setLayoutDirection(Qt::RightToLeft);
1088 setLayoutDirection(Qt::LeftToRight);
1093 void GuiApplication::execBatchCommands()
1098 if (!readUIFile(toqstr(lyxrc.ui_file)))
1099 // Gives some error box here.
1102 // init the global menubar on Mac. This must be done after the session
1103 // was recovered to know the "last files".
1104 if (d->global_menubar_)
1105 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1107 lyx::execBatchCommands();
1111 QAbstractItemModel * GuiApplication::languageModel()
1113 if (d->language_model_)
1114 return d->language_model_;
1116 QStandardItemModel * lang_model = new QStandardItemModel(this);
1117 lang_model->insertColumns(0, 1);
1119 Languages::const_iterator it = languages.begin();
1120 Languages::const_iterator end = languages.end();
1121 for (; it != end; ++it) {
1122 current_row = lang_model->rowCount();
1123 lang_model->insertRows(current_row, 1);
1124 QModelIndex item = lang_model->index(current_row, 0);
1125 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1126 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1128 d->language_model_ = new QSortFilterProxyModel(this);
1129 d->language_model_->setSourceModel(lang_model);
1130 #if QT_VERSION >= 0x040300
1131 d->language_model_->setSortLocaleAware(true);
1133 return d->language_model_;
1137 void GuiApplication::restoreGuiSession()
1139 if (!lyxrc.load_session)
1142 Session & session = theSession();
1143 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1144 // do not add to the lastfile list since these files are restored from
1145 // last session, and should be already there (regular files), or should
1146 // not be added at all (help files).
1147 for_each(lastopened.begin(), lastopened.end(),
1148 bind(&GuiView::loadDocument, current_view_, _1, false));
1150 // clear this list to save a few bytes of RAM
1151 session.lastOpened().clear();
1155 QString const GuiApplication::romanFontName()
1158 font.setKerning(false);
1159 font.setStyleHint(QFont::Serif);
1160 font.setFamily("serif");
1162 return QFontInfo(font).family();
1166 QString const GuiApplication::sansFontName()
1169 font.setKerning(false);
1170 font.setStyleHint(QFont::SansSerif);
1171 font.setFamily("sans");
1173 return QFontInfo(font).family();
1177 QString const GuiApplication::typewriterFontName()
1180 font.setKerning(false);
1181 font.setStyleHint(QFont::TypeWriter);
1182 font.setFamily("monospace");
1184 return QFontInfo(font).family();
1188 void GuiApplication::handleRegularEvents()
1190 ForkedCallsController::handleCompletedProcesses();
1194 bool GuiApplication::event(QEvent * e)
1197 case QEvent::FileOpen: {
1198 // Open a file; this happens only on Mac OS X for now
1199 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1200 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1201 qstring_to_ucs4(foe->file())));
1206 return QApplication::event(e);
1211 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1214 return QApplication::notify(receiver, event);
1216 catch (ExceptionMessage const & e) {
1218 case ErrorException:
1220 setQuitOnLastWindowClosed(false);
1222 Alert::error(e.title_, e.details_);
1224 // Properly crash in debug mode in order to get a useful backtrace.
1227 // In release mode, try to exit gracefully.
1230 case BufferException: {
1231 Buffer * buf = current_view_->buffer();
1232 docstring details = e.details_ + '\n';
1233 details += theBufferList().emergencyWrite(buf);
1234 theBufferList().release(buf);
1235 details += "\n" + _("The current document was closed.");
1236 Alert::error(e.title_, details);
1239 case WarningException:
1240 Alert::warning(e.title_, e.details_);
1244 catch (exception const & e) {
1245 docstring s = _("LyX has caught an exception, it will now "
1246 "attempt to save all unsaved documents and exit."
1248 s += from_ascii(e.what());
1249 Alert::error(_("Software exception Detected"), s);
1253 docstring s = _("LyX has caught some really weird exception, it will "
1254 "now attempt to save all unsaved documents and exit.");
1255 Alert::error(_("Software exception Detected"), s);
1263 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1265 QColor const & qcol = d->color_cache_.get(col);
1266 if (!qcol.isValid()) {
1272 rgbcol.r = qcol.red();
1273 rgbcol.g = qcol.green();
1274 rgbcol.b = qcol.blue();
1279 string const GuiApplication::hexName(ColorCode col)
1281 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1285 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1287 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1288 d->socket_notifiers_[fd] = sn;
1289 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1293 void GuiApplication::socketDataReceived(int fd)
1295 d->socket_notifiers_[fd]->func_();
1299 void GuiApplication::unregisterSocketCallback(int fd)
1301 d->socket_notifiers_.take(fd)->setEnabled(false);
1305 void GuiApplication::commitData(QSessionManager & sm)
1307 /// The implementation is required to avoid an application exit
1308 /// when session state save is triggered by session manager.
1309 /// The default implementation sends a close event to all
1310 /// visible top level widgets when session managment allows
1312 /// We are changing that to close all wiew one by one.
1313 /// FIXME: verify if the default implementation is enough now.
1314 if (sm.allowsInteraction() && !closeAllViews())
1319 void GuiApplication::unregisterView(GuiView * gv)
1321 LASSERT(d->views_[gv->id()] == gv, /**/);
1322 d->views_.remove(gv->id());
1323 if (current_view_ == gv) {
1325 theLyXFunc().setLyXView(0);
1330 bool GuiApplication::closeAllViews()
1332 if (d->views_.empty())
1335 QList<GuiView *> views = d->views_.values();
1336 foreach (GuiView * view, views) {
1346 GuiView & GuiApplication::view(int id) const
1348 LASSERT(d->views_.contains(id), /**/);
1349 return *d->views_.value(id);
1353 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1355 QList<GuiView *> views = d->views_.values();
1356 foreach (GuiView * view, views)
1357 view->hideDialog(name, inset);
1361 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1363 Buffer const * buffer_ = 0;
1364 QHash<int, GuiView *>::iterator end = d->views_.end();
1365 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1366 if (Buffer const * ptr = (*it)->updateInset(inset))
1373 bool GuiApplication::searchMenu(FuncRequest const & func,
1374 docstring_list & names) const
1376 return d->menus_.searchMenu(func, names);
1380 bool GuiApplication::readUIFile(QString const & name, bool include)
1390 LexerKeyword uitags[] = {
1391 { "include", ui_include },
1392 { "menuset", ui_menuset },
1393 { "toolbars", ui_toolbars },
1394 { "toolbarset", ui_toolbarset }
1397 LYXERR(Debug::INIT, "About to read " << name << "...");
1401 ui_path = libFileSearch("ui", name, "inc");
1402 if (ui_path.empty())
1403 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1405 ui_path = libFileSearch("ui", name, "ui");
1408 if (ui_path.empty()) {
1409 LYXERR(Debug::INIT, "Could not find " << name);
1410 Alert::warning(_("Could not find UI definition file"),
1411 bformat(_("Error while reading the configuration file\n%1$s.\n"
1412 "Please check your installation."), qstring_to_ucs4(name)));
1417 // Ensure that a file is read only once (prevents include loops)
1418 static QStringList uifiles;
1419 QString const uifile = toqstr(ui_path.absFilename());
1420 if (uifiles.contains(uifile)) {
1422 // We are reading again the top uifile so reset the safeguard:
1425 d->toolbars_.reset();
1427 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1428 << "Is this an include loop?");
1432 uifiles.push_back(uifile);
1434 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1437 lex.setFile(ui_path);
1439 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1443 if (lyxerr.debugging(Debug::PARSER))
1444 lex.printTable(lyxerr);
1446 while (lex.isOK()) {
1447 switch (lex.lex()) {
1450 QString const file = toqstr(lex.getString());
1451 if (!readUIFile(file, true))
1456 d->menus_.read(lex);
1460 d->toolbars_.readToolbars(lex);
1464 d->toolbars_.readToolbarSettings(lex);
1468 if (!rtrim(lex.getString()).empty())
1469 lex.printError("LyX::ReadUIFile: "
1470 "Unknown menu tag: `$$Token'");
1479 settings.beginGroup("ui_files");
1480 bool touched = false;
1481 for (int i = 0; i != uifiles.size(); ++i) {
1482 QFileInfo fi(uifiles[i]);
1483 QDateTime const date_value = fi.lastModified();
1484 QString const name_key = QString::number(i);
1485 if (!settings.contains(name_key)
1486 || settings.value(name_key).toString() != uifiles[i]
1487 || settings.value(name_key + "/date").toDateTime() != date_value) {
1489 settings.setValue(name_key, uifiles[i]);
1490 settings.setValue(name_key + "/date", date_value);
1493 settings.endGroup();
1495 settings.remove("views");
1501 void GuiApplication::onLastWindowClosed()
1503 if (d->global_menubar_)
1504 d->global_menubar_->grabKeyboard();
1508 ////////////////////////////////////////////////////////////////////////
1510 // X11 specific stuff goes here...
1513 bool GuiApplication::x11EventFilter(XEvent * xev)
1518 switch (xev->type) {
1519 case SelectionRequest: {
1520 if (xev->xselectionrequest.selection != XA_PRIMARY)
1522 LYXERR(Debug::SELECTION, "X requested selection.");
1523 BufferView * bv = current_view_->view();
1525 docstring const sel = bv->requestSelection();
1527 d->selection_.put(sel);
1531 case SelectionClear: {
1532 if (xev->xselectionclear.selection != XA_PRIMARY)
1534 LYXERR(Debug::SELECTION, "Lost selection.");
1535 BufferView * bv = current_view_->view();
1537 bv->clearSelection();
1545 } // namespace frontend
1548 void hideDialogs(std::string const & name, Inset * inset)
1551 theApp()->hideDialogs(name, inset);
1555 ////////////////////////////////////////////////////////////////////
1559 ////////////////////////////////////////////////////////////////////
1561 frontend::FontLoader & theFontLoader()
1563 LASSERT(frontend::guiApp, /**/);
1564 return frontend::guiApp->fontLoader();
1568 frontend::FontMetrics const & theFontMetrics(Font const & f)
1570 return theFontMetrics(f.fontInfo());
1574 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1576 LASSERT(frontend::guiApp, /**/);
1577 return frontend::guiApp->fontLoader().metrics(f);
1581 ////////////////////////////////////////////////////////////////////
1585 ////////////////////////////////////////////////////////////////////
1587 frontend::Clipboard & theClipboard()
1589 LASSERT(frontend::guiApp, /**/);
1590 return frontend::guiApp->clipboard();
1594 frontend::Selection & theSelection()
1596 LASSERT(frontend::guiApp, /**/);
1597 return frontend::guiApp->selection();
1602 #include "GuiApplication_moc.cpp"