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"
41 #include "GuiWorkArea.h"
45 #include "LaTeXPackages.h"
48 #include "LyXAction.h"
50 #include "Paragraph.h"
53 #include "SpellChecker.h"
54 #include "Thesaurus.h"
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/ExceptionMessage.h"
60 #include "support/FileName.h"
61 #include "support/filetools.h"
62 #include "support/foreach.h"
63 #include "support/ForkedCalls.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/lyxalgo.h" // sorted
68 #include "support/Messages.h"
69 #include "support/os.h"
70 #include "support/Package.h"
71 #include "support/Path.h"
72 #include "support/Systemcall.h"
75 #include "support/AppleScript.h"
76 #include "support/linkback/LinkBackProxy.h"
87 #include <QFileOpenEvent>
91 #include <QImageReader>
94 #include <QLibraryInfo>
96 #include <QMacPasteboardMime>
101 #include <QPixmapCache>
103 #include <QSessionManager>
105 #include <QShowEvent>
106 #include <QSocketNotifier>
107 #include <QSortFilterProxyModel>
108 #include <QStandardItemModel>
109 #include <QTextCodec>
111 #include <QTranslator>
112 #if QT_VERSION >= 0x040400
113 #include <QThreadPool>
118 #include <X11/Xatom.h>
119 #include <X11/Xlib.h>
125 #include <QWindowsMime>
132 #include "support/bind.h"
133 #include <boost/crc.hpp>
140 using namespace lyx::support;
143 static void initializeResources()
145 static bool initialized = false;
147 Q_INIT_RESOURCE(Resources);
155 frontend::Application * createApplication(int & argc, char * argv[])
158 // prune -geometry argument(s) by shifting
159 // the following ones 2 places down.
160 for (int i = 0 ; i < argc ; ++i) {
161 if (strcmp(argv[i], "-geometry") == 0) {
162 int const remove = (i+1) < argc ? 2 : 1;
164 for (int j = i; j < argc; ++j)
165 argv[j] = argv[j + remove];
170 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
171 // I'd rather do that in the constructor, but I do not think that
172 // the palette is accessible there.
173 guiApp->colorCache().setPalette(guiApp->palette());
180 /// Return the list of loadable formats.
181 vector<string> loadableImageFormats()
185 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
187 LYXERR(Debug::GRAPHICS,
188 "\nThe image loader can load the following directly:\n");
190 if (qt_formats.empty())
191 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
193 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
195 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
197 string ext = ascii_lowercase((const char *) *it);
208 ////////////////////////////////////////////////////////////////////////
210 // Icon loading support code
212 ////////////////////////////////////////////////////////////////////////
222 bool operator<(PngMap const & lhs, PngMap const & rhs)
224 return lhs.key < rhs.key;
230 CompareKey(QString const & name) : name_(name) {}
231 bool operator()(PngMap const & other) const { return other.key == name_; }
237 // this must be sorted alphabetically
238 // Upper case comes before lower case
239 PngMap sorted_png_map[] = {
240 { "Bumpeq", "bumpeq2" },
243 { "Delta", "delta2" },
244 { "Diamond", "diamond2" },
245 { "Downarrow", "downarrow2" },
246 { "Gamma", "gamma2" },
247 { "Lambda", "lambda2" },
248 { "Leftarrow", "leftarrow2" },
249 { "Leftrightarrow", "leftrightarrow2" },
250 { "Longleftarrow", "longleftarrow2" },
251 { "Longleftrightarrow", "longleftrightarrow2" },
252 { "Longrightarrow", "longrightarrow2" },
253 { "Omega", "omega2" },
257 { "Rightarrow", "rightarrow2" },
258 { "Sigma", "sigma2" },
259 { "Subset", "subset2" },
260 { "Supset", "supset2" },
261 { "Theta", "theta2" },
262 { "Uparrow", "uparrow2" },
263 { "Updownarrow", "updownarrow2" },
264 { "Upsilon", "upsilon2" },
265 { "Vdash", "vdash3" },
268 { "nLeftarrow", "nleftarrow2" },
269 { "nLeftrightarrow", "nleftrightarrow2" },
270 { "nRightarrow", "nrightarrow2" },
271 { "nVDash", "nvdash3" },
272 { "nvDash", "nvdash2" },
273 { "textrm \\AA", "textrm_AA"},
274 { "textrm \\O", "textrm_O"},
275 { "vDash", "vdash2" }
278 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
281 QString findPng(QString const & name)
283 PngMap const * const begin = sorted_png_map;
284 PngMap const * const end = begin + nr_sorted_png_map;
285 LASSERT(sorted(begin, end), /**/);
287 PngMap const * const it = find_if(begin, end, CompareKey(name));
291 png_name = it->value;
294 png_name.replace('_', "underscore");
295 png_name.replace(' ', '_');
297 // This way we can have "math-delim { }" on the toolbar.
298 png_name.replace('(', "lparen");
299 png_name.replace(')', "rparen");
300 png_name.replace('[', "lbracket");
301 png_name.replace(']', "rbracket");
302 png_name.replace('{', "lbrace");
303 png_name.replace('}', "rbrace");
304 png_name.replace('|', "bars");
305 png_name.replace(',', "thinspace");
306 png_name.replace(':', "mediumspace");
307 png_name.replace(';', "thickspace");
308 png_name.replace('!', "negthinspace");
311 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
312 << "Looking for math PNG called \"" << png_name << '"');
319 QString iconName(FuncRequest const & f, bool unknown)
321 initializeResources();
325 switch (f.action()) {
326 case LFUN_MATH_INSERT:
327 if (!f.argument().empty()) {
329 name1 = findPng(toqstr(f.argument()).mid(1));
332 case LFUN_MATH_DELIM:
333 case LFUN_MATH_BIGDELIM:
335 name1 = findPng(toqstr(f.argument()));
339 name1 = toqstr(f.argument());
341 case LFUN_COMMAND_ALTERNATIVES: {
342 // use the first of the alternative commands
344 docstring dummy = split(f.argument(), firstcom, ';');
345 name1 = toqstr(firstcom);
346 // FIXME: we should rename the icons to tabular-xxx instead of
347 // "tabular-feature-xxx"
348 name1.replace("inset-modify tabular", "tabular-feature");
349 name1.replace(' ', '_');
352 case LFUN_INSET_MODIFY: {
353 // FIXME: we should rename the icons to tabular-xxx instead of
354 // "tabular-feature-xxx" and generalize this naming to all
355 // insets, not to tabular using ones.
357 string const command = split(to_utf8(f.argument()), inset_name, ' ');
358 if (insetCode(inset_name) == TABULAR_CODE) {
359 name1 = "tabular-feature "+ toqstr(command);
360 name1.replace(' ', '_');
365 name2 = toqstr(lyxaction.getActionName(f.action()));
368 if (!f.argument().empty()) {
369 name1 = name2 + ' ' + toqstr(f.argument());
370 name1.replace(' ', '_');
371 name1.replace('\\', "backslash");
375 QString imagedir = "images/" + path;
376 FileName fname = imageLibFileSearch(imagedir, name1, "png");
378 return toqstr(fname.absFileName());
380 fname = imageLibFileSearch(imagedir, name2, "png");
382 return toqstr(fname.absFileName());
384 path = ":/images/" + path;
387 LYXERR0("Directory " << path << " not found in resource!");
391 if (res.exists(name1))
395 if (res.exists(name2))
398 LYXERR(Debug::GUI, "Cannot find icon with filename "
399 << "\"" << name1 << "\""
401 << "\"" << name2 << "\""
403 << lyxaction.getActionName(f.action())
404 << '(' << to_utf8(f.argument()) << ")\"");
407 imagedir = "images/";
408 fname = imageLibFileSearch(imagedir, "unknown", "png");
410 return toqstr(fname.absFileName());
411 return QString(":/images/unknown.png");
417 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
420 QString imagedir = path;
421 FileName fname = imageLibFileSearch(imagedir, name, ext);
422 QString path1 = toqstr(fname.absFileName());
423 QString path2 = ":/" + path + name + "." + ext;
425 if (pixmap.load(path1)) {
428 else if (pixmap.load(path2)) {
432 LYXERR0("Cannot load pixmap \""
433 << path << name << '.' << ext
434 << "\", please verify resource system!");
439 QIcon getIcon(FuncRequest const & f, bool unknown)
441 QString icon = iconName(f, unknown);
445 //LYXERR(Debug::GUI, "Found icon: " << icon);
447 if (!pm.load(icon)) {
448 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
456 ////////////////////////////////////////////////////////////////////////
458 // LyX server support code.
460 ////////////////////////////////////////////////////////////////////////
462 class SocketNotifier : public QSocketNotifier
465 /// connect a connection notification from the LyXServerSocket
466 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
467 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
471 /// The callback function
472 Application::SocketCallback func_;
476 ////////////////////////////////////////////////////////////////////////
478 // Mac specific stuff goes here...
480 ////////////////////////////////////////////////////////////////////////
482 class MenuTranslator : public QTranslator
485 MenuTranslator(QObject * parent)
486 : QTranslator(parent)
489 QString translate(const char * /*context*/,
490 const char * sourceText,
491 const char * /*comment*/ = 0)
493 string const s = sourceText;
494 if (s == N_("About %1") || s == N_("Preferences")
495 || s == N_("Reconfigure") || s == N_("Quit %1"))
502 class GlobalMenuBar : public QMenuBar
506 GlobalMenuBar() : QMenuBar(0) {}
509 bool event(QEvent * e)
511 if (e->type() == QEvent::ShortcutOverride) {
512 // && activeWindow() == 0) {
513 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
515 setKeySymbol(&sym, ke);
516 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
525 // QMacPasteboardMimeGraphics can only be compiled on Mac.
527 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
530 QMacPasteboardMimeGraphics()
531 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
534 QString convertorName() { return "Graphics"; }
536 QString flavorFor(QString const & mime)
538 LYXERR(Debug::ACTION, "flavorFor " << mime);
539 if (mime == pdfMimeType())
540 return QLatin1String("com.adobe.pdf");
544 QString mimeFor(QString flav)
546 LYXERR(Debug::ACTION, "mimeFor " << flav);
547 if (flav == QLatin1String("com.adobe.pdf"))
548 return pdfMimeType();
552 bool canConvert(QString const & mime, QString flav)
554 return mimeFor(flav) == mime;
557 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
561 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
565 QList<QByteArray> convertFromMime(QString const & /*mime*/,
566 QVariant data, QString /*flav*/)
568 QList<QByteArray> ret;
569 ret.append(data.toByteArray());
575 ///////////////////////////////////////////////////////////////
577 // You can find more platform specific stuff at the end of this file...
579 ///////////////////////////////////////////////////////////////
581 ////////////////////////////////////////////////////////////////////////
582 // Windows specific stuff goes here...
585 // QWindowsMimeMetafile can only be compiled on Windows.
587 static FORMATETC cfFromMime(QString const & mimetype)
590 if (mimetype == emfMimeType()) {
591 formatetc.cfFormat = CF_ENHMETAFILE;
592 formatetc.tymed = TYMED_ENHMF;
593 } else if (mimetype == wmfMimeType()) {
594 formatetc.cfFormat = CF_METAFILEPICT;
595 formatetc.tymed = TYMED_MFPICT;
598 formatetc.dwAspect = DVASPECT_CONTENT;
599 formatetc.lindex = -1;
604 class QWindowsMimeMetafile : public QWindowsMime {
606 QWindowsMimeMetafile() {}
608 bool canConvertFromMime(FORMATETC const & formatetc,
609 QMimeData const * mimedata) const
614 bool canConvertToMime(QString const & mimetype,
615 IDataObject * pDataObj) const
617 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
619 FORMATETC formatetc = cfFromMime(mimetype);
620 return pDataObj->QueryGetData(&formatetc) == S_OK;
623 bool convertFromMime(FORMATETC const & formatetc,
624 const QMimeData * mimedata, STGMEDIUM * pmedium) const
629 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
630 QVariant::Type preferredType) const
633 if (!canConvertToMime(mimetype, pDataObj))
636 FORMATETC formatetc = cfFromMime(mimetype);
638 if (pDataObj->GetData(&formatetc, &s) != S_OK)
642 if (s.tymed == TYMED_ENHMF) {
643 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
644 data.resize(dataSize);
645 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
646 (LPBYTE)data.data());
647 } else if (s.tymed == TYMED_MFPICT) {
648 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
649 data.resize(dataSize);
650 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
651 (LPBYTE)data.data());
654 ReleaseStgMedium(&s);
660 QVector<FORMATETC> formatsForMime(QString const & mimetype,
661 QMimeData const * mimedata) const
663 QVector<FORMATETC> formats;
664 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
665 formats += cfFromMime(mimetype);
669 QString mimeForFormat(FORMATETC const & formatetc) const
671 switch (formatetc.cfFormat) {
673 return emfMimeType();
674 case CF_METAFILEPICT:
675 return wmfMimeType();
684 /// Allows to check whether ESC was pressed during a long operation
685 class KeyChecker : public QObject {
694 QCoreApplication::instance()->installEventFilter(this);
699 QCoreApplication::instance()->removeEventFilter(this);
703 QCoreApplication::processEvents();
706 bool started() const {
709 bool eventFilter(QObject *obj, QEvent *event) {
710 LYXERR(Debug::ACTION, "Event Type: " << event->type());
711 switch (event->type()) {
715 return QObject::eventFilter(obj, event);
717 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
718 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
726 ////////////////////////////////////////////////////////////////////////
727 // GuiApplication::Private definition and implementation.
728 ////////////////////////////////////////////////////////////////////////
730 struct GuiApplication::Private
732 Private(): language_model_(0), meta_fake_bit(NoModifier),
736 /// WMF Mime handler for Windows clipboard.
737 wmf_mime_ = new QWindowsMimeMetafile();
739 initKeySequences(&theTopLevelKeymap());
742 void initKeySequences(KeyMap * kb)
744 keyseq = KeySequence(kb, kb);
745 cancel_meta_seq = KeySequence(kb, kb);
749 QSortFilterProxyModel * language_model_;
751 GuiClipboard clipboard_;
753 GuiSelection selection_;
755 FontLoader font_loader_;
757 ColorCache color_cache_;
759 QTranslator qt_trans_;
761 QHash<int, SocketNotifier *> socket_notifiers_;
765 /// The global instance
768 /// this timer is used for any regular events one wants to
769 /// perform. at present it is used to check if forked processes
771 QTimer general_timer_;
773 /// delayed FuncRequests
774 std::queue<FuncRequest> func_request_queue_;
779 KeySequence cancel_meta_seq;
781 KeyModifier meta_fake_bit;
783 /// Multiple views container.
785 * Warning: This must not be a smart pointer as the destruction of the
786 * object is handled by Qt when the view is closed
787 * \sa Qt::WA_DeleteOnClose attribute.
789 QHash<int, GuiView *> views_;
791 /// Only used on mac.
792 GlobalMenuBar * global_menubar_;
795 /// Linkback mime handler for MacOSX.
796 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
800 /// WMF Mime handler for Windows clipboard.
801 QWindowsMimeMetafile * wmf_mime_;
804 /// Allows to check whether ESC was pressed during a long operation
805 KeyChecker key_checker_;
809 GuiApplication * guiApp;
811 GuiApplication::~GuiApplication()
814 closeAllLinkBackLinks();
820 GuiApplication::GuiApplication(int & argc, char ** argv)
821 : QApplication(argc, argv), current_view_(0),
822 d(new GuiApplication::Private)
824 QString app_name = "LyX";
825 QCoreApplication::setOrganizationName(app_name);
826 QCoreApplication::setOrganizationDomain("lyx.org");
827 QCoreApplication::setApplicationName(lyx_package);
829 // Install translator for GUI elements.
830 installTranslator(&d->qt_trans_);
832 // FIXME: quitOnLastWindowClosed is true by default. We should have a
833 // lyxrc setting for this in order to let the application stay resident.
834 // But then we need some kind of dock icon, at least on Windows.
836 if (lyxrc.quit_on_last_window_closed)
837 setQuitOnLastWindowClosed(false);
840 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
841 // seems to be the default case for applications like LyX.
842 setQuitOnLastWindowClosed(false);
843 // This allows to translate the strings that appear in the LyX menu.
844 /// A translator suitable for the entries in the LyX menu.
845 /// Only needed with Qt/Mac.
846 installTranslator(new MenuTranslator(this));
852 // doubleClickInterval() is 400 ms on X11 which is just too long.
853 // On Windows and Mac OS X, the operating system's value is used.
854 // On Microsoft Windows, calling this function sets the double
855 // click interval for all applications. So we don't!
856 QApplication::setDoubleClickInterval(300);
859 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
861 // needs to be done before reading lyxrc
863 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
867 // Set the cache to 5120 kilobytes which corresponds to screen size of
868 // 1280 by 1024 pixels with a color depth of 32 bits.
869 QPixmapCache::setCacheLimit(5120);
871 // Initialize RC Fonts
872 if (lyxrc.roman_font_name.empty())
873 lyxrc.roman_font_name = fromqstr(romanFontName());
875 if (lyxrc.sans_font_name.empty())
876 lyxrc.sans_font_name = fromqstr(sansFontName());
878 if (lyxrc.typewriter_font_name.empty())
879 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
881 d->general_timer_.setInterval(500);
882 connect(&d->general_timer_, SIGNAL(timeout()),
883 this, SLOT(handleRegularEvents()));
884 d->general_timer_.start();
886 #if QT_VERSION >= 0x040400
887 // maxThreadCount() defaults in general to 2 on single or dual-processor.
888 // This is clearly not enough in a time where we use threads for
889 // document preview and/or export. 20 should be OK.
890 QThreadPool::globalInstance()->setMaxThreadCount(20);
895 GuiApplication * theGuiApp()
897 return dynamic_cast<GuiApplication *>(theApp());
901 void GuiApplication::clearSession()
908 docstring Application::iconName(FuncRequest const & f, bool unknown)
910 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
914 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
919 BufferView * doc_bv = 0;
921 if (cmd.action() == LFUN_NOACTION) {
922 status.message(from_utf8(N_("Nothing to do")));
923 status.setEnabled(false);
926 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
927 status.setUnknown(true);
928 status.message(from_utf8(N_("Unknown action")));
929 status.setEnabled(false);
932 // Does the GuiApplication know something?
933 else if (getStatus(cmd, status)) { }
935 // If we do not have a GuiView, then other functions are disabled
936 else if (!current_view_)
937 status.setEnabled(false);
939 // Does the GuiView know something?
940 else if (current_view_->getStatus(cmd, status)) { }
942 // In LyX/Mac, when a dialog is open, the menus of the
943 // application can still be accessed without giving focus to
944 // the main window. In this case, we want to disable the menu
945 // entries that are buffer or view-related.
946 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
948 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
949 status.setEnabled(false);
952 // If we do not have a BufferView, then other functions are disabled
953 else if (!(bv = current_view_->currentBufferView()))
954 status.setEnabled(false);
956 // Does the current BufferView know something?
957 else if (bv->getStatus(cmd, status)) { }
959 // Does the current Buffer know something?
960 else if (bv->buffer().getStatus(cmd, status)) { }
962 // If we do not have a document BufferView, different from the
963 // current BufferView, then other functions are disabled
964 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
965 status.setEnabled(false);
967 // Does the document Buffer know something?
968 else if (doc_bv->buffer().getStatus(cmd, status)) { }
971 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
972 status.message(from_utf8(N_("Command not handled")));
973 status.setEnabled(false);
976 // the default error message if we disable the command
977 if (!status.enabled() && status.message().empty())
978 status.message(from_utf8(N_("Command disabled")));
984 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
986 // I would really like to avoid having this switch and rather try to
987 // encode this in the function itself.
988 // -- And I'd rather let an inset decide which LFUNs it is willing
989 // to handle (Andre')
991 switch (cmd.action()) {
993 // This could be used for the no-GUI version. The GUI version is handled in
994 // GuiView::getStatus(). See above.
996 case LFUN_BUFFER_WRITE:
997 case LFUN_BUFFER_WRITE_AS: {
998 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
999 enable = b && (b->isUnnamed() || !b->isClean());
1004 case LFUN_BOOKMARK_GOTO: {
1005 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1006 enable = theSession().bookmarks().isValid(num);
1010 case LFUN_BOOKMARK_CLEAR:
1011 enable = theSession().bookmarks().hasValid();
1014 // this one is difficult to get right. As a half-baked
1015 // solution, we consider only the first action of the sequence
1016 case LFUN_COMMAND_SEQUENCE: {
1017 // argument contains ';'-terminated commands
1018 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1019 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1020 func.setOrigin(cmd.origin());
1021 flag = getStatus(func);
1025 // we want to check if at least one of these is enabled
1026 case LFUN_COMMAND_ALTERNATIVES: {
1027 // argument contains ';'-terminated commands
1028 string arg = to_utf8(cmd.argument());
1029 while (!arg.empty()) {
1031 arg = split(arg, first, ';');
1032 FuncRequest func(lyxaction.lookupFunc(first));
1033 func.setOrigin(cmd.origin());
1034 flag = getStatus(func);
1035 // if this one is enabled, the whole thing is
1044 string name = to_utf8(cmd.argument());
1045 if (theTopLevelCmdDef().lock(name, func)) {
1046 func.setOrigin(cmd.origin());
1047 flag = getStatus(func);
1048 theTopLevelCmdDef().release(name);
1050 // catch recursion or unknown command
1051 // definition. all operations until the
1052 // recursion or unknown command definition
1053 // occurs are performed, so set the state to
1060 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1062 case LFUN_PREFERENCES_SAVE:
1063 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1064 case LFUN_DEBUG_LEVEL_SET:
1065 // these are handled in our dispatch()
1068 case LFUN_WINDOW_CLOSE:
1069 enable = d->views_.size() > 0;
1072 case LFUN_BUFFER_NEW:
1073 case LFUN_BUFFER_NEW_TEMPLATE:
1074 case LFUN_FILE_OPEN:
1075 case LFUN_HELP_OPEN:
1076 case LFUN_SCREEN_FONT_UPDATE:
1077 case LFUN_SET_COLOR:
1078 case LFUN_WINDOW_NEW:
1080 case LFUN_LYXRC_APPLY:
1081 case LFUN_COMMAND_PREFIX:
1083 case LFUN_META_PREFIX:
1084 case LFUN_RECONFIGURE:
1085 case LFUN_SERVER_GET_FILENAME:
1086 case LFUN_SERVER_NOTIFY:
1090 case LFUN_BUFFER_FORALL: {
1091 if (!currentView() || !currentView()->currentBufferView() || !¤tView()->currentBufferView()->buffer()) {
1092 flag.message(from_utf8(N_("Command not allowed without any visible document in the active window")));
1093 flag.setEnabled(false);
1104 flag.setEnabled(false);
1108 /// make a post-dispatch status message
1109 static docstring makeDispatchMessage(docstring const & msg,
1110 FuncRequest const & cmd)
1112 const bool verbose = (cmd.origin() == FuncRequest::MENU
1113 || cmd.origin() == FuncRequest::TOOLBAR
1114 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1116 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1117 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1121 docstring dispatch_msg = msg;
1122 if (!dispatch_msg.empty())
1123 dispatch_msg += ' ';
1125 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1127 bool argsadded = false;
1129 if (!cmd.argument().empty()) {
1130 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1131 comname += ' ' + cmd.argument();
1135 docstring const shortcuts = theTopLevelKeymap().
1136 printBindings(cmd, KeySequence::ForGui);
1138 if (!shortcuts.empty())
1139 comname += ": " + shortcuts;
1140 else if (!argsadded && !cmd.argument().empty())
1141 comname += ' ' + cmd.argument();
1143 if (!comname.empty()) {
1144 comname = rtrim(comname);
1145 dispatch_msg += '(' + rtrim(comname) + ')';
1147 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1148 return dispatch_msg;
1152 void GuiApplication::dispatch(FuncRequest const & cmd)
1154 Buffer * buffer = 0;
1155 if (current_view_ && current_view_->currentBufferView()) {
1156 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1157 buffer = ¤t_view_->currentBufferView()->buffer();
1159 buffer->undo().beginUndoGroup();
1163 // redraw the screen at the end (first of the two drawing steps).
1164 // This is done unless explicitly requested otherwise
1165 dr.screenUpdate(Update::FitCursor);
1167 updateCurrentView(cmd, dr);
1169 // the buffer may have been closed by one action
1170 if (theBufferList().isLoaded(buffer))
1171 buffer->undo().endUndoGroup();
1175 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1180 BufferView * bv = current_view_->currentBufferView();
1182 if (dr.needBufferUpdate()) {
1183 bv->cursor().clearBufferUpdate();
1184 bv->buffer().updateBuffer();
1186 // BufferView::update() updates the ViewMetricsInfo and
1187 // also initializes the position cache for all insets in
1188 // (at least partially) visible top-level paragraphs.
1189 // We will redraw the screen only if needed.
1190 bv->processUpdateFlags(dr.screenUpdate());
1192 // Do we have a selection?
1193 theSelection().haveSelection(bv->cursor().selection());
1196 current_view_->restartCursor();
1198 if (dr.needMessageUpdate()) {
1199 // Some messages may already be translated, so we cannot use _()
1200 current_view_->message(makeDispatchMessage(
1201 translateIfPossible(dr.message()), cmd));
1206 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1207 bool switchToBuffer)
1209 if (!theSession().bookmarks().isValid(idx))
1211 BookmarksSection::Bookmark const & bm =
1212 theSession().bookmarks().bookmark(idx);
1213 LASSERT(!bm.filename.empty(), /**/);
1214 string const file = bm.filename.absFileName();
1215 // if the file is not opened, open it.
1216 if (!theBufferList().exists(bm.filename)) {
1218 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1222 // open may fail, so we need to test it again
1223 if (!theBufferList().exists(bm.filename))
1226 // bm can be changed when saving
1227 BookmarksSection::Bookmark tmp = bm;
1229 // Special case idx == 0 used for back-from-back jump navigation
1231 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1233 // if the current buffer is not that one, switch to it.
1234 BufferView * doc_bv = current_view_ ?
1235 current_view_->documentBufferView() : 0;
1236 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1237 if (switchToBuffer) {
1238 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1241 doc_bv = current_view_->documentBufferView();
1246 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1247 if (!doc_bv->moveToPosition(
1248 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1255 // Cursor jump succeeded!
1256 Cursor const & cur = doc_bv->cursor();
1257 pit_type new_pit = cur.pit();
1258 pos_type new_pos = cur.pos();
1259 int new_id = cur.paragraph().id();
1261 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1262 // see http://www.lyx.org/trac/ticket/3092
1263 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1264 || bm.top_id != new_id) {
1265 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1266 new_pit, new_pos, new_id);
1270 // This function runs "configure" and then rereads lyx.defaults to
1271 // reconfigure the automatic settings.
1272 void GuiApplication::reconfigure(string const & option)
1274 // emit message signal.
1276 current_view_->message(_("Running configure..."));
1278 // Run configure in user lyx directory
1279 PathChanger p(package().user_support());
1280 string configure_command = package().configure_command();
1281 configure_command += option;
1283 int ret = one.startscript(Systemcall::Wait, configure_command);
1285 // emit message signal.
1287 current_view_->message(_("Reloading configuration..."));
1288 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1289 // Re-read packages.lst
1290 LaTeXPackages::getAvailable();
1293 Alert::information(_("System reconfiguration failed"),
1294 _("The system reconfiguration has failed.\n"
1295 "Default textclass is used but LyX may "
1296 "not be able to work properly.\n"
1297 "Please reconfigure again if needed."));
1299 Alert::information(_("System reconfigured"),
1300 _("The system has been reconfigured.\n"
1301 "You need to restart LyX to make use of any\n"
1302 "updated document class specifications."));
1305 void GuiApplication::validateCurrentView()
1307 if (!d->views_.empty() && !current_view_) {
1308 // currently at least one view exists but no view has the focus.
1309 // choose the last view to make it current.
1310 // a view without any open document is preferred.
1311 GuiView * candidate = 0;
1312 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1313 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1314 for (; it != end; ++it) {
1316 if (!candidate->documentBufferView())
1319 setCurrentView(candidate);
1323 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1325 string const argument = to_utf8(cmd.argument());
1326 FuncCode const action = cmd.action();
1328 LYXERR(Debug::ACTION, "cmd: " << cmd);
1330 // we have not done anything wrong yet.
1333 FuncStatus const flag = getStatus(cmd);
1334 if (!flag.enabled()) {
1335 // We cannot use this function here
1336 LYXERR(Debug::ACTION, "action "
1337 << lyxaction.getActionName(action)
1338 << " [" << action << "] is disabled at this location");
1339 dr.setMessage(flag.message());
1341 dr.dispatched(false);
1342 dr.screenUpdate(Update::None);
1343 dr.clearBufferUpdate();
1347 if (cmd.origin() == FuncRequest::LYXSERVER) {
1348 if (current_view_ && current_view_->currentBufferView())
1349 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1350 // we will also need to redraw the screen at the end
1351 dr.screenUpdate(Update::FitCursor);
1354 // Assumes that the action will be dispatched.
1355 dr.dispatched(true);
1357 switch (cmd.action()) {
1359 case LFUN_WINDOW_NEW:
1360 createView(toqstr(cmd.argument()));
1363 case LFUN_WINDOW_CLOSE:
1364 // update bookmark pit of the current buffer before window close
1365 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1366 gotoBookmark(i+1, false, false);
1367 // clear the last opened list, because
1368 // maybe this will end the session
1369 theSession().lastOpened().clear();
1370 // check for valid current_view_
1371 validateCurrentView();
1373 current_view_->closeScheduled();
1377 // quitting is triggered by the gui code
1378 // (leaving the event loop).
1380 current_view_->message(from_utf8(N_("Exiting.")));
1381 if (closeAllViews())
1385 case LFUN_SCREEN_FONT_UPDATE: {
1386 // handle the screen font changes.
1387 d->font_loader_.update();
1388 // Backup current_view_
1389 GuiView * view = current_view_;
1390 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1391 // to skip the refresh.
1393 theBufferList().changed(false);
1394 // Restore current_view_
1395 current_view_ = view;
1399 case LFUN_BUFFER_NEW:
1400 validateCurrentView();
1401 if (d->views_.empty()
1402 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1403 createView(QString(), false); // keep hidden
1404 current_view_->newDocument(to_utf8(cmd.argument()), false);
1405 current_view_->show();
1406 setActiveWindow(current_view_);
1408 current_view_->newDocument(to_utf8(cmd.argument()), false);
1412 case LFUN_BUFFER_NEW_TEMPLATE:
1413 validateCurrentView();
1414 if (d->views_.empty()
1415 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1417 current_view_->newDocument(to_utf8(cmd.argument()), true);
1418 if (!current_view_->documentBufferView())
1419 current_view_->close();
1421 current_view_->newDocument(to_utf8(cmd.argument()), true);
1425 case LFUN_FILE_OPEN: {
1426 validateCurrentView();
1427 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1428 string const fname = to_utf8(cmd.argument());
1429 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1430 && current_view_->documentBufferView() != 0)) {
1431 // We want the ui session to be saved per document and not per
1432 // window number. The filename crc is a good enough identifier.
1433 boost::crc_32_type crc;
1434 crc = for_each(fname.begin(), fname.end(), crc);
1435 createView(crc.checksum());
1436 current_view_->openDocument(fname);
1437 if (current_view_ && !current_view_->documentBufferView())
1438 current_view_->close();
1440 current_view_->openDocument(fname);
1444 case LFUN_HELP_OPEN: {
1445 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1446 if (current_view_ == 0)
1448 string const arg = to_utf8(cmd.argument());
1450 current_view_->message(_("Missing argument"));
1453 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1455 fname = i18nLibFileSearch("examples", arg, "lyx");
1457 if (fname.empty()) {
1458 lyxerr << "LyX: unable to find documentation file `"
1459 << arg << "'. Bad installation?" << endl;
1462 current_view_->message(bformat(_("Opening help file %1$s..."),
1463 makeDisplayPath(fname.absFileName())));
1464 Buffer * buf = current_view_->loadDocument(fname, false);
1466 #ifndef DEVEL_VERSION
1468 buf->setReadonly(true);
1475 case LFUN_SET_COLOR: {
1477 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1478 if (lyx_name.empty() || x11_name.empty()) {
1480 current_view_->message(
1481 _("Syntax: set-color <lyx_name> <x11_name>"));
1486 // FIXME: The graphics cache no longer has a changeDisplay method.
1487 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1488 bool const graphicsbg_changed =
1489 lyx_name == graphicsbg && x11_name != graphicsbg;
1490 if (graphicsbg_changed)
1491 graphics::GCache::get().changeDisplay(true);
1494 if (!lcolor.setColor(lyx_name, x11_name)) {
1496 current_view_->message(
1497 bformat(_("Set-color \"%1$s\" failed "
1498 "- color is undefined or "
1499 "may not be redefined"),
1500 from_utf8(lyx_name)));
1503 // Make sure we don't keep old colors in cache.
1504 d->color_cache_.clear();
1508 case LFUN_LYXRC_APPLY: {
1509 // reset active key sequences, since the bindings
1510 // are updated (bug 6064)
1512 LyXRC const lyxrc_orig = lyxrc;
1514 istringstream ss(to_utf8(cmd.argument()));
1515 bool const success = lyxrc.read(ss);
1518 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1519 << "Unable to read lyxrc data"
1524 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1530 case LFUN_COMMAND_PREFIX:
1531 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1536 d->meta_fake_bit = NoModifier;
1537 GuiView * gv = currentView();
1538 if (gv && gv->currentBufferView())
1539 // cancel any selection
1540 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1541 dr.setMessage(from_ascii(N_("Cancel")));
1544 case LFUN_META_PREFIX:
1545 d->meta_fake_bit = AltModifier;
1546 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1549 // --- Menus -----------------------------------------------
1550 case LFUN_RECONFIGURE:
1551 // argument is any additional parameter to the configure.py command
1552 reconfigure(to_utf8(cmd.argument()));
1555 // --- lyxserver commands ----------------------------
1556 case LFUN_SERVER_GET_FILENAME: {
1557 if (current_view_ && current_view_->documentBufferView()) {
1558 docstring const fname = from_utf8(
1559 current_view_->documentBufferView()->buffer().absFileName());
1560 dr.setMessage(fname);
1561 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1563 dr.setMessage(docstring());
1564 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1569 case LFUN_SERVER_NOTIFY: {
1570 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1571 dr.setMessage(dispatch_buffer);
1572 theServer().notifyClient(to_utf8(dispatch_buffer));
1576 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1577 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1583 string rest = split(argument, countstr, ' ');
1584 istringstream is(countstr);
1587 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1588 for (int i = 0; i < count; ++i)
1589 dispatch(lyxaction.lookupFunc(rest));
1593 case LFUN_COMMAND_SEQUENCE: {
1594 // argument contains ';'-terminated commands
1595 string arg = argument;
1596 // FIXME: this LFUN should also work without any view.
1597 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1598 ? &(current_view_->documentBufferView()->buffer()) : 0;
1600 buffer->undo().beginUndoGroup();
1601 while (!arg.empty()) {
1603 arg = split(arg, first, ';');
1604 FuncRequest func(lyxaction.lookupFunc(first));
1605 func.setOrigin(cmd.origin());
1608 // the buffer may have been closed by one action
1609 if (theBufferList().isLoaded(buffer))
1610 buffer->undo().endUndoGroup();
1614 case LFUN_BUFFER_FORALL: {
1615 GuiView * gv = currentView();
1616 Buffer * const buf = &gv->currentBufferView()->buffer();
1618 bool processVisible = true;
1619 bool processHidden = false;
1620 docstring msg = _("Applied the following command to all visible buffers in the active window: ");
1621 string commandToRun = argument;
1622 if (cmd.getArg(0) == "both") {
1623 processHidden = true;
1624 msg = _("Applied the following command to all visible and hidden buffers in the active window: ");
1625 commandToRun = cmd.getLongArg(1);
1626 } else if (cmd.getArg(0) == "visible") {
1627 commandToRun = cmd.getLongArg(1);
1628 } else if (cmd.getArg(0) == "hidden") {
1629 processHidden = true;
1630 processVisible = false;
1631 commandToRun = cmd.getLongArg(1);
1632 msg = _("Applied the following command to all hidden buffers in the active window: ");
1634 FuncRequest const funcToRun = lyxaction.lookupFunc(commandToRun);
1635 dr.setMessage(bformat(_("%1$s%2$s"), msg, from_utf8(commandToRun)));
1637 Buffer * const last = theBufferList().last();
1638 Buffer * b = theBufferList().first();
1639 Buffer * nextBuf = 0;
1640 // We cannot use a for loop as the buffer list cycles.
1643 nextBuf = theBufferList().next(b); //get next now bc LFUN might close current
1645 bool const hidden = !(gv && gv->workArea(*b));
1647 if (processHidden) {
1649 lyx::dispatch(funcToRun);
1650 gv->currentWorkArea()->view().hideWorkArea(gv->currentWorkArea());
1655 if (processVisible) {
1657 lyx::dispatch(funcToRun);
1666 if (theBufferList().isLoaded(buf)) //the LFUN might have closed buf
1671 case LFUN_COMMAND_ALTERNATIVES: {
1672 // argument contains ';'-terminated commands
1673 string arg = argument;
1674 while (!arg.empty()) {
1676 arg = split(arg, first, ';');
1677 FuncRequest func(lyxaction.lookupFunc(first));
1678 func.setOrigin(cmd.origin());
1679 FuncStatus const stat = getStatus(func);
1680 if (stat.enabled()) {
1690 if (theTopLevelCmdDef().lock(argument, func)) {
1691 func.setOrigin(cmd.origin());
1693 theTopLevelCmdDef().release(argument);
1695 if (func.action() == LFUN_UNKNOWN_ACTION) {
1696 // unknown command definition
1697 lyxerr << "Warning: unknown command definition `"
1701 // recursion detected
1702 lyxerr << "Warning: Recursion in the command definition `"
1703 << argument << "' detected"
1710 case LFUN_PREFERENCES_SAVE:
1711 lyxrc.write(support::makeAbsPath("preferences",
1712 package().user_support().absFileName()), false);
1715 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1716 string const fname = addName(addPath(package().user_support().absFileName(),
1717 "templates/"), "defaults.lyx");
1718 Buffer defaults(fname);
1720 istringstream ss(argument);
1723 int const unknown_tokens = defaults.readHeader(lex);
1725 if (unknown_tokens != 0) {
1726 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1727 << unknown_tokens << " unknown token"
1728 << (unknown_tokens == 1 ? "" : "s")
1732 if (defaults.writeFile(FileName(defaults.absFileName())))
1733 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1734 makeDisplayPath(fname)));
1737 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1742 case LFUN_BOOKMARK_GOTO:
1743 // go to bookmark, open unopened file and switch to buffer if necessary
1744 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1745 dr.screenUpdate(Update::Force | Update::FitCursor);
1748 case LFUN_BOOKMARK_CLEAR:
1749 theSession().bookmarks().clear();
1752 case LFUN_DEBUG_LEVEL_SET:
1753 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1757 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1760 current_view_->dispatch(cmd, dr);
1764 if (cmd.origin() == FuncRequest::LYXSERVER)
1765 updateCurrentView(cmd, dr);
1769 docstring GuiApplication::viewStatusMessage()
1771 // When meta-fake key is pressed, show the key sequence so far + "M-".
1772 if (d->meta_fake_bit != NoModifier)
1773 return d->keyseq.print(KeySequence::ForGui) + "M-";
1775 // Else, when a non-complete key sequence is pressed,
1776 // show the available options.
1777 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1778 return d->keyseq.printOptions(true);
1784 void GuiApplication::handleKeyFunc(FuncCode action)
1788 if (d->keyseq.length())
1790 GuiView * gv = currentView();
1791 LASSERT(gv && gv->currentBufferView(), return);
1792 BufferView * bv = gv->currentBufferView();
1793 bv->getIntl().getTransManager().deadkey(
1794 c, get_accent(action).accent, bv->cursor().innerText(),
1796 // Need to clear, in case the minibuffer calls these
1799 // copied verbatim from do_accent_char
1800 bv->cursor().resetAnchor();
1804 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1806 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1808 // Do nothing if we have nothing (JMarc)
1809 if (!keysym.isOK()) {
1810 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1812 current_view_->restartCursor();
1816 if (keysym.isModifier()) {
1818 current_view_->restartCursor();
1822 char_type encoded_last_key = keysym.getUCSEncoded();
1824 // Do a one-deep top-level lookup for
1825 // cancel and meta-fake keys. RVDK_PATCH_5
1826 d->cancel_meta_seq.reset();
1828 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1829 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1831 // When not cancel or meta-fake, do the normal lookup.
1832 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1833 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1834 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1835 // remove Caps Lock and Mod2 as a modifiers
1836 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1837 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1840 // Dont remove this unless you know what you are doing.
1841 d->meta_fake_bit = NoModifier;
1843 // Can this happen now ?
1844 if (func.action() == LFUN_NOACTION)
1845 func = FuncRequest(LFUN_COMMAND_PREFIX);
1847 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1848 << d->keyseq.print(KeySequence::Portable) << ']');
1850 // already here we know if it any point in going further
1851 // why not return already here if action == -1 and
1852 // num_bytes == 0? (Lgb)
1854 if (d->keyseq.length() > 1 && current_view_)
1855 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1858 // Maybe user can only reach the key via holding down shift.
1859 // Let's see. But only if shift is the only modifier
1860 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1861 LYXERR(Debug::KEY, "Trying without shift");
1862 func = d->keyseq.addkey(keysym, NoModifier);
1863 LYXERR(Debug::KEY, "Action now " << func.action());
1866 if (func.action() == LFUN_UNKNOWN_ACTION) {
1867 // Hmm, we didn't match any of the keysequences. See
1868 // if it's normal insertable text not already covered
1870 if (keysym.isText() && d->keyseq.length() == 1) {
1871 LYXERR(Debug::KEY, "isText() is true, inserting.");
1872 func = FuncRequest(LFUN_SELF_INSERT,
1873 FuncRequest::KEYBOARD);
1875 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1876 if (current_view_) {
1877 current_view_->message(_("Unknown function."));
1878 current_view_->restartCursor();
1884 if (func.action() == LFUN_SELF_INSERT) {
1885 if (encoded_last_key != 0) {
1886 docstring const arg(1, encoded_last_key);
1887 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1888 FuncRequest::KEYBOARD));
1889 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1892 processFuncRequest(func);
1896 void GuiApplication::processFuncRequest(FuncRequest const & func)
1898 lyx::dispatch(func);
1902 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1904 addToFuncRequestQueue(func);
1905 processFuncRequestQueueAsync();
1909 void GuiApplication::processFuncRequestQueue()
1911 while (!d->func_request_queue_.empty()) {
1912 processFuncRequest(d->func_request_queue_.front());
1913 d->func_request_queue_.pop();
1918 void GuiApplication::processFuncRequestQueueAsync()
1920 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1924 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1926 d->func_request_queue_.push(func);
1930 void GuiApplication::resetGui()
1932 // Set the language defined by the user.
1936 if (!readUIFile(toqstr(lyxrc.ui_file)))
1937 // Gives some error box here.
1940 if (d->global_menubar_)
1941 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1943 QHash<int, GuiView *>::iterator it;
1944 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1947 gv->setLayoutDirection(layoutDirection());
1951 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1955 void GuiApplication::createView(int view_id)
1957 createView(QString(), true, view_id);
1961 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1964 // release the keyboard which might have been grabed by the global
1965 // menubar on Mac to catch shortcuts even without any GuiView.
1966 if (d->global_menubar_)
1967 d->global_menubar_->releaseKeyboard();
1971 while (d->views_.find(id) != d->views_.end())
1974 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1975 GuiView * view = new GuiView(id);
1977 d->views_[id] = view;
1981 setActiveWindow(view);
1984 if (!geometry_arg.isEmpty()) {
1988 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1989 re.indexIn(geometry_arg);
1990 w = re.cap(1).toInt();
1991 h = re.cap(2).toInt();
1992 x = re.cap(3).toInt();
1993 y = re.cap(4).toInt();
1994 view->setGeometry(x, y, w, h);
2001 Clipboard & GuiApplication::clipboard()
2003 return d->clipboard_;
2007 Selection & GuiApplication::selection()
2009 return d->selection_;
2013 FontLoader & GuiApplication::fontLoader()
2015 return d->font_loader_;
2019 Toolbars const & GuiApplication::toolbars() const
2021 return d->toolbars_;
2025 Toolbars & GuiApplication::toolbars()
2027 return d->toolbars_;
2031 Menus const & GuiApplication::menus() const
2037 Menus & GuiApplication::menus()
2043 QList<int> GuiApplication::viewIds() const
2045 return d->views_.keys();
2049 ColorCache & GuiApplication::colorCache()
2051 return d->color_cache_;
2055 int GuiApplication::exec()
2057 // asynchronously handle batch commands. This event will be in
2058 // the event queue in front of other asynchronous events. Hence,
2059 // we can assume in the latter that the gui is setup already.
2060 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2062 return QApplication::exec();
2066 void GuiApplication::exit(int status)
2068 QApplication::exit(status);
2072 void GuiApplication::setGuiLanguage()
2074 QString const default_language = toqstr(getGuiMessages().language());
2075 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2076 QLocale const default_locale(default_language);
2077 QLocale::setDefault(default_locale);
2079 // install translation file for Qt built-in dialogs
2080 QString const language_name = QString("qt_") + default_locale.name();
2082 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2083 // Short-named translator can be loaded from a long name, but not the
2084 // opposite. Therefore, long name should be used without truncation.
2085 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2086 if (!d->qt_trans_.load(language_name,
2087 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2088 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2091 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2095 switch (default_locale.language()) {
2096 case QLocale::Arabic :
2097 case QLocale::Hebrew :
2098 case QLocale::Persian :
2099 case QLocale::Urdu :
2100 setLayoutDirection(Qt::RightToLeft);
2103 setLayoutDirection(Qt::LeftToRight);
2108 void GuiApplication::execBatchCommands()
2113 if (!readUIFile(toqstr(lyxrc.ui_file)))
2114 // Gives some error box here.
2118 #if QT_VERSION > 0x040600
2119 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2121 // Create the global default menubar which is shown for the dialogs
2122 // and if no GuiView is visible.
2123 // This must be done after the session was recovered to know the "last files".
2124 d->global_menubar_ = new GlobalMenuBar();
2125 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2128 lyx::execBatchCommands();
2132 QAbstractItemModel * GuiApplication::languageModel()
2134 if (d->language_model_)
2135 return d->language_model_;
2137 QStandardItemModel * lang_model = new QStandardItemModel(this);
2138 lang_model->insertColumns(0, 3);
2140 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2141 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2142 Languages::const_iterator it = lyx::languages.begin();
2143 Languages::const_iterator end = lyx::languages.end();
2144 for (; it != end; ++it) {
2145 current_row = lang_model->rowCount();
2146 lang_model->insertRows(current_row, 1);
2147 QModelIndex pl_item = lang_model->index(current_row, 0);
2148 QModelIndex sp_item = lang_model->index(current_row, 1);
2149 QModelIndex th_item = lang_model->index(current_row, 2);
2150 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2151 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2152 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2153 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2154 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2155 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2156 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2157 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2158 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2159 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2161 d->language_model_ = new QSortFilterProxyModel(this);
2162 d->language_model_->setSourceModel(lang_model);
2163 #if QT_VERSION >= 0x040300
2164 d->language_model_->setSortLocaleAware(true);
2166 return d->language_model_;
2170 void GuiApplication::restoreGuiSession()
2172 if (!lyxrc.load_session)
2175 Session & session = theSession();
2176 LastOpenedSection::LastOpened const & lastopened =
2177 session.lastOpened().getfiles();
2179 validateCurrentView();
2181 FileName active_file;
2182 // do not add to the lastfile list since these files are restored from
2183 // last session, and should be already there (regular files), or should
2184 // not be added at all (help files).
2185 for (size_t i = 0; i < lastopened.size(); ++i) {
2186 FileName const & file_name = lastopened[i].file_name;
2187 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2188 && current_view_->documentBufferView() != 0)) {
2189 boost::crc_32_type crc;
2190 string const & fname = file_name.absFileName();
2191 crc = for_each(fname.begin(), fname.end(), crc);
2192 createView(crc.checksum());
2194 current_view_->loadDocument(file_name, false);
2196 if (lastopened[i].active)
2197 active_file = file_name;
2200 // Restore last active buffer
2201 Buffer * buffer = theBufferList().getBuffer(active_file);
2202 if (buffer && current_view_)
2203 current_view_->setBuffer(buffer);
2205 // clear this list to save a few bytes of RAM
2206 session.lastOpened().clear();
2210 QString const GuiApplication::romanFontName()
2213 font.setKerning(false);
2214 font.setStyleHint(QFont::Serif);
2215 font.setFamily("serif");
2217 return QFontInfo(font).family();
2221 QString const GuiApplication::sansFontName()
2224 font.setKerning(false);
2225 font.setStyleHint(QFont::SansSerif);
2226 font.setFamily("sans");
2228 return QFontInfo(font).family();
2232 QString const GuiApplication::typewriterFontName()
2235 font.setKerning(false);
2236 font.setStyleHint(QFont::TypeWriter);
2237 font.setFamily("monospace");
2239 return QFontInfo(font).family();
2243 void GuiApplication::handleRegularEvents()
2245 ForkedCallsController::handleCompletedProcesses();
2249 bool GuiApplication::event(QEvent * e)
2252 case QEvent::FileOpen: {
2253 // Open a file; this happens only on Mac OS X for now.
2255 // We do this asynchronously because on startup the batch
2256 // commands are not executed here yet and the gui is not ready
2258 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2259 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2260 processFuncRequestAsync(fr);
2265 return QApplication::event(e);
2270 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2273 return QApplication::notify(receiver, event);
2275 catch (ExceptionMessage const & e) {
2277 case ErrorException:
2279 setQuitOnLastWindowClosed(false);
2281 Alert::error(e.title_, e.details_);
2283 // Properly crash in debug mode in order to get a useful backtrace.
2286 // In release mode, try to exit gracefully.
2289 case BufferException: {
2290 if (!current_view_ || !current_view_->documentBufferView())
2292 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2293 docstring details = e.details_ + '\n';
2294 details += buf->emergencyWrite();
2295 theBufferList().release(buf);
2296 details += "\n" + _("The current document was closed.");
2297 Alert::error(e.title_, details);
2300 case WarningException:
2301 Alert::warning(e.title_, e.details_);
2305 catch (exception const & e) {
2306 docstring s = _("LyX has caught an exception, it will now "
2307 "attempt to save all unsaved documents and exit."
2309 s += from_ascii(e.what());
2310 Alert::error(_("Software exception Detected"), s);
2314 docstring s = _("LyX has caught some really weird exception, it will "
2315 "now attempt to save all unsaved documents and exit.");
2316 Alert::error(_("Software exception Detected"), s);
2324 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2326 QColor const & qcol = d->color_cache_.get(col);
2327 if (!qcol.isValid()) {
2333 rgbcol.r = qcol.red();
2334 rgbcol.g = qcol.green();
2335 rgbcol.b = qcol.blue();
2340 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2342 QColor const qcol(lcolor.getX11Name(col).c_str());
2343 if (!qcol.isValid()) {
2349 rgbcol.r = qcol.red();
2350 rgbcol.g = qcol.green();
2351 rgbcol.b = qcol.blue();
2356 string const GuiApplication::hexName(ColorCode col)
2358 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2362 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2364 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2365 d->socket_notifiers_[fd] = sn;
2366 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2370 void GuiApplication::socketDataReceived(int fd)
2372 d->socket_notifiers_[fd]->func_();
2376 void GuiApplication::unregisterSocketCallback(int fd)
2378 d->socket_notifiers_.take(fd)->setEnabled(false);
2382 void GuiApplication::commitData(QSessionManager & sm)
2384 /// The implementation is required to avoid an application exit
2385 /// when session state save is triggered by session manager.
2386 /// The default implementation sends a close event to all
2387 /// visible top level widgets when session managment allows
2389 /// We are changing that to close all wiew one by one.
2390 /// FIXME: verify if the default implementation is enough now.
2391 #ifdef QT_NO_SESSIONMANAGER
2393 #warning Qt is compiled without session manager
2395 #pragma message("warning: Qt is compiled without session manager")
2399 if (sm.allowsInteraction() && !closeAllViews())
2405 void GuiApplication::unregisterView(GuiView * gv)
2407 LASSERT(d->views_[gv->id()] == gv, /**/);
2408 d->views_.remove(gv->id());
2409 if (current_view_ == gv)
2414 bool GuiApplication::closeAllViews()
2416 if (d->views_.empty())
2419 // When a view/window was closed before without quitting LyX, there
2420 // are already entries in the lastOpened list.
2421 theSession().lastOpened().clear();
2423 QList<GuiView *> views = d->views_.values();
2424 foreach (GuiView * view, views) {
2425 if (!view->closeScheduled())
2434 GuiView & GuiApplication::view(int id) const
2436 LASSERT(d->views_.contains(id), /**/);
2437 return *d->views_.value(id);
2441 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2443 QList<GuiView *> views = d->views_.values();
2444 foreach (GuiView * view, views)
2445 view->hideDialog(name, inset);
2449 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2451 Buffer const * buffer_ = 0;
2452 QHash<int, GuiView *>::iterator end = d->views_.end();
2453 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2454 if (Buffer const * ptr = (*it)->updateInset(inset))
2461 bool GuiApplication::searchMenu(FuncRequest const & func,
2462 docstring_list & names) const
2464 return d->menus_.searchMenu(func, names);
2468 // Ensure that a file is read only once (prevents include loops)
2469 static QStringList uifiles;
2470 // store which ui files define Toolbars
2471 static QStringList toolbar_uifiles;
2474 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2485 LexerKeyword uitags[] = {
2486 { "format", ui_format },
2487 { "include", ui_include },
2488 { "menuset", ui_menuset },
2489 { "toolbars", ui_toolbars },
2490 { "toolbarset", ui_toolbarset }
2494 lex.setFile(ui_path);
2496 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2500 if (lyxerr.debugging(Debug::PARSER))
2501 lex.printTable(lyxerr);
2504 // format before introduction of format tag
2505 unsigned int format = 0;
2506 while (lex.isOK()) {
2507 int const status = lex.lex();
2509 // we have to do this check here, outside the switch,
2510 // because otherwise we would start reading include files,
2511 // e.g., if the first tag we hit was an include tag.
2512 if (status == ui_format)
2514 format = lex.getInteger();
2518 // this will trigger unless the first tag we hit is a format
2519 // tag, with the right format.
2520 if (format != LFUN_FORMAT)
2521 return FormatMismatch;
2524 case Lexer::LEX_FEOF:
2529 QString const file = toqstr(lex.getString());
2530 bool const success = readUIFile(file, true);
2532 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2539 d->menus_.read(lex);
2543 d->toolbars_.readToolbars(lex);
2547 d->toolbars_.readToolbarSettings(lex);
2548 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2552 if (!rtrim(lex.getString()).empty())
2553 lex.printError("LyX::ReadUIFile: "
2554 "Unknown menu tag: `$$Token'");
2556 LYXERR0("Error with status: " << status);
2562 return (error ? ReadError : ReadOK);
2566 bool GuiApplication::readUIFile(QString const & name, bool include)
2568 LYXERR(Debug::INIT, "About to read " << name << "...");
2572 ui_path = libFileSearch("ui", name, "inc");
2573 if (ui_path.empty())
2574 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2576 ui_path = libFileSearch("ui", name, "ui");
2579 if (ui_path.empty()) {
2580 static const QString defaultUIFile = "default";
2581 LYXERR(Debug::INIT, "Could not find " << name);
2583 Alert::warning(_("Could not find UI definition file"),
2584 bformat(_("Error while reading the included file\n%1$s\n"
2585 "Please check your installation."), qstring_to_ucs4(name)));
2588 if (name == defaultUIFile) {
2589 LYXERR(Debug::INIT, "Could not find default UI file!!");
2590 Alert::warning(_("Could not find default UI file"),
2591 _("LyX could not find the default UI file!\n"
2592 "Please check your installation."));
2595 Alert::warning(_("Could not find UI definition file"),
2596 bformat(_("Error while reading the configuration file\n%1$s\n"
2597 "Falling back to default.\n"
2598 "Please look under Tools>Preferences>User Interface and\n"
2599 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2600 return readUIFile(defaultUIFile, false);
2603 QString const uifile = toqstr(ui_path.absFileName());
2604 if (uifiles.contains(uifile)) {
2606 // We are reading again the top uifile so reset the safeguard:
2609 d->toolbars_.reset();
2611 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2612 << "Is this an include loop?");
2616 uifiles.push_back(uifile);
2618 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2620 ReturnValues retval = readUIFile(ui_path);
2622 if (retval == FormatMismatch) {
2623 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2624 FileName const tempfile = FileName::tempName("convert_ui");
2625 bool const success = prefs2prefs(ui_path, tempfile, true);
2627 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2628 " to format " << LFUN_FORMAT << ".");
2630 retval = readUIFile(tempfile);
2631 tempfile.removeFile();
2635 if (retval != ReadOK) {
2636 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2644 settings.beginGroup("ui_files");
2645 bool touched = false;
2646 for (int i = 0; i != uifiles.size(); ++i) {
2647 QFileInfo fi(uifiles[i]);
2648 QDateTime const date_value = fi.lastModified();
2649 QString const name_key = QString::number(i);
2650 // if an ui file which defines Toolbars has changed,
2651 // we have to reset the settings
2652 if (toolbar_uifiles.contains(uifiles[i])
2653 && (!settings.contains(name_key)
2654 || settings.value(name_key).toString() != uifiles[i]
2655 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2657 settings.setValue(name_key, uifiles[i]);
2658 settings.setValue(name_key + "/date", date_value);
2661 settings.endGroup();
2663 settings.remove("views");
2669 void GuiApplication::onLastWindowClosed()
2671 if (d->global_menubar_)
2672 d->global_menubar_->grabKeyboard();
2676 void GuiApplication::startLongOperation() {
2677 d->key_checker_.start();
2681 bool GuiApplication::longOperationCancelled() {
2682 return d->key_checker_.pressed();
2686 void GuiApplication::stopLongOperation() {
2687 d->key_checker_.stop();
2691 bool GuiApplication::longOperationStarted() {
2692 return d->key_checker_.started();
2696 ////////////////////////////////////////////////////////////////////////
2698 // X11 specific stuff goes here...
2701 bool GuiApplication::x11EventFilter(XEvent * xev)
2706 switch (xev->type) {
2707 case SelectionRequest: {
2708 if (xev->xselectionrequest.selection != XA_PRIMARY)
2710 LYXERR(Debug::SELECTION, "X requested selection.");
2711 BufferView * bv = current_view_->currentBufferView();
2713 docstring const sel = bv->requestSelection();
2715 d->selection_.put(sel);
2719 case SelectionClear: {
2720 if (xev->xselectionclear.selection != XA_PRIMARY)
2722 LYXERR(Debug::SELECTION, "Lost selection.");
2723 BufferView * bv = current_view_->currentBufferView();
2725 bv->clearSelection();
2733 } // namespace frontend
2736 void hideDialogs(std::string const & name, Inset * inset)
2739 frontend::guiApp->hideDialogs(name, inset);
2743 ////////////////////////////////////////////////////////////////////
2747 ////////////////////////////////////////////////////////////////////
2749 frontend::FontLoader & theFontLoader()
2751 LASSERT(frontend::guiApp, /**/);
2752 return frontend::guiApp->fontLoader();
2756 frontend::FontMetrics const & theFontMetrics(Font const & f)
2758 return theFontMetrics(f.fontInfo());
2762 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2764 LASSERT(frontend::guiApp, /**/);
2765 return frontend::guiApp->fontLoader().metrics(f);
2769 ////////////////////////////////////////////////////////////////////
2773 ////////////////////////////////////////////////////////////////////
2775 frontend::Clipboard & theClipboard()
2777 LASSERT(frontend::guiApp, /**/);
2778 return frontend::guiApp->clipboard();
2782 frontend::Selection & theSelection()
2784 LASSERT(frontend::guiApp, /**/);
2785 return frontend::guiApp->selection();
2791 #include "moc_GuiApplication.cpp"