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(' ', '_');
322 name1.replace('\\', "backslash");
326 FileName fname = libFileSearch("images/" + path, name1, "png");
328 return toqstr(fname.absFilename());
330 fname = libFileSearch("images/" + path, name2, "png");
332 return toqstr(fname.absFilename());
334 path = ":/images/" + path;
337 LYXERR0("Directory " << path << " not found in resource!");
341 if (res.exists(name1))
345 if (res.exists(name2))
348 LYXERR(Debug::GUI, "Cannot find icon for command \""
349 << lyxaction.getActionName(f.action)
350 << '(' << to_utf8(f.argument()) << ")\"");
353 return QString(":/images/unknown.png");
359 QIcon getIcon(FuncRequest const & f, bool unknown)
361 QString icon = iconName(f, unknown);
365 //LYXERR(Debug::GUI, "Found icon: " << icon);
367 if (!pm.load(icon)) {
368 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
376 ////////////////////////////////////////////////////////////////////////
378 // LyX server support code.
380 ////////////////////////////////////////////////////////////////////////
382 class SocketNotifier : public QSocketNotifier
385 /// connect a connection notification from the LyXServerSocket
386 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
387 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
391 /// The callback function
392 Application::SocketCallback func_;
396 ////////////////////////////////////////////////////////////////////////
398 // Mac specific stuff goes here...
400 ////////////////////////////////////////////////////////////////////////
402 class MenuTranslator : public QTranslator
405 MenuTranslator(QObject * parent)
406 : QTranslator(parent)
409 QString translate(const char * /*context*/,
410 const char * sourceText,
411 const char * /*comment*/ = 0)
413 string const s = sourceText;
414 if (s == N_("About %1") || s == N_("Preferences")
415 || s == N_("Reconfigure") || s == N_("Quit %1"))
422 class GlobalMenuBar : public QMenuBar
426 GlobalMenuBar() : QMenuBar(0) {}
429 bool event(QEvent * e)
431 if (e->type() == QEvent::ShortcutOverride) {
432 // && activeWindow() == 0) {
433 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
435 setKeySymbol(&sym, ke);
436 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
445 // QMacPasteboardMimeGraphics can only be compiled on Mac.
447 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
450 QMacPasteboardMimeGraphics()
451 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
454 QString convertorName() { return "Graphics"; }
456 QString flavorFor(QString const & mime)
458 LYXERR(Debug::ACTION, "flavorFor " << mime);
459 if (mime == pdfMimeType())
460 return QLatin1String("com.adobe.pdf");
464 QString mimeFor(QString flav)
466 LYXERR(Debug::ACTION, "mimeFor " << flav);
467 if (flav == QLatin1String("com.adobe.pdf"))
468 return pdfMimeType();
472 bool canConvert(QString const & mime, QString flav)
474 return mimeFor(flav) == mime;
477 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
481 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
485 QList<QByteArray> convertFromMime(QString const & /*mime*/,
486 QVariant data, QString /*flav*/)
488 QList<QByteArray> ret;
489 ret.append(data.toByteArray());
495 ///////////////////////////////////////////////////////////////
497 // You can find more platform specific stuff at the end of this file...
499 ///////////////////////////////////////////////////////////////
501 ////////////////////////////////////////////////////////////////////////
502 // Windows specific stuff goes here...
505 // QWindowsMimeMetafile can only be compiled on Windows.
507 static FORMATETC cfFromMime(QString const & mimetype)
510 if (mimetype == emfMimeType()) {
511 formatetc.cfFormat = CF_ENHMETAFILE;
512 formatetc.tymed = TYMED_ENHMF;
513 } else if (mimetype == wmfMimeType()) {
514 formatetc.cfFormat = CF_METAFILEPICT;
515 formatetc.tymed = TYMED_MFPICT;
518 formatetc.dwAspect = DVASPECT_CONTENT;
519 formatetc.lindex = -1;
524 class QWindowsMimeMetafile : public QWindowsMime {
526 QWindowsMimeMetafile() {}
528 bool canConvertFromMime(FORMATETC const & formatetc,
529 QMimeData const * mimedata) const
534 bool canConvertToMime(QString const & mimetype,
535 IDataObject * pDataObj) const
537 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
539 FORMATETC formatetc = cfFromMime(mimetype);
540 return pDataObj->QueryGetData(&formatetc) == S_OK;
543 bool convertFromMime(FORMATETC const & formatetc,
544 const QMimeData * mimedata, STGMEDIUM * pmedium) const
549 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
550 QVariant::Type preferredType) const
553 if (!canConvertToMime(mimetype, pDataObj))
556 FORMATETC formatetc = cfFromMime(mimetype);
558 if (pDataObj->GetData(&formatetc, &s) != S_OK)
562 if (s.tymed == TYMED_ENHMF) {
563 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
564 data.resize(dataSize);
565 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
566 (LPBYTE)data.data());
567 } else if (s.tymed == TYMED_MFPICT) {
568 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
569 data.resize(dataSize);
570 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
571 (LPBYTE)data.data());
574 ReleaseStgMedium(&s);
580 QVector<FORMATETC> formatsForMime(QString const & mimetype,
581 QMimeData const * mimedata) const
583 QVector<FORMATETC> formats;
584 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
585 formats += cfFromMime(mimetype);
589 QString mimeForFormat(FORMATETC const & formatetc) const
591 switch (formatetc.cfFormat) {
593 return emfMimeType();
594 case CF_METAFILEPICT:
595 return wmfMimeType();
603 ////////////////////////////////////////////////////////////////////////
604 // GuiApplication::Private definition and implementation.
605 ////////////////////////////////////////////////////////////////////////
607 struct GuiApplication::Private
609 Private(): language_model_(0), global_menubar_(0) {}
612 QSortFilterProxyModel * language_model_;
614 GuiClipboard clipboard_;
616 GuiSelection selection_;
618 FontLoader font_loader_;
620 ColorCache color_cache_;
622 QTranslator qt_trans_;
624 QHash<int, SocketNotifier *> socket_notifiers_;
628 /// The global instance
631 /// this timer is used for any regular events one wants to
632 /// perform. at present it is used to check if forked processes
634 QTimer general_timer_;
636 /// delayed FuncRequests
637 std::queue<FuncRequest> func_request_queue_;
639 /// Multiple views container.
641 * Warning: This must not be a smart pointer as the destruction of the
642 * object is handled by Qt when the view is closed
643 * \sa Qt::WA_DeleteOnClose attribute.
645 QHash<int, GuiView *> views_;
647 /// Only used on mac.
648 GlobalMenuBar * global_menubar_;
651 /// Linkback mime handler for MacOSX.
652 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
656 /// WMF Mime handler for Windows clipboard.
657 /// \warning: see comment in ~GuiApplication and in bug 4846.
658 QWindowsMimeMetafile wmf_mime_;
663 GuiApplication * guiApp;
665 GuiApplication::~GuiApplication()
668 closeAllLinkBackLinks();
670 // FIXME: Work around bug 4846 for Windows Vista and Qt4
671 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
672 // If the clipboard is not cleared, LyX crashes on exit when it is
673 // compiled in release mode and if there is something in the clipboard.
674 // This is related to QWindowsMimeMetafile which is apparently not
675 // properly destroyed.
676 qApp->clipboard()->clear(QClipboard::Clipboard);
681 GuiApplication::GuiApplication(int & argc, char ** argv)
682 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
684 QString app_name = "LyX";
685 QCoreApplication::setOrganizationName(app_name);
686 QCoreApplication::setOrganizationDomain("lyx.org");
687 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
689 // Install translator for GUI elements.
690 installTranslator(&d->qt_trans_);
692 // FIXME: quitOnLastWindowClosed is true by default. We should have a
693 // lyxrc setting for this in order to let the application stay resident.
694 // But then we need some kind of dock icon, at least on Windows.
696 if (lyxrc.quit_on_last_window_closed)
697 setQuitOnLastWindowClosed(false);
700 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
701 // seems to be the default case for applications like LyX.
702 setQuitOnLastWindowClosed(false);
704 // This allows to translate the strings that appear in the LyX menu.
705 /// A translator suitable for the entries in the LyX menu.
706 /// Only needed with Qt/Mac.
707 installTranslator(new MenuTranslator(this));
711 // doubleClickInterval() is 400 ms on X11 which is just too long.
712 // On Windows and Mac OS X, the operating system's value is used.
713 // On Microsoft Windows, calling this function sets the double
714 // click interval for all applications. So we don't!
715 QApplication::setDoubleClickInterval(300);
718 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
720 // needs to be done before reading lyxrc
722 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
726 // Set the cache to 5120 kilobytes which corresponds to screen size of
727 // 1280 by 1024 pixels with a color depth of 32 bits.
728 QPixmapCache::setCacheLimit(5120);
730 // Initialize RC Fonts
731 if (lyxrc.roman_font_name.empty())
732 lyxrc.roman_font_name = fromqstr(romanFontName());
734 if (lyxrc.sans_font_name.empty())
735 lyxrc.sans_font_name = fromqstr(sansFontName());
737 if (lyxrc.typewriter_font_name.empty())
738 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
740 d->general_timer_.setInterval(500);
741 connect(&d->general_timer_, SIGNAL(timeout()),
742 this, SLOT(handleRegularEvents()));
743 d->general_timer_.start();
747 GuiApplication * theGuiApp()
749 return dynamic_cast<GuiApplication *>(theApp());
753 void GuiApplication::clearSession()
760 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
762 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
767 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
773 case LFUN_WINDOW_CLOSE:
774 enable = d->views_.size() > 0;
777 case LFUN_BUFFER_NEW:
778 case LFUN_BUFFER_NEW_TEMPLATE:
780 case LFUN_SCREEN_FONT_UPDATE:
782 case LFUN_WINDOW_NEW:
792 flag.setEnabled(false);
798 bool GuiApplication::dispatch(FuncRequest const & cmd)
800 switch (cmd.action) {
802 case LFUN_WINDOW_NEW:
803 createView(toqstr(cmd.argument()));
806 case LFUN_WINDOW_CLOSE:
807 // update bookmark pit of the current buffer before window close
808 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
809 theLyXFunc().gotoBookmark(i+1, false, false);
810 current_view_->close();
814 // quitting is triggered by the gui code
815 // (leaving the event loop).
817 current_view_->message(from_utf8(N_("Exiting.")));
822 case LFUN_SCREEN_FONT_UPDATE: {
823 // handle the screen font changes.
824 d->font_loader_.update();
825 // Backup current_view_
826 GuiView * view = current_view_;
827 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
828 // to skip the refresh.
830 BufferList::iterator it = theBufferList().begin();
831 BufferList::iterator const end = theBufferList().end();
832 for (; it != end; ++it)
834 // Restore current_view_
835 current_view_ = view;
839 case LFUN_BUFFER_NEW:
840 if (d->views_.empty()
841 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
842 createView(QString(), false); // keep hidden
843 current_view_->newDocument(to_utf8(cmd.argument()), false);
844 current_view_->show();
845 setActiveWindow(current_view_);
847 current_view_->newDocument(to_utf8(cmd.argument()), false);
851 case LFUN_BUFFER_NEW_TEMPLATE:
852 if (d->views_.empty()
853 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
855 current_view_->newDocument(to_utf8(cmd.argument()), true);
856 if (!current_view_->buffer())
857 current_view_->close();
859 current_view_->newDocument(to_utf8(cmd.argument()), true);
864 if (d->views_.empty()
865 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
866 string const fname = to_utf8(cmd.argument());
867 // We want the ui session to be saved per document and not per
868 // window number. The filename crc is a good enough identifier.
869 boost::crc_32_type crc;
870 crc = for_each(fname.begin(), fname.end(), crc);
871 createView(crc.checksum());
872 current_view_->openDocument(fname);
873 if (current_view_ && !current_view_->buffer())
874 current_view_->close();
876 current_view_->openDocument(to_utf8(cmd.argument()));
879 case LFUN_SET_COLOR: {
881 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
882 if (lyx_name.empty() || x11_name.empty()) {
883 current_view_->message(
884 _("Syntax: set-color <lyx_name> <x11_name>"));
888 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
889 bool const graphicsbg_changed = lyx_name == graphicsbg
890 && x11_name != graphicsbg;
891 if (graphicsbg_changed) {
892 // FIXME: The graphics cache no longer has a changeDisplay method.
894 graphics::GCache::get().changeDisplay(true);
898 if (!lcolor.setColor(lyx_name, x11_name)) {
899 current_view_->message(
900 bformat(_("Set-color \"%1$s\" failed "
901 "- color is undefined or "
902 "may not be redefined"),
903 from_utf8(lyx_name)));
906 // Make sure we don't keep old colors in cache.
907 d->color_cache_.clear();
912 // Notify the caller that the action has not been dispatched.
916 // The action has been dispatched.
921 void GuiApplication::dispatchDelayed(FuncRequest const & func)
923 d->func_request_queue_.push(func);
924 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
928 void GuiApplication::resetGui()
930 // Set the language defined by the user.
934 if (!readUIFile(toqstr(lyxrc.ui_file)))
935 // Gives some error box here.
938 if (d->global_menubar_)
939 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
941 QHash<int, GuiView *>::iterator it;
942 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
944 gv->setLayoutDirection(layoutDirection());
948 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
952 void GuiApplication::createView(int view_id)
954 createView(QString(), true, view_id);
958 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
961 // release the keyboard which might have been grabed by the global
962 // menubar on Mac to catch shortcuts even without any GuiView.
963 if (d->global_menubar_)
964 d->global_menubar_->releaseKeyboard();
969 while (d->views_.find(id) != d->views_.end())
972 LYXERR(Debug::GUI, "About to create new window with ID " << id);
973 GuiView * view = new GuiView(id);
975 d->views_[id] = view;
979 setActiveWindow(view);
982 if (!geometry_arg.isEmpty()) {
986 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
987 re.indexIn(geometry_arg);
988 w = re.cap(1).toInt();
989 h = re.cap(2).toInt();
990 x = re.cap(3).toInt();
991 y = re.cap(4).toInt();
992 view->setGeometry(x, y, w, h);
999 Clipboard & GuiApplication::clipboard()
1001 return d->clipboard_;
1005 Selection & GuiApplication::selection()
1007 return d->selection_;
1011 FontLoader & GuiApplication::fontLoader()
1013 return d->font_loader_;
1017 Toolbars const & GuiApplication::toolbars() const
1019 return d->toolbars_;
1023 Toolbars & GuiApplication::toolbars()
1025 return d->toolbars_;
1029 Menus const & GuiApplication::menus() const
1035 Menus & GuiApplication::menus()
1041 QList<int> GuiApplication::viewIds() const
1043 return d->views_.keys();
1047 ColorCache & GuiApplication::colorCache()
1049 return d->color_cache_;
1053 int GuiApplication::exec()
1055 // asynchronously handle batch commands. This event will be in
1056 // the event queue in front of other asynchronous events. Hence,
1057 // we can assume in the latter that the gui is setup already.
1058 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1060 return QApplication::exec();
1064 void GuiApplication::exit(int status)
1066 QApplication::exit(status);
1070 void GuiApplication::setGuiLanguage()
1072 // Set the language defined by the user.
1075 QString const default_language = toqstr(Messages::defaultLanguage());
1076 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1077 QLocale const default_locale(default_language);
1078 QLocale::setDefault(default_locale);
1080 // install translation file for Qt built-in dialogs
1081 QString const language_name = QString("qt_") + default_locale.name();
1083 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1084 // Short-named translator can be loaded from a long name, but not the
1085 // opposite. Therefore, long name should be used without truncation.
1086 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1087 if (!d->qt_trans_.load(language_name,
1088 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1089 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1092 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1096 switch (default_locale.language()) {
1097 case QLocale::Arabic :
1098 case QLocale::Hebrew :
1099 case QLocale::Persian :
1100 case QLocale::Urdu :
1101 setLayoutDirection(Qt::RightToLeft);
1104 setLayoutDirection(Qt::LeftToRight);
1109 void GuiApplication::processFuncRequestQueue()
1111 while (!d->func_request_queue_.empty()) {
1112 lyx::dispatch(d->func_request_queue_.back());
1113 d->func_request_queue_.pop();
1118 void GuiApplication::execBatchCommands()
1123 if (!readUIFile(toqstr(lyxrc.ui_file)))
1124 // Gives some error box here.
1128 // Create the global default menubar which is shown for the dialogs
1129 // and if no GuiView is visible.
1130 // This must be done after the session was recovered to know the "last files".
1131 d->global_menubar_ = new GlobalMenuBar();
1132 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1135 lyx::execBatchCommands();
1139 QAbstractItemModel * GuiApplication::languageModel()
1141 if (d->language_model_)
1142 return d->language_model_;
1144 QStandardItemModel * lang_model = new QStandardItemModel(this);
1145 lang_model->insertColumns(0, 1);
1147 Languages::const_iterator it = languages.begin();
1148 Languages::const_iterator end = languages.end();
1149 for (; it != end; ++it) {
1150 current_row = lang_model->rowCount();
1151 lang_model->insertRows(current_row, 1);
1152 QModelIndex item = lang_model->index(current_row, 0);
1153 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1154 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1156 d->language_model_ = new QSortFilterProxyModel(this);
1157 d->language_model_->setSourceModel(lang_model);
1158 #if QT_VERSION >= 0x040300
1159 d->language_model_->setSortLocaleAware(true);
1161 return d->language_model_;
1165 void GuiApplication::restoreGuiSession()
1167 if (!lyxrc.load_session)
1170 Session & session = theSession();
1171 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1172 // do not add to the lastfile list since these files are restored from
1173 // last session, and should be already there (regular files), or should
1174 // not be added at all (help files).
1175 for_each(lastopened.begin(), lastopened.end(),
1176 bind(&GuiView::loadDocument, current_view_, _1, false));
1178 // clear this list to save a few bytes of RAM
1179 session.lastOpened().clear();
1183 QString const GuiApplication::romanFontName()
1186 font.setKerning(false);
1187 font.setStyleHint(QFont::Serif);
1188 font.setFamily("serif");
1190 return QFontInfo(font).family();
1194 QString const GuiApplication::sansFontName()
1197 font.setKerning(false);
1198 font.setStyleHint(QFont::SansSerif);
1199 font.setFamily("sans");
1201 return QFontInfo(font).family();
1205 QString const GuiApplication::typewriterFontName()
1208 font.setKerning(false);
1209 font.setStyleHint(QFont::TypeWriter);
1210 font.setFamily("monospace");
1212 return QFontInfo(font).family();
1216 void GuiApplication::handleRegularEvents()
1218 ForkedCallsController::handleCompletedProcesses();
1222 bool GuiApplication::event(QEvent * e)
1225 case QEvent::FileOpen: {
1226 // Open a file; this happens only on Mac OS X for now.
1228 // We do this asynchronously because on startup the batch
1229 // commands are not executed here yet and the gui is not ready
1231 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1232 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
1237 return QApplication::event(e);
1242 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1245 return QApplication::notify(receiver, event);
1247 catch (ExceptionMessage const & e) {
1249 case ErrorException:
1251 setQuitOnLastWindowClosed(false);
1253 Alert::error(e.title_, e.details_);
1255 // Properly crash in debug mode in order to get a useful backtrace.
1258 // In release mode, try to exit gracefully.
1261 case BufferException: {
1262 Buffer * buf = current_view_->buffer();
1263 docstring details = e.details_ + '\n';
1264 details += theBufferList().emergencyWrite(buf);
1265 theBufferList().release(buf);
1266 details += "\n" + _("The current document was closed.");
1267 Alert::error(e.title_, details);
1270 case WarningException:
1271 Alert::warning(e.title_, e.details_);
1275 catch (exception const & e) {
1276 docstring s = _("LyX has caught an exception, it will now "
1277 "attempt to save all unsaved documents and exit."
1279 s += from_ascii(e.what());
1280 Alert::error(_("Software exception Detected"), s);
1284 docstring s = _("LyX has caught some really weird exception, it will "
1285 "now attempt to save all unsaved documents and exit.");
1286 Alert::error(_("Software exception Detected"), s);
1294 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1296 QColor const & qcol = d->color_cache_.get(col);
1297 if (!qcol.isValid()) {
1303 rgbcol.r = qcol.red();
1304 rgbcol.g = qcol.green();
1305 rgbcol.b = qcol.blue();
1310 string const GuiApplication::hexName(ColorCode col)
1312 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1316 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1318 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1319 d->socket_notifiers_[fd] = sn;
1320 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1324 void GuiApplication::socketDataReceived(int fd)
1326 d->socket_notifiers_[fd]->func_();
1330 void GuiApplication::unregisterSocketCallback(int fd)
1332 d->socket_notifiers_.take(fd)->setEnabled(false);
1336 void GuiApplication::commitData(QSessionManager & sm)
1338 /// The implementation is required to avoid an application exit
1339 /// when session state save is triggered by session manager.
1340 /// The default implementation sends a close event to all
1341 /// visible top level widgets when session managment allows
1343 /// We are changing that to close all wiew one by one.
1344 /// FIXME: verify if the default implementation is enough now.
1345 if (sm.allowsInteraction() && !closeAllViews())
1350 void GuiApplication::unregisterView(GuiView * gv)
1352 LASSERT(d->views_[gv->id()] == gv, /**/);
1353 d->views_.remove(gv->id());
1354 if (current_view_ == gv) {
1356 theLyXFunc().setLyXView(0);
1361 bool GuiApplication::closeAllViews()
1363 if (d->views_.empty())
1366 QList<GuiView *> views = d->views_.values();
1367 foreach (GuiView * view, views) {
1377 GuiView & GuiApplication::view(int id) const
1379 LASSERT(d->views_.contains(id), /**/);
1380 return *d->views_.value(id);
1384 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1386 QList<GuiView *> views = d->views_.values();
1387 foreach (GuiView * view, views)
1388 view->hideDialog(name, inset);
1392 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1394 Buffer const * buffer_ = 0;
1395 QHash<int, GuiView *>::iterator end = d->views_.end();
1396 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1397 if (Buffer const * ptr = (*it)->updateInset(inset))
1404 bool GuiApplication::searchMenu(FuncRequest const & func,
1405 docstring_list & names) const
1407 return d->menus_.searchMenu(func, names);
1411 bool GuiApplication::readUIFile(QString const & name, bool include)
1421 LexerKeyword uitags[] = {
1422 { "include", ui_include },
1423 { "menuset", ui_menuset },
1424 { "toolbars", ui_toolbars },
1425 { "toolbarset", ui_toolbarset }
1428 LYXERR(Debug::INIT, "About to read " << name << "...");
1432 ui_path = libFileSearch("ui", name, "inc");
1433 if (ui_path.empty())
1434 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1436 ui_path = libFileSearch("ui", name, "ui");
1439 if (ui_path.empty()) {
1440 LYXERR(Debug::INIT, "Could not find " << name);
1441 Alert::warning(_("Could not find UI definition file"),
1442 bformat(_("Error while reading the configuration file\n%1$s.\n"
1443 "Please check your installation."), qstring_to_ucs4(name)));
1448 // Ensure that a file is read only once (prevents include loops)
1449 static QStringList uifiles;
1450 QString const uifile = toqstr(ui_path.absFilename());
1451 if (uifiles.contains(uifile)) {
1453 // We are reading again the top uifile so reset the safeguard:
1456 d->toolbars_.reset();
1458 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1459 << "Is this an include loop?");
1463 uifiles.push_back(uifile);
1465 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1468 lex.setFile(ui_path);
1470 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1474 if (lyxerr.debugging(Debug::PARSER))
1475 lex.printTable(lyxerr);
1477 while (lex.isOK()) {
1478 switch (lex.lex()) {
1481 QString const file = toqstr(lex.getString());
1482 if (!readUIFile(file, true))
1487 d->menus_.read(lex);
1491 d->toolbars_.readToolbars(lex);
1495 d->toolbars_.readToolbarSettings(lex);
1499 if (!rtrim(lex.getString()).empty())
1500 lex.printError("LyX::ReadUIFile: "
1501 "Unknown menu tag: `$$Token'");
1510 settings.beginGroup("ui_files");
1511 bool touched = false;
1512 for (int i = 0; i != uifiles.size(); ++i) {
1513 QFileInfo fi(uifiles[i]);
1514 QDateTime const date_value = fi.lastModified();
1515 QString const name_key = QString::number(i);
1516 if (!settings.contains(name_key)
1517 || settings.value(name_key).toString() != uifiles[i]
1518 || settings.value(name_key + "/date").toDateTime() != date_value) {
1520 settings.setValue(name_key, uifiles[i]);
1521 settings.setValue(name_key + "/date", date_value);
1524 settings.endGroup();
1526 settings.remove("views");
1532 void GuiApplication::onLastWindowClosed()
1534 if (d->global_menubar_)
1535 d->global_menubar_->grabKeyboard();
1539 ////////////////////////////////////////////////////////////////////////
1541 // X11 specific stuff goes here...
1544 bool GuiApplication::x11EventFilter(XEvent * xev)
1549 switch (xev->type) {
1550 case SelectionRequest: {
1551 if (xev->xselectionrequest.selection != XA_PRIMARY)
1553 LYXERR(Debug::SELECTION, "X requested selection.");
1554 BufferView * bv = current_view_->view();
1556 docstring const sel = bv->requestSelection();
1558 d->selection_.put(sel);
1562 case SelectionClear: {
1563 if (xev->xselectionclear.selection != XA_PRIMARY)
1565 LYXERR(Debug::SELECTION, "Lost selection.");
1566 BufferView * bv = current_view_->view();
1568 bv->clearSelection();
1576 } // namespace frontend
1579 void hideDialogs(std::string const & name, Inset * inset)
1582 theApp()->hideDialogs(name, inset);
1586 ////////////////////////////////////////////////////////////////////
1590 ////////////////////////////////////////////////////////////////////
1592 frontend::FontLoader & theFontLoader()
1594 LASSERT(frontend::guiApp, /**/);
1595 return frontend::guiApp->fontLoader();
1599 frontend::FontMetrics const & theFontMetrics(Font const & f)
1601 return theFontMetrics(f.fontInfo());
1605 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1607 LASSERT(frontend::guiApp, /**/);
1608 return frontend::guiApp->fontLoader().metrics(f);
1612 ////////////////////////////////////////////////////////////////////
1616 ////////////////////////////////////////////////////////////////////
1618 frontend::Clipboard & theClipboard()
1620 LASSERT(frontend::guiApp, /**/);
1621 return frontend::guiApp->clipboard();
1625 frontend::Selection & theSelection()
1627 LASSERT(frontend::guiApp, /**/);
1628 return frontend::guiApp->selection();
1634 #include "moc_GuiApplication.cpp"