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(QString("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 /// WMF Mime handler for Windows clipboard.
650 wmf_mime_ = new QWindowsMimeMetafile();
655 QSortFilterProxyModel * language_model_;
657 GuiClipboard clipboard_;
659 GuiSelection selection_;
661 FontLoader font_loader_;
663 ColorCache color_cache_;
665 QTranslator qt_trans_;
667 QHash<int, SocketNotifier *> socket_notifiers_;
671 /// The global instance
674 /// this timer is used for any regular events one wants to
675 /// perform. at present it is used to check if forked processes
677 QTimer general_timer_;
679 /// delayed FuncRequests
680 std::queue<FuncRequest> func_request_queue_;
682 /// Multiple views container.
684 * Warning: This must not be a smart pointer as the destruction of the
685 * object is handled by Qt when the view is closed
686 * \sa Qt::WA_DeleteOnClose attribute.
688 QHash<int, GuiView *> views_;
690 /// Only used on mac.
691 GlobalMenuBar * global_menubar_;
694 /// Linkback mime handler for MacOSX.
695 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
699 /// WMF Mime handler for Windows clipboard.
700 QWindowsMimeMetafile * wmf_mime_;
705 GuiApplication * guiApp;
707 GuiApplication::~GuiApplication()
710 closeAllLinkBackLinks();
716 GuiApplication::GuiApplication(int & argc, char ** argv)
717 : QApplication(argc, argv), current_view_(0),
718 d(new GuiApplication::Private)
720 QString app_name = "LyX";
721 QCoreApplication::setOrganizationName(app_name);
722 QCoreApplication::setOrganizationDomain("lyx.org");
723 QCoreApplication::setApplicationName(lyx_package);
725 // Install translator for GUI elements.
726 installTranslator(&d->qt_trans_);
728 // FIXME: quitOnLastWindowClosed is true by default. We should have a
729 // lyxrc setting for this in order to let the application stay resident.
730 // But then we need some kind of dock icon, at least on Windows.
732 if (lyxrc.quit_on_last_window_closed)
733 setQuitOnLastWindowClosed(false);
736 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
737 // seems to be the default case for applications like LyX.
738 setQuitOnLastWindowClosed(false);
740 // This allows to translate the strings that appear in the LyX menu.
741 /// A translator suitable for the entries in the LyX menu.
742 /// Only needed with Qt/Mac.
743 installTranslator(new MenuTranslator(this));
747 // doubleClickInterval() is 400 ms on X11 which is just too long.
748 // On Windows and Mac OS X, the operating system's value is used.
749 // On Microsoft Windows, calling this function sets the double
750 // click interval for all applications. So we don't!
751 QApplication::setDoubleClickInterval(300);
754 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
756 // needs to be done before reading lyxrc
758 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
762 // Set the cache to 5120 kilobytes which corresponds to screen size of
763 // 1280 by 1024 pixels with a color depth of 32 bits.
764 QPixmapCache::setCacheLimit(5120);
766 // Initialize RC Fonts
767 if (lyxrc.roman_font_name.empty())
768 lyxrc.roman_font_name = fromqstr(romanFontName());
770 if (lyxrc.sans_font_name.empty())
771 lyxrc.sans_font_name = fromqstr(sansFontName());
773 if (lyxrc.typewriter_font_name.empty())
774 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
776 d->general_timer_.setInterval(500);
777 connect(&d->general_timer_, SIGNAL(timeout()),
778 this, SLOT(handleRegularEvents()));
779 d->general_timer_.start();
783 GuiApplication * theGuiApp()
785 return dynamic_cast<GuiApplication *>(theApp());
789 void GuiApplication::clearSession()
796 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
798 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
803 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
809 case LFUN_WINDOW_CLOSE:
810 enable = d->views_.size() > 0;
813 case LFUN_BUFFER_NEW:
814 case LFUN_BUFFER_NEW_TEMPLATE:
816 case LFUN_SCREEN_FONT_UPDATE:
818 case LFUN_WINDOW_NEW:
828 flag.setEnabled(false);
834 bool GuiApplication::dispatch(FuncRequest const & cmd)
836 switch (cmd.action) {
838 case LFUN_WINDOW_NEW:
839 createView(toqstr(cmd.argument()));
842 case LFUN_WINDOW_CLOSE:
843 // update bookmark pit of the current buffer before window close
844 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
845 theLyXFunc().gotoBookmark(i+1, false, false);
846 // clear the last opened list, because
847 // maybe this will end the session
848 theSession().lastOpened().clear();
849 current_view_->close();
853 // quitting is triggered by the gui code
854 // (leaving the event loop).
856 current_view_->message(from_utf8(N_("Exiting.")));
861 case LFUN_SCREEN_FONT_UPDATE: {
862 // handle the screen font changes.
863 d->font_loader_.update();
864 // Backup current_view_
865 GuiView * view = current_view_;
866 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
867 // to skip the refresh.
869 BufferList::iterator it = theBufferList().begin();
870 BufferList::iterator const end = theBufferList().end();
871 for (; it != end; ++it)
873 // Restore current_view_
874 current_view_ = view;
878 case LFUN_BUFFER_NEW:
879 if (d->views_.empty()
880 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
881 createView(QString(), false); // keep hidden
882 current_view_->newDocument(to_utf8(cmd.argument()), false);
883 current_view_->show();
884 setActiveWindow(current_view_);
886 current_view_->newDocument(to_utf8(cmd.argument()), false);
890 case LFUN_BUFFER_NEW_TEMPLATE:
891 if (d->views_.empty()
892 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
894 current_view_->newDocument(to_utf8(cmd.argument()), true);
895 if (!current_view_->documentBufferView())
896 current_view_->close();
898 current_view_->newDocument(to_utf8(cmd.argument()), true);
903 if (d->views_.empty()
904 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
905 string const fname = to_utf8(cmd.argument());
906 // We want the ui session to be saved per document and not per
907 // window number. The filename crc is a good enough identifier.
908 boost::crc_32_type crc;
909 crc = for_each(fname.begin(), fname.end(), crc);
910 createView(crc.checksum());
911 current_view_->openDocument(fname);
912 if (current_view_ && !current_view_->documentBufferView())
913 current_view_->close();
915 current_view_->openDocument(to_utf8(cmd.argument()));
918 case LFUN_SET_COLOR: {
920 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
921 if (lyx_name.empty() || x11_name.empty()) {
922 current_view_->message(
923 _("Syntax: set-color <lyx_name> <x11_name>"));
927 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
928 bool const graphicsbg_changed = lyx_name == graphicsbg
929 && x11_name != graphicsbg;
930 if (graphicsbg_changed) {
931 // FIXME: The graphics cache no longer has a changeDisplay method.
933 graphics::GCache::get().changeDisplay(true);
937 if (!lcolor.setColor(lyx_name, x11_name)) {
938 current_view_->message(
939 bformat(_("Set-color \"%1$s\" failed "
940 "- color is undefined or "
941 "may not be redefined"),
942 from_utf8(lyx_name)));
945 // Make sure we don't keep old colors in cache.
946 d->color_cache_.clear();
951 // Notify the caller that the action has not been dispatched.
955 // The action has been dispatched.
960 void GuiApplication::dispatchDelayed(FuncRequest const & func)
962 d->func_request_queue_.push(func);
963 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
967 void GuiApplication::resetGui()
969 // Set the language defined by the user.
973 if (!readUIFile(toqstr(lyxrc.ui_file)))
974 // Gives some error box here.
977 if (d->global_menubar_)
978 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
980 QHash<int, GuiView *>::iterator it;
981 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
983 gv->setLayoutDirection(layoutDirection());
987 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
991 void GuiApplication::createView(int view_id)
993 createView(QString(), true, view_id);
997 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1000 // release the keyboard which might have been grabed by the global
1001 // menubar on Mac to catch shortcuts even without any GuiView.
1002 if (d->global_menubar_)
1003 d->global_menubar_->releaseKeyboard();
1007 while (d->views_.find(id) != d->views_.end())
1010 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1011 GuiView * view = new GuiView(id);
1013 d->views_[id] = view;
1017 setActiveWindow(view);
1020 if (!geometry_arg.isEmpty()) {
1024 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1025 re.indexIn(geometry_arg);
1026 w = re.cap(1).toInt();
1027 h = re.cap(2).toInt();
1028 x = re.cap(3).toInt();
1029 y = re.cap(4).toInt();
1030 view->setGeometry(x, y, w, h);
1037 Clipboard & GuiApplication::clipboard()
1039 return d->clipboard_;
1043 Selection & GuiApplication::selection()
1045 return d->selection_;
1049 FontLoader & GuiApplication::fontLoader()
1051 return d->font_loader_;
1055 Toolbars const & GuiApplication::toolbars() const
1057 return d->toolbars_;
1061 Toolbars & GuiApplication::toolbars()
1063 return d->toolbars_;
1067 Menus const & GuiApplication::menus() const
1073 Menus & GuiApplication::menus()
1079 QList<int> GuiApplication::viewIds() const
1081 return d->views_.keys();
1085 ColorCache & GuiApplication::colorCache()
1087 return d->color_cache_;
1091 int GuiApplication::exec()
1093 // asynchronously handle batch commands. This event will be in
1094 // the event queue in front of other asynchronous events. Hence,
1095 // we can assume in the latter that the gui is setup already.
1096 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1098 return QApplication::exec();
1102 void GuiApplication::exit(int status)
1104 QApplication::exit(status);
1108 void GuiApplication::setGuiLanguage()
1110 // Set the language defined by the user.
1113 QString const default_language = toqstr(Messages::defaultLanguage());
1114 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1115 QLocale const default_locale(default_language);
1116 QLocale::setDefault(default_locale);
1118 // install translation file for Qt built-in dialogs
1119 QString const language_name = QString("qt_") + default_locale.name();
1121 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1122 // Short-named translator can be loaded from a long name, but not the
1123 // opposite. Therefore, long name should be used without truncation.
1124 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1125 if (!d->qt_trans_.load(language_name,
1126 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1127 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1130 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1134 switch (default_locale.language()) {
1135 case QLocale::Arabic :
1136 case QLocale::Hebrew :
1137 case QLocale::Persian :
1138 case QLocale::Urdu :
1139 setLayoutDirection(Qt::RightToLeft);
1142 setLayoutDirection(Qt::LeftToRight);
1147 void GuiApplication::processFuncRequestQueue()
1149 while (!d->func_request_queue_.empty()) {
1150 lyx::dispatch(d->func_request_queue_.back());
1151 d->func_request_queue_.pop();
1156 void GuiApplication::execBatchCommands()
1161 if (!readUIFile(toqstr(lyxrc.ui_file)))
1162 // Gives some error box here.
1166 // Create the global default menubar which is shown for the dialogs
1167 // and if no GuiView is visible.
1168 // This must be done after the session was recovered to know the "last files".
1169 d->global_menubar_ = new GlobalMenuBar();
1170 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1173 lyx::execBatchCommands();
1177 QAbstractItemModel * GuiApplication::languageModel()
1179 if (d->language_model_)
1180 return d->language_model_;
1182 QStandardItemModel * lang_model = new QStandardItemModel(this);
1183 lang_model->insertColumns(0, 1);
1185 Languages::const_iterator it = languages.begin();
1186 Languages::const_iterator end = languages.end();
1187 for (; it != end; ++it) {
1188 current_row = lang_model->rowCount();
1189 lang_model->insertRows(current_row, 1);
1190 QModelIndex item = lang_model->index(current_row, 0);
1191 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1192 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1194 d->language_model_ = new QSortFilterProxyModel(this);
1195 d->language_model_->setSourceModel(lang_model);
1196 #if QT_VERSION >= 0x040300
1197 d->language_model_->setSortLocaleAware(true);
1199 return d->language_model_;
1203 void GuiApplication::restoreGuiSession()
1205 if (!lyxrc.load_session)
1208 Session & session = theSession();
1209 LastOpenedSection::LastOpened const & lastopened =
1210 session.lastOpened().getfiles();
1212 FileName active_file;
1213 // do not add to the lastfile list since these files are restored from
1214 // last session, and should be already there (regular files), or should
1215 // not be added at all (help files).
1216 for (size_t i = 0; i < lastopened.size(); ++i) {
1217 FileName const & file_name = lastopened[i].file_name;
1218 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1219 && current_view_->documentBufferView() != 0)) {
1220 boost::crc_32_type crc;
1221 string const & fname = file_name.absFilename();
1222 crc = for_each(fname.begin(), fname.end(), crc);
1223 createView(crc.checksum());
1225 current_view_->loadDocument(file_name, false);
1227 if (lastopened[i].active)
1228 active_file = file_name;
1231 // Restore last active buffer
1232 Buffer * buffer = theBufferList().getBuffer(active_file);
1234 current_view_->setBuffer(buffer);
1236 // clear this list to save a few bytes of RAM
1237 session.lastOpened().clear();
1241 QString const GuiApplication::romanFontName()
1244 font.setKerning(false);
1245 font.setStyleHint(QFont::Serif);
1246 font.setFamily("serif");
1248 return QFontInfo(font).family();
1252 QString const GuiApplication::sansFontName()
1255 font.setKerning(false);
1256 font.setStyleHint(QFont::SansSerif);
1257 font.setFamily("sans");
1259 return QFontInfo(font).family();
1263 QString const GuiApplication::typewriterFontName()
1266 font.setKerning(false);
1267 font.setStyleHint(QFont::TypeWriter);
1268 font.setFamily("monospace");
1270 return QFontInfo(font).family();
1274 void GuiApplication::handleRegularEvents()
1276 ForkedCallsController::handleCompletedProcesses();
1280 bool GuiApplication::event(QEvent * e)
1283 case QEvent::FileOpen: {
1284 // Open a file; this happens only on Mac OS X for now.
1286 // We do this asynchronously because on startup the batch
1287 // commands are not executed here yet and the gui is not ready
1289 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1290 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1295 return QApplication::event(e);
1300 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1303 return QApplication::notify(receiver, event);
1305 catch (ExceptionMessage const & e) {
1307 case ErrorException:
1309 setQuitOnLastWindowClosed(false);
1311 Alert::error(e.title_, e.details_);
1313 // Properly crash in debug mode in order to get a useful backtrace.
1316 // In release mode, try to exit gracefully.
1319 case BufferException: {
1320 if (!current_view_->documentBufferView())
1322 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
1323 docstring details = e.details_ + '\n';
1324 details += buf->emergencyWrite();
1325 theBufferList().release(buf);
1326 details += "\n" + _("The current document was closed.");
1327 Alert::error(e.title_, details);
1330 case WarningException:
1331 Alert::warning(e.title_, e.details_);
1335 catch (exception const & e) {
1336 docstring s = _("LyX has caught an exception, it will now "
1337 "attempt to save all unsaved documents and exit."
1339 s += from_ascii(e.what());
1340 Alert::error(_("Software exception Detected"), s);
1344 docstring s = _("LyX has caught some really weird exception, it will "
1345 "now attempt to save all unsaved documents and exit.");
1346 Alert::error(_("Software exception Detected"), s);
1354 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1356 QColor const & qcol = d->color_cache_.get(col);
1357 if (!qcol.isValid()) {
1363 rgbcol.r = qcol.red();
1364 rgbcol.g = qcol.green();
1365 rgbcol.b = qcol.blue();
1370 string const GuiApplication::hexName(ColorCode col)
1372 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1376 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1378 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1379 d->socket_notifiers_[fd] = sn;
1380 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1384 void GuiApplication::socketDataReceived(int fd)
1386 d->socket_notifiers_[fd]->func_();
1390 void GuiApplication::unregisterSocketCallback(int fd)
1392 d->socket_notifiers_.take(fd)->setEnabled(false);
1396 void GuiApplication::commitData(QSessionManager & sm)
1398 /// The implementation is required to avoid an application exit
1399 /// when session state save is triggered by session manager.
1400 /// The default implementation sends a close event to all
1401 /// visible top level widgets when session managment allows
1403 /// We are changing that to close all wiew one by one.
1404 /// FIXME: verify if the default implementation is enough now.
1405 if (sm.allowsInteraction() && !closeAllViews())
1410 void GuiApplication::unregisterView(GuiView * gv)
1412 LASSERT(d->views_[gv->id()] == gv, /**/);
1413 d->views_.remove(gv->id());
1414 if (current_view_ == gv) {
1416 theLyXFunc().setLyXView(0);
1421 bool GuiApplication::closeAllViews()
1423 if (d->views_.empty())
1426 // When a view/window was closed before without quitting LyX, there
1427 // are already entries in the lastOpened list.
1428 theSession().lastOpened().clear();
1430 QList<GuiView *> views = d->views_.values();
1431 foreach (GuiView * view, views) {
1441 GuiView & GuiApplication::view(int id) const
1443 LASSERT(d->views_.contains(id), /**/);
1444 return *d->views_.value(id);
1448 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1450 QList<GuiView *> views = d->views_.values();
1451 foreach (GuiView * view, views)
1452 view->hideDialog(name, inset);
1456 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1458 Buffer const * buffer_ = 0;
1459 QHash<int, GuiView *>::iterator end = d->views_.end();
1460 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1461 if (Buffer const * ptr = (*it)->updateInset(inset))
1468 bool GuiApplication::searchMenu(FuncRequest const & func,
1469 docstring_list & names) const
1471 return d->menus_.searchMenu(func, names);
1475 bool GuiApplication::readUIFile(QString const & name, bool include)
1477 LYXERR(Debug::INIT, "About to read " << name << "...");
1481 ui_path = libFileSearch("ui", name, "inc");
1482 if (ui_path.empty())
1483 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1485 ui_path = libFileSearch("ui", name, "ui");
1488 if (ui_path.empty()) {
1489 static const QString defaultUIFile = "default";
1490 LYXERR(Debug::INIT, "Could not find " << name);
1492 Alert::warning(_("Could not find UI definition file"),
1493 bformat(_("Error while reading the included file\n%1$s\n"
1494 "Please check your installation."), qstring_to_ucs4(name)));
1497 if (name == defaultUIFile) {
1498 LYXERR(Debug::INIT, "Could not find default UI file!!");
1499 Alert::warning(_("Could not find default UI file"),
1500 _("LyX could not find the default UI file!\n"
1501 "Please check your installation."));
1504 Alert::warning(_("Could not find UI definition file"),
1505 bformat(_("Error while reading the configuration file\n%1$s\n"
1506 "Falling back to default.\n"
1507 "Please look under Tools>Preferences>User Interface and\n"
1508 "check which User Interface file you are using."), qstring_to_ucs4(name)));
1509 return readUIFile(defaultUIFile, false);
1512 // Ensure that a file is read only once (prevents include loops)
1513 static QStringList uifiles;
1514 QString const uifile = toqstr(ui_path.absFilename());
1515 if (uifiles.contains(uifile)) {
1517 // We are reading again the top uifile so reset the safeguard:
1520 d->toolbars_.reset();
1522 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1523 << "Is this an include loop?");
1527 uifiles.push_back(uifile);
1529 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1539 LexerKeyword uitags[] = {
1540 { "include", ui_include },
1541 { "menuset", ui_menuset },
1542 { "toolbars", ui_toolbars },
1543 { "toolbarset", ui_toolbarset }
1547 lex.setFile(ui_path);
1549 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1553 if (lyxerr.debugging(Debug::PARSER))
1554 lex.printTable(lyxerr);
1556 // store which ui files define Toolbars
1557 static QStringList toolbar_uifiles;
1559 while (lex.isOK()) {
1560 switch (lex.lex()) {
1563 QString const file = toqstr(lex.getString());
1564 if (!readUIFile(file, true))
1569 d->menus_.read(lex);
1573 d->toolbars_.readToolbars(lex);
1577 d->toolbars_.readToolbarSettings(lex);
1578 toolbar_uifiles.push_back(uifile);
1582 if (!rtrim(lex.getString()).empty())
1583 lex.printError("LyX::ReadUIFile: "
1584 "Unknown menu tag: `$$Token'");
1593 settings.beginGroup("ui_files");
1594 bool touched = false;
1595 for (int i = 0; i != uifiles.size(); ++i) {
1596 QFileInfo fi(uifiles[i]);
1597 QDateTime const date_value = fi.lastModified();
1598 QString const name_key = QString::number(i);
1599 // if an ui file which defines Toolbars has changed,
1600 // we have to reset the settings
1601 if (toolbar_uifiles.contains(uifiles[i])
1602 && (!settings.contains(name_key)
1603 || settings.value(name_key).toString() != uifiles[i]
1604 || settings.value(name_key + "/date").toDateTime() != date_value)) {
1606 settings.setValue(name_key, uifiles[i]);
1607 settings.setValue(name_key + "/date", date_value);
1610 settings.endGroup();
1612 settings.remove("views");
1618 void GuiApplication::onLastWindowClosed()
1620 if (d->global_menubar_)
1621 d->global_menubar_->grabKeyboard();
1625 ////////////////////////////////////////////////////////////////////////
1627 // X11 specific stuff goes here...
1630 bool GuiApplication::x11EventFilter(XEvent * xev)
1635 switch (xev->type) {
1636 case SelectionRequest: {
1637 if (xev->xselectionrequest.selection != XA_PRIMARY)
1639 LYXERR(Debug::SELECTION, "X requested selection.");
1640 BufferView * bv = current_view_->currentBufferView();
1642 docstring const sel = bv->requestSelection();
1644 d->selection_.put(sel);
1648 case SelectionClear: {
1649 if (xev->xselectionclear.selection != XA_PRIMARY)
1651 LYXERR(Debug::SELECTION, "Lost selection.");
1652 BufferView * bv = current_view_->currentBufferView();
1654 bv->clearSelection();
1662 } // namespace frontend
1665 void hideDialogs(std::string const & name, Inset * inset)
1668 theApp()->hideDialogs(name, inset);
1672 ////////////////////////////////////////////////////////////////////
1676 ////////////////////////////////////////////////////////////////////
1678 frontend::FontLoader & theFontLoader()
1680 LASSERT(frontend::guiApp, /**/);
1681 return frontend::guiApp->fontLoader();
1685 frontend::FontMetrics const & theFontMetrics(Font const & f)
1687 return theFontMetrics(f.fontInfo());
1691 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1693 LASSERT(frontend::guiApp, /**/);
1694 return frontend::guiApp->fontLoader().metrics(f);
1698 ////////////////////////////////////////////////////////////////////
1702 ////////////////////////////////////////////////////////////////////
1704 frontend::Clipboard & theClipboard()
1706 LASSERT(frontend::guiApp, /**/);
1707 return frontend::guiApp->clipboard();
1711 frontend::Selection & theSelection()
1713 LASSERT(frontend::guiApp, /**/);
1714 return frontend::guiApp->selection();
1720 #include "moc_GuiApplication.cpp"