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"
69 #include <QFileOpenEvent>
72 #include <QImageReader>
74 #include <QLibraryInfo>
76 #include <QMacPasteboardMime>
81 #include <QPixmapCache>
83 #include <QSessionManager>
84 #include <QSocketNotifier>
85 #include <QSortFilterProxyModel>
86 #include <QStandardItemModel>
89 #include <QTranslator>
93 #include <X11/Xatom.h>
100 #include <QWindowsMime>
101 #if defined(Q_CYGWIN_WIN) || defined(Q_CC_MINGW)
107 #include <boost/bind.hpp>
108 #include <boost/crc.hpp>
114 using namespace lyx::support;
117 static void initializeResources()
119 static bool initialized = false;
121 Q_INIT_RESOURCE(Resources);
129 frontend::Application * createApplication(int & argc, char * argv[])
131 return new frontend::GuiApplication(argc, argv);
137 /// Return the list of loadable formats.
138 vector<string> loadableImageFormats()
142 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
144 LYXERR(Debug::GRAPHICS,
145 "\nThe image loader can load the following directly:\n");
147 if (qt_formats.empty())
148 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
150 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
152 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
154 string ext = ascii_lowercase((const char *) *it);
164 ////////////////////////////////////////////////////////////////////////
165 // Icon loading support code.
166 ////////////////////////////////////////////////////////////////////////
176 bool operator<(PngMap const & lhs, PngMap const & rhs)
178 return lhs.key < rhs.key;
184 CompareKey(QString const & name) : name_(name) {}
185 bool operator()(PngMap const & other) const { return other.key == name_; }
191 // this must be sorted alphabetically
192 // Upper case comes before lower case
193 PngMap sorted_png_map[] = {
194 { "Bumpeq", "bumpeq2" },
197 { "Delta", "delta2" },
198 { "Downarrow", "downarrow2" },
199 { "Gamma", "gamma2" },
200 { "Lambda", "lambda2" },
201 { "Leftarrow", "leftarrow2" },
202 { "Leftrightarrow", "leftrightarrow2" },
203 { "Longleftarrow", "longleftarrow2" },
204 { "Longleftrightarrow", "longleftrightarrow2" },
205 { "Longrightarrow", "longrightarrow2" },
206 { "Omega", "omega2" },
210 { "Rightarrow", "rightarrow2" },
211 { "Sigma", "sigma2" },
212 { "Subset", "subset2" },
213 { "Supset", "supset2" },
214 { "Theta", "theta2" },
215 { "Uparrow", "uparrow2" },
216 { "Updownarrow", "updownarrow2" },
217 { "Upsilon", "upsilon2" },
218 { "Vdash", "vdash3" },
221 { "nLeftarrow", "nleftarrow2" },
222 { "nLeftrightarrow", "nleftrightarrow2" },
223 { "nRightarrow", "nrightarrow2" },
224 { "nVDash", "nvdash3" },
225 { "nvDash", "nvdash2" },
226 { "textrm \\AA", "textrm_AA"},
227 { "textrm \\O", "textrm_O"},
228 { "vDash", "vdash2" }
231 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
234 QString findPng(QString const & name)
236 PngMap const * const begin = sorted_png_map;
237 PngMap const * const end = begin + nr_sorted_png_map;
238 LASSERT(sorted(begin, end), /**/);
240 PngMap const * const it = find_if(begin, end, CompareKey(name));
244 png_name = it->value;
247 png_name.replace('_', "underscore");
248 png_name.replace(' ', '_');
250 // This way we can have "math-delim { }" on the toolbar.
251 png_name.replace('(', "lparen");
252 png_name.replace(')', "rparen");
253 png_name.replace('[', "lbracket");
254 png_name.replace(']', "rbracket");
255 png_name.replace('{', "lbrace");
256 png_name.replace('}', "rbrace");
257 png_name.replace('|', "bars");
258 png_name.replace(',', "thinspace");
259 png_name.replace(':', "mediumspace");
260 png_name.replace(';', "thickspace");
261 png_name.replace('!', "negthinspace");
264 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
265 << "Looking for math PNG called \"" << png_name << '"');
272 QString iconName(FuncRequest const & f, bool unknown)
274 initializeResources();
279 case LFUN_MATH_INSERT:
280 if (!f.argument().empty()) {
282 name1 = findPng(toqstr(f.argument()).mid(1));
285 case LFUN_MATH_DELIM:
286 case LFUN_MATH_BIGDELIM:
288 name1 = findPng(toqstr(f.argument()));
292 name1 = toqstr(f.argument());
295 name2 = toqstr(lyxaction.getActionName(f.action));
298 if (!f.argument().empty()) {
299 name1 = name2 + ' ' + toqstr(f.argument());
300 name1.replace(' ', '_');
304 FileName fname = libFileSearch("images/" + path, name1, "png");
306 return toqstr(fname.absFilename());
308 fname = libFileSearch("images/" + path, name2, "png");
310 return toqstr(fname.absFilename());
312 path = ":/images/" + path;
315 LYXERR0("Directory " << path << " not found in resource!");
319 if (res.exists(name1))
323 if (res.exists(name2))
326 LYXERR(Debug::GUI, "Cannot find icon for command \""
327 << lyxaction.getActionName(f.action)
328 << '(' << to_utf8(f.argument()) << ")\"");
331 return QString(":/images/unknown.png");
337 QIcon getIcon(FuncRequest const & f, bool unknown)
339 QString icon = iconName(f, unknown);
343 //LYXERR(Debug::GUI, "Found icon: " << icon);
345 if (!pm.load(icon)) {
346 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
354 ////////////////////////////////////////////////////////////////////////
355 // LyX server support code.
356 ////////////////////////////////////////////////////////////////////////
357 class SocketNotifier : public QSocketNotifier
360 /// connect a connection notification from the LyXServerSocket
361 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
362 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
366 /// The callback function
367 Application::SocketCallback func_;
371 ////////////////////////////////////////////////////////////////////////
372 // Mac specific stuff goes here...
373 ////////////////////////////////////////////////////////////////////////
375 class MenuTranslator : public QTranslator
378 MenuTranslator(QObject * parent)
379 : QTranslator(parent)
382 QString translate(const char * /*context*/,
383 const char * sourceText,
384 const char * /*comment*/ = 0)
386 string const s = sourceText;
387 if (s == N_("About %1") || s == N_("Preferences")
388 || s == N_("Reconfigure") || s == N_("Quit %1"))
395 class GlobalMenuBar : public QMenuBar
399 GlobalMenuBar() : QMenuBar(0) {}
402 bool event(QEvent * e)
404 if (e->type() == QEvent::ShortcutOverride) {
405 // && activeWindow() == 0) {
406 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
408 setKeySymbol(&sym, ke);
409 theLyXFunc().processKeySym(sym, q_key_state(ke->modifiers()));
418 // QMacPasteboardMimeGraphics can only be compiled on Mac.
420 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
423 QMacPasteboardMimeGraphics()
424 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
427 QString convertorName() { return "Graphics"; }
429 QString flavorFor(QString const & mime)
431 LYXERR(Debug::ACTION, "flavorFor " << mime);
432 if (mime == pdfMimeType())
433 return QLatin1String("com.adobe.pdf");
437 QString mimeFor(QString flav)
439 LYXERR(Debug::ACTION, "mimeFor " << flav);
440 if (flav == QLatin1String("com.adobe.pdf"))
441 return pdfMimeType();
445 bool canConvert(QString const & mime, QString flav)
447 return mimeFor(flav) == mime;
450 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
454 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
458 QList<QByteArray> convertFromMime(QString const & /*mime*/,
459 QVariant data, QString /*flav*/)
461 QList<QByteArray> ret;
462 ret.append(data.toByteArray());
468 ///////////////////////////////////////////////////////////////
469 // You can find more platform specific stuff
470 // at the end of this file...
471 ///////////////////////////////////////////////////////////////
473 ////////////////////////////////////////////////////////////////////////
474 // Windows specific stuff goes here...
477 // QWindowsMimeMetafile can only be compiled on Windows.
479 static FORMATETC cfFromMime(QString const & mimetype)
482 if (mimetype == emfMimeType()) {
483 formatetc.cfFormat = CF_ENHMETAFILE;
484 formatetc.tymed = TYMED_ENHMF;
485 } else if (mimetype == wmfMimeType()) {
486 formatetc.cfFormat = CF_METAFILEPICT;
487 formatetc.tymed = TYMED_MFPICT;
490 formatetc.dwAspect = DVASPECT_CONTENT;
491 formatetc.lindex = -1;
496 class QWindowsMimeMetafile : public QWindowsMime {
498 QWindowsMimeMetafile() {}
500 bool canConvertFromMime(FORMATETC const & formatetc,
501 QMimeData const * mimedata) const
506 bool canConvertToMime(QString const & mimetype,
507 IDataObject * pDataObj) const
509 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
511 FORMATETC formatetc = cfFromMime(mimetype);
512 return pDataObj->QueryGetData(&formatetc) == S_OK;
515 bool convertFromMime(FORMATETC const & formatetc,
516 const QMimeData * mimedata, STGMEDIUM * pmedium) const
521 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
522 QVariant::Type preferredType) const
525 if (!canConvertToMime(mimetype, pDataObj))
528 FORMATETC formatetc = cfFromMime(mimetype);
530 if (pDataObj->GetData(&formatetc, &s) != S_OK)
534 if (s.tymed == TYMED_ENHMF) {
535 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
536 data.resize(dataSize);
537 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
538 (LPBYTE)data.data());
539 } else if (s.tymed == TYMED_MFPICT) {
540 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
541 data.resize(dataSize);
542 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
543 (LPBYTE)data.data());
546 ReleaseStgMedium(&s);
552 QVector<FORMATETC> formatsForMime(QString const & mimeType,
553 QMimeData const * mimeData) const
555 QVector<FORMATETC> formats;
556 formats += cfFromMime(mimeType);
560 QString mimeForFormat(FORMATETC const & formatetc) const
562 switch (formatetc.cfFormat) {
564 return emfMimeType();
565 case CF_METAFILEPICT:
566 return wmfMimeType();
574 ////////////////////////////////////////////////////////////////////////
575 // GuiApplication::Private definition and implementation.
576 ////////////////////////////////////////////////////////////////////////
578 struct GuiApplication::Private
581 : language_model_(0), global_menubar_(0)
584 // Create the global default menubar which is shown for the dialogs
585 // and if no GuiView is visible.
586 global_menubar_ = new GlobalMenuBar();
591 QSortFilterProxyModel * language_model_;
593 GuiClipboard clipboard_;
595 GuiSelection selection_;
597 FontLoader font_loader_;
599 ColorCache color_cache_;
601 QTranslator qt_trans_;
603 QHash<int, SocketNotifier *> socket_notifiers_;
607 /// The global instance
610 /// this timer is used for any regular events one wants to
611 /// perform. at present it is used to check if forked processes
613 QTimer general_timer_;
615 /// Multiple views container.
617 * Warning: This must not be a smart pointer as the destruction of the
618 * object is handled by Qt when the view is closed
619 * \sa Qt::WA_DeleteOnClose attribute.
621 QHash<int, GuiView *> views_;
623 /// Only used on mac.
624 GlobalMenuBar * global_menubar_;
627 /// Linkback mime handler for MacOSX.
628 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
632 /// WMF Mime handler for Windows clipboard.
633 /// \warning: see comment in ~GuiApplication and in bug 4846.
634 QWindowsMimeMetafile wmf_mime_;
639 GuiApplication * guiApp;
641 GuiApplication::~GuiApplication()
644 closeAllLinkBackLinks();
646 // FIXME: Work around bug 4846 for Windows Vista and Qt4
647 // (see http://bugzilla.lyx.org/show_bug.cgi?id=4846)
648 // If the clipboard is not cleared, LyX crashes on exit when it is
649 // compiled in release mode and if there is something in the clipboard.
650 // This is related to QWindowsMimeMetafile which is apparently not
651 // properly destroyed.
652 qApp->clipboard()->clear(QClipboard::Clipboard);
657 GuiApplication::GuiApplication(int & argc, char ** argv)
658 : QApplication(argc, argv), current_view_(0), d(new GuiApplication::Private)
660 QString app_name = "LyX";
661 QCoreApplication::setOrganizationName(app_name);
662 QCoreApplication::setOrganizationDomain("lyx.org");
663 QCoreApplication::setApplicationName(app_name + "-" + lyx_version);
665 // Install translator for GUI elements.
666 installTranslator(&d->qt_trans_);
668 // FIXME: quitOnLastWindowClosed is true by default. We should have a
669 // lyxrc setting for this in order to let the application stay resident.
670 // But then we need some kind of dock icon, at least on Windows.
672 if (lyxrc.quit_on_last_window_closed)
673 setQuitOnLastWindowClosed(false);
676 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
677 // seems to be the default case for applications like LyX.
678 setQuitOnLastWindowClosed(false);
680 // This allows to translate the strings that appear in the LyX menu.
681 /// A translator suitable for the entries in the LyX menu.
682 /// Only needed with Qt/Mac.
683 installTranslator(new MenuTranslator(this));
687 // doubleClickInterval() is 400 ms on X11 which is just too long.
688 // On Windows and Mac OS X, the operating system's value is used.
689 // On Microsoft Windows, calling this function sets the double
690 // click interval for all applications. So we don't!
691 QApplication::setDoubleClickInterval(300);
694 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
696 using namespace lyx::graphics;
698 Image::newImage = boost::bind(&GuiImage::newImage);
700 // needs to be done before reading lyxrc
702 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
706 // Set the cache to 5120 kilobytes which corresponds to screen size of
707 // 1280 by 1024 pixels with a color depth of 32 bits.
708 QPixmapCache::setCacheLimit(5120);
710 // Initialize RC Fonts
711 if (lyxrc.roman_font_name.empty())
712 lyxrc.roman_font_name = fromqstr(romanFontName());
714 if (lyxrc.sans_font_name.empty())
715 lyxrc.sans_font_name = fromqstr(sansFontName());
717 if (lyxrc.typewriter_font_name.empty())
718 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
720 d->general_timer_.setInterval(500);
721 connect(&d->general_timer_, SIGNAL(timeout()),
722 this, SLOT(handleRegularEvents()));
723 d->general_timer_.start();
727 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
729 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
734 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
740 case LFUN_WINDOW_CLOSE:
741 enable = d->views_.size() > 0;
744 case LFUN_BUFFER_NEW:
745 case LFUN_BUFFER_NEW_TEMPLATE:
747 case LFUN_SCREEN_FONT_UPDATE:
749 case LFUN_WINDOW_NEW:
759 flag.setEnabled(false);
765 bool GuiApplication::dispatch(FuncRequest const & cmd)
767 switch (cmd.action) {
769 case LFUN_WINDOW_NEW:
770 createView(toqstr(cmd.argument()));
773 case LFUN_WINDOW_CLOSE:
774 // update bookmark pit of the current buffer before window close
775 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
776 theLyXFunc().gotoBookmark(i+1, false, false);
777 current_view_->close();
781 // quitting is triggered by the gui code
782 // (leaving the event loop).
784 current_view_->message(from_utf8(N_("Exiting.")));
789 case LFUN_SCREEN_FONT_UPDATE: {
790 // handle the screen font changes.
791 d->font_loader_.update();
792 // Backup current_view_
793 GuiView * view = current_view_;
794 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
795 // to skip the refresh.
797 BufferList::iterator it = theBufferList().begin();
798 BufferList::iterator const end = theBufferList().end();
799 for (; it != end; ++it)
801 // Restore current_view_
802 current_view_ = view;
806 case LFUN_BUFFER_NEW:
807 if (d->views_.empty()
808 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
809 createView(QString(), false); // keep hidden
810 current_view_->newDocument(to_utf8(cmd.argument()), false);
811 current_view_->show();
812 setActiveWindow(current_view_);
814 current_view_->newDocument(to_utf8(cmd.argument()), false);
818 case LFUN_BUFFER_NEW_TEMPLATE:
819 if (d->views_.empty()
820 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
822 current_view_->newDocument(to_utf8(cmd.argument()), true);
823 if (!current_view_->buffer())
824 current_view_->close();
826 current_view_->newDocument(to_utf8(cmd.argument()), true);
831 if (d->views_.empty()
832 || (!lyxrc.open_buffers_in_tabs && current_view_->buffer() != 0)) {
833 string const fname = to_utf8(cmd.argument());
834 // We want the ui session to be saved per document and not per
835 // window number. The filename crc is a good enough identifier.
836 boost::crc_32_type crc;
837 crc = for_each(fname.begin(), fname.end(), crc);
838 createView(crc.checksum());
839 current_view_->openDocument(fname);
840 if (!current_view_->buffer())
841 current_view_->close();
843 current_view_->openDocument(to_utf8(cmd.argument()));
846 case LFUN_SET_COLOR: {
848 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
849 if (lyx_name.empty() || x11_name.empty()) {
850 current_view_->message(
851 _("Syntax: set-color <lyx_name> <x11_name>"));
855 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
856 bool const graphicsbg_changed = lyx_name == graphicsbg
857 && x11_name != graphicsbg;
858 if (graphicsbg_changed) {
859 // FIXME: The graphics cache no longer has a changeDisplay method.
861 graphics::GCache::get().changeDisplay(true);
865 if (!lcolor.setColor(lyx_name, x11_name)) {
866 current_view_->message(
867 bformat(_("Set-color \"%1$s\" failed "
868 "- color is undefined or "
869 "may not be redefined"),
870 from_utf8(lyx_name)));
873 // Make sure we don't keep old colors in cache.
874 d->color_cache_.clear();
879 // Notify the caller that the action has not been dispatched.
883 // The action has been dispatched.
888 void GuiApplication::resetGui()
890 // Set the language defined by the user.
894 if (!readUIFile(toqstr(lyxrc.ui_file)))
895 // Gives some error box here.
898 // init the global menubar on Mac. This must be done after the session
899 // was recovered to know the "last files".
900 if (d->global_menubar_)
901 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
903 QHash<int, GuiView *>::iterator it;
904 for (it = d->views_.begin(); it != d->views_.end(); ++it)
905 (*it)->resetDialogs();
907 dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
911 void GuiApplication::createView(int view_id)
913 createView(QString(), true, view_id);
917 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
920 // release the keyboard which might have been grabed by the global
921 // menubar on Mac to catch shortcuts even without any GuiView.
922 if (d->global_menubar_)
923 d->global_menubar_->releaseKeyboard();
928 while (d->views_.find(id) != d->views_.end())
931 LYXERR(Debug::GUI, "About to create new window with ID " << id);
932 GuiView * view = new GuiView(id);
934 d->views_[id] = view;
938 setActiveWindow(view);
941 if (!geometry_arg.isEmpty()) {
945 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
946 re.indexIn(geometry_arg);
947 w = re.cap(1).toInt();
948 h = re.cap(2).toInt();
949 x = re.cap(3).toInt();
950 y = re.cap(4).toInt();
951 view->setGeometry(x, y, w, h);
955 setCurrentView(view);
959 Clipboard & GuiApplication::clipboard()
961 return d->clipboard_;
965 Selection & GuiApplication::selection()
967 return d->selection_;
971 FontLoader & GuiApplication::fontLoader()
973 return d->font_loader_;
977 Toolbars const & GuiApplication::toolbars() const
983 Toolbars & GuiApplication::toolbars()
989 Menus const & GuiApplication::menus() const
995 Menus & GuiApplication::menus()
1001 QList<int> GuiApplication::viewIds() const
1003 return d->views_.keys();
1007 ColorCache & GuiApplication::colorCache()
1009 return d->color_cache_;
1013 int GuiApplication::exec()
1015 QTimer::singleShot(1, this, SLOT(execBatchCommands()));
1016 return QApplication::exec();
1020 void GuiApplication::exit(int status)
1022 QApplication::exit(status);
1026 void GuiApplication::setGuiLanguage()
1028 // Set the language defined by the user.
1031 QString const default_language = toqstr(Messages::defaultLanguage());
1032 LYXERR(Debug::LOCALE, "Tring to set default locale to: " << default_language);
1033 QLocale const default_locale(default_language);
1034 QLocale::setDefault(default_locale);
1036 // install translation file for Qt built-in dialogs
1037 QString const language_name = QString("qt_") + default_locale.name();
1039 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1040 // Short-named translator can be loaded from a long name, but not the
1041 // opposite. Therefore, long name should be used without truncation.
1042 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1043 if (!d->qt_trans_.load(language_name,
1044 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1045 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1048 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1052 switch (default_locale.language()) {
1053 case QLocale::Arabic :
1054 case QLocale::Hebrew :
1055 case QLocale::Persian :
1056 case QLocale::Urdu :
1057 setLayoutDirection(Qt::RightToLeft);
1060 setLayoutDirection(Qt::LeftToRight);
1065 void GuiApplication::execBatchCommands()
1070 if (!readUIFile(toqstr(lyxrc.ui_file)))
1071 // Gives some error box here.
1074 // init the global menubar on Mac. This must be done after the session
1075 // was recovered to know the "last files".
1076 if (d->global_menubar_)
1077 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1079 lyx::execBatchCommands();
1082 QAbstractItemModel * GuiApplication::languageModel()
1084 if (d->language_model_)
1085 return d->language_model_;
1087 QStandardItemModel * lang_model = new QStandardItemModel(this);
1088 lang_model->insertColumns(0, 1);
1090 Languages::const_iterator it = languages.begin();
1091 Languages::const_iterator end = languages.end();
1092 for (; it != end; ++it) {
1093 current_row = lang_model->rowCount();
1094 lang_model->insertRows(current_row, 1);
1095 QModelIndex item = lang_model->index(current_row, 0);
1096 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1097 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1099 d->language_model_ = new QSortFilterProxyModel(this);
1100 d->language_model_->setSourceModel(lang_model);
1101 #if QT_VERSION >= 0x040300
1102 d->language_model_->setSortLocaleAware(true);
1104 return d->language_model_;
1108 void GuiApplication::restoreGuiSession()
1110 if (!lyxrc.load_session)
1113 Session & session = theSession();
1114 vector<FileName> const & lastopened = session.lastOpened().getfiles();
1115 // do not add to the lastfile list since these files are restored from
1116 // last session, and should be already there (regular files), or should
1117 // not be added at all (help files).
1118 for_each(lastopened.begin(), lastopened.end(),
1119 bind(&GuiView::loadDocument, current_view_, _1, false));
1121 // clear this list to save a few bytes of RAM
1122 session.lastOpened().clear();
1126 QString const GuiApplication::romanFontName()
1129 font.setKerning(false);
1130 font.setStyleHint(QFont::Serif);
1131 font.setFamily("serif");
1133 return QFontInfo(font).family();
1137 QString const GuiApplication::sansFontName()
1140 font.setKerning(false);
1141 font.setStyleHint(QFont::SansSerif);
1142 font.setFamily("sans");
1144 return QFontInfo(font).family();
1148 QString const GuiApplication::typewriterFontName()
1151 font.setKerning(false);
1152 font.setStyleHint(QFont::TypeWriter);
1153 font.setFamily("monospace");
1155 return QFontInfo(font).family();
1159 void GuiApplication::handleRegularEvents()
1161 ForkedCallsController::handleCompletedProcesses();
1165 bool GuiApplication::event(QEvent * e)
1168 case QEvent::FileOpen: {
1169 // Open a file; this happens only on Mac OS X for now
1170 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
1171 lyx::dispatch(FuncRequest(LFUN_FILE_OPEN,
1172 qstring_to_ucs4(foe->file())));
1177 return QApplication::event(e);
1182 bool GuiApplication::notify(QObject * receiver, QEvent * event)
1185 return QApplication::notify(receiver, event);
1187 catch (ExceptionMessage const & e) {
1189 case ErrorException:
1191 setQuitOnLastWindowClosed(false);
1193 Alert::error(e.title_, e.details_);
1195 // Properly crash in debug mode in order to get a useful backtrace.
1198 // In release mode, try to exit gracefully.
1201 case BufferException: {
1202 Buffer * buf = current_view_->buffer();
1203 docstring details = e.details_ + '\n';
1204 details += theBufferList().emergencyWrite(buf);
1205 theBufferList().release(buf);
1206 details += "\n" + _("The current document was closed.");
1207 Alert::error(e.title_, details);
1210 case WarningException:
1211 Alert::warning(e.title_, e.details_);
1215 catch (exception const & e) {
1216 docstring s = _("LyX has caught an exception, it will now "
1217 "attempt to save all unsaved documents and exit."
1219 s += from_ascii(e.what());
1220 Alert::error(_("Software exception Detected"), s);
1224 docstring s = _("LyX has caught some really weird exception, it will "
1225 "now attempt to save all unsaved documents and exit.");
1226 Alert::error(_("Software exception Detected"), s);
1234 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
1236 QColor const & qcol = d->color_cache_.get(col);
1237 if (!qcol.isValid()) {
1243 rgbcol.r = qcol.red();
1244 rgbcol.g = qcol.green();
1245 rgbcol.b = qcol.blue();
1250 string const GuiApplication::hexName(ColorCode col)
1252 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
1256 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
1258 SocketNotifier * sn = new SocketNotifier(this, fd, func);
1259 d->socket_notifiers_[fd] = sn;
1260 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
1264 void GuiApplication::socketDataReceived(int fd)
1266 d->socket_notifiers_[fd]->func_();
1270 void GuiApplication::unregisterSocketCallback(int fd)
1272 d->socket_notifiers_.take(fd)->setEnabled(false);
1276 void GuiApplication::commitData(QSessionManager & sm)
1278 /// The implementation is required to avoid an application exit
1279 /// when session state save is triggered by session manager.
1280 /// The default implementation sends a close event to all
1281 /// visible top level widgets when session managment allows
1283 /// We are changing that to close all wiew one by one.
1284 /// FIXME: verify if the default implementation is enough now.
1285 if (sm.allowsInteraction() && !closeAllViews())
1290 void GuiApplication::unregisterView(GuiView * gv)
1292 LASSERT(d->views_[gv->id()] == gv, /**/);
1293 d->views_.remove(gv->id());
1294 if (current_view_ == gv) {
1296 theLyXFunc().setLyXView(0);
1301 bool GuiApplication::closeAllViews()
1303 if (d->views_.empty())
1306 QList<GuiView *> views = d->views_.values();
1307 foreach (GuiView * view, views) {
1317 GuiView & GuiApplication::view(int id) const
1319 LASSERT(d->views_.contains(id), /**/);
1320 return *d->views_.value(id);
1324 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
1326 QList<GuiView *> views = d->views_.values();
1327 foreach (GuiView * view, views)
1328 view->hideDialog(name, inset);
1332 Buffer const * GuiApplication::updateInset(Inset const * inset) const
1334 Buffer const * buffer_ = 0;
1335 QHash<int, GuiView *>::iterator end = d->views_.end();
1336 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
1337 if (Buffer const * ptr = (*it)->updateInset(inset))
1344 bool GuiApplication::searchMenu(FuncRequest const & func,
1345 docstring_list & names) const
1347 return d->menus_.searchMenu(func, names);
1351 bool GuiApplication::readUIFile(QString const & name, bool include)
1361 LexerKeyword uitags[] = {
1362 { "include", ui_include },
1363 { "menuset", ui_menuset },
1364 { "toolbars", ui_toolbars },
1365 { "toolbarset", ui_toolbarset }
1368 // Ensure that a file is read only once (prevents include loops)
1369 static QStringList uifiles;
1370 if (uifiles.contains(name)) {
1372 // We are reading again the top uifile so reset the safeguard:
1375 d->toolbars_.reset();
1377 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
1378 << "Is this an include loop?");
1383 LYXERR(Debug::INIT, "About to read " << name << "...");
1387 ui_path = libFileSearch("ui", name, "inc");
1388 if (ui_path.empty())
1389 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
1391 ui_path = libFileSearch("ui", name, "ui");
1394 if (ui_path.empty()) {
1395 LYXERR(Debug::INIT, "Could not find " << name);
1396 Alert::warning(_("Could not find UI definition file"),
1397 bformat(_("Error while reading the configuration file\n%1$s.\n"
1398 "Please check your installation."), qstring_to_ucs4(name)));
1402 uifiles.push_back(name);
1404 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
1406 lex.setFile(ui_path);
1408 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
1412 if (lyxerr.debugging(Debug::PARSER))
1413 lex.printTable(lyxerr);
1415 while (lex.isOK()) {
1416 switch (lex.lex()) {
1419 QString const file = toqstr(lex.getString());
1420 if (!readUIFile(file, true))
1425 d->menus_.read(lex);
1429 d->toolbars_.readToolbars(lex);
1433 d->toolbars_.readToolbarSettings(lex);
1437 if (!rtrim(lex.getString()).empty())
1438 lex.printError("LyX::ReadUIFile: "
1439 "Unknown menu tag: `$$Token'");
1447 void GuiApplication::onLastWindowClosed()
1449 if (d->global_menubar_)
1450 d->global_menubar_->grabKeyboard();
1454 ////////////////////////////////////////////////////////////////////////
1456 // X11 specific stuff goes here...
1459 bool GuiApplication::x11EventFilter(XEvent * xev)
1464 switch (xev->type) {
1465 case SelectionRequest: {
1466 if (xev->xselectionrequest.selection != XA_PRIMARY)
1468 LYXERR(Debug::SELECTION, "X requested selection.");
1469 BufferView * bv = current_view_->view();
1471 docstring const sel = bv->requestSelection();
1473 d->selection_.put(sel);
1477 case SelectionClear: {
1478 if (xev->xselectionclear.selection != XA_PRIMARY)
1480 LYXERR(Debug::SELECTION, "Lost selection.");
1481 BufferView * bv = current_view_->view();
1483 bv->clearSelection();
1491 } // namespace frontend
1494 void hideDialogs(std::string const & name, Inset * inset)
1497 theApp()->hideDialogs(name, inset);
1501 ////////////////////////////////////////////////////////////////////
1505 ////////////////////////////////////////////////////////////////////
1507 frontend::FontLoader & theFontLoader()
1509 LASSERT(frontend::guiApp, /**/);
1510 return frontend::guiApp->fontLoader();
1514 frontend::FontMetrics const & theFontMetrics(Font const & f)
1516 return theFontMetrics(f.fontInfo());
1520 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
1522 LASSERT(frontend::guiApp, /**/);
1523 return frontend::guiApp->fontLoader().metrics(f);
1527 ////////////////////////////////////////////////////////////////////
1531 ////////////////////////////////////////////////////////////////////
1533 frontend::Clipboard & theClipboard()
1535 LASSERT(frontend::guiApp, /**/);
1536 return frontend::guiApp->clipboard();
1540 frontend::Selection & theSelection()
1542 LASSERT(frontend::guiApp, /**/);
1543 return frontend::guiApp->selection();
1548 #include "GuiApplication_moc.cpp"