2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
44 #include "LaTeXFeatures.h"
47 #include "LyXAction.h"
49 #include "Paragraph.h"
52 #include "SpellChecker.h"
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/FileName.h"
59 #include "support/filetools.h"
60 #include "support/foreach.h"
61 #include "support/ForkedCalls.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/lyxalgo.h" // sorted
66 #include "support/Messages.h"
67 #include "support/os.h"
68 #include "support/Package.h"
69 #include "support/Path.h"
70 #include "support/Systemcall.h"
73 #include "support/linkback/LinkBackProxy.h"
83 #include <QFileOpenEvent>
87 #include <QImageReader>
89 #include <QLibraryInfo>
91 #include <QMacPasteboardMime>
96 #include <QPixmapCache>
98 #include <QSessionManager>
100 #include <QSocketNotifier>
101 #include <QSortFilterProxyModel>
102 #include <QStandardItemModel>
103 #include <QTextCodec>
105 #include <QTranslator>
109 #include <X11/Xatom.h>
110 #include <X11/Xlib.h>
116 #include <QWindowsMime>
123 #include <boost/bind.hpp>
124 #include <boost/crc.hpp>
131 using namespace lyx::support;
134 static void initializeResources()
136 static bool initialized = false;
138 Q_INIT_RESOURCE(Resources);
146 frontend::Application * createApplication(int & argc, char * argv[])
149 // prune -geometry argument(s) by shifting
150 // the following ones 2 places down.
151 for (int i = 0 ; i < argc ; ++i) {
152 if (strcmp(argv[i], "-geometry") == 0) {
153 int const remove = (i+1) < argc ? 2 : 1;
155 for (int j = i; j < argc; ++j)
156 argv[j] = argv[j + remove];
161 return new frontend::GuiApplication(argc, argv);
167 /// Return the list of loadable formats.
168 vector<string> loadableImageFormats()
172 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
174 LYXERR(Debug::GRAPHICS,
175 "\nThe image loader can load the following directly:\n");
177 if (qt_formats.empty())
178 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
180 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
182 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
184 string ext = ascii_lowercase((const char *) *it);
195 ////////////////////////////////////////////////////////////////////////
197 // Icon loading support code
199 ////////////////////////////////////////////////////////////////////////
209 bool operator<(PngMap const & lhs, PngMap const & rhs)
211 return lhs.key < rhs.key;
217 CompareKey(QString const & name) : name_(name) {}
218 bool operator()(PngMap const & other) const { return other.key == name_; }
224 // this must be sorted alphabetically
225 // Upper case comes before lower case
226 PngMap sorted_png_map[] = {
227 { "Bumpeq", "bumpeq2" },
230 { "Delta", "delta2" },
231 { "Diamond", "diamond2" },
232 { "Downarrow", "downarrow2" },
233 { "Gamma", "gamma2" },
234 { "Lambda", "lambda2" },
235 { "Leftarrow", "leftarrow2" },
236 { "Leftrightarrow", "leftrightarrow2" },
237 { "Longleftarrow", "longleftarrow2" },
238 { "Longleftrightarrow", "longleftrightarrow2" },
239 { "Longrightarrow", "longrightarrow2" },
240 { "Omega", "omega2" },
244 { "Rightarrow", "rightarrow2" },
245 { "Sigma", "sigma2" },
246 { "Subset", "subset2" },
247 { "Supset", "supset2" },
248 { "Theta", "theta2" },
249 { "Uparrow", "uparrow2" },
250 { "Updownarrow", "updownarrow2" },
251 { "Upsilon", "upsilon2" },
252 { "Vdash", "vdash3" },
255 { "nLeftarrow", "nleftarrow2" },
256 { "nLeftrightarrow", "nleftrightarrow2" },
257 { "nRightarrow", "nrightarrow2" },
258 { "nVDash", "nvdash3" },
259 { "nvDash", "nvdash2" },
260 { "textrm \\AA", "textrm_AA"},
261 { "textrm \\O", "textrm_O"},
262 { "vDash", "vdash2" }
265 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
268 QString findPng(QString const & name)
270 PngMap const * const begin = sorted_png_map;
271 PngMap const * const end = begin + nr_sorted_png_map;
272 LASSERT(sorted(begin, end), /**/);
274 PngMap const * const it = find_if(begin, end, CompareKey(name));
278 png_name = it->value;
281 png_name.replace('_', "underscore");
282 png_name.replace(' ', '_');
284 // This way we can have "math-delim { }" on the toolbar.
285 png_name.replace('(', "lparen");
286 png_name.replace(')', "rparen");
287 png_name.replace('[', "lbracket");
288 png_name.replace(']', "rbracket");
289 png_name.replace('{', "lbrace");
290 png_name.replace('}', "rbrace");
291 png_name.replace('|', "bars");
292 png_name.replace(',', "thinspace");
293 png_name.replace(':', "mediumspace");
294 png_name.replace(';', "thickspace");
295 png_name.replace('!', "negthinspace");
298 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
299 << "Looking for math PNG called \"" << png_name << '"');
306 QString iconName(FuncRequest const & f, bool unknown)
308 initializeResources();
313 case LFUN_MATH_INSERT:
314 if (!f.argument().empty()) {
316 name1 = findPng(toqstr(f.argument()).mid(1));
319 case LFUN_MATH_DELIM:
320 case LFUN_MATH_BIGDELIM:
322 name1 = findPng(toqstr(f.argument()));
326 name1 = toqstr(f.argument());
328 case LFUN_COMMAND_ALTERNATIVES: {
329 // use the first of the alternative commands
331 docstring dummy = split(f.argument(), firstcom, ';');
332 name1 = toqstr(firstcom);
333 name1.replace(' ', '_');
337 name2 = toqstr(lyxaction.getActionName(f.action));
340 if (!f.argument().empty()) {
341 name1 = name2 + ' ' + toqstr(f.argument());
342 name1.replace(' ', '_');
343 name1.replace('\\', "backslash");
347 FileName fname = libFileSearch("images/" + path, name1, "png");
349 return toqstr(fname.absFilename());
351 fname = libFileSearch("images/" + path, name2, "png");
353 return toqstr(fname.absFilename());
355 path = ":/images/" + path;
358 LYXERR0("Directory " << path << " not found in resource!");
362 if (res.exists(name1))
366 if (res.exists(name2))
369 LYXERR(Debug::GUI, "Cannot find icon with filename "
370 << "\"" << name1 << "\""
372 << "\"" << name2 << "\""
374 << lyxaction.getActionName(f.action)
375 << '(' << to_utf8(f.argument()) << ")\"");
378 fname = libFileSearch(QString("images/"), "unknown", "png");
380 return toqstr(fname.absFilename());
381 return QString(":/images/unknown.png");
387 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
390 FileName fname = libFileSearch(path, name, ext);
391 QString path1 = toqstr(fname.absFilename());
392 QString path2 = ":/" + path + name + "." + ext;
394 if (pixmap.load(path1)) {
397 else if (pixmap.load(path2)) {
401 LYXERR0("Cannot load pixmap \""
402 << path << name << '.' << ext
403 << "\", please verify resource system!");
408 QIcon getIcon(FuncRequest const & f, bool unknown)
410 QString icon = iconName(f, unknown);
414 //LYXERR(Debug::GUI, "Found icon: " << icon);
416 if (!pm.load(icon)) {
417 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
425 ////////////////////////////////////////////////////////////////////////
427 // LyX server support code.
429 ////////////////////////////////////////////////////////////////////////
431 class SocketNotifier : public QSocketNotifier
434 /// connect a connection notification from the LyXServerSocket
435 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
436 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
440 /// The callback function
441 Application::SocketCallback func_;
445 ////////////////////////////////////////////////////////////////////////
447 // Mac specific stuff goes here...
449 ////////////////////////////////////////////////////////////////////////
451 class MenuTranslator : public QTranslator
454 MenuTranslator(QObject * parent)
455 : QTranslator(parent)
458 QString translate(const char * /*context*/,
459 const char * sourceText,
460 const char * /*comment*/ = 0)
462 string const s = sourceText;
463 if (s == N_("About %1") || s == N_("Preferences")
464 || s == N_("Reconfigure") || s == N_("Quit %1"))
471 class GlobalMenuBar : public QMenuBar
475 GlobalMenuBar() : QMenuBar(0) {}
478 bool event(QEvent * e)
480 if (e->type() == QEvent::ShortcutOverride) {
481 // && activeWindow() == 0) {
482 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
484 setKeySymbol(&sym, ke);
485 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
494 // QMacPasteboardMimeGraphics can only be compiled on Mac.
496 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
499 QMacPasteboardMimeGraphics()
500 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
503 QString convertorName() { return "Graphics"; }
505 QString flavorFor(QString const & mime)
507 LYXERR(Debug::ACTION, "flavorFor " << mime);
508 if (mime == pdfMimeType())
509 return QLatin1String("com.adobe.pdf");
513 QString mimeFor(QString flav)
515 LYXERR(Debug::ACTION, "mimeFor " << flav);
516 if (flav == QLatin1String("com.adobe.pdf"))
517 return pdfMimeType();
521 bool canConvert(QString const & mime, QString flav)
523 return mimeFor(flav) == mime;
526 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
530 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
534 QList<QByteArray> convertFromMime(QString const & /*mime*/,
535 QVariant data, QString /*flav*/)
537 QList<QByteArray> ret;
538 ret.append(data.toByteArray());
544 ///////////////////////////////////////////////////////////////
546 // You can find more platform specific stuff at the end of this file...
548 ///////////////////////////////////////////////////////////////
550 ////////////////////////////////////////////////////////////////////////
551 // Windows specific stuff goes here...
554 // QWindowsMimeMetafile can only be compiled on Windows.
556 static FORMATETC cfFromMime(QString const & mimetype)
559 if (mimetype == emfMimeType()) {
560 formatetc.cfFormat = CF_ENHMETAFILE;
561 formatetc.tymed = TYMED_ENHMF;
562 } else if (mimetype == wmfMimeType()) {
563 formatetc.cfFormat = CF_METAFILEPICT;
564 formatetc.tymed = TYMED_MFPICT;
567 formatetc.dwAspect = DVASPECT_CONTENT;
568 formatetc.lindex = -1;
573 class QWindowsMimeMetafile : public QWindowsMime {
575 QWindowsMimeMetafile() {}
577 bool canConvertFromMime(FORMATETC const & formatetc,
578 QMimeData const * mimedata) const
583 bool canConvertToMime(QString const & mimetype,
584 IDataObject * pDataObj) const
586 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
588 FORMATETC formatetc = cfFromMime(mimetype);
589 return pDataObj->QueryGetData(&formatetc) == S_OK;
592 bool convertFromMime(FORMATETC const & formatetc,
593 const QMimeData * mimedata, STGMEDIUM * pmedium) const
598 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
599 QVariant::Type preferredType) const
602 if (!canConvertToMime(mimetype, pDataObj))
605 FORMATETC formatetc = cfFromMime(mimetype);
607 if (pDataObj->GetData(&formatetc, &s) != S_OK)
611 if (s.tymed == TYMED_ENHMF) {
612 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
613 data.resize(dataSize);
614 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
615 (LPBYTE)data.data());
616 } else if (s.tymed == TYMED_MFPICT) {
617 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
618 data.resize(dataSize);
619 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
620 (LPBYTE)data.data());
623 ReleaseStgMedium(&s);
629 QVector<FORMATETC> formatsForMime(QString const & mimetype,
630 QMimeData const * mimedata) const
632 QVector<FORMATETC> formats;
633 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
634 formats += cfFromMime(mimetype);
638 QString mimeForFormat(FORMATETC const & formatetc) const
640 switch (formatetc.cfFormat) {
642 return emfMimeType();
643 case CF_METAFILEPICT:
644 return wmfMimeType();
652 ////////////////////////////////////////////////////////////////////////
653 // GuiApplication::Private definition and implementation.
654 ////////////////////////////////////////////////////////////////////////
656 struct GuiApplication::Private
658 Private(): language_model_(0), meta_fake_bit(NoModifier),
662 /// WMF Mime handler for Windows clipboard.
663 wmf_mime_ = new QWindowsMimeMetafile();
665 initKeySequences(&theTopLevelKeymap());
668 void initKeySequences(KeyMap * kb)
670 keyseq = KeySequence(kb, kb);
671 cancel_meta_seq = KeySequence(kb, kb);
675 QSortFilterProxyModel * language_model_;
677 GuiClipboard clipboard_;
679 GuiSelection selection_;
681 FontLoader font_loader_;
683 ColorCache color_cache_;
685 QTranslator qt_trans_;
687 QHash<int, SocketNotifier *> socket_notifiers_;
691 /// The global instance
694 /// this timer is used for any regular events one wants to
695 /// perform. at present it is used to check if forked processes
697 QTimer general_timer_;
699 /// delayed FuncRequests
700 std::queue<FuncRequest> func_request_queue_;
705 KeySequence cancel_meta_seq;
707 KeyModifier meta_fake_bit;
709 /// Multiple views container.
711 * Warning: This must not be a smart pointer as the destruction of the
712 * object is handled by Qt when the view is closed
713 * \sa Qt::WA_DeleteOnClose attribute.
715 QHash<int, GuiView *> views_;
717 /// Only used on mac.
718 GlobalMenuBar * global_menubar_;
721 /// Linkback mime handler for MacOSX.
722 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
726 /// WMF Mime handler for Windows clipboard.
727 QWindowsMimeMetafile * wmf_mime_;
732 GuiApplication * guiApp;
734 GuiApplication::~GuiApplication()
737 closeAllLinkBackLinks();
743 GuiApplication::GuiApplication(int & argc, char ** argv)
744 : QApplication(argc, argv), current_view_(0),
745 d(new GuiApplication::Private)
747 QString app_name = "LyX";
748 QCoreApplication::setOrganizationName(app_name);
749 QCoreApplication::setOrganizationDomain("lyx.org");
750 QCoreApplication::setApplicationName(lyx_package);
752 // Install translator for GUI elements.
753 installTranslator(&d->qt_trans_);
755 // FIXME: quitOnLastWindowClosed is true by default. We should have a
756 // lyxrc setting for this in order to let the application stay resident.
757 // But then we need some kind of dock icon, at least on Windows.
759 if (lyxrc.quit_on_last_window_closed)
760 setQuitOnLastWindowClosed(false);
763 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
764 // seems to be the default case for applications like LyX.
765 setQuitOnLastWindowClosed(false);
767 // This allows to translate the strings that appear in the LyX menu.
768 /// A translator suitable for the entries in the LyX menu.
769 /// Only needed with Qt/Mac.
770 installTranslator(new MenuTranslator(this));
774 // doubleClickInterval() is 400 ms on X11 which is just too long.
775 // On Windows and Mac OS X, the operating system's value is used.
776 // On Microsoft Windows, calling this function sets the double
777 // click interval for all applications. So we don't!
778 QApplication::setDoubleClickInterval(300);
781 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
783 // needs to be done before reading lyxrc
785 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
789 // Set the cache to 5120 kilobytes which corresponds to screen size of
790 // 1280 by 1024 pixels with a color depth of 32 bits.
791 QPixmapCache::setCacheLimit(5120);
793 // Initialize RC Fonts
794 if (lyxrc.roman_font_name.empty())
795 lyxrc.roman_font_name = fromqstr(romanFontName());
797 if (lyxrc.sans_font_name.empty())
798 lyxrc.sans_font_name = fromqstr(sansFontName());
800 if (lyxrc.typewriter_font_name.empty())
801 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
803 d->general_timer_.setInterval(500);
804 connect(&d->general_timer_, SIGNAL(timeout()),
805 this, SLOT(handleRegularEvents()));
806 d->general_timer_.start();
810 GuiApplication * theGuiApp()
812 return dynamic_cast<GuiApplication *>(theApp());
816 void GuiApplication::clearSession()
823 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
825 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
829 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
833 if (cmd.action == LFUN_NOACTION) {
834 flag.message(from_utf8(N_("Nothing to do")));
835 flag.setEnabled(false);
839 if (cmd.action == LFUN_UNKNOWN_ACTION) {
841 flag.setEnabled(false);
842 flag.message(from_utf8(N_("Unknown action")));
846 // I would really like to avoid having this switch and rather try to
847 // encode this in the function itself.
848 // -- And I'd rather let an inset decide which LFUNs it is willing
849 // to handle (Andre')
851 switch (cmd.action) {
853 // This could be used for the no-GUI version. The GUI version is handled in
854 // GuiView::getStatus(). See above.
856 case LFUN_BUFFER_WRITE:
857 case LFUN_BUFFER_WRITE_AS: {
858 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
859 enable = b && (b->isUnnamed() || !b->isClean());
864 case LFUN_BOOKMARK_GOTO: {
865 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
866 enable = theSession().bookmarks().isValid(num);
870 case LFUN_BOOKMARK_CLEAR:
871 enable = theSession().bookmarks().hasValid();
874 // this one is difficult to get right. As a half-baked
875 // solution, we consider only the first action of the sequence
876 case LFUN_COMMAND_SEQUENCE: {
877 // argument contains ';'-terminated commands
878 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
879 FuncRequest func(lyxaction.lookupFunc(firstcmd));
880 func.origin = cmd.origin;
881 flag = getStatus(func);
885 // we want to check if at least one of these is enabled
886 case LFUN_COMMAND_ALTERNATIVES: {
887 // argument contains ';'-terminated commands
888 string arg = to_utf8(cmd.argument());
889 while (!arg.empty()) {
891 arg = split(arg, first, ';');
892 FuncRequest func(lyxaction.lookupFunc(first));
893 func.origin = cmd.origin;
894 flag = getStatus(func);
895 // if this one is enabled, the whole thing is
904 string name = to_utf8(cmd.argument());
905 if (theTopLevelCmdDef().lock(name, func)) {
906 func.origin = cmd.origin;
907 flag = getStatus(func);
908 theTopLevelCmdDef().release(name);
910 // catch recursion or unknown command
911 // definition. all operations until the
912 // recursion or unknown command definition
913 // occurs are performed, so set the state to
920 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
922 case LFUN_PREFERENCES_SAVE:
923 case LFUN_BUFFER_SAVE_AS_DEFAULT:
924 case LFUN_DEBUG_LEVEL_SET:
925 // these are handled in our dispatch()
928 case LFUN_WINDOW_CLOSE:
929 enable = d->views_.size() > 0;
932 case LFUN_BUFFER_NEW:
933 case LFUN_BUFFER_NEW_TEMPLATE:
936 case LFUN_SCREEN_FONT_UPDATE:
938 case LFUN_WINDOW_NEW:
940 case LFUN_LYXRC_APPLY:
941 case LFUN_COMMAND_PREFIX:
943 case LFUN_META_PREFIX:
944 case LFUN_RECONFIGURE:
945 case LFUN_SERVER_GET_FILENAME:
946 case LFUN_SERVER_NOTIFY:
951 // Does the view know something?
952 if (!current_view_) {
957 if (current_view_->getStatus(cmd, flag))
960 // In LyX/Mac, when a dialog is open, the menus of the
961 // application can still be accessed without giving focus to
962 // the main window. In this case, we want to disable the menu
963 // entries that are buffer or view-related.
964 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
966 if (cmd.origin == FuncRequest::MENU && !current_view_->hasFocus()) {
972 BufferView * bv = current_view_->currentBufferView();
973 BufferView * doc_bv = current_view_->documentBufferView();
974 // If we do not have a BufferView, then other functions are disabled
979 // try the BufferView
980 bool decided = bv->getStatus(cmd, flag);
983 decided = bv->buffer().getStatus(cmd, flag);
984 if (!decided && doc_bv)
985 // try the Document Buffer
986 decided = doc_bv->buffer().getStatus(cmd, flag);
990 flag.setEnabled(false);
992 // the default error message if we disable the command
993 if (!flag.enabled() && flag.message().empty())
994 flag.message(from_utf8(N_("Command disabled")));
999 /// make a post-dispatch status message
1000 static docstring makeDispatchMessage(docstring const & msg,
1001 FuncRequest const & cmd)
1003 const bool verbose = (cmd.origin == FuncRequest::MENU
1004 || cmd.origin == FuncRequest::TOOLBAR
1005 || cmd.origin == FuncRequest::COMMANDBUFFER);
1007 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1008 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1012 docstring dispatch_msg = msg;
1013 if (!dispatch_msg.empty())
1014 dispatch_msg += ' ';
1016 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1018 bool argsadded = false;
1020 if (!cmd.argument().empty()) {
1021 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1022 comname += ' ' + cmd.argument();
1026 docstring const shortcuts = theTopLevelKeymap().
1027 printBindings(cmd, KeySequence::ForGui);
1029 if (!shortcuts.empty())
1030 comname += ": " + shortcuts;
1031 else if (!argsadded && !cmd.argument().empty())
1032 comname += ' ' + cmd.argument();
1034 if (!comname.empty()) {
1035 comname = rtrim(comname);
1036 dispatch_msg += '(' + rtrim(comname) + ')';
1038 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1039 return dispatch_msg;
1043 void GuiApplication::dispatch(FuncRequest const & cmd)
1045 if (current_view_ && current_view_->currentBufferView())
1046 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1049 // redraw the screen at the end (first of the two drawing steps).
1050 //This is done unless explicitly requested otherwise
1051 dr.update(Update::FitCursor);
1057 BufferView * bv = current_view_->currentBufferView();
1059 // BufferView::update() updates the ViewMetricsInfo and
1060 // also initializes the position cache for all insets in
1061 // (at least partially) visible top-level paragraphs.
1062 // We will redraw the screen only if needed.
1063 bv->processUpdateFlags(dr.update());
1065 // Do we have a selection?
1066 theSelection().haveSelection(bv->cursor().selection());
1069 current_view_->restartCursor();
1071 // Some messages may already be translated, so we cannot use _()
1072 current_view_->message(makeDispatchMessage(
1073 translateIfPossible(dr.message()), cmd));
1077 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
1079 GuiView * lv = current_view_;
1081 if (!theSession().bookmarks().isValid(idx))
1083 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
1084 LASSERT(!bm.filename.empty(), /**/);
1085 string const file = bm.filename.absFilename();
1086 // if the file is not opened, open it.
1087 if (!theBufferList().exists(bm.filename)) {
1089 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1093 // open may fail, so we need to test it again
1094 if (!theBufferList().exists(bm.filename))
1097 // bm can be changed when saving
1098 BookmarksSection::Bookmark tmp = bm;
1100 // Special case idx == 0 used for back-from-back jump navigation
1102 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1104 // if the current buffer is not that one, switch to it.
1105 if (!lv->documentBufferView()
1106 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
1107 if (!switchToBuffer)
1109 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1112 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1113 if (!lv->documentBufferView()->moveToPosition(
1114 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1121 // Cursor jump succeeded!
1122 Cursor const & cur = lv->documentBufferView()->cursor();
1123 pit_type new_pit = cur.pit();
1124 pos_type new_pos = cur.pos();
1125 int new_id = cur.paragraph().id();
1127 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1128 // see http://www.lyx.org/trac/ticket/3092
1129 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1130 || bm.top_id != new_id) {
1131 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1132 new_pit, new_pos, new_id);
1136 // This function runs "configure" and then rereads lyx.defaults to
1137 // reconfigure the automatic settings.
1138 static void reconfigure(GuiView * lv, string const & option)
1140 // emit message signal.
1142 lv->message(_("Running configure..."));
1144 // Run configure in user lyx directory
1145 PathChanger p(package().user_support());
1146 string configure_command = package().configure_command();
1147 configure_command += option;
1149 int ret = one.startscript(Systemcall::Wait, configure_command);
1151 // emit message signal.
1153 lv->message(_("Reloading configuration..."));
1154 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1155 // Re-read packages.lst
1156 LaTeXFeatures::getAvailable();
1159 Alert::information(_("System reconfiguration failed"),
1160 _("The system reconfiguration has failed.\n"
1161 "Default textclass is used but LyX may "
1162 "not be able to work properly.\n"
1163 "Please reconfigure again if needed."));
1166 Alert::information(_("System reconfigured"),
1167 _("The system has been reconfigured.\n"
1168 "You need to restart LyX to make use of any\n"
1169 "updated document class specifications."));
1174 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1176 string const argument = to_utf8(cmd.argument());
1177 FuncCode const action = cmd.action;
1179 LYXERR(Debug::ACTION, "cmd: " << cmd);
1181 // we have not done anything wrong yet.
1184 FuncStatus const flag = getStatus(cmd);
1185 if (!flag.enabled()) {
1186 // We cannot use this function here
1187 LYXERR(Debug::ACTION, "action "
1188 << lyxaction.getActionName(action)
1189 << " [" << action << "] is disabled at this location");
1191 current_view_->restartCursor();
1192 dr.setMessage(flag.message());
1194 dr.dispatched(false);
1195 dr.update(Update::None);
1199 // Assumes that the action will be dispatched.
1200 dr.dispatched(true);
1202 switch (cmd.action) {
1204 case LFUN_WINDOW_NEW:
1205 createView(toqstr(cmd.argument()));
1208 case LFUN_WINDOW_CLOSE:
1209 // update bookmark pit of the current buffer before window close
1210 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1211 gotoBookmark(i+1, false, false);
1212 // clear the last opened list, because
1213 // maybe this will end the session
1214 theSession().lastOpened().clear();
1215 current_view_->close();
1219 // quitting is triggered by the gui code
1220 // (leaving the event loop).
1222 current_view_->message(from_utf8(N_("Exiting.")));
1223 if (closeAllViews())
1227 case LFUN_SCREEN_FONT_UPDATE: {
1228 // handle the screen font changes.
1229 d->font_loader_.update();
1230 // Backup current_view_
1231 GuiView * view = current_view_;
1232 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1233 // to skip the refresh.
1235 theBufferList().changed(false);
1236 // Restore current_view_
1237 current_view_ = view;
1241 case LFUN_BUFFER_NEW:
1242 if (d->views_.empty()
1243 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1244 createView(QString(), false); // keep hidden
1245 current_view_->newDocument(to_utf8(cmd.argument()), false);
1246 current_view_->show();
1247 setActiveWindow(current_view_);
1249 current_view_->newDocument(to_utf8(cmd.argument()), false);
1253 case LFUN_BUFFER_NEW_TEMPLATE:
1254 if (d->views_.empty()
1255 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1257 current_view_->newDocument(to_utf8(cmd.argument()), true);
1258 if (!current_view_->documentBufferView())
1259 current_view_->close();
1261 current_view_->newDocument(to_utf8(cmd.argument()), true);
1265 case LFUN_FILE_OPEN:
1266 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1267 if (d->views_.empty()
1268 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1269 string const fname = to_utf8(cmd.argument());
1270 // We want the ui session to be saved per document and not per
1271 // window number. The filename crc is a good enough identifier.
1272 boost::crc_32_type crc;
1273 crc = for_each(fname.begin(), fname.end(), crc);
1274 createView(crc.checksum());
1275 current_view_->openDocument(fname);
1276 if (current_view_ && !current_view_->documentBufferView())
1277 current_view_->close();
1279 current_view_->openDocument(to_utf8(cmd.argument()));
1282 case LFUN_HELP_OPEN: {
1283 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1284 if (current_view_ == 0)
1286 string const arg = to_utf8(cmd.argument());
1288 current_view_->message(_("Missing argument"));
1291 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1293 fname = i18nLibFileSearch("examples", arg, "lyx");
1295 if (fname.empty()) {
1296 lyxerr << "LyX: unable to find documentation file `"
1297 << arg << "'. Bad installation?" << endl;
1300 current_view_->message(bformat(_("Opening help file %1$s..."),
1301 makeDisplayPath(fname.absFilename())));
1302 Buffer * buf = current_view_->loadDocument(fname, false);
1304 current_view_->setBuffer(buf);
1305 #ifndef DEVEL_VERSION
1306 buf->setReadonly(true);
1308 buf->updateLabels();
1309 buf->errors("Parse");
1314 case LFUN_SET_COLOR: {
1316 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1317 if (lyx_name.empty() || x11_name.empty()) {
1318 current_view_->message(
1319 _("Syntax: set-color <lyx_name> <x11_name>"));
1323 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1324 bool const graphicsbg_changed =
1325 lyx_name == graphicsbg && x11_name != graphicsbg;
1326 if (graphicsbg_changed) {
1327 // FIXME: The graphics cache no longer has a changeDisplay method.
1329 graphics::GCache::get().changeDisplay(true);
1333 if (!lcolor.setColor(lyx_name, x11_name)) {
1334 current_view_->message(
1335 bformat(_("Set-color \"%1$s\" failed "
1336 "- color is undefined or "
1337 "may not be redefined"),
1338 from_utf8(lyx_name)));
1341 // Make sure we don't keep old colors in cache.
1342 d->color_cache_.clear();
1346 case LFUN_LYXRC_APPLY: {
1347 // reset active key sequences, since the bindings
1348 // are updated (bug 6064)
1350 LyXRC const lyxrc_orig = lyxrc;
1352 istringstream ss(to_utf8(cmd.argument()));
1353 bool const success = lyxrc.read(ss) == 0;
1356 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1357 << "Unable to read lyxrc data"
1362 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1369 case LFUN_COMMAND_PREFIX:
1370 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1375 d->meta_fake_bit = NoModifier;
1376 GuiView * gv = currentView();
1377 if (gv && gv->currentBufferView())
1378 // cancel any selection
1379 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1380 dr.setMessage(from_ascii(N_("Cancel")));
1383 case LFUN_META_PREFIX:
1384 d->meta_fake_bit = AltModifier;
1385 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1388 // --- Menus -----------------------------------------------
1389 case LFUN_RECONFIGURE:
1390 // argument is any additional parameter to the configure.py command
1391 reconfigure(currentView(), to_utf8(cmd.argument()));
1394 // --- lyxserver commands ----------------------------
1395 case LFUN_SERVER_GET_FILENAME: {
1396 GuiView * lv = currentView();
1397 LASSERT(lv && lv->documentBufferView(), return);
1398 docstring const fname = from_utf8(
1399 lv->documentBufferView()->buffer().absFileName());
1400 dr.setMessage(fname);
1401 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1404 case LFUN_SERVER_NOTIFY: {
1405 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1406 dr.setMessage(dispatch_buffer);
1407 theServer().notifyClient(to_utf8(dispatch_buffer));
1411 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1412 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1418 string rest = split(argument, countstr, ' ');
1419 istringstream is(countstr);
1422 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1423 for (int i = 0; i < count; ++i)
1424 dispatch(lyxaction.lookupFunc(rest));
1428 case LFUN_COMMAND_SEQUENCE: {
1429 // argument contains ';'-terminated commands
1430 string arg = argument;
1431 // FIXME: this LFUN should also work without any view.
1432 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1433 ? &(current_view_->documentBufferView()->buffer()) : 0;
1435 buffer->undo().beginUndoGroup();
1436 while (!arg.empty()) {
1438 arg = split(arg, first, ';');
1439 FuncRequest func(lyxaction.lookupFunc(first));
1440 func.origin = cmd.origin;
1443 // the buffer may have been closed by one action
1444 if (theBufferList().isLoaded(buffer))
1445 buffer->undo().endUndoGroup();
1449 case LFUN_COMMAND_ALTERNATIVES: {
1450 // argument contains ';'-terminated commands
1451 string arg = argument;
1452 while (!arg.empty()) {
1454 arg = split(arg, first, ';');
1455 FuncRequest func(lyxaction.lookupFunc(first));
1456 func.origin = cmd.origin;
1457 FuncStatus stat = getStatus(func);
1458 if (stat.enabled()) {
1468 if (theTopLevelCmdDef().lock(argument, func)) {
1469 func.origin = cmd.origin;
1471 theTopLevelCmdDef().release(argument);
1473 if (func.action == LFUN_UNKNOWN_ACTION) {
1474 // unknown command definition
1475 lyxerr << "Warning: unknown command definition `"
1479 // recursion detected
1480 lyxerr << "Warning: Recursion in the command definition `"
1481 << argument << "' detected"
1488 case LFUN_PREFERENCES_SAVE:
1489 lyxrc.write(support::makeAbsPath("preferences",
1490 package().user_support().absFilename()), false);
1493 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1494 string const fname = addName(addPath(package().user_support().absFilename(),
1495 "templates/"), "defaults.lyx");
1496 Buffer defaults(fname);
1498 istringstream ss(argument);
1501 int const unknown_tokens = defaults.readHeader(lex);
1503 if (unknown_tokens != 0) {
1504 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1505 << unknown_tokens << " unknown token"
1506 << (unknown_tokens == 1 ? "" : "s")
1510 if (defaults.writeFile(FileName(defaults.absFileName())))
1511 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1512 makeDisplayPath(fname)));
1515 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1520 case LFUN_BOOKMARK_GOTO:
1521 // go to bookmark, open unopened file and switch to buffer if necessary
1522 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1523 dr.update(Update::FitCursor);
1526 case LFUN_BOOKMARK_CLEAR:
1527 theSession().bookmarks().clear();
1530 case LFUN_DEBUG_LEVEL_SET:
1531 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1535 // Notify the caller that the action has not been dispatched.
1536 dr.dispatched(false);
1540 // The action has been dispatched in this method, nothing more to do.
1541 if (dr.dispatched())
1544 GuiView * lv = current_view_;
1546 // Everything below is only for active window
1550 // Let the current GuiView dispatch its own actions.
1551 lv->dispatch(cmd, dr);
1552 if (dr.dispatched() && lv )
1555 BufferView * bv = lv->currentBufferView();
1558 // Let the current BufferView dispatch its own actions.
1559 bv->dispatch(cmd, dr);
1560 if (dr.dispatched())
1563 BufferView * doc_bv = lv->documentBufferView();
1564 // Try with the document BufferView dispatch if any.
1566 doc_bv->dispatch(cmd, dr);
1567 if (dr.dispatched())
1571 // OK, so try the current Buffer itself...
1572 bv->buffer().dispatch(cmd, dr);
1573 if (dr.dispatched())
1576 // and with the document Buffer.
1578 doc_bv->buffer().dispatch(cmd, dr);
1579 if (dr.dispatched())
1583 // Let the current Cursor dispatch its own actions.
1584 Cursor old = bv->cursor();
1585 bv->cursor().dispatch(cmd);
1587 // notify insets we just left
1588 if (bv->cursor() != old) {
1590 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1592 bv->cursor().fixIfBroken();
1595 // update completion. We do it here and not in
1596 // processKeySym to avoid another redraw just for a
1597 // changed inline completion
1598 if (cmd.origin == FuncRequest::KEYBOARD) {
1599 if (cmd.action == LFUN_SELF_INSERT
1600 || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1601 lv->updateCompletion(bv->cursor(), true, true);
1602 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
1603 lv->updateCompletion(bv->cursor(), false, true);
1605 lv->updateCompletion(bv->cursor(), false, false);
1608 dr = bv->cursor().result();
1610 // if we executed a mutating lfun, mark the buffer as dirty
1611 Buffer * doc_buffer = (lv && lv->documentBufferView())
1612 ? &(lv->documentBufferView()->buffer()) : 0;
1613 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1615 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1616 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1617 lv->currentBufferView()->buffer().markDirty();
1621 docstring GuiApplication::viewStatusMessage()
1623 // When meta-fake key is pressed, show the key sequence so far + "M-".
1624 if (d->meta_fake_bit != NoModifier)
1625 return d->keyseq.print(KeySequence::ForGui) + "M-";
1627 // Else, when a non-complete key sequence is pressed,
1628 // show the available options.
1629 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1630 return d->keyseq.printOptions(true);
1636 void GuiApplication::handleKeyFunc(FuncCode action)
1640 if (d->keyseq.length())
1642 GuiView * gv = currentView();
1643 LASSERT(gv && gv->currentBufferView(), return);
1644 BufferView * bv = gv->currentBufferView();
1645 bv->getIntl().getTransManager().deadkey(
1646 c, get_accent(action).accent, bv->cursor().innerText(),
1648 // Need to clear, in case the minibuffer calls these
1651 // copied verbatim from do_accent_char
1652 bv->cursor().resetAnchor();
1653 bv->processUpdateFlags(Update::FitCursor);
1657 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1659 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1661 GuiView * lv = currentView();
1663 // Do nothing if we have nothing (JMarc)
1664 if (!keysym.isOK()) {
1665 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1666 lv->restartCursor();
1670 if (keysym.isModifier()) {
1671 LYXERR(Debug::KEY, "isModifier true");
1673 lv->restartCursor();
1677 char_type encoded_last_key = keysym.getUCSEncoded();
1679 // Do a one-deep top-level lookup for
1680 // cancel and meta-fake keys. RVDK_PATCH_5
1681 d->cancel_meta_seq.reset();
1683 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1684 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
1686 // When not cancel or meta-fake, do the normal lookup.
1687 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1688 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1689 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
1690 // remove Caps Lock and Mod2 as a modifiers
1691 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1692 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
1695 // Dont remove this unless you know what you are doing.
1696 d->meta_fake_bit = NoModifier;
1698 // Can this happen now ?
1699 if (func.action == LFUN_NOACTION)
1700 func = FuncRequest(LFUN_COMMAND_PREFIX);
1702 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
1703 << d->keyseq.print(KeySequence::Portable) << ']');
1705 // already here we know if it any point in going further
1706 // why not return already here if action == -1 and
1707 // num_bytes == 0? (Lgb)
1709 if (d->keyseq.length() > 1)
1710 lv->message(d->keyseq.print(KeySequence::ForGui));
1713 // Maybe user can only reach the key via holding down shift.
1714 // Let's see. But only if shift is the only modifier
1715 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1716 LYXERR(Debug::KEY, "Trying without shift");
1717 func = d->keyseq.addkey(keysym, NoModifier);
1718 LYXERR(Debug::KEY, "Action now " << func.action);
1721 if (func.action == LFUN_UNKNOWN_ACTION) {
1722 // Hmm, we didn't match any of the keysequences. See
1723 // if it's normal insertable text not already covered
1725 if (keysym.isText() && d->keyseq.length() == 1) {
1726 LYXERR(Debug::KEY, "isText() is true, inserting.");
1727 func = FuncRequest(LFUN_SELF_INSERT,
1728 FuncRequest::KEYBOARD);
1730 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1731 lv->message(_("Unknown function."));
1732 lv->restartCursor();
1737 if (func.action == LFUN_SELF_INSERT) {
1738 if (encoded_last_key != 0) {
1739 docstring const arg(1, encoded_last_key);
1740 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
1741 FuncRequest::KEYBOARD));
1742 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1745 lyx::dispatch(func);
1752 void GuiApplication::dispatchDelayed(FuncRequest const & func)
1754 d->func_request_queue_.push(func);
1755 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
1759 void GuiApplication::resetGui()
1761 // Set the language defined by the user.
1765 if (!readUIFile(toqstr(lyxrc.ui_file)))
1766 // Gives some error box here.
1769 if (d->global_menubar_)
1770 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1772 QHash<int, GuiView *>::iterator it;
1773 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1776 gv->setLayoutDirection(layoutDirection());
1780 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1784 void GuiApplication::createView(int view_id)
1786 createView(QString(), true, view_id);
1790 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1793 // release the keyboard which might have been grabed by the global
1794 // menubar on Mac to catch shortcuts even without any GuiView.
1795 if (d->global_menubar_)
1796 d->global_menubar_->releaseKeyboard();
1800 while (d->views_.find(id) != d->views_.end())
1803 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1804 GuiView * view = new GuiView(id);
1806 d->views_[id] = view;
1810 setActiveWindow(view);
1813 if (!geometry_arg.isEmpty()) {
1817 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1818 re.indexIn(geometry_arg);
1819 w = re.cap(1).toInt();
1820 h = re.cap(2).toInt();
1821 x = re.cap(3).toInt();
1822 y = re.cap(4).toInt();
1823 view->setGeometry(x, y, w, h);
1830 Clipboard & GuiApplication::clipboard()
1832 return d->clipboard_;
1836 Selection & GuiApplication::selection()
1838 return d->selection_;
1842 FontLoader & GuiApplication::fontLoader()
1844 return d->font_loader_;
1848 Toolbars const & GuiApplication::toolbars() const
1850 return d->toolbars_;
1854 Toolbars & GuiApplication::toolbars()
1856 return d->toolbars_;
1860 Menus const & GuiApplication::menus() const
1866 Menus & GuiApplication::menus()
1872 QList<int> GuiApplication::viewIds() const
1874 return d->views_.keys();
1878 ColorCache & GuiApplication::colorCache()
1880 return d->color_cache_;
1884 int GuiApplication::exec()
1886 // asynchronously handle batch commands. This event will be in
1887 // the event queue in front of other asynchronous events. Hence,
1888 // we can assume in the latter that the gui is setup already.
1889 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1891 return QApplication::exec();
1895 void GuiApplication::exit(int status)
1897 QApplication::exit(status);
1901 void GuiApplication::setGuiLanguage()
1903 // Set the language defined by the user.
1906 QString const default_language = toqstr(Messages::defaultLanguage());
1907 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1908 QLocale const default_locale(default_language);
1909 QLocale::setDefault(default_locale);
1911 // install translation file for Qt built-in dialogs
1912 QString const language_name = QString("qt_") + default_locale.name();
1914 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1915 // Short-named translator can be loaded from a long name, but not the
1916 // opposite. Therefore, long name should be used without truncation.
1917 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1918 if (!d->qt_trans_.load(language_name,
1919 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1920 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1923 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1927 switch (default_locale.language()) {
1928 case QLocale::Arabic :
1929 case QLocale::Hebrew :
1930 case QLocale::Persian :
1931 case QLocale::Urdu :
1932 setLayoutDirection(Qt::RightToLeft);
1935 setLayoutDirection(Qt::LeftToRight);
1940 void GuiApplication::processFuncRequestQueue()
1942 while (!d->func_request_queue_.empty()) {
1943 lyx::dispatch(d->func_request_queue_.back());
1944 d->func_request_queue_.pop();
1949 void GuiApplication::execBatchCommands()
1954 if (!readUIFile(toqstr(lyxrc.ui_file)))
1955 // Gives some error box here.
1959 // Create the global default menubar which is shown for the dialogs
1960 // and if no GuiView is visible.
1961 // This must be done after the session was recovered to know the "last files".
1962 d->global_menubar_ = new GlobalMenuBar();
1963 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1966 lyx::execBatchCommands();
1970 QAbstractItemModel * GuiApplication::languageModel()
1972 if (d->language_model_)
1973 return d->language_model_;
1975 QStandardItemModel * lang_model = new QStandardItemModel(this);
1976 lang_model->insertColumns(0, 1);
1978 Languages::const_iterator it = lyx::languages.begin();
1979 Languages::const_iterator end = lyx::languages.end();
1980 for (; it != end; ++it) {
1981 current_row = lang_model->rowCount();
1982 lang_model->insertRows(current_row, 1);
1983 QModelIndex item = lang_model->index(current_row, 0);
1984 lang_model->setData(item, qt_(it->second.display()), Qt::DisplayRole);
1985 lang_model->setData(item, toqstr(it->second.lang()), Qt::UserRole);
1987 d->language_model_ = new QSortFilterProxyModel(this);
1988 d->language_model_->setSourceModel(lang_model);
1989 #if QT_VERSION >= 0x040300
1990 d->language_model_->setSortLocaleAware(true);
1992 return d->language_model_;
1996 void GuiApplication::restoreGuiSession()
1998 if (!lyxrc.load_session)
2001 Session & session = theSession();
2002 LastOpenedSection::LastOpened const & lastopened =
2003 session.lastOpened().getfiles();
2005 FileName active_file;
2006 // do not add to the lastfile list since these files are restored from
2007 // last session, and should be already there (regular files), or should
2008 // not be added at all (help files).
2009 for (size_t i = 0; i < lastopened.size(); ++i) {
2010 FileName const & file_name = lastopened[i].file_name;
2011 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2012 && current_view_->documentBufferView() != 0)) {
2013 boost::crc_32_type crc;
2014 string const & fname = file_name.absFilename();
2015 crc = for_each(fname.begin(), fname.end(), crc);
2016 createView(crc.checksum());
2018 current_view_->loadDocument(file_name, false);
2020 if (lastopened[i].active)
2021 active_file = file_name;
2024 // Restore last active buffer
2025 Buffer * buffer = theBufferList().getBuffer(active_file);
2027 current_view_->setBuffer(buffer);
2029 // clear this list to save a few bytes of RAM
2030 session.lastOpened().clear();
2034 QString const GuiApplication::romanFontName()
2037 font.setKerning(false);
2038 font.setStyleHint(QFont::Serif);
2039 font.setFamily("serif");
2041 return QFontInfo(font).family();
2045 QString const GuiApplication::sansFontName()
2048 font.setKerning(false);
2049 font.setStyleHint(QFont::SansSerif);
2050 font.setFamily("sans");
2052 return QFontInfo(font).family();
2056 QString const GuiApplication::typewriterFontName()
2059 font.setKerning(false);
2060 font.setStyleHint(QFont::TypeWriter);
2061 font.setFamily("monospace");
2063 return QFontInfo(font).family();
2067 void GuiApplication::handleRegularEvents()
2069 ForkedCallsController::handleCompletedProcesses();
2073 bool GuiApplication::event(QEvent * e)
2076 case QEvent::FileOpen: {
2077 // Open a file; this happens only on Mac OS X for now.
2079 // We do this asynchronously because on startup the batch
2080 // commands are not executed here yet and the gui is not ready
2082 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2083 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
2088 return QApplication::event(e);
2093 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2096 return QApplication::notify(receiver, event);
2098 catch (ExceptionMessage const & e) {
2100 case ErrorException:
2102 setQuitOnLastWindowClosed(false);
2104 Alert::error(e.title_, e.details_);
2106 // Properly crash in debug mode in order to get a useful backtrace.
2109 // In release mode, try to exit gracefully.
2112 case BufferException: {
2113 if (!current_view_->documentBufferView())
2115 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2116 docstring details = e.details_ + '\n';
2117 details += buf->emergencyWrite();
2118 theBufferList().release(buf);
2119 details += "\n" + _("The current document was closed.");
2120 Alert::error(e.title_, details);
2123 case WarningException:
2124 Alert::warning(e.title_, e.details_);
2128 catch (exception const & e) {
2129 docstring s = _("LyX has caught an exception, it will now "
2130 "attempt to save all unsaved documents and exit."
2132 s += from_ascii(e.what());
2133 Alert::error(_("Software exception Detected"), s);
2137 docstring s = _("LyX has caught some really weird exception, it will "
2138 "now attempt to save all unsaved documents and exit.");
2139 Alert::error(_("Software exception Detected"), s);
2147 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2149 QColor const & qcol = d->color_cache_.get(col);
2150 if (!qcol.isValid()) {
2156 rgbcol.r = qcol.red();
2157 rgbcol.g = qcol.green();
2158 rgbcol.b = qcol.blue();
2163 string const GuiApplication::hexName(ColorCode col)
2165 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2169 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2171 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2172 d->socket_notifiers_[fd] = sn;
2173 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2177 void GuiApplication::socketDataReceived(int fd)
2179 d->socket_notifiers_[fd]->func_();
2183 void GuiApplication::unregisterSocketCallback(int fd)
2185 d->socket_notifiers_.take(fd)->setEnabled(false);
2189 void GuiApplication::commitData(QSessionManager & sm)
2191 /// The implementation is required to avoid an application exit
2192 /// when session state save is triggered by session manager.
2193 /// The default implementation sends a close event to all
2194 /// visible top level widgets when session managment allows
2196 /// We are changing that to close all wiew one by one.
2197 /// FIXME: verify if the default implementation is enough now.
2198 if (sm.allowsInteraction() && !closeAllViews())
2203 void GuiApplication::unregisterView(GuiView * gv)
2205 LASSERT(d->views_[gv->id()] == gv, /**/);
2206 d->views_.remove(gv->id());
2207 if (current_view_ == gv)
2212 bool GuiApplication::closeAllViews()
2214 if (d->views_.empty())
2217 // When a view/window was closed before without quitting LyX, there
2218 // are already entries in the lastOpened list.
2219 theSession().lastOpened().clear();
2221 QList<GuiView *> views = d->views_.values();
2222 foreach (GuiView * view, views) {
2232 GuiView & GuiApplication::view(int id) const
2234 LASSERT(d->views_.contains(id), /**/);
2235 return *d->views_.value(id);
2239 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2241 QList<GuiView *> views = d->views_.values();
2242 foreach (GuiView * view, views)
2243 view->hideDialog(name, inset);
2247 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2249 Buffer const * buffer_ = 0;
2250 QHash<int, GuiView *>::iterator end = d->views_.end();
2251 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2252 if (Buffer const * ptr = (*it)->updateInset(inset))
2259 bool GuiApplication::searchMenu(FuncRequest const & func,
2260 docstring_list & names) const
2262 return d->menus_.searchMenu(func, names);
2266 bool GuiApplication::readUIFile(QString const & name, bool include)
2268 LYXERR(Debug::INIT, "About to read " << name << "...");
2272 ui_path = libFileSearch("ui", name, "inc");
2273 if (ui_path.empty())
2274 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2276 ui_path = libFileSearch("ui", name, "ui");
2279 if (ui_path.empty()) {
2280 static const QString defaultUIFile = "default";
2281 LYXERR(Debug::INIT, "Could not find " << name);
2283 Alert::warning(_("Could not find UI definition file"),
2284 bformat(_("Error while reading the included file\n%1$s\n"
2285 "Please check your installation."), qstring_to_ucs4(name)));
2288 if (name == defaultUIFile) {
2289 LYXERR(Debug::INIT, "Could not find default UI file!!");
2290 Alert::warning(_("Could not find default UI file"),
2291 _("LyX could not find the default UI file!\n"
2292 "Please check your installation."));
2295 Alert::warning(_("Could not find UI definition file"),
2296 bformat(_("Error while reading the configuration file\n%1$s\n"
2297 "Falling back to default.\n"
2298 "Please look under Tools>Preferences>User Interface and\n"
2299 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2300 return readUIFile(defaultUIFile, false);
2303 // Ensure that a file is read only once (prevents include loops)
2304 static QStringList uifiles;
2305 QString const uifile = toqstr(ui_path.absFilename());
2306 if (uifiles.contains(uifile)) {
2308 // We are reading again the top uifile so reset the safeguard:
2311 d->toolbars_.reset();
2313 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2314 << "Is this an include loop?");
2318 uifiles.push_back(uifile);
2320 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2330 LexerKeyword uitags[] = {
2331 { "include", ui_include },
2332 { "menuset", ui_menuset },
2333 { "toolbars", ui_toolbars },
2334 { "toolbarset", ui_toolbarset }
2338 lex.setFile(ui_path);
2340 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2344 if (lyxerr.debugging(Debug::PARSER))
2345 lex.printTable(lyxerr);
2347 // store which ui files define Toolbars
2348 static QStringList toolbar_uifiles;
2350 while (lex.isOK()) {
2351 switch (lex.lex()) {
2354 QString const file = toqstr(lex.getString());
2355 if (!readUIFile(file, true))
2360 d->menus_.read(lex);
2364 d->toolbars_.readToolbars(lex);
2368 d->toolbars_.readToolbarSettings(lex);
2369 toolbar_uifiles.push_back(uifile);
2373 if (!rtrim(lex.getString()).empty())
2374 lex.printError("LyX::ReadUIFile: "
2375 "Unknown menu tag: `$$Token'");
2384 settings.beginGroup("ui_files");
2385 bool touched = false;
2386 for (int i = 0; i != uifiles.size(); ++i) {
2387 QFileInfo fi(uifiles[i]);
2388 QDateTime const date_value = fi.lastModified();
2389 QString const name_key = QString::number(i);
2390 // if an ui file which defines Toolbars has changed,
2391 // we have to reset the settings
2392 if (toolbar_uifiles.contains(uifiles[i])
2393 && (!settings.contains(name_key)
2394 || settings.value(name_key).toString() != uifiles[i]
2395 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2397 settings.setValue(name_key, uifiles[i]);
2398 settings.setValue(name_key + "/date", date_value);
2401 settings.endGroup();
2403 settings.remove("views");
2409 void GuiApplication::onLastWindowClosed()
2411 if (d->global_menubar_)
2412 d->global_menubar_->grabKeyboard();
2416 ////////////////////////////////////////////////////////////////////////
2418 // X11 specific stuff goes here...
2421 bool GuiApplication::x11EventFilter(XEvent * xev)
2426 switch (xev->type) {
2427 case SelectionRequest: {
2428 if (xev->xselectionrequest.selection != XA_PRIMARY)
2430 LYXERR(Debug::SELECTION, "X requested selection.");
2431 BufferView * bv = current_view_->currentBufferView();
2433 docstring const sel = bv->requestSelection();
2435 d->selection_.put(sel);
2439 case SelectionClear: {
2440 if (xev->xselectionclear.selection != XA_PRIMARY)
2442 LYXERR(Debug::SELECTION, "Lost selection.");
2443 BufferView * bv = current_view_->currentBufferView();
2445 bv->clearSelection();
2453 } // namespace frontend
2456 void hideDialogs(std::string const & name, Inset * inset)
2459 frontend::guiApp->hideDialogs(name, inset);
2463 ////////////////////////////////////////////////////////////////////
2467 ////////////////////////////////////////////////////////////////////
2469 frontend::FontLoader & theFontLoader()
2471 LASSERT(frontend::guiApp, /**/);
2472 return frontend::guiApp->fontLoader();
2476 frontend::FontMetrics const & theFontMetrics(Font const & f)
2478 return theFontMetrics(f.fontInfo());
2482 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2484 LASSERT(frontend::guiApp, /**/);
2485 return frontend::guiApp->fontLoader().metrics(f);
2489 ////////////////////////////////////////////////////////////////////
2493 ////////////////////////////////////////////////////////////////////
2495 frontend::Clipboard & theClipboard()
2497 LASSERT(frontend::guiApp, /**/);
2498 return frontend::guiApp->clipboard();
2502 frontend::Selection & theSelection()
2504 LASSERT(frontend::guiApp, /**/);
2505 return frontend::guiApp->selection();
2511 #include "moc_GuiApplication.cpp"