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());
316 name2 = toqstr(lyxaction.getActionName(f.action));
319 if (!f.argument().empty()) {
320 name1 = name2 + ' ' + toqstr(f.argument());
321 name1.replace(' ', '_');
325 FileName fname = libFileSearch("images/" + path, name1, "png");
327 return toqstr(fname.absFilename());
329 fname = libFileSearch("images/" + path, name2, "png");
331 return toqstr(fname.absFilename());
333 path = ":/images/" + path;
336 LYXERR0("Directory " << path << " not found in resource!");
340 if (res.exists(name1))
344 if (res.exists(name2))
347 LYXERR(Debug::GUI, "Cannot find icon for command \""
348 << lyxaction.getActionName(f.action)
349 << '(' << to_utf8(f.argument()) << ")\"");
352 return QString(":/images/unknown.png");
358 QIcon getIcon(FuncRequest const & f, bool unknown)
360 QString icon = iconName(f, unknown);
364 //LYXERR(Debug::GUI, "Found icon: " << icon);
366 if (!pm.load(icon)) {
367 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
375 ////////////////////////////////////////////////////////////////////////
377 // LyX server support code.
379 ////////////////////////////////////////////////////////////////////////
381 class SocketNotifier : public QSocketNotifier
384 /// connect a connection notification from the LyXServerSocket
385 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
386 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
390 /// The callback function
391 Application::SocketCallback func_;
395 ////////////////////////////////////////////////////////////////////////
397 // Mac specific stuff goes here...
399 ////////////////////////////////////////////////////////////////////////
401 class MenuTranslator : public QTranslator
404 MenuTranslator(QObject * parent)
405 : QTranslator(parent)
408 QString translate(const char * /*context*/,
409 const char * sourceText,
410 const char * /*comment*/ = 0)
412 string const s = sourceText;
413 if (s == N_("About %1") || s == N_("Preferences")
414 || s == N_("Reconfigure") || s == N_("Quit %1"))
421 class GlobalMenuBar : public QMenuBar
425 GlobalMenuBar() : QMenuBar(0) {}
428 bool event(QEvent * e)
430 if (e->type() == QEvent::ShortcutOverride) {
431 // && activeWindow() == 0) {
432 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
434 setKeySymbol(&sym, ke);
435 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
444 // QMacPasteboardMimeGraphics can only be compiled on Mac.
446 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
449 QMacPasteboardMimeGraphics()
450 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
453 QString convertorName() { return "Graphics"; }
455 QString flavorFor(QString const & mime)
457 LYXERR(Debug::ACTION, "flavorFor " << mime);
458 if (mime == pdfMimeType())
459 return QLatin1String("com.adobe.pdf");
463 QString mimeFor(QString flav)
465 LYXERR(Debug::ACTION, "mimeFor " << flav);
466 if (flav == QLatin1String("com.adobe.pdf"))
467 return pdfMimeType();
471 bool canConvert(QString const & mime, QString flav)
473 return mimeFor(flav) == mime;
476 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
480 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
484 QList<QByteArray> convertFromMime(QString const & /*mime*/,
485 QVariant data, QString /*flav*/)
487 QList<QByteArray> ret;
488 ret.append(data.toByteArray());
494 ///////////////////////////////////////////////////////////////
496 // You can find more platform specific stuff at the end of this file...
498 ///////////////////////////////////////////////////////////////
500 ////////////////////////////////////////////////////////////////////////
501 // Windows specific stuff goes here...
504 // QWindowsMimeMetafile can only be compiled on Windows.
506 static FORMATETC cfFromMime(QString const & mimetype)
509 if (mimetype == emfMimeType()) {
510 formatetc.cfFormat = CF_ENHMETAFILE;
511 formatetc.tymed = TYMED_ENHMF;
512 } else if (mimetype == wmfMimeType()) {
513 formatetc.cfFormat = CF_METAFILEPICT;
514 formatetc.tymed = TYMED_MFPICT;
517 formatetc.dwAspect = DVASPECT_CONTENT;
518 formatetc.lindex = -1;
523 class QWindowsMimeMetafile : public QWindowsMime {
525 QWindowsMimeMetafile() {}
527 bool canConvertFromMime(FORMATETC const & formatetc,
528 QMimeData const * mimedata) const
533 bool canConvertToMime(QString const & mimetype,
534 IDataObject * pDataObj) const
536 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
538 FORMATETC formatetc = cfFromMime(mimetype);
539 return pDataObj->QueryGetData(&formatetc) == S_OK;
542 bool convertFromMime(FORMATETC const & formatetc,
543 const QMimeData * mimedata, STGMEDIUM * pmedium) const
548 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
549 QVariant::Type preferredType) const
552 if (!canConvertToMime(mimetype, pDataObj))
555 FORMATETC formatetc = cfFromMime(mimetype);
557 if (pDataObj->GetData(&formatetc, &s) != S_OK)
561 if (s.tymed == TYMED_ENHMF) {
562 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
563 data.resize(dataSize);
564 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
565 (LPBYTE)data.data());
566 } else if (s.tymed == TYMED_MFPICT) {
567 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
568 data.resize(dataSize);
569 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
570 (LPBYTE)data.data());
573 ReleaseStgMedium(&s);
579 QVector<FORMATETC> formatsForMime(QString const & mimeType,
580 QMimeData const * mimeData) const
582 QVector<FORMATETC> formats;
583 formats += cfFromMime(mimeType);
587 QString mimeForFormat(FORMATETC const & formatetc) const
589 switch (formatetc.cfFormat) {
591 return emfMimeType();
592 case CF_METAFILEPICT:
593 return wmfMimeType();
601 ////////////////////////////////////////////////////////////////////////
602 // GuiApplication::Private definition and implementation.
603 ////////////////////////////////////////////////////////////////////////
605 struct GuiApplication::Private
607 Private(): language_model_(0), global_menubar_(0) {}
610 QSortFilterProxyModel * language_model_;
612 GuiClipboard clipboard_;
614 GuiSelection selection_;
616 FontLoader font_loader_;
618 ColorCache color_cache_;
620 QTranslator qt_trans_;
622 QHash<int, SocketNotifier *> socket_notifiers_;
626 /// The global instance
629 /// this timer is used for any regular events one wants to
630 /// perform. at present it is used to check if forked processes
632 QTimer general_timer_;
634 /// delayed FuncRequests
635 std::queue<FuncRequest> func_request_queue_;
637 /// Multiple views container.
639 * Warning: This must not be a smart pointer as the destruction of the
640 * object is handled by Qt when the view is closed
641 * \sa Qt::WA_DeleteOnClose attribute.
643 QHash<int, GuiView *> views_;
645 /// Only used on mac.
646 GlobalMenuBar * global_menubar_;
649 /// Linkback mime handler for MacOSX.
650 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
654 /// WMF Mime handler for Windows clipboard.
655 /// \warning: see comment in ~GuiApplication and in bug 4846.
656 QWindowsMimeMetafile wmf_mime_;
661 GuiApplication * guiApp;
663 GuiApplication::~GuiApplication()
666 closeAllLinkBackLinks();
668 // FIXME: Work around bug 4846 for Windows Vista and Qt4
669 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
670 // If the clipboard is not cleared, LyX crashes on exit when it is
671 // compiled in release mode and if there is something in the clipboard.
672 // This is related to QWindowsMimeMetafile which is apparently not
673 // properly destroyed.
674 qApp->clipboard()->clear(QClipboard::Clipboard);
679 GuiApplication::GuiApplication(int & argc, char ** argv)
680 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
682 QString app_name = "LyX";
683 QCoreApplication::setOrganizationName(app_name);
684 QCoreApplication::setOrganizationDomain("lyx.org");
685 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
687 // Install translator for GUI elements.
688 installTranslator(&d->qt_trans_);
690 // FIXME: quitOnLastWindowClosed is true by default. We should have a
691 // lyxrc setting for this in order to let the application stay resident.
692 // But then we need some kind of dock icon, at least on Windows.
694 if (lyxrc.quit_on_last_window_closed)
695 setQuitOnLastWindowClosed(false);
698 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
699 // seems to be the default case for applications like LyX.
700 setQuitOnLastWindowClosed(false);
702 // This allows to translate the strings that appear in the LyX menu.
703 /// A translator suitable for the entries in the LyX menu.
704 /// Only needed with Qt/Mac.
705 installTranslator(new MenuTranslator(this));
709 // doubleClickInterval() is 400 ms on X11 which is just too long.
710 // On Windows and Mac OS X, the operating system's value is used.
711 // On Microsoft Windows, calling this function sets the double
712 // click interval for all applications. So we don't!
713 QApplication::setDoubleClickInterval(300);
716 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
718 // needs to be done before reading lyxrc
720 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
724 // Set the cache to 5120 kilobytes which corresponds to screen size of
725 // 1280 by 1024 pixels with a color depth of 32 bits.
726 QPixmapCache::setCacheLimit(5120);
728 // Initialize RC Fonts
729 if (lyxrc.roman_font_name.empty())
730 lyxrc.roman_font_name = fromqstr(romanFontName());
732 if (lyxrc.sans_font_name.empty())
733 lyxrc.sans_font_name = fromqstr(sansFontName());
735 if (lyxrc.typewriter_font_name.empty())
736 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
738 d->general_timer_.setInterval(500);
739 connect(&d->general_timer_, SIGNAL(timeout()),
740 this, SLOT(handleRegularEvents()));
741 d->general_timer_.start();
745 GuiApplication * theGuiApp()
747 return dynamic_cast<GuiApplication *>(theApp());
751 void GuiApplication::clearSession()
758 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
760 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
765 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
771 case LFUN_WINDOW_CLOSE:
772 enable = d->views_.size() > 0;
775 case LFUN_BUFFER_NEW:
776 case LFUN_BUFFER_NEW_TEMPLATE:
778 case LFUN_SCREEN_FONT_UPDATE:
780 case LFUN_WINDOW_NEW:
790 flag.setEnabled(false);
796 bool GuiApplication::dispatch(FuncRequest const & cmd)
798 switch (cmd.action) {
800 case LFUN_WINDOW_NEW:
801 createView(toqstr(cmd.argument()));
804 case LFUN_WINDOW_CLOSE:
805 // update bookmark pit of the current buffer before window close
806 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
807 theLyXFunc().gotoBookmark(i+1, false, false);
808 current_view_->close();
812 // quitting is triggered by the gui code
813 // (leaving the event loop).
815 current_view_->message(from_utf8(N_("Exiting.")));
820 case LFUN_SCREEN_FONT_UPDATE: {
821 // handle the screen font changes.
822 d->font_loader_.update();
823 // Backup current_view_
824 GuiView * view = current_view_;
825 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
826 // to skip the refresh.
828 BufferList::iterator it = theBufferList().begin();
829 BufferList::iterator const end = theBufferList().end();
830 for (; it != end; ++it)
832 // Restore current_view_
833 current_view_ = view;
837 case LFUN_BUFFER_NEW:
838 if (d->views_.empty()
839 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
840 createView(QString(), false); // keep hidden
841 current_view_->newDocument(to_utf8(cmd.argument()), false);
842 current_view_->show();
843 setActiveWindow(current_view_);
845 current_view_->newDocument(to_utf8(cmd.argument()), false);
849 case LFUN_BUFFER_NEW_TEMPLATE:
850 if (d->views_.empty()
851 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
853 current_view_->newDocument(to_utf8(cmd.argument()), true);
854 if (!current_view_->buffer())
855 current_view_->close();
857 current_view_->newDocument(to_utf8(cmd.argument()), true);
862 if (d->views_.empty()
863 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
864 string const fname = to_utf8(cmd.argument());
865 // We want the ui session to be saved per document and not per
866 // window number. The filename crc is a good enough identifier.
867 boost::crc_32_type crc;
868 crc = for_each(fname.begin(), fname.end(), crc);
869 createView(crc.checksum());
870 current_view_->openDocument(fname);
871 if (current_view_ && !current_view_->buffer())
872 current_view_->close();
874 current_view_->openDocument(to_utf8(cmd.argument()));
877 case LFUN_SET_COLOR: {
879 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
880 if (lyx_name.empty() || x11_name.empty()) {
881 current_view_->message(
882 _("Syntax: set-color <lyx_name> <x11_name>"));
886 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
887 bool const graphicsbg_changed = lyx_name == graphicsbg
888 && x11_name != graphicsbg;
889 if (graphicsbg_changed) {
890 // FIXME: The graphics cache no longer has a changeDisplay method.
892 graphics::GCache::get().changeDisplay(true);
896 if (!lcolor.setColor(lyx_name, x11_name)) {
897 current_view_->message(
898 bformat(_("Set-color \"%1$s\" failed "
899 "- color is undefined or "
900 "may not be redefined"),
901 from_utf8(lyx_name)));
904 // Make sure we don't keep old colors in cache.
905 d->color_cache_.clear();
910 // Notify the caller that the action has not been dispatched.
914 // The action has been dispatched.
919 void GuiApplication::dispatchDelayed(FuncRequest const & func)
921 d->func_request_queue_.push(func);
922 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
926 void GuiApplication::resetGui()
928 // Set the language defined by the user.
932 if (!readUIFile(toqstr(lyxrc.ui_file)))
933 // Gives some error box here.
936 if (d->global_menubar_)
937 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
939 QHash<int, GuiView *>::iterator it;
940 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
942 gv->setLayoutDirection(layoutDirection());
946 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
950 void GuiApplication::createView(int view_id)
952 createView(QString(), true, view_id);
956 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
959 // release the keyboard which might have been grabed by the global
960 // menubar on Mac to catch shortcuts even without any GuiView.
961 if (d->global_menubar_)
962 d->global_menubar_->releaseKeyboard();
967 while (d->views_.find(id) != d->views_.end())
970 LYXERR(Debug::GUI, "About to create new window with ID " << id);
971 GuiView * view = new GuiView(id);
973 d->views_[id] = view;
977 setActiveWindow(view);
980 if (!geometry_arg.isEmpty()) {
984 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
985 re.indexIn(geometry_arg);
986 w = re.cap(1).toInt();
987 h = re.cap(2).toInt();
988 x = re.cap(3).toInt();
989 y = re.cap(4).toInt();
990 view->setGeometry(x, y, w, h);
997 Clipboard & GuiApplication::clipboard()
999 return d->clipboard_;
1003 Selection & GuiApplication::selection()
1005 return d->selection_;
1009 FontLoader & GuiApplication::fontLoader()
1011 return d->font_loader_;
1015 Toolbars const & GuiApplication::toolbars() const
1017 return d->toolbars_;
1021 Toolbars & GuiApplication::toolbars()
1023 return d->toolbars_;
1027 Menus const & GuiApplication::menus() const
1033 Menus & GuiApplication::menus()
1039 QList<int> GuiApplication::viewIds() const
1041 return d->views_.keys();
1045 ColorCache & GuiApplication::colorCache()
1047 return d->color_cache_;
1051 int GuiApplication::exec()
1053 // asynchronously handle batch commands. This event will be in
1054 // the event queue in front of other asynchronous events. Hence,
1055 // we can assume in the latter that the gui is setup already.
1056 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1058 return QApplication::exec();
1062 void GuiApplication::exit(int status)
1064 QApplication::exit(status);
1068 void GuiApplication::setGuiLanguage()
1070 // Set the language defined by the user.
1073 QString const default_language = toqstr(Messages::defaultLanguage());
1074 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1075 QLocale const default_locale(default_language);
1076 QLocale::setDefault(default_locale);
1078 // install translation file for Qt built-in dialogs
1079 QString const language_name = QString("qt_") + default_locale.name();
1081 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1082 // Short-named translator can be loaded from a long name, but not the
1083 // opposite. Therefore, long name should be used without truncation.
1084 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1085 if (!d->qt_trans_.load(language_name,
1086 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1087 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1090 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1094 switch (default_locale.language()) {
1095 case QLocale::Arabic :
1096 case QLocale::Hebrew :
1097 case QLocale::Persian :
1098 case QLocale::Urdu :
1099 setLayoutDirection(Qt::RightToLeft);
1102 setLayoutDirection(Qt::LeftToRight);
1107 void GuiApplication::processFuncRequestQueue()
1109 while (!d->func_request_queue_.empty()) {
1110 lyx::dispatch(d->func_request_queue_.back());
1111 d->func_request_queue_.pop();
1116 void GuiApplication::execBatchCommands()
1121 if (!readUIFile(toqstr(lyxrc.ui_file)))
1122 // Gives some error box here.
1126 // Create the global default menubar which is shown for the dialogs
1127 // and if no GuiView is visible.
1128 // This must be done after the session was recovered to know the "last files".
1129 d->global_menubar_ = new GlobalMenuBar();
1130 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1133 lyx::execBatchCommands();
1137 QAbstractItemModel * GuiApplication::languageModel()
1139 if (d->language_model_)
1140 return d->language_model_;
1142 QStandardItemModel * lang_model = new QStandardItemModel(this);
1143 lang_model->insertColumns(0, 1);
1145 Languages::const_iterator it = languages.begin();
1146 Languages::const_iterator end = languages.end();
1147 for (; it != end; ++it) {
1148 current_row = lang_model->rowCount();
1149 lang_model->insertRows(current_row, 1);
1150 QModelIndex item = lang_model->index(current_row, 0);
1151 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1152 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1154 d->language_model_ = new QSortFilterProxyModel(this);
1155 d->language_model_->setSourceModel(lang_model);
1156 #if QT_VERSION >= 0x040300
1157 d->language_model_->setSortLocaleAware(true);
1159 return d->language_model_;
1163 void GuiApplication::restoreGuiSession()
1165 if (!lyxrc.load_session)
1168 Session & session = theSession();
1169 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1170 // do not add to the lastfile list since these files are restored from
1171 // last session, and should be already there (regular files), or should
1172 // not be added at all (help files).
1173 for_each(lastopened.begin(), lastopened.end(),
1174 bind(&GuiView::loadDocument, current_view_, _1, false));
1176 // clear this list to save a few bytes of RAM
1177 session.lastOpened().clear();
1181 QString const GuiApplication::romanFontName()
1184 font.setKerning(false);
1185 font.setStyleHint(QFont::Serif);
1186 font.setFamily("serif");
1188 return QFontInfo(font).family();
1192 QString const GuiApplication::sansFontName()
1195 font.setKerning(false);
1196 font.setStyleHint(QFont::SansSerif);
1197 font.setFamily("sans");
1199 return QFontInfo(font).family();
1203 QString const GuiApplication::typewriterFontName()
1206 font.setKerning(false);
1207 font.setStyleHint(QFont::TypeWriter);
1208 font.setFamily("monospace");
1210 return QFontInfo(font).family();
1214 void GuiApplication::handleRegularEvents()
1216 ForkedCallsController::handleCompletedProcesses();
1220 bool GuiApplication::event(QEvent * e)
1223 case QEvent::FileOpen: {
1224 // Open a file; this happens only on Mac OS X for now.
1226 // We do this asynchronously because on startup the batch
1227 // commands are not executed here yet and the gui is not ready
1229 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1230 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1235 return QApplication::event(e);
1240 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1243 return QApplication::notify(receiver, event);
1245 catch (ExceptionMessage const & e) {
1247 case ErrorException:
1249 setQuitOnLastWindowClosed(false);
1251 Alert::error(e.title_, e.details_);
1253 // Properly crash in debug mode in order to get a useful backtrace.
1256 // In release mode, try to exit gracefully.
1259 case BufferException: {
1260 Buffer * buf = current_view_->buffer();
1261 docstring details = e.details_ + '\n';
1262 details += theBufferList().emergencyWrite(buf);
1263 theBufferList().release(buf);
1264 details += "\n" + _("The current document was closed.");
1265 Alert::error(e.title_, details);
1268 case WarningException:
1269 Alert::warning(e.title_, e.details_);
1273 catch (exception const & e) {
1274 docstring s = _("LyX has caught an exception, it will now "
1275 "attempt to save all unsaved documents and exit."
1277 s += from_ascii(e.what());
1278 Alert::error(_("Software exception Detected"), s);
1282 docstring s = _("LyX has caught some really weird exception, it will "
1283 "now attempt to save all unsaved documents and exit.");
1284 Alert::error(_("Software exception Detected"), s);
1292 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1294 QColor const & qcol = d->color_cache_.get(col);
1295 if (!qcol.isValid()) {
1301 rgbcol.r = qcol.red();
1302 rgbcol.g = qcol.green();
1303 rgbcol.b = qcol.blue();
1308 string const GuiApplication::hexName(ColorCode col)
1310 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1314 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1316 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1317 d->socket_notifiers_[fd] = sn;
1318 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1322 void GuiApplication::socketDataReceived(int fd)
1324 d->socket_notifiers_[fd]->func_();
1328 void GuiApplication::unregisterSocketCallback(int fd)
1330 d->socket_notifiers_.take(fd)->setEnabled(false);
1334 void GuiApplication::commitData(QSessionManager & sm)
1336 /// The implementation is required to avoid an application exit
1337 /// when session state save is triggered by session manager.
1338 /// The default implementation sends a close event to all
1339 /// visible top level widgets when session managment allows
1341 /// We are changing that to close all wiew one by one.
1342 /// FIXME: verify if the default implementation is enough now.
1343 if (sm.allowsInteraction() && !closeAllViews())
1348 void GuiApplication::unregisterView(GuiView * gv)
1350 LASSERT(d->views_[gv->id()] == gv, /**/);
1351 d->views_.remove(gv->id());
1352 if (current_view_ == gv) {
1354 theLyXFunc().setLyXView(0);
1359 bool GuiApplication::closeAllViews()
1361 if (d->views_.empty())
1364 QList<GuiView *> views = d->views_.values();
1365 foreach (GuiView * view, views) {
1375 GuiView & GuiApplication::view(int id) const
1377 LASSERT(d->views_.contains(id), /**/);
1378 return *d->views_.value(id);
1382 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1384 QList<GuiView *> views = d->views_.values();
1385 foreach (GuiView * view, views)
1386 view->hideDialog(name, inset);
1390 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1392 Buffer const * buffer_ = 0;
1393 QHash<int, GuiView *>::iterator end = d->views_.end();
1394 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1395 if (Buffer const * ptr = (*it)->updateInset(inset))
1402 bool GuiApplication::searchMenu(FuncRequest const & func,
1403 docstring_list & names) const
1405 return d->menus_.searchMenu(func, names);
1409 bool GuiApplication::readUIFile(QString const & name, bool include)
1419 LexerKeyword uitags[] = {
1420 { "include", ui_include },
1421 { "menuset", ui_menuset },
1422 { "toolbars", ui_toolbars },
1423 { "toolbarset", ui_toolbarset }
1426 LYXERR(Debug::INIT, "About to read " << name << "...");
1430 ui_path = libFileSearch("ui", name, "inc");
1431 if (ui_path.empty())
1432 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1434 ui_path = libFileSearch("ui", name, "ui");
1437 if (ui_path.empty()) {
1438 LYXERR(Debug::INIT, "Could not find " << name);
1439 Alert::warning(_("Could not find UI definition file"),
1440 bformat(_("Error while reading the configuration file\n%1$s.\n"
1441 "Please check your installation."), qstring_to_ucs4(name)));
1446 // Ensure that a file is read only once (prevents include loops)
1447 static QStringList uifiles;
1448 QString const uifile = toqstr(ui_path.absFilename());
1449 if (uifiles.contains(uifile)) {
1451 // We are reading again the top uifile so reset the safeguard:
1454 d->toolbars_.reset();
1456 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1457 << "Is this an include loop?");
1461 uifiles.push_back(uifile);
1463 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1466 lex.setFile(ui_path);
1468 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1472 if (lyxerr.debugging(Debug::PARSER))
1473 lex.printTable(lyxerr);
1475 while (lex.isOK()) {
1476 switch (lex.lex()) {
1479 QString const file = toqstr(lex.getString());
1480 if (!readUIFile(file, true))
1485 d->menus_.read(lex);
1489 d->toolbars_.readToolbars(lex);
1493 d->toolbars_.readToolbarSettings(lex);
1497 if (!rtrim(lex.getString()).empty())
1498 lex.printError("LyX::ReadUIFile: "
1499 "Unknown menu tag: `$$Token'");
1508 settings.beginGroup("ui_files");
1509 bool touched = false;
1510 for (int i = 0; i != uifiles.size(); ++i) {
1511 QFileInfo fi(uifiles[i]);
1512 QDateTime const date_value = fi.lastModified();
1513 QString const name_key = QString::number(i);
1514 if (!settings.contains(name_key)
1515 || settings.value(name_key).toString() != uifiles[i]
1516 || settings.value(name_key + "/date").toDateTime() != date_value) {
1518 settings.setValue(name_key, uifiles[i]);
1519 settings.setValue(name_key + "/date", date_value);
1522 settings.endGroup();
1524 settings.remove("views");
1530 void GuiApplication::onLastWindowClosed()
1532 if (d->global_menubar_)
1533 d->global_menubar_->grabKeyboard();
1537 ////////////////////////////////////////////////////////////////////////
1539 // X11 specific stuff goes here...
1542 bool GuiApplication::x11EventFilter(XEvent * xev)
1547 switch (xev->type) {
1548 case SelectionRequest: {
1549 if (xev->xselectionrequest.selection != XA_PRIMARY)
1551 LYXERR(Debug::SELECTION, "X requested selection.");
1552 BufferView * bv = current_view_->view();
1554 docstring const sel = bv->requestSelection();
1556 d->selection_.put(sel);
1560 case SelectionClear: {
1561 if (xev->xselectionclear.selection != XA_PRIMARY)
1563 LYXERR(Debug::SELECTION, "Lost selection.");
1564 BufferView * bv = current_view_->view();
1566 bv->clearSelection();
1574 } // namespace frontend
1577 void hideDialogs(std::string const & name, Inset * inset)
1580 theApp()->hideDialogs(name, inset);
1584 ////////////////////////////////////////////////////////////////////
1588 ////////////////////////////////////////////////////////////////////
1590 frontend::FontLoader & theFontLoader()
1592 LASSERT(frontend::guiApp, /**/);
1593 return frontend::guiApp->fontLoader();
1597 frontend::FontMetrics const & theFontMetrics(Font const & f)
1599 return theFontMetrics(f.fontInfo());
1603 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1605 LASSERT(frontend::guiApp, /**/);
1606 return frontend::guiApp->fontLoader().metrics(f);
1610 ////////////////////////////////////////////////////////////////////
1614 ////////////////////////////////////////////////////////////////////
1616 frontend::Clipboard & theClipboard()
1618 LASSERT(frontend::guiApp, /**/);
1619 return frontend::guiApp->clipboard();
1623 frontend::Selection & theSelection()
1625 LASSERT(frontend::guiApp, /**/);
1626 return frontend::guiApp->selection();
1632 #include "moc_GuiApplication.cpp"