2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
38 #include "FuncRequest.h"
39 #include "FuncStatus.h"
43 #include "LyXAction.h"
49 #include "support/lassert.h"
50 #include "support/debug.h"
51 #include "support/ExceptionMessage.h"
52 #include "support/FileName.h"
53 #include "support/foreach.h"
54 #include "support/ForkedCalls.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/lyxalgo.h" // sorted
58 #include "support/Messages.h"
59 #include "support/os.h"
60 #include "support/Package.h"
63 #include "support/linkback/LinkBackProxy.h"
73 #include <QFileOpenEvent>
77 #include <QImageReader>
79 #include <QLibraryInfo>
81 #include <QMacPasteboardMime>
86 #include <QPixmapCache>
88 #include <QSessionManager>
90 #include <QSocketNotifier>
91 #include <QSortFilterProxyModel>
92 #include <QStandardItemModel>
95 #include <QTranslator>
99 #include <X11/Xatom.h>
100 #include <X11/Xlib.h>
106 #include <QWindowsMime>
113 #include <boost/bind.hpp>
114 #include <boost/crc.hpp>
120 using namespace lyx::support;
123 static void initializeResources()
125 static bool initialized = false;
127 Q_INIT_RESOURCE(Resources);
135 frontend::Application * createApplication(int & argc, char * argv[])
138 // prune -geometry argument(s) by shifting
139 // the following ones 2 places down.
140 for (int i = 0 ; i < argc ; ++i) {
141 if (strcmp(argv[i], "-geometry") == 0) {
142 int const remove = (i+1) < argc ? 2 : 1;
144 for (int j = i; j < argc; ++j)
145 argv[j] = argv[j + remove];
150 return new frontend::GuiApplication(argc, argv);
156 /// Return the list of loadable formats.
157 vector<string> loadableImageFormats()
161 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
163 LYXERR(Debug::GRAPHICS,
164 "\nThe image loader can load the following directly:\n");
166 if (qt_formats.empty())
167 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
169 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
171 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
173 string ext = ascii_lowercase((const char *) *it);
184 ////////////////////////////////////////////////////////////////////////
186 // Icon loading support code
188 ////////////////////////////////////////////////////////////////////////
198 bool operator<(PngMap const & lhs, PngMap const & rhs)
200 return lhs.key < rhs.key;
206 CompareKey(QString const & name) : name_(name) {}
207 bool operator()(PngMap const & other) const { return other.key == name_; }
213 // this must be sorted alphabetically
214 // Upper case comes before lower case
215 PngMap sorted_png_map[] = {
216 { "Bumpeq", "bumpeq2" },
219 { "Delta", "delta2" },
220 { "Downarrow", "downarrow2" },
221 { "Gamma", "gamma2" },
222 { "Lambda", "lambda2" },
223 { "Leftarrow", "leftarrow2" },
224 { "Leftrightarrow", "leftrightarrow2" },
225 { "Longleftarrow", "longleftarrow2" },
226 { "Longleftrightarrow", "longleftrightarrow2" },
227 { "Longrightarrow", "longrightarrow2" },
228 { "Omega", "omega2" },
232 { "Rightarrow", "rightarrow2" },
233 { "Sigma", "sigma2" },
234 { "Subset", "subset2" },
235 { "Supset", "supset2" },
236 { "Theta", "theta2" },
237 { "Uparrow", "uparrow2" },
238 { "Updownarrow", "updownarrow2" },
239 { "Upsilon", "upsilon2" },
240 { "Vdash", "vdash3" },
243 { "nLeftarrow", "nleftarrow2" },
244 { "nLeftrightarrow", "nleftrightarrow2" },
245 { "nRightarrow", "nrightarrow2" },
246 { "nVDash", "nvdash3" },
247 { "nvDash", "nvdash2" },
248 { "textrm \\AA", "textrm_AA"},
249 { "textrm \\O", "textrm_O"},
250 { "vDash", "vdash2" }
253 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
256 QString findPng(QString const & name)
258 PngMap const * const begin = sorted_png_map;
259 PngMap const * const end = begin + nr_sorted_png_map;
260 LASSERT(sorted(begin, end), /**/);
262 PngMap const * const it = find_if(begin, end, CompareKey(name));
266 png_name = it->value;
269 png_name.replace('_', "underscore");
270 png_name.replace(' ', '_');
272 // This way we can have "math-delim { }" on the toolbar.
273 png_name.replace('(', "lparen");
274 png_name.replace(')', "rparen");
275 png_name.replace('[', "lbracket");
276 png_name.replace(']', "rbracket");
277 png_name.replace('{', "lbrace");
278 png_name.replace('}', "rbrace");
279 png_name.replace('|', "bars");
280 png_name.replace(',', "thinspace");
281 png_name.replace(':', "mediumspace");
282 png_name.replace(';', "thickspace");
283 png_name.replace('!', "negthinspace");
286 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
287 << "Looking for math PNG called \"" << png_name << '"');
294 QString iconName(FuncRequest const & f, bool unknown)
296 initializeResources();
301 case LFUN_MATH_INSERT:
302 if (!f.argument().empty()) {
304 name1 = findPng(toqstr(f.argument()).mid(1));
307 case LFUN_MATH_DELIM:
308 case LFUN_MATH_BIGDELIM:
310 name1 = findPng(toqstr(f.argument()));
314 name1 = toqstr(f.argument());
316 case LFUN_COMMAND_ALTERNATIVES: {
317 // use the first of the alternative commands
319 docstring dummy = split(f.argument(), firstcom, ';');
320 name1 = toqstr(firstcom);
321 name1.replace(' ', '_');
325 name2 = toqstr(lyxaction.getActionName(f.action));
328 if (!f.argument().empty()) {
329 name1 = name2 + ' ' + toqstr(f.argument());
330 name1.replace(' ', '_');
331 name1.replace('\\', "backslash");
335 FileName fname = libFileSearch("images/" + path, name1, "png");
337 return toqstr(fname.absFilename());
339 fname = libFileSearch("images/" + path, name2, "png");
341 return toqstr(fname.absFilename());
343 path = ":/images/" + path;
346 LYXERR0("Directory " << path << " not found in resource!");
350 if (res.exists(name1))
354 if (res.exists(name2))
357 LYXERR(Debug::GUI, "Cannot find icon with filename "
358 << "\"" << name1 << "\""
360 << "\"" << name2 << "\""
362 << lyxaction.getActionName(f.action)
363 << '(' << to_utf8(f.argument()) << ")\"");
366 fname = libFileSearch("images/", "unknown", "png");
368 return toqstr(fname.absFilename());
369 return QString(":/images/unknown.png");
375 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
378 FileName fname = libFileSearch(path, name, ext);
379 QString path1 = toqstr(fname.absFilename());
380 QString path2 = ":/" + path + name + "." + ext;
382 if (pixmap.load(path1)) {
385 else if (pixmap.load(path2)) {
389 LYXERR0("Cannot load pixmap \""
390 << path << name << '.' << ext
391 << "\", please verify resource system!");
396 QIcon getIcon(FuncRequest const & f, bool unknown)
398 QString icon = iconName(f, unknown);
402 //LYXERR(Debug::GUI, "Found icon: " << icon);
404 if (!pm.load(icon)) {
405 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
413 ////////////////////////////////////////////////////////////////////////
415 // LyX server support code.
417 ////////////////////////////////////////////////////////////////////////
419 class SocketNotifier : public QSocketNotifier
422 /// connect a connection notification from the LyXServerSocket
423 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
424 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
428 /// The callback function
429 Application::SocketCallback func_;
433 ////////////////////////////////////////////////////////////////////////
435 // Mac specific stuff goes here...
437 ////////////////////////////////////////////////////////////////////////
439 class MenuTranslator : public QTranslator
442 MenuTranslator(QObject * parent)
443 : QTranslator(parent)
446 QString translate(const char * /*context*/,
447 const char * sourceText,
448 const char * /*comment*/ = 0)
450 string const s = sourceText;
451 if (s == N_("About %1") || s == N_("Preferences")
452 || s == N_("Reconfigure") || s == N_("Quit %1"))
459 class GlobalMenuBar : public QMenuBar
463 GlobalMenuBar() : QMenuBar(0) {}
466 bool event(QEvent * e)
468 if (e->type() == QEvent::ShortcutOverride) {
469 // && activeWindow() == 0) {
470 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
472 setKeySymbol(&sym, ke);
473 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
482 // QMacPasteboardMimeGraphics can only be compiled on Mac.
484 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
487 QMacPasteboardMimeGraphics()
488 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
491 QString convertorName() { return "Graphics"; }
493 QString flavorFor(QString const & mime)
495 LYXERR(Debug::ACTION, "flavorFor " << mime);
496 if (mime == pdfMimeType())
497 return QLatin1String("com.adobe.pdf");
501 QString mimeFor(QString flav)
503 LYXERR(Debug::ACTION, "mimeFor " << flav);
504 if (flav == QLatin1String("com.adobe.pdf"))
505 return pdfMimeType();
509 bool canConvert(QString const & mime, QString flav)
511 return mimeFor(flav) == mime;
514 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
518 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
522 QList<QByteArray> convertFromMime(QString const & /*mime*/,
523 QVariant data, QString /*flav*/)
525 QList<QByteArray> ret;
526 ret.append(data.toByteArray());
532 ///////////////////////////////////////////////////////////////
534 // You can find more platform specific stuff at the end of this file...
536 ///////////////////////////////////////////////////////////////
538 ////////////////////////////////////////////////////////////////////////
539 // Windows specific stuff goes here...
542 // QWindowsMimeMetafile can only be compiled on Windows.
544 static FORMATETC cfFromMime(QString const & mimetype)
547 if (mimetype == emfMimeType()) {
548 formatetc.cfFormat = CF_ENHMETAFILE;
549 formatetc.tymed = TYMED_ENHMF;
550 } else if (mimetype == wmfMimeType()) {
551 formatetc.cfFormat = CF_METAFILEPICT;
552 formatetc.tymed = TYMED_MFPICT;
555 formatetc.dwAspect = DVASPECT_CONTENT;
556 formatetc.lindex = -1;
561 class QWindowsMimeMetafile : public QWindowsMime {
563 QWindowsMimeMetafile() {}
565 bool canConvertFromMime(FORMATETC const & formatetc,
566 QMimeData const * mimedata) const
571 bool canConvertToMime(QString const & mimetype,
572 IDataObject * pDataObj) const
574 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
576 FORMATETC formatetc = cfFromMime(mimetype);
577 return pDataObj->QueryGetData(&formatetc) == S_OK;
580 bool convertFromMime(FORMATETC const & formatetc,
581 const QMimeData * mimedata, STGMEDIUM * pmedium) const
586 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
587 QVariant::Type preferredType) const
590 if (!canConvertToMime(mimetype, pDataObj))
593 FORMATETC formatetc = cfFromMime(mimetype);
595 if (pDataObj->GetData(&formatetc, &s) != S_OK)
599 if (s.tymed == TYMED_ENHMF) {
600 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
601 data.resize(dataSize);
602 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
603 (LPBYTE)data.data());
604 } else if (s.tymed == TYMED_MFPICT) {
605 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
606 data.resize(dataSize);
607 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
608 (LPBYTE)data.data());
611 ReleaseStgMedium(&s);
617 QVector<FORMATETC> formatsForMime(QString const & mimetype,
618 QMimeData const * mimedata) const
620 QVector<FORMATETC> formats;
621 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
622 formats += cfFromMime(mimetype);
626 QString mimeForFormat(FORMATETC const & formatetc) const
628 switch (formatetc.cfFormat) {
630 return emfMimeType();
631 case CF_METAFILEPICT:
632 return wmfMimeType();
640 ////////////////////////////////////////////////////////////////////////
641 // GuiApplication::Private definition and implementation.
642 ////////////////////////////////////////////////////////////////////////
644 struct GuiApplication::Private
646 Private(): language_model_(0), global_menubar_(0) {}
649 QSortFilterProxyModel * language_model_;
651 GuiClipboard clipboard_;
653 GuiSelection selection_;
655 FontLoader font_loader_;
657 ColorCache color_cache_;
659 QTranslator qt_trans_;
661 QHash<int, SocketNotifier *> socket_notifiers_;
665 /// The global instance
668 /// this timer is used for any regular events one wants to
669 /// perform. at present it is used to check if forked processes
671 QTimer general_timer_;
673 /// delayed FuncRequests
674 std::queue<FuncRequest> func_request_queue_;
676 /// Multiple views container.
678 * Warning: This must not be a smart pointer as the destruction of the
679 * object is handled by Qt when the view is closed
680 * \sa Qt::WA_DeleteOnClose attribute.
682 QHash<int, GuiView *> views_;
684 /// Only used on mac.
685 GlobalMenuBar * global_menubar_;
688 /// Linkback mime handler for MacOSX.
689 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
693 /// WMF Mime handler for Windows clipboard.
694 QWindowsMimeMetafile wmf_mime_;
699 GuiApplication * guiApp;
701 GuiApplication::~GuiApplication()
704 closeAllLinkBackLinks();
710 GuiApplication::GuiApplication(int & argc, char ** argv)
711 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
713 QString app_name = "LyX";
714 QCoreApplication::setOrganizationName(app_name);
715 QCoreApplication::setOrganizationDomain("lyx.org");
716 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
718 // Install translator for GUI elements.
719 installTranslator(&d->qt_trans_);
721 // FIXME: quitOnLastWindowClosed is true by default. We should have a
722 // lyxrc setting for this in order to let the application stay resident.
723 // But then we need some kind of dock icon, at least on Windows.
725 if (lyxrc.quit_on_last_window_closed)
726 setQuitOnLastWindowClosed(false);
729 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
730 // seems to be the default case for applications like LyX.
731 setQuitOnLastWindowClosed(false);
733 // This allows to translate the strings that appear in the LyX menu.
734 /// A translator suitable for the entries in the LyX menu.
735 /// Only needed with Qt/Mac.
736 installTranslator(new MenuTranslator(this));
740 // doubleClickInterval() is 400 ms on X11 which is just too long.
741 // On Windows and Mac OS X, the operating system's value is used.
742 // On Microsoft Windows, calling this function sets the double
743 // click interval for all applications. So we don't!
744 QApplication::setDoubleClickInterval(300);
747 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
749 // needs to be done before reading lyxrc
751 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
755 // Set the cache to 5120 kilobytes which corresponds to screen size of
756 // 1280 by 1024 pixels with a color depth of 32 bits.
757 QPixmapCache::setCacheLimit(5120);
759 // Initialize RC Fonts
760 if (lyxrc.roman_font_name.empty())
761 lyxrc.roman_font_name = fromqstr(romanFontName());
763 if (lyxrc.sans_font_name.empty())
764 lyxrc.sans_font_name = fromqstr(sansFontName());
766 if (lyxrc.typewriter_font_name.empty())
767 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
769 d->general_timer_.setInterval(500);
770 connect(&d->general_timer_, SIGNAL(timeout()),
771 this, SLOT(handleRegularEvents()));
772 d->general_timer_.start();
776 GuiApplication * theGuiApp()
778 return dynamic_cast<GuiApplication *>(theApp());
782 void GuiApplication::clearSession()
789 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
791 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
796 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
802 case LFUN_WINDOW_CLOSE:
803 enable = d->views_.size() > 0;
806 case LFUN_BUFFER_NEW:
807 case LFUN_BUFFER_NEW_TEMPLATE:
809 case LFUN_SCREEN_FONT_UPDATE:
811 case LFUN_WINDOW_NEW:
821 flag.setEnabled(false);
827 bool GuiApplication::dispatch(FuncRequest const & cmd)
829 switch (cmd.action) {
831 case LFUN_WINDOW_NEW:
832 createView(toqstr(cmd.argument()));
835 case LFUN_WINDOW_CLOSE:
836 // update bookmark pit of the current buffer before window close
837 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
838 theLyXFunc().gotoBookmark(i+1, false, false);
839 current_view_->close();
843 // quitting is triggered by the gui code
844 // (leaving the event loop).
846 current_view_->message(from_utf8(N_("Exiting.")));
851 case LFUN_SCREEN_FONT_UPDATE: {
852 // handle the screen font changes.
853 d->font_loader_.update();
854 // Backup current_view_
855 GuiView * view = current_view_;
856 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
857 // to skip the refresh.
859 BufferList::iterator it = theBufferList().begin();
860 BufferList::iterator const end = theBufferList().end();
861 for (; it != end; ++it)
863 // Restore current_view_
864 current_view_ = view;
868 case LFUN_BUFFER_NEW:
869 if (d->views_.empty()
870 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
871 createView(QString(), false); // keep hidden
872 current_view_->newDocument(to_utf8(cmd.argument()), false);
873 current_view_->show();
874 setActiveWindow(current_view_);
876 current_view_->newDocument(to_utf8(cmd.argument()), false);
880 case LFUN_BUFFER_NEW_TEMPLATE:
881 if (d->views_.empty()
882 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
884 current_view_->newDocument(to_utf8(cmd.argument()), true);
885 if (!current_view_->buffer())
886 current_view_->close();
888 current_view_->newDocument(to_utf8(cmd.argument()), true);
893 if (d->views_.empty()
894 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
895 string const fname = to_utf8(cmd.argument());
896 // We want the ui session to be saved per document and not per
897 // window number. The filename crc is a good enough identifier.
898 boost::crc_32_type crc;
899 crc = for_each(fname.begin(), fname.end(), crc);
900 createView(crc.checksum());
901 current_view_->openDocument(fname);
902 if (current_view_ && !current_view_->buffer())
903 current_view_->close();
905 current_view_->openDocument(to_utf8(cmd.argument()));
908 case LFUN_SET_COLOR: {
910 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
911 if (lyx_name.empty() || x11_name.empty()) {
912 current_view_->message(
913 _("Syntax: set-color <lyx_name> <x11_name>"));
917 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
918 bool const graphicsbg_changed = lyx_name == graphicsbg
919 && x11_name != graphicsbg;
920 if (graphicsbg_changed) {
921 // FIXME: The graphics cache no longer has a changeDisplay method.
923 graphics::GCache::get().changeDisplay(true);
927 if (!lcolor.setColor(lyx_name, x11_name)) {
928 current_view_->message(
929 bformat(_("Set-color \"%1$s\" failed "
930 "- color is undefined or "
931 "may not be redefined"),
932 from_utf8(lyx_name)));
935 // Make sure we don't keep old colors in cache.
936 d->color_cache_.clear();
941 // Notify the caller that the action has not been dispatched.
945 // The action has been dispatched.
950 void GuiApplication::dispatchDelayed(FuncRequest const & func)
952 d->func_request_queue_.push(func);
953 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
957 void GuiApplication::resetGui()
959 // Set the language defined by the user.
963 if (!readUIFile(toqstr(lyxrc.ui_file)))
964 // Gives some error box here.
967 if (d->global_menubar_)
968 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
970 QHash<int, GuiView *>::iterator it;
971 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
973 gv->setLayoutDirection(layoutDirection());
977 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
981 void GuiApplication::createView(int view_id)
983 createView(QString(), true, view_id);
987 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
990 // release the keyboard which might have been grabed by the global
991 // menubar on Mac to catch shortcuts even without any GuiView.
992 if (d->global_menubar_)
993 d->global_menubar_->releaseKeyboard();
998 while (d->views_.find(id) != d->views_.end())
1001 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1002 GuiView * view = new GuiView(id);
1004 d->views_[id] = view;
1008 setActiveWindow(view);
1011 if (!geometry_arg.isEmpty()) {
1015 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1016 re.indexIn(geometry_arg);
1017 w = re.cap(1).toInt();
1018 h = re.cap(2).toInt();
1019 x = re.cap(3).toInt();
1020 y = re.cap(4).toInt();
1021 view->setGeometry(x, y, w, h);
1028 Clipboard & GuiApplication::clipboard()
1030 return d->clipboard_;
1034 Selection & GuiApplication::selection()
1036 return d->selection_;
1040 FontLoader & GuiApplication::fontLoader()
1042 return d->font_loader_;
1046 Toolbars const & GuiApplication::toolbars() const
1048 return d->toolbars_;
1052 Toolbars & GuiApplication::toolbars()
1054 return d->toolbars_;
1058 Menus const & GuiApplication::menus() const
1064 Menus & GuiApplication::menus()
1070 QList<int> GuiApplication::viewIds() const
1072 return d->views_.keys();
1076 ColorCache & GuiApplication::colorCache()
1078 return d->color_cache_;
1082 int GuiApplication::exec()
1084 // asynchronously handle batch commands. This event will be in
1085 // the event queue in front of other asynchronous events. Hence,
1086 // we can assume in the latter that the gui is setup already.
1087 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1089 return QApplication::exec();
1093 void GuiApplication::exit(int status)
1095 QApplication::exit(status);
1099 void GuiApplication::setGuiLanguage()
1101 // Set the language defined by the user.
1104 QString const default_language = toqstr(Messages::defaultLanguage());
1105 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1106 QLocale const default_locale(default_language);
1107 QLocale::setDefault(default_locale);
1109 // install translation file for Qt built-in dialogs
1110 QString const language_name = QString("qt_") + default_locale.name();
1112 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1113 // Short-named translator can be loaded from a long name, but not the
1114 // opposite. Therefore, long name should be used without truncation.
1115 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1116 if (!d->qt_trans_.load(language_name,
1117 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1118 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1121 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1125 switch (default_locale.language()) {
1126 case QLocale::Arabic :
1127 case QLocale::Hebrew :
1128 case QLocale::Persian :
1129 case QLocale::Urdu :
1130 setLayoutDirection(Qt::RightToLeft);
1133 setLayoutDirection(Qt::LeftToRight);
1138 void GuiApplication::processFuncRequestQueue()
1140 while (!d->func_request_queue_.empty()) {
1141 lyx::dispatch(d->func_request_queue_.back());
1142 d->func_request_queue_.pop();
1147 void GuiApplication::execBatchCommands()
1152 if (!readUIFile(toqstr(lyxrc.ui_file)))
1153 // Gives some error box here.
1157 // Create the global default menubar which is shown for the dialogs
1158 // and if no GuiView is visible.
1159 // This must be done after the session was recovered to know the "last files".
1160 d->global_menubar_ = new GlobalMenuBar();
1161 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1164 lyx::execBatchCommands();
1168 QAbstractItemModel * GuiApplication::languageModel()
1170 if (d->language_model_)
1171 return d->language_model_;
1173 QStandardItemModel * lang_model = new QStandardItemModel(this);
1174 lang_model->insertColumns(0, 1);
1176 Languages::const_iterator it = languages.begin();
1177 Languages::const_iterator end = languages.end();
1178 for (; it != end; ++it) {
1179 current_row = lang_model->rowCount();
1180 lang_model->insertRows(current_row, 1);
1181 QModelIndex item = lang_model->index(current_row, 0);
1182 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1183 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1185 d->language_model_ = new QSortFilterProxyModel(this);
1186 d->language_model_->setSourceModel(lang_model);
1187 #if QT_VERSION >= 0x040300
1188 d->language_model_->setSortLocaleAware(true);
1190 return d->language_model_;
1194 void GuiApplication::restoreGuiSession()
1196 if (!lyxrc.load_session)
1199 Session & session = theSession();
1200 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1201 // do not add to the lastfile list since these files are restored from
1202 // last session, and should be already there (regular files), or should
1203 // not be added at all (help files).
1204 for_each(lastopened.begin(), lastopened.end(),
1205 bind(&GuiView::loadDocument, current_view_, _1, false));
1207 // clear this list to save a few bytes of RAM
1208 session.lastOpened().clear();
1212 QString const GuiApplication::romanFontName()
1215 font.setKerning(false);
1216 font.setStyleHint(QFont::Serif);
1217 font.setFamily("serif");
1219 return QFontInfo(font).family();
1223 QString const GuiApplication::sansFontName()
1226 font.setKerning(false);
1227 font.setStyleHint(QFont::SansSerif);
1228 font.setFamily("sans");
1230 return QFontInfo(font).family();
1234 QString const GuiApplication::typewriterFontName()
1237 font.setKerning(false);
1238 font.setStyleHint(QFont::TypeWriter);
1239 font.setFamily("monospace");
1241 return QFontInfo(font).family();
1245 void GuiApplication::handleRegularEvents()
1247 ForkedCallsController::handleCompletedProcesses();
1251 bool GuiApplication::event(QEvent * e)
1254 case QEvent::FileOpen: {
1255 // Open a file; this happens only on Mac OS X for now.
1257 // We do this asynchronously because on startup the batch
1258 // commands are not executed here yet and the gui is not ready
1260 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1261 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1266 return QApplication::event(e);
1271 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1274 return QApplication::notify(receiver, event);
1276 catch (ExceptionMessage const & e) {
1278 case ErrorException:
1280 setQuitOnLastWindowClosed(false);
1282 Alert::error(e.title_, e.details_);
1284 // Properly crash in debug mode in order to get a useful backtrace.
1287 // In release mode, try to exit gracefully.
1290 case BufferException: {
1291 Buffer * buf = current_view_->buffer();
1292 docstring details = e.details_ + '\n';
1293 details += theBufferList().emergencyWrite(buf);
1294 theBufferList().release(buf);
1295 details += "\n" + _("The current document was closed.");
1296 Alert::error(e.title_, details);
1299 case WarningException:
1300 Alert::warning(e.title_, e.details_);
1304 catch (exception const & e) {
1305 docstring s = _("LyX has caught an exception, it will now "
1306 "attempt to save all unsaved documents and exit."
1308 s += from_ascii(e.what());
1309 Alert::error(_("Software exception Detected"), s);
1313 docstring s = _("LyX has caught some really weird exception, it will "
1314 "now attempt to save all unsaved documents and exit.");
1315 Alert::error(_("Software exception Detected"), s);
1323 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1325 QColor const & qcol = d->color_cache_.get(col);
1326 if (!qcol.isValid()) {
1332 rgbcol.r = qcol.red();
1333 rgbcol.g = qcol.green();
1334 rgbcol.b = qcol.blue();
1339 string const GuiApplication::hexName(ColorCode col)
1341 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1345 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1347 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1348 d->socket_notifiers_[fd] = sn;
1349 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1353 void GuiApplication::socketDataReceived(int fd)
1355 d->socket_notifiers_[fd]->func_();
1359 void GuiApplication::unregisterSocketCallback(int fd)
1361 d->socket_notifiers_.take(fd)->setEnabled(false);
1365 void GuiApplication::commitData(QSessionManager & sm)
1367 /// The implementation is required to avoid an application exit
1368 /// when session state save is triggered by session manager.
1369 /// The default implementation sends a close event to all
1370 /// visible top level widgets when session managment allows
1372 /// We are changing that to close all wiew one by one.
1373 /// FIXME: verify if the default implementation is enough now.
1374 if (sm.allowsInteraction() && !closeAllViews())
1379 void GuiApplication::unregisterView(GuiView * gv)
1381 LASSERT(d->views_[gv->id()] == gv, /**/);
1382 d->views_.remove(gv->id());
1383 if (current_view_ == gv) {
1385 theLyXFunc().setLyXView(0);
1390 bool GuiApplication::closeAllViews()
1392 if (d->views_.empty())
1395 QList<GuiView *> views = d->views_.values();
1396 foreach (GuiView * view, views) {
1406 GuiView & GuiApplication::view(int id) const
1408 LASSERT(d->views_.contains(id), /**/);
1409 return *d->views_.value(id);
1413 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1415 QList<GuiView *> views = d->views_.values();
1416 foreach (GuiView * view, views)
1417 view->hideDialog(name, inset);
1421 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1423 Buffer const * buffer_ = 0;
1424 QHash<int, GuiView *>::iterator end = d->views_.end();
1425 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1426 if (Buffer const * ptr = (*it)->updateInset(inset))
1433 bool GuiApplication::searchMenu(FuncRequest const & func,
1434 docstring_list & names) const
1436 return d->menus_.searchMenu(func, names);
1440 bool GuiApplication::readUIFile(QString const & name, bool include)
1450 LexerKeyword uitags[] = {
1451 { "include", ui_include },
1452 { "menuset", ui_menuset },
1453 { "toolbars", ui_toolbars },
1454 { "toolbarset", ui_toolbarset }
1457 LYXERR(Debug::INIT, "About to read " << name << "...");
1461 ui_path = libFileSearch("ui", name, "inc");
1462 if (ui_path.empty())
1463 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1465 ui_path = libFileSearch("ui", name, "ui");
1468 if (ui_path.empty()) {
1469 LYXERR(Debug::INIT, "Could not find " << name);
1470 Alert::warning(_("Could not find UI definition file"),
1471 bformat(_("Error while reading the configuration file\n%1$s.\n"
1472 "Please check your installation."), qstring_to_ucs4(name)));
1477 // Ensure that a file is read only once (prevents include loops)
1478 static QStringList uifiles;
1479 QString const uifile = toqstr(ui_path.absFilename());
1480 if (uifiles.contains(uifile)) {
1482 // We are reading again the top uifile so reset the safeguard:
1485 d->toolbars_.reset();
1487 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1488 << "Is this an include loop?");
1492 uifiles.push_back(uifile);
1494 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1497 lex.setFile(ui_path);
1499 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1503 if (lyxerr.debugging(Debug::PARSER))
1504 lex.printTable(lyxerr);
1506 while (lex.isOK()) {
1507 switch (lex.lex()) {
1510 QString const file = toqstr(lex.getString());
1511 if (!readUIFile(file, true))
1516 d->menus_.read(lex);
1520 d->toolbars_.readToolbars(lex);
1524 d->toolbars_.readToolbarSettings(lex);
1528 if (!rtrim(lex.getString()).empty())
1529 lex.printError("LyX::ReadUIFile: "
1530 "Unknown menu tag: `$$Token'");
1539 settings.beginGroup("ui_files");
1540 bool touched = false;
1541 for (int i = 0; i != uifiles.size(); ++i) {
1542 QFileInfo fi(uifiles[i]);
1543 QDateTime const date_value = fi.lastModified();
1544 QString const name_key = QString::number(i);
1545 if (!settings.contains(name_key)
1546 || settings.value(name_key).toString() != uifiles[i]
1547 || settings.value(name_key + "/date").toDateTime() != date_value) {
1549 settings.setValue(name_key, uifiles[i]);
1550 settings.setValue(name_key + "/date", date_value);
1553 settings.endGroup();
1555 settings.remove("views");
1561 void GuiApplication::onLastWindowClosed()
1563 if (d->global_menubar_)
1564 d->global_menubar_->grabKeyboard();
1568 ////////////////////////////////////////////////////////////////////////
1570 // X11 specific stuff goes here...
1573 bool GuiApplication::x11EventFilter(XEvent * xev)
1578 switch (xev->type) {
1579 case SelectionRequest: {
1580 if (xev->xselectionrequest.selection != XA_PRIMARY)
1582 LYXERR(Debug::SELECTION, "X requested selection.");
1583 BufferView * bv = current_view_->view();
1585 docstring const sel = bv->requestSelection();
1587 d->selection_.put(sel);
1591 case SelectionClear: {
1592 if (xev->xselectionclear.selection != XA_PRIMARY)
1594 LYXERR(Debug::SELECTION, "Lost selection.");
1595 BufferView * bv = current_view_->view();
1597 bv->clearSelection();
1605 } // namespace frontend
1608 void hideDialogs(std::string const & name, Inset * inset)
1611 theApp()->hideDialogs(name, inset);
1615 ////////////////////////////////////////////////////////////////////
1619 ////////////////////////////////////////////////////////////////////
1621 frontend::FontLoader & theFontLoader()
1623 LASSERT(frontend::guiApp, /**/);
1624 return frontend::guiApp->fontLoader();
1628 frontend::FontMetrics const & theFontMetrics(Font const & f)
1630 return theFontMetrics(f.fontInfo());
1634 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1636 LASSERT(frontend::guiApp, /**/);
1637 return frontend::guiApp->fontLoader().metrics(f);
1641 ////////////////////////////////////////////////////////////////////
1645 ////////////////////////////////////////////////////////////////////
1647 frontend::Clipboard & theClipboard()
1649 LASSERT(frontend::guiApp, /**/);
1650 return frontend::guiApp->clipboard();
1654 frontend::Selection & theSelection()
1656 LASSERT(frontend::guiApp, /**/);
1657 return frontend::guiApp->selection();
1663 #include "moc_GuiApplication.cpp"