2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
18 #include "GuiClipboard.h"
20 #include "GuiKeySymbol.h"
21 #include "GuiSelection.h"
24 #include "qt_helpers.h"
27 #include "frontends/alert.h"
28 #include "frontends/Application.h"
29 #include "frontends/FontLoader.h"
30 #include "frontends/FontMetrics.h"
33 #include "BufferList.h"
34 #include "BufferView.h"
37 #include "FuncRequest.h"
38 #include "FuncStatus.h"
42 #include "LyXAction.h"
48 #include "support/lassert.h"
49 #include "support/debug.h"
50 #include "support/ExceptionMessage.h"
51 #include "support/FileName.h"
52 #include "support/foreach.h"
53 #include "support/ForkedCalls.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // sorted
57 #include "support/Messages.h"
58 #include "support/os.h"
59 #include "support/Package.h"
62 #include "support/linkback/LinkBackProxy.h"
72 #include <QFileOpenEvent>
76 #include <QImageReader>
78 #include <QLibraryInfo>
80 #include <QMacPasteboardMime>
85 #include <QPixmapCache>
87 #include <QSessionManager>
89 #include <QSocketNotifier>
90 #include <QSortFilterProxyModel>
91 #include <QStandardItemModel>
94 #include <QTranslator>
98 #include <X11/Xatom.h>
105 #include <QWindowsMime>
112 #include <boost/bind.hpp>
113 #include <boost/crc.hpp>
119 using namespace lyx::support;
122 static void initializeResources()
124 static bool initialized = false;
126 Q_INIT_RESOURCE(Resources);
134 frontend::Application * createApplication(int & argc, char * argv[])
137 // prune -geometry argument(s) by shifting
138 // the following ones 2 places down.
139 for (int i = 0 ; i < argc ; ++i) {
140 if (strcmp(argv[i], "-geometry") == 0) {
141 int const remove = (i+1) < argc ? 2 : 1;
143 for (int j = i; j < argc; ++j)
144 argv[j] = argv[j + remove];
149 return new frontend::GuiApplication(argc, argv);
155 /// Return the list of loadable formats.
156 vector<string> loadableImageFormats()
160 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
162 LYXERR(Debug::GRAPHICS,
163 "\nThe image loader can load the following directly:\n");
165 if (qt_formats.empty())
166 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
168 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
170 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
172 string ext = ascii_lowercase((const char *) *it);
183 ////////////////////////////////////////////////////////////////////////
185 // Icon loading support code
187 ////////////////////////////////////////////////////////////////////////
197 bool operator<(PngMap const & lhs, PngMap const & rhs)
199 return lhs.key < rhs.key;
205 CompareKey(QString const & name) : name_(name) {}
206 bool operator()(PngMap const & other) const { return other.key == name_; }
212 // this must be sorted alphabetically
213 // Upper case comes before lower case
214 PngMap sorted_png_map[] = {
215 { "Bumpeq", "bumpeq2" },
218 { "Delta", "delta2" },
219 { "Downarrow", "downarrow2" },
220 { "Gamma", "gamma2" },
221 { "Lambda", "lambda2" },
222 { "Leftarrow", "leftarrow2" },
223 { "Leftrightarrow", "leftrightarrow2" },
224 { "Longleftarrow", "longleftarrow2" },
225 { "Longleftrightarrow", "longleftrightarrow2" },
226 { "Longrightarrow", "longrightarrow2" },
227 { "Omega", "omega2" },
231 { "Rightarrow", "rightarrow2" },
232 { "Sigma", "sigma2" },
233 { "Subset", "subset2" },
234 { "Supset", "supset2" },
235 { "Theta", "theta2" },
236 { "Uparrow", "uparrow2" },
237 { "Updownarrow", "updownarrow2" },
238 { "Upsilon", "upsilon2" },
239 { "Vdash", "vdash3" },
242 { "nLeftarrow", "nleftarrow2" },
243 { "nLeftrightarrow", "nleftrightarrow2" },
244 { "nRightarrow", "nrightarrow2" },
245 { "nVDash", "nvdash3" },
246 { "nvDash", "nvdash2" },
247 { "textrm \\AA", "textrm_AA"},
248 { "textrm \\O", "textrm_O"},
249 { "vDash", "vdash2" }
252 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
255 QString findPng(QString const & name)
257 PngMap const * const begin = sorted_png_map;
258 PngMap const * const end = begin + nr_sorted_png_map;
259 LASSERT(sorted(begin, end), /**/);
261 PngMap const * const it = find_if(begin, end, CompareKey(name));
265 png_name = it->value;
268 png_name.replace('_', "underscore");
269 png_name.replace(' ', '_');
271 // This way we can have "math-delim { }" on the toolbar.
272 png_name.replace('(', "lparen");
273 png_name.replace(')', "rparen");
274 png_name.replace('[', "lbracket");
275 png_name.replace(']', "rbracket");
276 png_name.replace('{', "lbrace");
277 png_name.replace('}', "rbrace");
278 png_name.replace('|', "bars");
279 png_name.replace(',', "thinspace");
280 png_name.replace(':', "mediumspace");
281 png_name.replace(';', "thickspace");
282 png_name.replace('!', "negthinspace");
285 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
286 << "Looking for math PNG called \"" << png_name << '"');
293 QString iconName(FuncRequest const & f, bool unknown)
295 initializeResources();
300 case LFUN_MATH_INSERT:
301 if (!f.argument().empty()) {
303 name1 = findPng(toqstr(f.argument()).mid(1));
306 case LFUN_MATH_DELIM:
307 case LFUN_MATH_BIGDELIM:
309 name1 = findPng(toqstr(f.argument()));
313 name1 = toqstr(f.argument());
315 case LFUN_COMMAND_ALTERNATIVES: {
316 // use the first of the alternative commands
318 docstring dummy = split(f.argument(), firstcom, ';');
319 name1 = toqstr(firstcom);
320 name1.replace(' ', '_');
324 name2 = toqstr(lyxaction.getActionName(f.action));
327 if (!f.argument().empty()) {
328 name1 = name2 + ' ' + toqstr(f.argument());
329 name1.replace(' ', '_');
330 name1.replace('\\', "backslash");
334 FileName fname = libFileSearch("images/" + path, name1, "png");
336 return toqstr(fname.absFilename());
338 fname = libFileSearch("images/" + path, name2, "png");
340 return toqstr(fname.absFilename());
342 path = ":/images/" + path;
345 LYXERR0("Directory " << path << " not found in resource!");
349 if (res.exists(name1))
353 if (res.exists(name2))
356 LYXERR(Debug::GUI, "Cannot find icon with filename "
357 << "\"" << name1 << "\""
359 << "\"" << name2 << "\""
361 << lyxaction.getActionName(f.action)
362 << '(' << to_utf8(f.argument()) << ")\"");
365 return QString(":/images/unknown.png");
371 QIcon getIcon(FuncRequest const & f, bool unknown)
373 QString icon = iconName(f, unknown);
377 //LYXERR(Debug::GUI, "Found icon: " << icon);
379 if (!pm.load(icon)) {
380 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
388 ////////////////////////////////////////////////////////////////////////
390 // LyX server support code.
392 ////////////////////////////////////////////////////////////////////////
394 class SocketNotifier : public QSocketNotifier
397 /// connect a connection notification from the LyXServerSocket
398 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
399 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
403 /// The callback function
404 Application::SocketCallback func_;
408 ////////////////////////////////////////////////////////////////////////
410 // Mac specific stuff goes here...
412 ////////////////////////////////////////////////////////////////////////
414 class MenuTranslator : public QTranslator
417 MenuTranslator(QObject * parent)
418 : QTranslator(parent)
421 QString translate(const char * /*context*/,
422 const char * sourceText,
423 const char * /*comment*/ = 0)
425 string const s = sourceText;
426 if (s == N_("About %1") || s == N_("Preferences")
427 || s == N_("Reconfigure") || s == N_("Quit %1"))
434 class GlobalMenuBar : public QMenuBar
438 GlobalMenuBar() : QMenuBar(0) {}
441 bool event(QEvent * e)
443 if (e->type() == QEvent::ShortcutOverride) {
444 // && activeWindow() == 0) {
445 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
447 setKeySymbol(&sym, ke);
448 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
457 // QMacPasteboardMimeGraphics can only be compiled on Mac.
459 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
462 QMacPasteboardMimeGraphics()
463 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
466 QString convertorName() { return "Graphics"; }
468 QString flavorFor(QString const & mime)
470 LYXERR(Debug::ACTION, "flavorFor " << mime);
471 if (mime == pdfMimeType())
472 return QLatin1String("com.adobe.pdf");
476 QString mimeFor(QString flav)
478 LYXERR(Debug::ACTION, "mimeFor " << flav);
479 if (flav == QLatin1String("com.adobe.pdf"))
480 return pdfMimeType();
484 bool canConvert(QString const & mime, QString flav)
486 return mimeFor(flav) == mime;
489 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
493 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
497 QList<QByteArray> convertFromMime(QString const & /*mime*/,
498 QVariant data, QString /*flav*/)
500 QList<QByteArray> ret;
501 ret.append(data.toByteArray());
507 ///////////////////////////////////////////////////////////////
509 // You can find more platform specific stuff at the end of this file...
511 ///////////////////////////////////////////////////////////////
513 ////////////////////////////////////////////////////////////////////////
514 // Windows specific stuff goes here...
517 // QWindowsMimeMetafile can only be compiled on Windows.
519 static FORMATETC cfFromMime(QString const & mimetype)
522 if (mimetype == emfMimeType()) {
523 formatetc.cfFormat = CF_ENHMETAFILE;
524 formatetc.tymed = TYMED_ENHMF;
525 } else if (mimetype == wmfMimeType()) {
526 formatetc.cfFormat = CF_METAFILEPICT;
527 formatetc.tymed = TYMED_MFPICT;
530 formatetc.dwAspect = DVASPECT_CONTENT;
531 formatetc.lindex = -1;
536 class QWindowsMimeMetafile : public QWindowsMime {
538 QWindowsMimeMetafile() {}
540 bool canConvertFromMime(FORMATETC const & formatetc,
541 QMimeData const * mimedata) const
546 bool canConvertToMime(QString const & mimetype,
547 IDataObject * pDataObj) const
549 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
551 FORMATETC formatetc = cfFromMime(mimetype);
552 return pDataObj->QueryGetData(&formatetc) == S_OK;
555 bool convertFromMime(FORMATETC const & formatetc,
556 const QMimeData * mimedata, STGMEDIUM * pmedium) const
561 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
562 QVariant::Type preferredType) const
565 if (!canConvertToMime(mimetype, pDataObj))
568 FORMATETC formatetc = cfFromMime(mimetype);
570 if (pDataObj->GetData(&formatetc, &s) != S_OK)
574 if (s.tymed == TYMED_ENHMF) {
575 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
576 data.resize(dataSize);
577 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
578 (LPBYTE)data.data());
579 } else if (s.tymed == TYMED_MFPICT) {
580 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
581 data.resize(dataSize);
582 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
583 (LPBYTE)data.data());
586 ReleaseStgMedium(&s);
592 QVector<FORMATETC> formatsForMime(QString const & mimetype,
593 QMimeData const * mimedata) const
595 QVector<FORMATETC> formats;
596 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
597 formats += cfFromMime(mimetype);
601 QString mimeForFormat(FORMATETC const & formatetc) const
603 switch (formatetc.cfFormat) {
605 return emfMimeType();
606 case CF_METAFILEPICT:
607 return wmfMimeType();
615 ////////////////////////////////////////////////////////////////////////
616 // GuiApplication::Private definition and implementation.
617 ////////////////////////////////////////////////////////////////////////
619 struct GuiApplication::Private
621 Private(): language_model_(0), global_menubar_(0) {}
624 QSortFilterProxyModel * language_model_;
626 GuiClipboard clipboard_;
628 GuiSelection selection_;
630 FontLoader font_loader_;
632 ColorCache color_cache_;
634 QTranslator qt_trans_;
636 QHash<int, SocketNotifier *> socket_notifiers_;
640 /// The global instance
643 /// this timer is used for any regular events one wants to
644 /// perform. at present it is used to check if forked processes
646 QTimer general_timer_;
648 /// delayed FuncRequests
649 std::queue<FuncRequest> func_request_queue_;
651 /// Multiple views container.
653 * Warning: This must not be a smart pointer as the destruction of the
654 * object is handled by Qt when the view is closed
655 * \sa Qt::WA_DeleteOnClose attribute.
657 QHash<int, GuiView *> views_;
659 /// Only used on mac.
660 GlobalMenuBar * global_menubar_;
663 /// Linkback mime handler for MacOSX.
664 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
668 /// WMF Mime handler for Windows clipboard.
669 /// \warning: see comment in ~GuiApplication and in bug 4846.
670 QWindowsMimeMetafile wmf_mime_;
675 GuiApplication * guiApp;
677 GuiApplication::~GuiApplication()
680 closeAllLinkBackLinks();
682 // FIXME: Work around bug 4846 for Windows Vista and Qt4
683 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
684 // If the clipboard is not cleared, LyX crashes on exit when it is
685 // compiled in release mode and if there is something in the clipboard.
686 // This is related to QWindowsMimeMetafile which is apparently not
687 // properly destroyed.
688 qApp->clipboard()->clear(QClipboard::Clipboard);
693 GuiApplication::GuiApplication(int & argc, char ** argv)
694 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
696 QString app_name = "LyX";
697 QCoreApplication::setOrganizationName(app_name);
698 QCoreApplication::setOrganizationDomain("lyx.org");
699 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
701 // Install translator for GUI elements.
702 installTranslator(&d->qt_trans_);
704 // FIXME: quitOnLastWindowClosed is true by default. We should have a
705 // lyxrc setting for this in order to let the application stay resident.
706 // But then we need some kind of dock icon, at least on Windows.
708 if (lyxrc.quit_on_last_window_closed)
709 setQuitOnLastWindowClosed(false);
712 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
713 // seems to be the default case for applications like LyX.
714 setQuitOnLastWindowClosed(false);
716 // This allows to translate the strings that appear in the LyX menu.
717 /// A translator suitable for the entries in the LyX menu.
718 /// Only needed with Qt/Mac.
719 installTranslator(new MenuTranslator(this));
723 // doubleClickInterval() is 400 ms on X11 which is just too long.
724 // On Windows and Mac OS X, the operating system's value is used.
725 // On Microsoft Windows, calling this function sets the double
726 // click interval for all applications. So we don't!
727 QApplication::setDoubleClickInterval(300);
730 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
732 // needs to be done before reading lyxrc
734 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
738 // Set the cache to 5120 kilobytes which corresponds to screen size of
739 // 1280 by 1024 pixels with a color depth of 32 bits.
740 QPixmapCache::setCacheLimit(5120);
742 // Initialize RC Fonts
743 if (lyxrc.roman_font_name.empty())
744 lyxrc.roman_font_name = fromqstr(romanFontName());
746 if (lyxrc.sans_font_name.empty())
747 lyxrc.sans_font_name = fromqstr(sansFontName());
749 if (lyxrc.typewriter_font_name.empty())
750 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
752 d->general_timer_.setInterval(500);
753 connect(&d->general_timer_, SIGNAL(timeout()),
754 this, SLOT(handleRegularEvents()));
755 d->general_timer_.start();
759 GuiApplication * theGuiApp()
761 return dynamic_cast<GuiApplication *>(theApp());
765 void GuiApplication::clearSession()
772 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
774 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
779 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
785 case LFUN_WINDOW_CLOSE:
786 enable = d->views_.size() > 0;
789 case LFUN_BUFFER_NEW:
790 case LFUN_BUFFER_NEW_TEMPLATE:
792 case LFUN_SCREEN_FONT_UPDATE:
794 case LFUN_WINDOW_NEW:
804 flag.setEnabled(false);
810 bool GuiApplication::dispatch(FuncRequest const & cmd)
812 switch (cmd.action) {
814 case LFUN_WINDOW_NEW:
815 createView(toqstr(cmd.argument()));
818 case LFUN_WINDOW_CLOSE:
819 // update bookmark pit of the current buffer before window close
820 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
821 theLyXFunc().gotoBookmark(i+1, false, false);
822 current_view_->close();
826 // quitting is triggered by the gui code
827 // (leaving the event loop).
829 current_view_->message(from_utf8(N_("Exiting.")));
834 case LFUN_SCREEN_FONT_UPDATE: {
835 // handle the screen font changes.
836 d->font_loader_.update();
837 // Backup current_view_
838 GuiView * view = current_view_;
839 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
840 // to skip the refresh.
842 BufferList::iterator it = theBufferList().begin();
843 BufferList::iterator const end = theBufferList().end();
844 for (; it != end; ++it)
846 // Restore current_view_
847 current_view_ = view;
851 case LFUN_BUFFER_NEW:
852 if (d->views_.empty()
853 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
854 createView(QString(), false); // keep hidden
855 current_view_->newDocument(to_utf8(cmd.argument()), false);
856 current_view_->show();
857 setActiveWindow(current_view_);
859 current_view_->newDocument(to_utf8(cmd.argument()), false);
863 case LFUN_BUFFER_NEW_TEMPLATE:
864 if (d->views_.empty()
865 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
867 current_view_->newDocument(to_utf8(cmd.argument()), true);
868 if (!current_view_->buffer())
869 current_view_->close();
871 current_view_->newDocument(to_utf8(cmd.argument()), true);
876 if (d->views_.empty()
877 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
878 string const fname = to_utf8(cmd.argument());
879 // We want the ui session to be saved per document and not per
880 // window number. The filename crc is a good enough identifier.
881 boost::crc_32_type crc;
882 crc = for_each(fname.begin(), fname.end(), crc);
883 createView(crc.checksum());
884 current_view_->openDocument(fname);
885 if (current_view_ && !current_view_->buffer())
886 current_view_->close();
888 current_view_->openDocument(to_utf8(cmd.argument()));
891 case LFUN_SET_COLOR: {
893 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
894 if (lyx_name.empty() || x11_name.empty()) {
895 current_view_->message(
896 _("Syntax: set-color <lyx_name> <x11_name>"));
900 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
901 bool const graphicsbg_changed = lyx_name == graphicsbg
902 && x11_name != graphicsbg;
903 if (graphicsbg_changed) {
904 // FIXME: The graphics cache no longer has a changeDisplay method.
906 graphics::GCache::get().changeDisplay(true);
910 if (!lcolor.setColor(lyx_name, x11_name)) {
911 current_view_->message(
912 bformat(_("Set-color \"%1$s\" failed "
913 "- color is undefined or "
914 "may not be redefined"),
915 from_utf8(lyx_name)));
918 // Make sure we don't keep old colors in cache.
919 d->color_cache_.clear();
924 // Notify the caller that the action has not been dispatched.
928 // The action has been dispatched.
933 void GuiApplication::dispatchDelayed(FuncRequest const & func)
935 d->func_request_queue_.push(func);
936 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
940 void GuiApplication::resetGui()
942 // Set the language defined by the user.
946 if (!readUIFile(toqstr(lyxrc.ui_file)))
947 // Gives some error box here.
950 if (d->global_menubar_)
951 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
953 QHash<int, GuiView *>::iterator it;
954 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
956 gv->setLayoutDirection(layoutDirection());
960 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
964 void GuiApplication::createView(int view_id)
966 createView(QString(), true, view_id);
970 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
973 // release the keyboard which might have been grabed by the global
974 // menubar on Mac to catch shortcuts even without any GuiView.
975 if (d->global_menubar_)
976 d->global_menubar_->releaseKeyboard();
981 while (d->views_.find(id) != d->views_.end())
984 LYXERR(Debug::GUI, "About to create new window with ID " << id);
985 GuiView * view = new GuiView(id);
987 d->views_[id] = view;
991 setActiveWindow(view);
994 if (!geometry_arg.isEmpty()) {
998 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
999 re.indexIn(geometry_arg);
1000 w = re.cap(1).toInt();
1001 h = re.cap(2).toInt();
1002 x = re.cap(3).toInt();
1003 y = re.cap(4).toInt();
1004 view->setGeometry(x, y, w, h);
1011 Clipboard & GuiApplication::clipboard()
1013 return d->clipboard_;
1017 Selection & GuiApplication::selection()
1019 return d->selection_;
1023 FontLoader & GuiApplication::fontLoader()
1025 return d->font_loader_;
1029 Toolbars const & GuiApplication::toolbars() const
1031 return d->toolbars_;
1035 Toolbars & GuiApplication::toolbars()
1037 return d->toolbars_;
1041 Menus const & GuiApplication::menus() const
1047 Menus & GuiApplication::menus()
1053 QList<int> GuiApplication::viewIds() const
1055 return d->views_.keys();
1059 ColorCache & GuiApplication::colorCache()
1061 return d->color_cache_;
1065 int GuiApplication::exec()
1067 // asynchronously handle batch commands. This event will be in
1068 // the event queue in front of other asynchronous events. Hence,
1069 // we can assume in the latter that the gui is setup already.
1070 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1072 return QApplication::exec();
1076 void GuiApplication::exit(int status)
1078 QApplication::exit(status);
1082 void GuiApplication::setGuiLanguage()
1084 // Set the language defined by the user.
1087 QString const default_language = toqstr(Messages::defaultLanguage());
1088 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1089 QLocale const default_locale(default_language);
1090 QLocale::setDefault(default_locale);
1092 // install translation file for Qt built-in dialogs
1093 QString const language_name = QString("qt_") + default_locale.name();
1095 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1096 // Short-named translator can be loaded from a long name, but not the
1097 // opposite. Therefore, long name should be used without truncation.
1098 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1099 if (!d->qt_trans_.load(language_name,
1100 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1101 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1104 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1108 switch (default_locale.language()) {
1109 case QLocale::Arabic :
1110 case QLocale::Hebrew :
1111 case QLocale::Persian :
1112 case QLocale::Urdu :
1113 setLayoutDirection(Qt::RightToLeft);
1116 setLayoutDirection(Qt::LeftToRight);
1121 void GuiApplication::processFuncRequestQueue()
1123 while (!d->func_request_queue_.empty()) {
1124 lyx::dispatch(d->func_request_queue_.back());
1125 d->func_request_queue_.pop();
1130 void GuiApplication::execBatchCommands()
1135 if (!readUIFile(toqstr(lyxrc.ui_file)))
1136 // Gives some error box here.
1140 // Create the global default menubar which is shown for the dialogs
1141 // and if no GuiView is visible.
1142 // This must be done after the session was recovered to know the "last files".
1143 d->global_menubar_ = new GlobalMenuBar();
1144 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1147 lyx::execBatchCommands();
1151 QAbstractItemModel * GuiApplication::languageModel()
1153 if (d->language_model_)
1154 return d->language_model_;
1156 QStandardItemModel * lang_model = new QStandardItemModel(this);
1157 lang_model->insertColumns(0, 1);
1159 Languages::const_iterator it = languages.begin();
1160 Languages::const_iterator end = languages.end();
1161 for (; it != end; ++it) {
1162 current_row = lang_model->rowCount();
1163 lang_model->insertRows(current_row, 1);
1164 QModelIndex item = lang_model->index(current_row, 0);
1165 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1166 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1168 d->language_model_ = new QSortFilterProxyModel(this);
1169 d->language_model_->setSourceModel(lang_model);
1170 #if QT_VERSION >= 0x040300
1171 d->language_model_->setSortLocaleAware(true);
1173 return d->language_model_;
1177 void GuiApplication::restoreGuiSession()
1179 if (!lyxrc.load_session)
1182 Session & session = theSession();
1183 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1184 // do not add to the lastfile list since these files are restored from
1185 // last session, and should be already there (regular files), or should
1186 // not be added at all (help files).
1187 for_each(lastopened.begin(), lastopened.end(),
1188 bind(&GuiView::loadDocument, current_view_, _1, false));
1190 // clear this list to save a few bytes of RAM
1191 session.lastOpened().clear();
1195 QString const GuiApplication::romanFontName()
1198 font.setKerning(false);
1199 font.setStyleHint(QFont::Serif);
1200 font.setFamily("serif");
1202 return QFontInfo(font).family();
1206 QString const GuiApplication::sansFontName()
1209 font.setKerning(false);
1210 font.setStyleHint(QFont::SansSerif);
1211 font.setFamily("sans");
1213 return QFontInfo(font).family();
1217 QString const GuiApplication::typewriterFontName()
1220 font.setKerning(false);
1221 font.setStyleHint(QFont::TypeWriter);
1222 font.setFamily("monospace");
1224 return QFontInfo(font).family();
1228 void GuiApplication::handleRegularEvents()
1230 ForkedCallsController::handleCompletedProcesses();
1234 bool GuiApplication::event(QEvent * e)
1237 case QEvent::FileOpen: {
1238 // Open a file; this happens only on Mac OS X for now.
1240 // We do this asynchronously because on startup the batch
1241 // commands are not executed here yet and the gui is not ready
1243 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1244 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1249 return QApplication::event(e);
1254 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1257 return QApplication::notify(receiver, event);
1259 catch (ExceptionMessage const & e) {
1261 case ErrorException:
1263 setQuitOnLastWindowClosed(false);
1265 Alert::error(e.title_, e.details_);
1267 // Properly crash in debug mode in order to get a useful backtrace.
1270 // In release mode, try to exit gracefully.
1273 case BufferException: {
1274 Buffer * buf = current_view_->buffer();
1275 docstring details = e.details_ + '\n';
1276 details += theBufferList().emergencyWrite(buf);
1277 theBufferList().release(buf);
1278 details += "\n" + _("The current document was closed.");
1279 Alert::error(e.title_, details);
1282 case WarningException:
1283 Alert::warning(e.title_, e.details_);
1287 catch (exception const & e) {
1288 docstring s = _("LyX has caught an exception, it will now "
1289 "attempt to save all unsaved documents and exit."
1291 s += from_ascii(e.what());
1292 Alert::error(_("Software exception Detected"), s);
1296 docstring s = _("LyX has caught some really weird exception, it will "
1297 "now attempt to save all unsaved documents and exit.");
1298 Alert::error(_("Software exception Detected"), s);
1306 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1308 QColor const & qcol = d->color_cache_.get(col);
1309 if (!qcol.isValid()) {
1315 rgbcol.r = qcol.red();
1316 rgbcol.g = qcol.green();
1317 rgbcol.b = qcol.blue();
1322 string const GuiApplication::hexName(ColorCode col)
1324 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1328 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1330 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1331 d->socket_notifiers_[fd] = sn;
1332 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1336 void GuiApplication::socketDataReceived(int fd)
1338 d->socket_notifiers_[fd]->func_();
1342 void GuiApplication::unregisterSocketCallback(int fd)
1344 d->socket_notifiers_.take(fd)->setEnabled(false);
1348 void GuiApplication::commitData(QSessionManager & sm)
1350 /// The implementation is required to avoid an application exit
1351 /// when session state save is triggered by session manager.
1352 /// The default implementation sends a close event to all
1353 /// visible top level widgets when session managment allows
1355 /// We are changing that to close all wiew one by one.
1356 /// FIXME: verify if the default implementation is enough now.
1357 if (sm.allowsInteraction() && !closeAllViews())
1362 void GuiApplication::unregisterView(GuiView * gv)
1364 LASSERT(d->views_[gv->id()] == gv, /**/);
1365 d->views_.remove(gv->id());
1366 if (current_view_ == gv) {
1368 theLyXFunc().setLyXView(0);
1373 bool GuiApplication::closeAllViews()
1375 if (d->views_.empty())
1378 QList<GuiView *> views = d->views_.values();
1379 foreach (GuiView * view, views) {
1389 GuiView & GuiApplication::view(int id) const
1391 LASSERT(d->views_.contains(id), /**/);
1392 return *d->views_.value(id);
1396 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1398 QList<GuiView *> views = d->views_.values();
1399 foreach (GuiView * view, views)
1400 view->hideDialog(name, inset);
1404 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1406 Buffer const * buffer_ = 0;
1407 QHash<int, GuiView *>::iterator end = d->views_.end();
1408 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1409 if (Buffer const * ptr = (*it)->updateInset(inset))
1416 bool GuiApplication::searchMenu(FuncRequest const & func,
1417 docstring_list & names) const
1419 return d->menus_.searchMenu(func, names);
1423 bool GuiApplication::readUIFile(QString const & name, bool include)
1433 LexerKeyword uitags[] = {
1434 { "include", ui_include },
1435 { "menuset", ui_menuset },
1436 { "toolbars", ui_toolbars },
1437 { "toolbarset", ui_toolbarset }
1440 LYXERR(Debug::INIT, "About to read " << name << "...");
1444 ui_path = libFileSearch("ui", name, "inc");
1445 if (ui_path.empty())
1446 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1448 ui_path = libFileSearch("ui", name, "ui");
1451 if (ui_path.empty()) {
1452 LYXERR(Debug::INIT, "Could not find " << name);
1453 Alert::warning(_("Could not find UI definition file"),
1454 bformat(_("Error while reading the configuration file\n%1$s.\n"
1455 "Please check your installation."), qstring_to_ucs4(name)));
1460 // Ensure that a file is read only once (prevents include loops)
1461 static QStringList uifiles;
1462 QString const uifile = toqstr(ui_path.absFilename());
1463 if (uifiles.contains(uifile)) {
1465 // We are reading again the top uifile so reset the safeguard:
1468 d->toolbars_.reset();
1470 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1471 << "Is this an include loop?");
1475 uifiles.push_back(uifile);
1477 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1480 lex.setFile(ui_path);
1482 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1486 if (lyxerr.debugging(Debug::PARSER))
1487 lex.printTable(lyxerr);
1489 while (lex.isOK()) {
1490 switch (lex.lex()) {
1493 QString const file = toqstr(lex.getString());
1494 if (!readUIFile(file, true))
1499 d->menus_.read(lex);
1503 d->toolbars_.readToolbars(lex);
1507 d->toolbars_.readToolbarSettings(lex);
1511 if (!rtrim(lex.getString()).empty())
1512 lex.printError("LyX::ReadUIFile: "
1513 "Unknown menu tag: `$$Token'");
1522 settings.beginGroup("ui_files");
1523 bool touched = false;
1524 for (int i = 0; i != uifiles.size(); ++i) {
1525 QFileInfo fi(uifiles[i]);
1526 QDateTime const date_value = fi.lastModified();
1527 QString const name_key = QString::number(i);
1528 if (!settings.contains(name_key)
1529 || settings.value(name_key).toString() != uifiles[i]
1530 || settings.value(name_key + "/date").toDateTime() != date_value) {
1532 settings.setValue(name_key, uifiles[i]);
1533 settings.setValue(name_key + "/date", date_value);
1536 settings.endGroup();
1538 settings.remove("views");
1544 void GuiApplication::onLastWindowClosed()
1546 if (d->global_menubar_)
1547 d->global_menubar_->grabKeyboard();
1551 ////////////////////////////////////////////////////////////////////////
1553 // X11 specific stuff goes here...
1556 bool GuiApplication::x11EventFilter(XEvent * xev)
1561 switch (xev->type) {
1562 case SelectionRequest: {
1563 if (xev->xselectionrequest.selection != XA_PRIMARY)
1565 LYXERR(Debug::SELECTION, "X requested selection.");
1566 BufferView * bv = current_view_->view();
1568 docstring const sel = bv->requestSelection();
1570 d->selection_.put(sel);
1574 case SelectionClear: {
1575 if (xev->xselectionclear.selection != XA_PRIMARY)
1577 LYXERR(Debug::SELECTION, "Lost selection.");
1578 BufferView * bv = current_view_->view();
1580 bv->clearSelection();
1588 } // namespace frontend
1591 void hideDialogs(std::string const & name, Inset * inset)
1594 theApp()->hideDialogs(name, inset);
1598 ////////////////////////////////////////////////////////////////////
1602 ////////////////////////////////////////////////////////////////////
1604 frontend::FontLoader & theFontLoader()
1606 LASSERT(frontend::guiApp, /**/);
1607 return frontend::guiApp->fontLoader();
1611 frontend::FontMetrics const & theFontMetrics(Font const & f)
1613 return theFontMetrics(f.fontInfo());
1617 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1619 LASSERT(frontend::guiApp, /**/);
1620 return frontend::guiApp->fontLoader().metrics(f);
1624 ////////////////////////////////////////////////////////////////////
1628 ////////////////////////////////////////////////////////////////////
1630 frontend::Clipboard & theClipboard()
1632 LASSERT(frontend::guiApp, /**/);
1633 return frontend::guiApp->clipboard();
1637 frontend::Selection & theSelection()
1639 LASSERT(frontend::guiApp, /**/);
1640 return frontend::guiApp->selection();
1646 #include "moc_GuiApplication.cpp"