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"
53 #include "Thesaurus.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/FileName.h"
60 #include "support/filetools.h"
61 #include "support/foreach.h"
62 #include "support/ForkedCalls.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/lyxalgo.h" // sorted
67 #include "support/Messages.h"
68 #include "support/os.h"
69 #include "support/Package.h"
70 #include "support/Path.h"
71 #include "support/Systemcall.h"
74 #include "support/linkback/LinkBackProxy.h"
84 #include <QFileOpenEvent>
88 #include <QImageReader>
90 #include <QLibraryInfo>
92 #include <QMacPasteboardMime>
97 #include <QPixmapCache>
99 #include <QSessionManager>
101 #include <QSocketNotifier>
102 #include <QSortFilterProxyModel>
103 #include <QStandardItemModel>
104 #include <QTextCodec>
106 #include <QTranslator>
110 #include <X11/Xatom.h>
111 #include <X11/Xlib.h>
117 #include <QWindowsMime>
124 #include <boost/bind.hpp>
125 #include <boost/crc.hpp>
132 using namespace lyx::support;
135 static void initializeResources()
137 static bool initialized = false;
139 Q_INIT_RESOURCE(Resources);
147 frontend::Application * createApplication(int & argc, char * argv[])
150 // prune -geometry argument(s) by shifting
151 // the following ones 2 places down.
152 for (int i = 0 ; i < argc ; ++i) {
153 if (strcmp(argv[i], "-geometry") == 0) {
154 int const remove = (i+1) < argc ? 2 : 1;
156 for (int j = i; j < argc; ++j)
157 argv[j] = argv[j + remove];
162 return new frontend::GuiApplication(argc, argv);
168 /// Return the list of loadable formats.
169 vector<string> loadableImageFormats()
173 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
175 LYXERR(Debug::GRAPHICS,
176 "\nThe image loader can load the following directly:\n");
178 if (qt_formats.empty())
179 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
181 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
183 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
185 string ext = ascii_lowercase((const char *) *it);
196 ////////////////////////////////////////////////////////////////////////
198 // Icon loading support code
200 ////////////////////////////////////////////////////////////////////////
210 bool operator<(PngMap const & lhs, PngMap const & rhs)
212 return lhs.key < rhs.key;
218 CompareKey(QString const & name) : name_(name) {}
219 bool operator()(PngMap const & other) const { return other.key == name_; }
225 // this must be sorted alphabetically
226 // Upper case comes before lower case
227 PngMap sorted_png_map[] = {
228 { "Bumpeq", "bumpeq2" },
231 { "Delta", "delta2" },
232 { "Diamond", "diamond2" },
233 { "Downarrow", "downarrow2" },
234 { "Gamma", "gamma2" },
235 { "Lambda", "lambda2" },
236 { "Leftarrow", "leftarrow2" },
237 { "Leftrightarrow", "leftrightarrow2" },
238 { "Longleftarrow", "longleftarrow2" },
239 { "Longleftrightarrow", "longleftrightarrow2" },
240 { "Longrightarrow", "longrightarrow2" },
241 { "Omega", "omega2" },
245 { "Rightarrow", "rightarrow2" },
246 { "Sigma", "sigma2" },
247 { "Subset", "subset2" },
248 { "Supset", "supset2" },
249 { "Theta", "theta2" },
250 { "Uparrow", "uparrow2" },
251 { "Updownarrow", "updownarrow2" },
252 { "Upsilon", "upsilon2" },
253 { "Vdash", "vdash3" },
256 { "nLeftarrow", "nleftarrow2" },
257 { "nLeftrightarrow", "nleftrightarrow2" },
258 { "nRightarrow", "nrightarrow2" },
259 { "nVDash", "nvdash3" },
260 { "nvDash", "nvdash2" },
261 { "textrm \\AA", "textrm_AA"},
262 { "textrm \\O", "textrm_O"},
263 { "vDash", "vdash2" }
266 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
269 QString findPng(QString const & name)
271 PngMap const * const begin = sorted_png_map;
272 PngMap const * const end = begin + nr_sorted_png_map;
273 LASSERT(sorted(begin, end), /**/);
275 PngMap const * const it = find_if(begin, end, CompareKey(name));
279 png_name = it->value;
282 png_name.replace('_', "underscore");
283 png_name.replace(' ', '_');
285 // This way we can have "math-delim { }" on the toolbar.
286 png_name.replace('(', "lparen");
287 png_name.replace(')', "rparen");
288 png_name.replace('[', "lbracket");
289 png_name.replace(']', "rbracket");
290 png_name.replace('{', "lbrace");
291 png_name.replace('}', "rbrace");
292 png_name.replace('|', "bars");
293 png_name.replace(',', "thinspace");
294 png_name.replace(':', "mediumspace");
295 png_name.replace(';', "thickspace");
296 png_name.replace('!', "negthinspace");
299 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
300 << "Looking for math PNG called \"" << png_name << '"');
307 QString iconName(FuncRequest const & f, bool unknown)
309 initializeResources();
314 case LFUN_MATH_INSERT:
315 if (!f.argument().empty()) {
317 name1 = findPng(toqstr(f.argument()).mid(1));
320 case LFUN_MATH_DELIM:
321 case LFUN_MATH_BIGDELIM:
323 name1 = findPng(toqstr(f.argument()));
327 name1 = toqstr(f.argument());
329 case LFUN_COMMAND_ALTERNATIVES: {
330 // use the first of the alternative commands
332 docstring dummy = split(f.argument(), firstcom, ';');
333 name1 = toqstr(firstcom);
334 name1.replace(' ', '_');
338 name2 = toqstr(lyxaction.getActionName(f.action));
341 if (!f.argument().empty()) {
342 name1 = name2 + ' ' + toqstr(f.argument());
343 name1.replace(' ', '_');
344 name1.replace('\\', "backslash");
348 FileName fname = libFileSearch("images/" + path, name1, "png");
350 return toqstr(fname.absFilename());
352 fname = libFileSearch("images/" + path, name2, "png");
354 return toqstr(fname.absFilename());
356 path = ":/images/" + path;
359 LYXERR0("Directory " << path << " not found in resource!");
363 if (res.exists(name1))
367 if (res.exists(name2))
370 LYXERR(Debug::GUI, "Cannot find icon with filename "
371 << "\"" << name1 << "\""
373 << "\"" << name2 << "\""
375 << lyxaction.getActionName(f.action)
376 << '(' << to_utf8(f.argument()) << ")\"");
379 fname = libFileSearch(QString("images/"), "unknown", "png");
381 return toqstr(fname.absFilename());
382 return QString(":/images/unknown.png");
388 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
391 FileName fname = libFileSearch(path, name, ext);
392 QString path1 = toqstr(fname.absFilename());
393 QString path2 = ":/" + path + name + "." + ext;
395 if (pixmap.load(path1)) {
398 else if (pixmap.load(path2)) {
402 LYXERR0("Cannot load pixmap \""
403 << path << name << '.' << ext
404 << "\", please verify resource system!");
409 QIcon getIcon(FuncRequest const & f, bool unknown)
411 QString icon = iconName(f, unknown);
415 //LYXERR(Debug::GUI, "Found icon: " << icon);
417 if (!pm.load(icon)) {
418 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
426 ////////////////////////////////////////////////////////////////////////
428 // LyX server support code.
430 ////////////////////////////////////////////////////////////////////////
432 class SocketNotifier : public QSocketNotifier
435 /// connect a connection notification from the LyXServerSocket
436 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
437 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
441 /// The callback function
442 Application::SocketCallback func_;
446 ////////////////////////////////////////////////////////////////////////
448 // Mac specific stuff goes here...
450 ////////////////////////////////////////////////////////////////////////
452 class MenuTranslator : public QTranslator
455 MenuTranslator(QObject * parent)
456 : QTranslator(parent)
459 QString translate(const char * /*context*/,
460 const char * sourceText,
461 const char * /*comment*/ = 0)
463 string const s = sourceText;
464 if (s == N_("About %1") || s == N_("Preferences")
465 || s == N_("Reconfigure") || s == N_("Quit %1"))
472 class GlobalMenuBar : public QMenuBar
476 GlobalMenuBar() : QMenuBar(0) {}
479 bool event(QEvent * e)
481 if (e->type() == QEvent::ShortcutOverride) {
482 // && activeWindow() == 0) {
483 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
485 setKeySymbol(&sym, ke);
486 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
495 // QMacPasteboardMimeGraphics can only be compiled on Mac.
497 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
500 QMacPasteboardMimeGraphics()
501 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
504 QString convertorName() { return "Graphics"; }
506 QString flavorFor(QString const & mime)
508 LYXERR(Debug::ACTION, "flavorFor " << mime);
509 if (mime == pdfMimeType())
510 return QLatin1String("com.adobe.pdf");
514 QString mimeFor(QString flav)
516 LYXERR(Debug::ACTION, "mimeFor " << flav);
517 if (flav == QLatin1String("com.adobe.pdf"))
518 return pdfMimeType();
522 bool canConvert(QString const & mime, QString flav)
524 return mimeFor(flav) == mime;
527 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
531 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
535 QList<QByteArray> convertFromMime(QString const & /*mime*/,
536 QVariant data, QString /*flav*/)
538 QList<QByteArray> ret;
539 ret.append(data.toByteArray());
545 ///////////////////////////////////////////////////////////////
547 // You can find more platform specific stuff at the end of this file...
549 ///////////////////////////////////////////////////////////////
551 ////////////////////////////////////////////////////////////////////////
552 // Windows specific stuff goes here...
555 // QWindowsMimeMetafile can only be compiled on Windows.
557 static FORMATETC cfFromMime(QString const & mimetype)
560 if (mimetype == emfMimeType()) {
561 formatetc.cfFormat = CF_ENHMETAFILE;
562 formatetc.tymed = TYMED_ENHMF;
563 } else if (mimetype == wmfMimeType()) {
564 formatetc.cfFormat = CF_METAFILEPICT;
565 formatetc.tymed = TYMED_MFPICT;
568 formatetc.dwAspect = DVASPECT_CONTENT;
569 formatetc.lindex = -1;
574 class QWindowsMimeMetafile : public QWindowsMime {
576 QWindowsMimeMetafile() {}
578 bool canConvertFromMime(FORMATETC const & formatetc,
579 QMimeData const * mimedata) const
584 bool canConvertToMime(QString const & mimetype,
585 IDataObject * pDataObj) const
587 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
589 FORMATETC formatetc = cfFromMime(mimetype);
590 return pDataObj->QueryGetData(&formatetc) == S_OK;
593 bool convertFromMime(FORMATETC const & formatetc,
594 const QMimeData * mimedata, STGMEDIUM * pmedium) const
599 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
600 QVariant::Type preferredType) const
603 if (!canConvertToMime(mimetype, pDataObj))
606 FORMATETC formatetc = cfFromMime(mimetype);
608 if (pDataObj->GetData(&formatetc, &s) != S_OK)
612 if (s.tymed == TYMED_ENHMF) {
613 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
614 data.resize(dataSize);
615 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
616 (LPBYTE)data.data());
617 } else if (s.tymed == TYMED_MFPICT) {
618 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
619 data.resize(dataSize);
620 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
621 (LPBYTE)data.data());
624 ReleaseStgMedium(&s);
630 QVector<FORMATETC> formatsForMime(QString const & mimetype,
631 QMimeData const * mimedata) const
633 QVector<FORMATETC> formats;
634 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
635 formats += cfFromMime(mimetype);
639 QString mimeForFormat(FORMATETC const & formatetc) const
641 switch (formatetc.cfFormat) {
643 return emfMimeType();
644 case CF_METAFILEPICT:
645 return wmfMimeType();
653 ////////////////////////////////////////////////////////////////////////
654 // GuiApplication::Private definition and implementation.
655 ////////////////////////////////////////////////////////////////////////
657 struct GuiApplication::Private
659 Private(): language_model_(0), meta_fake_bit(NoModifier),
663 /// WMF Mime handler for Windows clipboard.
664 wmf_mime_ = new QWindowsMimeMetafile();
666 initKeySequences(&theTopLevelKeymap());
669 void initKeySequences(KeyMap * kb)
671 keyseq = KeySequence(kb, kb);
672 cancel_meta_seq = KeySequence(kb, kb);
676 QSortFilterProxyModel * language_model_;
678 GuiClipboard clipboard_;
680 GuiSelection selection_;
682 FontLoader font_loader_;
684 ColorCache color_cache_;
686 QTranslator qt_trans_;
688 QHash<int, SocketNotifier *> socket_notifiers_;
692 /// The global instance
695 /// this timer is used for any regular events one wants to
696 /// perform. at present it is used to check if forked processes
698 QTimer general_timer_;
700 /// delayed FuncRequests
701 std::queue<FuncRequest> func_request_queue_;
706 KeySequence cancel_meta_seq;
708 KeyModifier meta_fake_bit;
710 /// Multiple views container.
712 * Warning: This must not be a smart pointer as the destruction of the
713 * object is handled by Qt when the view is closed
714 * \sa Qt::WA_DeleteOnClose attribute.
716 QHash<int, GuiView *> views_;
718 /// Only used on mac.
719 GlobalMenuBar * global_menubar_;
722 /// Linkback mime handler for MacOSX.
723 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
727 /// WMF Mime handler for Windows clipboard.
728 QWindowsMimeMetafile * wmf_mime_;
733 GuiApplication * guiApp;
735 GuiApplication::~GuiApplication()
738 closeAllLinkBackLinks();
744 GuiApplication::GuiApplication(int & argc, char ** argv)
745 : QApplication(argc, argv), current_view_(0),
746 d(new GuiApplication::Private)
748 QString app_name = "LyX";
749 QCoreApplication::setOrganizationName(app_name);
750 QCoreApplication::setOrganizationDomain("lyx.org");
751 QCoreApplication::setApplicationName(lyx_package);
753 // Install translator for GUI elements.
754 installTranslator(&d->qt_trans_);
756 // FIXME: quitOnLastWindowClosed is true by default. We should have a
757 // lyxrc setting for this in order to let the application stay resident.
758 // But then we need some kind of dock icon, at least on Windows.
760 if (lyxrc.quit_on_last_window_closed)
761 setQuitOnLastWindowClosed(false);
764 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
765 // seems to be the default case for applications like LyX.
766 setQuitOnLastWindowClosed(false);
768 // This allows to translate the strings that appear in the LyX menu.
769 /// A translator suitable for the entries in the LyX menu.
770 /// Only needed with Qt/Mac.
771 installTranslator(new MenuTranslator(this));
775 // doubleClickInterval() is 400 ms on X11 which is just too long.
776 // On Windows and Mac OS X, the operating system's value is used.
777 // On Microsoft Windows, calling this function sets the double
778 // click interval for all applications. So we don't!
779 QApplication::setDoubleClickInterval(300);
782 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
784 // needs to be done before reading lyxrc
786 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
790 // Set the cache to 5120 kilobytes which corresponds to screen size of
791 // 1280 by 1024 pixels with a color depth of 32 bits.
792 QPixmapCache::setCacheLimit(5120);
794 // Initialize RC Fonts
795 if (lyxrc.roman_font_name.empty())
796 lyxrc.roman_font_name = fromqstr(romanFontName());
798 if (lyxrc.sans_font_name.empty())
799 lyxrc.sans_font_name = fromqstr(sansFontName());
801 if (lyxrc.typewriter_font_name.empty())
802 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
804 d->general_timer_.setInterval(500);
805 connect(&d->general_timer_, SIGNAL(timeout()),
806 this, SLOT(handleRegularEvents()));
807 d->general_timer_.start();
811 GuiApplication * theGuiApp()
813 return dynamic_cast<GuiApplication *>(theApp());
817 void GuiApplication::clearSession()
824 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
826 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
830 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
834 if (cmd.action == LFUN_NOACTION) {
835 flag.message(from_utf8(N_("Nothing to do")));
836 flag.setEnabled(false);
840 if (cmd.action == LFUN_UNKNOWN_ACTION) {
842 flag.setEnabled(false);
843 flag.message(from_utf8(N_("Unknown action")));
847 // I would really like to avoid having this switch and rather try to
848 // encode this in the function itself.
849 // -- And I'd rather let an inset decide which LFUNs it is willing
850 // to handle (Andre')
852 switch (cmd.action) {
854 // This could be used for the no-GUI version. The GUI version is handled in
855 // GuiView::getStatus(). See above.
857 case LFUN_BUFFER_WRITE:
858 case LFUN_BUFFER_WRITE_AS: {
859 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
860 enable = b && (b->isUnnamed() || !b->isClean());
865 case LFUN_BOOKMARK_GOTO: {
866 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
867 enable = theSession().bookmarks().isValid(num);
871 case LFUN_BOOKMARK_CLEAR:
872 enable = theSession().bookmarks().hasValid();
875 // this one is difficult to get right. As a half-baked
876 // solution, we consider only the first action of the sequence
877 case LFUN_COMMAND_SEQUENCE: {
878 // argument contains ';'-terminated commands
879 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
880 FuncRequest func(lyxaction.lookupFunc(firstcmd));
881 func.origin = cmd.origin;
882 flag = getStatus(func);
886 // we want to check if at least one of these is enabled
887 case LFUN_COMMAND_ALTERNATIVES: {
888 // argument contains ';'-terminated commands
889 string arg = to_utf8(cmd.argument());
890 while (!arg.empty()) {
892 arg = split(arg, first, ';');
893 FuncRequest func(lyxaction.lookupFunc(first));
894 func.origin = cmd.origin;
895 flag = getStatus(func);
896 // if this one is enabled, the whole thing is
905 string name = to_utf8(cmd.argument());
906 if (theTopLevelCmdDef().lock(name, func)) {
907 func.origin = cmd.origin;
908 flag = getStatus(func);
909 theTopLevelCmdDef().release(name);
911 // catch recursion or unknown command
912 // definition. all operations until the
913 // recursion or unknown command definition
914 // occurs are performed, so set the state to
921 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
923 case LFUN_PREFERENCES_SAVE:
924 case LFUN_BUFFER_SAVE_AS_DEFAULT:
925 case LFUN_DEBUG_LEVEL_SET:
926 // these are handled in our dispatch()
929 case LFUN_WINDOW_CLOSE:
930 enable = d->views_.size() > 0;
933 case LFUN_BUFFER_NEW:
934 case LFUN_BUFFER_NEW_TEMPLATE:
937 case LFUN_SCREEN_FONT_UPDATE:
939 case LFUN_WINDOW_NEW:
941 case LFUN_LYXRC_APPLY:
942 case LFUN_COMMAND_PREFIX:
944 case LFUN_META_PREFIX:
945 case LFUN_RECONFIGURE:
946 case LFUN_SERVER_GET_FILENAME:
947 case LFUN_SERVER_NOTIFY:
952 // Does the view know something?
953 if (!current_view_) {
958 if (current_view_->getStatus(cmd, flag))
961 // In LyX/Mac, when a dialog is open, the menus of the
962 // application can still be accessed without giving focus to
963 // the main window. In this case, we want to disable the menu
964 // entries that are buffer or view-related.
965 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
967 if (cmd.origin == FuncRequest::MENU && !current_view_->hasFocus()) {
973 BufferView * bv = current_view_->currentBufferView();
974 BufferView * doc_bv = current_view_->documentBufferView();
975 // If we do not have a BufferView, then other functions are disabled
980 // try the BufferView
981 bool decided = bv->getStatus(cmd, flag);
984 decided = bv->buffer().getStatus(cmd, flag);
985 if (!decided && doc_bv)
986 // try the Document Buffer
987 decided = doc_bv->buffer().getStatus(cmd, flag);
991 flag.setEnabled(false);
993 // the default error message if we disable the command
994 if (!flag.enabled() && flag.message().empty())
995 flag.message(from_utf8(N_("Command disabled")));
1000 /// make a post-dispatch status message
1001 static docstring makeDispatchMessage(docstring const & msg,
1002 FuncRequest const & cmd)
1004 const bool verbose = (cmd.origin == FuncRequest::MENU
1005 || cmd.origin == FuncRequest::TOOLBAR
1006 || cmd.origin == FuncRequest::COMMANDBUFFER);
1008 if (cmd.action == LFUN_SELF_INSERT || !verbose) {
1009 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1013 docstring dispatch_msg = msg;
1014 if (!dispatch_msg.empty())
1015 dispatch_msg += ' ';
1017 docstring comname = from_utf8(lyxaction.getActionName(cmd.action));
1019 bool argsadded = false;
1021 if (!cmd.argument().empty()) {
1022 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1023 comname += ' ' + cmd.argument();
1027 docstring const shortcuts = theTopLevelKeymap().
1028 printBindings(cmd, KeySequence::ForGui);
1030 if (!shortcuts.empty())
1031 comname += ": " + shortcuts;
1032 else if (!argsadded && !cmd.argument().empty())
1033 comname += ' ' + cmd.argument();
1035 if (!comname.empty()) {
1036 comname = rtrim(comname);
1037 dispatch_msg += '(' + rtrim(comname) + ')';
1039 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1040 return dispatch_msg;
1044 void GuiApplication::dispatch(FuncRequest const & cmd)
1046 if (current_view_ && current_view_->currentBufferView())
1047 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1050 // redraw the screen at the end (first of the two drawing steps).
1051 //This is done unless explicitly requested otherwise
1052 dr.update(Update::FitCursor);
1058 BufferView * bv = current_view_->currentBufferView();
1060 // BufferView::update() updates the ViewMetricsInfo and
1061 // also initializes the position cache for all insets in
1062 // (at least partially) visible top-level paragraphs.
1063 // We will redraw the screen only if needed.
1064 bv->processUpdateFlags(dr.update());
1066 // Do we have a selection?
1067 theSelection().haveSelection(bv->cursor().selection());
1070 current_view_->restartCursor();
1072 // Some messages may already be translated, so we cannot use _()
1073 current_view_->message(makeDispatchMessage(
1074 translateIfPossible(dr.message()), cmd));
1078 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
1080 GuiView * lv = current_view_;
1082 if (!theSession().bookmarks().isValid(idx))
1084 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
1085 LASSERT(!bm.filename.empty(), /**/);
1086 string const file = bm.filename.absFilename();
1087 // if the file is not opened, open it.
1088 if (!theBufferList().exists(bm.filename)) {
1090 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1094 // open may fail, so we need to test it again
1095 if (!theBufferList().exists(bm.filename))
1098 // bm can be changed when saving
1099 BookmarksSection::Bookmark tmp = bm;
1101 // Special case idx == 0 used for back-from-back jump navigation
1103 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1105 // if the current buffer is not that one, switch to it.
1106 if (!lv->documentBufferView()
1107 || lv->documentBufferView()->buffer().fileName() != tmp.filename) {
1108 if (!switchToBuffer)
1110 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1113 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1114 if (!lv->documentBufferView()->moveToPosition(
1115 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1122 // Cursor jump succeeded!
1123 Cursor const & cur = lv->documentBufferView()->cursor();
1124 pit_type new_pit = cur.pit();
1125 pos_type new_pos = cur.pos();
1126 int new_id = cur.paragraph().id();
1128 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1129 // see http://www.lyx.org/trac/ticket/3092
1130 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1131 || bm.top_id != new_id) {
1132 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1133 new_pit, new_pos, new_id);
1137 // This function runs "configure" and then rereads lyx.defaults to
1138 // reconfigure the automatic settings.
1139 static void reconfigure(GuiView * lv, string const & option)
1141 // emit message signal.
1143 lv->message(_("Running configure..."));
1145 // Run configure in user lyx directory
1146 PathChanger p(package().user_support());
1147 string configure_command = package().configure_command();
1148 configure_command += option;
1150 int ret = one.startscript(Systemcall::Wait, configure_command);
1152 // emit message signal.
1154 lv->message(_("Reloading configuration..."));
1155 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1156 // Re-read packages.lst
1157 LaTeXFeatures::getAvailable();
1160 Alert::information(_("System reconfiguration failed"),
1161 _("The system reconfiguration has failed.\n"
1162 "Default textclass is used but LyX may "
1163 "not be able to work properly.\n"
1164 "Please reconfigure again if needed."));
1167 Alert::information(_("System reconfigured"),
1168 _("The system has been reconfigured.\n"
1169 "You need to restart LyX to make use of any\n"
1170 "updated document class specifications."));
1175 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1177 string const argument = to_utf8(cmd.argument());
1178 FuncCode const action = cmd.action;
1180 LYXERR(Debug::ACTION, "cmd: " << cmd);
1182 // we have not done anything wrong yet.
1185 FuncStatus const flag = getStatus(cmd);
1186 if (!flag.enabled()) {
1187 // We cannot use this function here
1188 LYXERR(Debug::ACTION, "action "
1189 << lyxaction.getActionName(action)
1190 << " [" << action << "] is disabled at this location");
1192 current_view_->restartCursor();
1193 dr.setMessage(flag.message());
1195 dr.dispatched(false);
1196 dr.update(Update::None);
1200 // Assumes that the action will be dispatched.
1201 dr.dispatched(true);
1203 switch (cmd.action) {
1205 case LFUN_WINDOW_NEW:
1206 createView(toqstr(cmd.argument()));
1209 case LFUN_WINDOW_CLOSE:
1210 // update bookmark pit of the current buffer before window close
1211 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1212 gotoBookmark(i+1, false, false);
1213 // clear the last opened list, because
1214 // maybe this will end the session
1215 theSession().lastOpened().clear();
1216 current_view_->close();
1220 // quitting is triggered by the gui code
1221 // (leaving the event loop).
1223 current_view_->message(from_utf8(N_("Exiting.")));
1224 if (closeAllViews())
1228 case LFUN_SCREEN_FONT_UPDATE: {
1229 // handle the screen font changes.
1230 d->font_loader_.update();
1231 // Backup current_view_
1232 GuiView * view = current_view_;
1233 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1234 // to skip the refresh.
1236 theBufferList().changed(false);
1237 // Restore current_view_
1238 current_view_ = view;
1242 case LFUN_BUFFER_NEW:
1243 if (d->views_.empty()
1244 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1245 createView(QString(), false); // keep hidden
1246 current_view_->newDocument(to_utf8(cmd.argument()), false);
1247 current_view_->show();
1248 setActiveWindow(current_view_);
1250 current_view_->newDocument(to_utf8(cmd.argument()), false);
1254 case LFUN_BUFFER_NEW_TEMPLATE:
1255 if (d->views_.empty()
1256 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1258 current_view_->newDocument(to_utf8(cmd.argument()), true);
1259 if (!current_view_->documentBufferView())
1260 current_view_->close();
1262 current_view_->newDocument(to_utf8(cmd.argument()), true);
1266 case LFUN_FILE_OPEN:
1267 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1268 if (d->views_.empty()
1269 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1270 string const fname = to_utf8(cmd.argument());
1271 // We want the ui session to be saved per document and not per
1272 // window number. The filename crc is a good enough identifier.
1273 boost::crc_32_type crc;
1274 crc = for_each(fname.begin(), fname.end(), crc);
1275 createView(crc.checksum());
1276 current_view_->openDocument(fname);
1277 if (current_view_ && !current_view_->documentBufferView())
1278 current_view_->close();
1280 current_view_->openDocument(to_utf8(cmd.argument()));
1283 case LFUN_HELP_OPEN: {
1284 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1285 if (current_view_ == 0)
1287 string const arg = to_utf8(cmd.argument());
1289 current_view_->message(_("Missing argument"));
1292 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1294 fname = i18nLibFileSearch("examples", arg, "lyx");
1296 if (fname.empty()) {
1297 lyxerr << "LyX: unable to find documentation file `"
1298 << arg << "'. Bad installation?" << endl;
1301 current_view_->message(bformat(_("Opening help file %1$s..."),
1302 makeDisplayPath(fname.absFilename())));
1303 Buffer * buf = current_view_->loadDocument(fname, false);
1305 current_view_->setBuffer(buf);
1306 #ifndef DEVEL_VERSION
1307 buf->setReadonly(true);
1309 buf->updateLabels();
1310 buf->errors("Parse");
1315 case LFUN_SET_COLOR: {
1317 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1318 if (lyx_name.empty() || x11_name.empty()) {
1319 current_view_->message(
1320 _("Syntax: set-color <lyx_name> <x11_name>"));
1324 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1325 bool const graphicsbg_changed =
1326 lyx_name == graphicsbg && x11_name != graphicsbg;
1327 if (graphicsbg_changed) {
1328 // FIXME: The graphics cache no longer has a changeDisplay method.
1330 graphics::GCache::get().changeDisplay(true);
1334 if (!lcolor.setColor(lyx_name, x11_name)) {
1335 current_view_->message(
1336 bformat(_("Set-color \"%1$s\" failed "
1337 "- color is undefined or "
1338 "may not be redefined"),
1339 from_utf8(lyx_name)));
1342 // Make sure we don't keep old colors in cache.
1343 d->color_cache_.clear();
1347 case LFUN_LYXRC_APPLY: {
1348 // reset active key sequences, since the bindings
1349 // are updated (bug 6064)
1351 LyXRC const lyxrc_orig = lyxrc;
1353 istringstream ss(to_utf8(cmd.argument()));
1354 bool const success = lyxrc.read(ss) == 0;
1357 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1358 << "Unable to read lyxrc data"
1363 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1370 case LFUN_COMMAND_PREFIX:
1371 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1376 d->meta_fake_bit = NoModifier;
1377 GuiView * gv = currentView();
1378 if (gv && gv->currentBufferView())
1379 // cancel any selection
1380 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1381 dr.setMessage(from_ascii(N_("Cancel")));
1384 case LFUN_META_PREFIX:
1385 d->meta_fake_bit = AltModifier;
1386 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1389 // --- Menus -----------------------------------------------
1390 case LFUN_RECONFIGURE:
1391 // argument is any additional parameter to the configure.py command
1392 reconfigure(currentView(), to_utf8(cmd.argument()));
1395 // --- lyxserver commands ----------------------------
1396 case LFUN_SERVER_GET_FILENAME: {
1397 GuiView * lv = currentView();
1398 LASSERT(lv && lv->documentBufferView(), return);
1399 docstring const fname = from_utf8(
1400 lv->documentBufferView()->buffer().absFileName());
1401 dr.setMessage(fname);
1402 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1405 case LFUN_SERVER_NOTIFY: {
1406 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1407 dr.setMessage(dispatch_buffer);
1408 theServer().notifyClient(to_utf8(dispatch_buffer));
1412 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1413 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1419 string rest = split(argument, countstr, ' ');
1420 istringstream is(countstr);
1423 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1424 for (int i = 0; i < count; ++i)
1425 dispatch(lyxaction.lookupFunc(rest));
1429 case LFUN_COMMAND_SEQUENCE: {
1430 // argument contains ';'-terminated commands
1431 string arg = argument;
1432 // FIXME: this LFUN should also work without any view.
1433 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1434 ? &(current_view_->documentBufferView()->buffer()) : 0;
1436 buffer->undo().beginUndoGroup();
1437 while (!arg.empty()) {
1439 arg = split(arg, first, ';');
1440 FuncRequest func(lyxaction.lookupFunc(first));
1441 func.origin = cmd.origin;
1444 // the buffer may have been closed by one action
1445 if (theBufferList().isLoaded(buffer))
1446 buffer->undo().endUndoGroup();
1450 case LFUN_COMMAND_ALTERNATIVES: {
1451 // argument contains ';'-terminated commands
1452 string arg = argument;
1453 while (!arg.empty()) {
1455 arg = split(arg, first, ';');
1456 FuncRequest func(lyxaction.lookupFunc(first));
1457 func.origin = cmd.origin;
1458 FuncStatus stat = getStatus(func);
1459 if (stat.enabled()) {
1469 if (theTopLevelCmdDef().lock(argument, func)) {
1470 func.origin = cmd.origin;
1472 theTopLevelCmdDef().release(argument);
1474 if (func.action == LFUN_UNKNOWN_ACTION) {
1475 // unknown command definition
1476 lyxerr << "Warning: unknown command definition `"
1480 // recursion detected
1481 lyxerr << "Warning: Recursion in the command definition `"
1482 << argument << "' detected"
1489 case LFUN_PREFERENCES_SAVE:
1490 lyxrc.write(support::makeAbsPath("preferences",
1491 package().user_support().absFilename()), false);
1494 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1495 string const fname = addName(addPath(package().user_support().absFilename(),
1496 "templates/"), "defaults.lyx");
1497 Buffer defaults(fname);
1499 istringstream ss(argument);
1502 int const unknown_tokens = defaults.readHeader(lex);
1504 if (unknown_tokens != 0) {
1505 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1506 << unknown_tokens << " unknown token"
1507 << (unknown_tokens == 1 ? "" : "s")
1511 if (defaults.writeFile(FileName(defaults.absFileName())))
1512 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1513 makeDisplayPath(fname)));
1516 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1521 case LFUN_BOOKMARK_GOTO:
1522 // go to bookmark, open unopened file and switch to buffer if necessary
1523 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1524 dr.update(Update::FitCursor);
1527 case LFUN_BOOKMARK_CLEAR:
1528 theSession().bookmarks().clear();
1531 case LFUN_DEBUG_LEVEL_SET:
1532 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1536 // Notify the caller that the action has not been dispatched.
1537 dr.dispatched(false);
1541 // The action has been dispatched in this method, nothing more to do.
1542 if (dr.dispatched())
1545 GuiView * lv = current_view_;
1547 // Everything below is only for active window
1551 // Let the current GuiView dispatch its own actions.
1552 lv->dispatch(cmd, dr);
1553 if (dr.dispatched() && lv )
1556 BufferView * bv = lv->currentBufferView();
1559 // Let the current BufferView dispatch its own actions.
1560 bv->dispatch(cmd, dr);
1561 if (dr.dispatched())
1564 BufferView * doc_bv = lv->documentBufferView();
1565 // Try with the document BufferView dispatch if any.
1567 doc_bv->dispatch(cmd, dr);
1568 if (dr.dispatched())
1572 // OK, so try the current Buffer itself...
1573 bv->buffer().dispatch(cmd, dr);
1574 if (dr.dispatched())
1577 // and with the document Buffer.
1579 doc_bv->buffer().dispatch(cmd, dr);
1580 if (dr.dispatched())
1584 // Let the current Cursor dispatch its own actions.
1585 Cursor old = bv->cursor();
1586 bv->cursor().dispatch(cmd);
1588 // notify insets we just left
1589 if (bv->cursor() != old) {
1591 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1593 bv->cursor().fixIfBroken();
1596 // update completion. We do it here and not in
1597 // processKeySym to avoid another redraw just for a
1598 // changed inline completion
1599 if (cmd.origin == FuncRequest::KEYBOARD) {
1600 if (cmd.action == LFUN_SELF_INSERT
1601 || (cmd.action == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1602 lv->updateCompletion(bv->cursor(), true, true);
1603 else if (cmd.action == LFUN_CHAR_DELETE_BACKWARD)
1604 lv->updateCompletion(bv->cursor(), false, true);
1606 lv->updateCompletion(bv->cursor(), false, false);
1609 dr = bv->cursor().result();
1611 // if we executed a mutating lfun, mark the buffer as dirty
1612 Buffer * doc_buffer = (lv && lv->documentBufferView())
1613 ? &(lv->documentBufferView()->buffer()) : 0;
1614 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1616 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1617 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1618 lv->currentBufferView()->buffer().markDirty();
1622 docstring GuiApplication::viewStatusMessage()
1624 // When meta-fake key is pressed, show the key sequence so far + "M-".
1625 if (d->meta_fake_bit != NoModifier)
1626 return d->keyseq.print(KeySequence::ForGui) + "M-";
1628 // Else, when a non-complete key sequence is pressed,
1629 // show the available options.
1630 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1631 return d->keyseq.printOptions(true);
1637 void GuiApplication::handleKeyFunc(FuncCode action)
1641 if (d->keyseq.length())
1643 GuiView * gv = currentView();
1644 LASSERT(gv && gv->currentBufferView(), return);
1645 BufferView * bv = gv->currentBufferView();
1646 bv->getIntl().getTransManager().deadkey(
1647 c, get_accent(action).accent, bv->cursor().innerText(),
1649 // Need to clear, in case the minibuffer calls these
1652 // copied verbatim from do_accent_char
1653 bv->cursor().resetAnchor();
1654 bv->processUpdateFlags(Update::FitCursor);
1658 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1660 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1662 GuiView * lv = currentView();
1664 // Do nothing if we have nothing (JMarc)
1665 if (!keysym.isOK()) {
1666 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1667 lv->restartCursor();
1671 if (keysym.isModifier()) {
1672 LYXERR(Debug::KEY, "isModifier true");
1674 lv->restartCursor();
1678 char_type encoded_last_key = keysym.getUCSEncoded();
1680 // Do a one-deep top-level lookup for
1681 // cancel and meta-fake keys. RVDK_PATCH_5
1682 d->cancel_meta_seq.reset();
1684 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1685 LYXERR(Debug::KEY, "action first set to [" << func.action << ']');
1687 // When not cancel or meta-fake, do the normal lookup.
1688 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1689 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1690 if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_PREFIX)) {
1691 // remove Caps Lock and Mod2 as a modifiers
1692 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1693 LYXERR(Debug::KEY, "action now set to [" << func.action << ']');
1696 // Dont remove this unless you know what you are doing.
1697 d->meta_fake_bit = NoModifier;
1699 // Can this happen now ?
1700 if (func.action == LFUN_NOACTION)
1701 func = FuncRequest(LFUN_COMMAND_PREFIX);
1703 LYXERR(Debug::KEY, " Key [action=" << func.action << "]["
1704 << d->keyseq.print(KeySequence::Portable) << ']');
1706 // already here we know if it any point in going further
1707 // why not return already here if action == -1 and
1708 // num_bytes == 0? (Lgb)
1710 if (d->keyseq.length() > 1)
1711 lv->message(d->keyseq.print(KeySequence::ForGui));
1714 // Maybe user can only reach the key via holding down shift.
1715 // Let's see. But only if shift is the only modifier
1716 if (func.action == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1717 LYXERR(Debug::KEY, "Trying without shift");
1718 func = d->keyseq.addkey(keysym, NoModifier);
1719 LYXERR(Debug::KEY, "Action now " << func.action);
1722 if (func.action == LFUN_UNKNOWN_ACTION) {
1723 // Hmm, we didn't match any of the keysequences. See
1724 // if it's normal insertable text not already covered
1726 if (keysym.isText() && d->keyseq.length() == 1) {
1727 LYXERR(Debug::KEY, "isText() is true, inserting.");
1728 func = FuncRequest(LFUN_SELF_INSERT,
1729 FuncRequest::KEYBOARD);
1731 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1732 lv->message(_("Unknown function."));
1733 lv->restartCursor();
1738 if (func.action == LFUN_SELF_INSERT) {
1739 if (encoded_last_key != 0) {
1740 docstring const arg(1, encoded_last_key);
1741 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
1742 FuncRequest::KEYBOARD));
1743 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1746 lyx::dispatch(func);
1753 void GuiApplication::dispatchDelayed(FuncRequest const & func)
1755 d->func_request_queue_.push(func);
1756 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
1760 void GuiApplication::resetGui()
1762 // Set the language defined by the user.
1766 if (!readUIFile(toqstr(lyxrc.ui_file)))
1767 // Gives some error box here.
1770 if (d->global_menubar_)
1771 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1773 QHash<int, GuiView *>::iterator it;
1774 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1777 gv->setLayoutDirection(layoutDirection());
1781 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1785 void GuiApplication::createView(int view_id)
1787 createView(QString(), true, view_id);
1791 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1794 // release the keyboard which might have been grabed by the global
1795 // menubar on Mac to catch shortcuts even without any GuiView.
1796 if (d->global_menubar_)
1797 d->global_menubar_->releaseKeyboard();
1801 while (d->views_.find(id) != d->views_.end())
1804 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1805 GuiView * view = new GuiView(id);
1807 d->views_[id] = view;
1811 setActiveWindow(view);
1814 if (!geometry_arg.isEmpty()) {
1818 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1819 re.indexIn(geometry_arg);
1820 w = re.cap(1).toInt();
1821 h = re.cap(2).toInt();
1822 x = re.cap(3).toInt();
1823 y = re.cap(4).toInt();
1824 view->setGeometry(x, y, w, h);
1831 Clipboard & GuiApplication::clipboard()
1833 return d->clipboard_;
1837 Selection & GuiApplication::selection()
1839 return d->selection_;
1843 FontLoader & GuiApplication::fontLoader()
1845 return d->font_loader_;
1849 Toolbars const & GuiApplication::toolbars() const
1851 return d->toolbars_;
1855 Toolbars & GuiApplication::toolbars()
1857 return d->toolbars_;
1861 Menus const & GuiApplication::menus() const
1867 Menus & GuiApplication::menus()
1873 QList<int> GuiApplication::viewIds() const
1875 return d->views_.keys();
1879 ColorCache & GuiApplication::colorCache()
1881 return d->color_cache_;
1885 int GuiApplication::exec()
1887 // asynchronously handle batch commands. This event will be in
1888 // the event queue in front of other asynchronous events. Hence,
1889 // we can assume in the latter that the gui is setup already.
1890 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1892 return QApplication::exec();
1896 void GuiApplication::exit(int status)
1898 QApplication::exit(status);
1902 void GuiApplication::setGuiLanguage()
1904 // Set the language defined by the user.
1907 QString const default_language = toqstr(Messages::defaultLanguage());
1908 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1909 QLocale const default_locale(default_language);
1910 QLocale::setDefault(default_locale);
1912 // install translation file for Qt built-in dialogs
1913 QString const language_name = QString("qt_") + default_locale.name();
1915 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1916 // Short-named translator can be loaded from a long name, but not the
1917 // opposite. Therefore, long name should be used without truncation.
1918 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1919 if (!d->qt_trans_.load(language_name,
1920 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1921 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1924 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1928 switch (default_locale.language()) {
1929 case QLocale::Arabic :
1930 case QLocale::Hebrew :
1931 case QLocale::Persian :
1932 case QLocale::Urdu :
1933 setLayoutDirection(Qt::RightToLeft);
1936 setLayoutDirection(Qt::LeftToRight);
1941 void GuiApplication::processFuncRequestQueue()
1943 while (!d->func_request_queue_.empty()) {
1944 lyx::dispatch(d->func_request_queue_.back());
1945 d->func_request_queue_.pop();
1950 void GuiApplication::execBatchCommands()
1955 if (!readUIFile(toqstr(lyxrc.ui_file)))
1956 // Gives some error box here.
1960 // Create the global default menubar which is shown for the dialogs
1961 // and if no GuiView is visible.
1962 // This must be done after the session was recovered to know the "last files".
1963 d->global_menubar_ = new GlobalMenuBar();
1964 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
1967 lyx::execBatchCommands();
1971 QAbstractItemModel * GuiApplication::languageModel()
1973 if (d->language_model_)
1974 return d->language_model_;
1976 QStandardItemModel * lang_model = new QStandardItemModel(this);
1977 lang_model->insertColumns(0, 3);
1979 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
1980 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
1981 Languages::const_iterator it = lyx::languages.begin();
1982 Languages::const_iterator end = lyx::languages.end();
1983 for (; it != end; ++it) {
1984 current_row = lang_model->rowCount();
1985 lang_model->insertRows(current_row, 1);
1986 QModelIndex pl_item = lang_model->index(current_row, 0);
1987 QModelIndex sp_item = lang_model->index(current_row, 1);
1988 QModelIndex th_item = lang_model->index(current_row, 2);
1989 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
1990 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
1991 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
1992 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
1993 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
1994 lang_model->setData(sp_item, speller, Qt::DecorationRole);
1995 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
1996 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
1997 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
1998 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2000 d->language_model_ = new QSortFilterProxyModel(this);
2001 d->language_model_->setSourceModel(lang_model);
2002 #if QT_VERSION >= 0x040300
2003 d->language_model_->setSortLocaleAware(true);
2005 return d->language_model_;
2009 void GuiApplication::restoreGuiSession()
2011 if (!lyxrc.load_session)
2014 Session & session = theSession();
2015 LastOpenedSection::LastOpened const & lastopened =
2016 session.lastOpened().getfiles();
2018 FileName active_file;
2019 // do not add to the lastfile list since these files are restored from
2020 // last session, and should be already there (regular files), or should
2021 // not be added at all (help files).
2022 for (size_t i = 0; i < lastopened.size(); ++i) {
2023 FileName const & file_name = lastopened[i].file_name;
2024 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2025 && current_view_->documentBufferView() != 0)) {
2026 boost::crc_32_type crc;
2027 string const & fname = file_name.absFilename();
2028 crc = for_each(fname.begin(), fname.end(), crc);
2029 createView(crc.checksum());
2031 current_view_->loadDocument(file_name, false);
2033 if (lastopened[i].active)
2034 active_file = file_name;
2037 // Restore last active buffer
2038 Buffer * buffer = theBufferList().getBuffer(active_file);
2040 current_view_->setBuffer(buffer);
2042 // clear this list to save a few bytes of RAM
2043 session.lastOpened().clear();
2047 QString const GuiApplication::romanFontName()
2050 font.setKerning(false);
2051 font.setStyleHint(QFont::Serif);
2052 font.setFamily("serif");
2054 return QFontInfo(font).family();
2058 QString const GuiApplication::sansFontName()
2061 font.setKerning(false);
2062 font.setStyleHint(QFont::SansSerif);
2063 font.setFamily("sans");
2065 return QFontInfo(font).family();
2069 QString const GuiApplication::typewriterFontName()
2072 font.setKerning(false);
2073 font.setStyleHint(QFont::TypeWriter);
2074 font.setFamily("monospace");
2076 return QFontInfo(font).family();
2080 void GuiApplication::handleRegularEvents()
2082 ForkedCallsController::handleCompletedProcesses();
2086 bool GuiApplication::event(QEvent * e)
2089 case QEvent::FileOpen: {
2090 // Open a file; this happens only on Mac OS X for now.
2092 // We do this asynchronously because on startup the batch
2093 // commands are not executed here yet and the gui is not ready
2095 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2096 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
2101 return QApplication::event(e);
2106 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2109 return QApplication::notify(receiver, event);
2111 catch (ExceptionMessage const & e) {
2113 case ErrorException:
2115 setQuitOnLastWindowClosed(false);
2117 Alert::error(e.title_, e.details_);
2119 // Properly crash in debug mode in order to get a useful backtrace.
2122 // In release mode, try to exit gracefully.
2125 case BufferException: {
2126 if (!current_view_->documentBufferView())
2128 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2129 docstring details = e.details_ + '\n';
2130 details += buf->emergencyWrite();
2131 theBufferList().release(buf);
2132 details += "\n" + _("The current document was closed.");
2133 Alert::error(e.title_, details);
2136 case WarningException:
2137 Alert::warning(e.title_, e.details_);
2141 catch (exception const & e) {
2142 docstring s = _("LyX has caught an exception, it will now "
2143 "attempt to save all unsaved documents and exit."
2145 s += from_ascii(e.what());
2146 Alert::error(_("Software exception Detected"), s);
2150 docstring s = _("LyX has caught some really weird exception, it will "
2151 "now attempt to save all unsaved documents and exit.");
2152 Alert::error(_("Software exception Detected"), s);
2160 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2162 QColor const & qcol = d->color_cache_.get(col);
2163 if (!qcol.isValid()) {
2169 rgbcol.r = qcol.red();
2170 rgbcol.g = qcol.green();
2171 rgbcol.b = qcol.blue();
2176 string const GuiApplication::hexName(ColorCode col)
2178 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2182 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2184 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2185 d->socket_notifiers_[fd] = sn;
2186 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2190 void GuiApplication::socketDataReceived(int fd)
2192 d->socket_notifiers_[fd]->func_();
2196 void GuiApplication::unregisterSocketCallback(int fd)
2198 d->socket_notifiers_.take(fd)->setEnabled(false);
2202 void GuiApplication::commitData(QSessionManager & sm)
2204 /// The implementation is required to avoid an application exit
2205 /// when session state save is triggered by session manager.
2206 /// The default implementation sends a close event to all
2207 /// visible top level widgets when session managment allows
2209 /// We are changing that to close all wiew one by one.
2210 /// FIXME: verify if the default implementation is enough now.
2211 if (sm.allowsInteraction() && !closeAllViews())
2216 void GuiApplication::unregisterView(GuiView * gv)
2218 LASSERT(d->views_[gv->id()] == gv, /**/);
2219 d->views_.remove(gv->id());
2220 if (current_view_ == gv)
2225 bool GuiApplication::closeAllViews()
2227 if (d->views_.empty())
2230 // When a view/window was closed before without quitting LyX, there
2231 // are already entries in the lastOpened list.
2232 theSession().lastOpened().clear();
2234 QList<GuiView *> views = d->views_.values();
2235 foreach (GuiView * view, views) {
2245 GuiView & GuiApplication::view(int id) const
2247 LASSERT(d->views_.contains(id), /**/);
2248 return *d->views_.value(id);
2252 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2254 QList<GuiView *> views = d->views_.values();
2255 foreach (GuiView * view, views)
2256 view->hideDialog(name, inset);
2260 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2262 Buffer const * buffer_ = 0;
2263 QHash<int, GuiView *>::iterator end = d->views_.end();
2264 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2265 if (Buffer const * ptr = (*it)->updateInset(inset))
2272 bool GuiApplication::searchMenu(FuncRequest const & func,
2273 docstring_list & names) const
2275 return d->menus_.searchMenu(func, names);
2279 bool GuiApplication::readUIFile(QString const & name, bool include)
2281 LYXERR(Debug::INIT, "About to read " << name << "...");
2285 ui_path = libFileSearch("ui", name, "inc");
2286 if (ui_path.empty())
2287 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2289 ui_path = libFileSearch("ui", name, "ui");
2292 if (ui_path.empty()) {
2293 static const QString defaultUIFile = "default";
2294 LYXERR(Debug::INIT, "Could not find " << name);
2296 Alert::warning(_("Could not find UI definition file"),
2297 bformat(_("Error while reading the included file\n%1$s\n"
2298 "Please check your installation."), qstring_to_ucs4(name)));
2301 if (name == defaultUIFile) {
2302 LYXERR(Debug::INIT, "Could not find default UI file!!");
2303 Alert::warning(_("Could not find default UI file"),
2304 _("LyX could not find the default UI file!\n"
2305 "Please check your installation."));
2308 Alert::warning(_("Could not find UI definition file"),
2309 bformat(_("Error while reading the configuration file\n%1$s\n"
2310 "Falling back to default.\n"
2311 "Please look under Tools>Preferences>User Interface and\n"
2312 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2313 return readUIFile(defaultUIFile, false);
2316 // Ensure that a file is read only once (prevents include loops)
2317 static QStringList uifiles;
2318 QString const uifile = toqstr(ui_path.absFilename());
2319 if (uifiles.contains(uifile)) {
2321 // We are reading again the top uifile so reset the safeguard:
2324 d->toolbars_.reset();
2326 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2327 << "Is this an include loop?");
2331 uifiles.push_back(uifile);
2333 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2343 LexerKeyword uitags[] = {
2344 { "include", ui_include },
2345 { "menuset", ui_menuset },
2346 { "toolbars", ui_toolbars },
2347 { "toolbarset", ui_toolbarset }
2351 lex.setFile(ui_path);
2353 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2357 if (lyxerr.debugging(Debug::PARSER))
2358 lex.printTable(lyxerr);
2360 // store which ui files define Toolbars
2361 static QStringList toolbar_uifiles;
2363 while (lex.isOK()) {
2364 switch (lex.lex()) {
2367 QString const file = toqstr(lex.getString());
2368 if (!readUIFile(file, true))
2373 d->menus_.read(lex);
2377 d->toolbars_.readToolbars(lex);
2381 d->toolbars_.readToolbarSettings(lex);
2382 toolbar_uifiles.push_back(uifile);
2386 if (!rtrim(lex.getString()).empty())
2387 lex.printError("LyX::ReadUIFile: "
2388 "Unknown menu tag: `$$Token'");
2397 settings.beginGroup("ui_files");
2398 bool touched = false;
2399 for (int i = 0; i != uifiles.size(); ++i) {
2400 QFileInfo fi(uifiles[i]);
2401 QDateTime const date_value = fi.lastModified();
2402 QString const name_key = QString::number(i);
2403 // if an ui file which defines Toolbars has changed,
2404 // we have to reset the settings
2405 if (toolbar_uifiles.contains(uifiles[i])
2406 && (!settings.contains(name_key)
2407 || settings.value(name_key).toString() != uifiles[i]
2408 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2410 settings.setValue(name_key, uifiles[i]);
2411 settings.setValue(name_key + "/date", date_value);
2414 settings.endGroup();
2416 settings.remove("views");
2422 void GuiApplication::onLastWindowClosed()
2424 if (d->global_menubar_)
2425 d->global_menubar_->grabKeyboard();
2429 ////////////////////////////////////////////////////////////////////////
2431 // X11 specific stuff goes here...
2434 bool GuiApplication::x11EventFilter(XEvent * xev)
2439 switch (xev->type) {
2440 case SelectionRequest: {
2441 if (xev->xselectionrequest.selection != XA_PRIMARY)
2443 LYXERR(Debug::SELECTION, "X requested selection.");
2444 BufferView * bv = current_view_->currentBufferView();
2446 docstring const sel = bv->requestSelection();
2448 d->selection_.put(sel);
2452 case SelectionClear: {
2453 if (xev->xselectionclear.selection != XA_PRIMARY)
2455 LYXERR(Debug::SELECTION, "Lost selection.");
2456 BufferView * bv = current_view_->currentBufferView();
2458 bv->clearSelection();
2466 } // namespace frontend
2469 void hideDialogs(std::string const & name, Inset * inset)
2472 frontend::guiApp->hideDialogs(name, inset);
2476 ////////////////////////////////////////////////////////////////////
2480 ////////////////////////////////////////////////////////////////////
2482 frontend::FontLoader & theFontLoader()
2484 LASSERT(frontend::guiApp, /**/);
2485 return frontend::guiApp->fontLoader();
2489 frontend::FontMetrics const & theFontMetrics(Font const & f)
2491 return theFontMetrics(f.fontInfo());
2495 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2497 LASSERT(frontend::guiApp, /**/);
2498 return frontend::guiApp->fontLoader().metrics(f);
2502 ////////////////////////////////////////////////////////////////////
2506 ////////////////////////////////////////////////////////////////////
2508 frontend::Clipboard & theClipboard()
2510 LASSERT(frontend::guiApp, /**/);
2511 return frontend::guiApp->clipboard();
2515 frontend::Selection & theSelection()
2517 LASSERT(frontend::guiApp, /**/);
2518 return frontend::guiApp->selection();
2524 #include "moc_GuiApplication.cpp"