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/linkback/LinkBackProxy.h"
86 #include <QFileOpenEvent>
90 #include <QImageReader>
93 #include <QLibraryInfo>
95 #include <QMacPasteboardMime>
100 #include <QPixmapCache>
102 #include <QSessionManager>
104 #include <QShowEvent>
105 #include <QSocketNotifier>
106 #include <QSortFilterProxyModel>
107 #include <QStandardItemModel>
108 #include <QTextCodec>
110 #include <QTranslator>
111 #if QT_VERSION >= 0x040400
112 #include <QThreadPool>
117 #include <X11/Xatom.h>
118 #include <X11/Xlib.h>
124 #include <QWindowsMime>
131 #include "support/bind.h"
132 #include <boost/crc.hpp>
139 using namespace lyx::support;
142 static void initializeResources()
144 static bool initialized = false;
146 Q_INIT_RESOURCE(Resources);
154 frontend::Application * createApplication(int & argc, char * argv[])
157 // prune -geometry argument(s) by shifting
158 // the following ones 2 places down.
159 for (int i = 0 ; i < argc ; ++i) {
160 if (strcmp(argv[i], "-geometry") == 0) {
161 int const remove = (i+1) < argc ? 2 : 1;
163 for (int j = i; j < argc; ++j)
164 argv[j] = argv[j + remove];
169 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
170 // I'd rather do that in the constructor, but I do not think that
171 // the palette is accessible there.
172 guiApp->colorCache().setPalette(guiApp->palette());
179 /// Return the list of loadable formats.
180 vector<string> loadableImageFormats()
184 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
186 LYXERR(Debug::GRAPHICS,
187 "\nThe image loader can load the following directly:\n");
189 if (qt_formats.empty())
190 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
192 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
194 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
196 string ext = ascii_lowercase((const char *) *it);
207 ////////////////////////////////////////////////////////////////////////
209 // Icon loading support code
211 ////////////////////////////////////////////////////////////////////////
221 bool operator<(PngMap const & lhs, PngMap const & rhs)
223 return lhs.key < rhs.key;
229 CompareKey(QString const & name) : name_(name) {}
230 bool operator()(PngMap const & other) const { return other.key == name_; }
236 // this must be sorted alphabetically
237 // Upper case comes before lower case
238 PngMap sorted_png_map[] = {
239 { "Bumpeq", "bumpeq2" },
242 { "Delta", "delta2" },
243 { "Diamond", "diamond2" },
244 { "Downarrow", "downarrow2" },
245 { "Gamma", "gamma2" },
246 { "Lambda", "lambda2" },
247 { "Leftarrow", "leftarrow2" },
248 { "Leftrightarrow", "leftrightarrow2" },
249 { "Longleftarrow", "longleftarrow2" },
250 { "Longleftrightarrow", "longleftrightarrow2" },
251 { "Longrightarrow", "longrightarrow2" },
252 { "Omega", "omega2" },
256 { "Rightarrow", "rightarrow2" },
257 { "Sigma", "sigma2" },
258 { "Subset", "subset2" },
259 { "Supset", "supset2" },
260 { "Theta", "theta2" },
261 { "Uparrow", "uparrow2" },
262 { "Updownarrow", "updownarrow2" },
263 { "Upsilon", "upsilon2" },
264 { "Vdash", "vdash3" },
267 { "nLeftarrow", "nleftarrow2" },
268 { "nLeftrightarrow", "nleftrightarrow2" },
269 { "nRightarrow", "nrightarrow2" },
270 { "nVDash", "nvdash3" },
271 { "nvDash", "nvdash2" },
272 { "textrm \\AA", "textrm_AA"},
273 { "textrm \\O", "textrm_O"},
274 { "vDash", "vdash2" }
277 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
280 QString findPng(QString const & name)
282 PngMap const * const begin = sorted_png_map;
283 PngMap const * const end = begin + nr_sorted_png_map;
284 LASSERT(sorted(begin, end), /**/);
286 PngMap const * const it = find_if(begin, end, CompareKey(name));
290 png_name = it->value;
293 png_name.replace('_', "underscore");
294 png_name.replace(' ', '_');
296 // This way we can have "math-delim { }" on the toolbar.
297 png_name.replace('(', "lparen");
298 png_name.replace(')', "rparen");
299 png_name.replace('[', "lbracket");
300 png_name.replace(']', "rbracket");
301 png_name.replace('{', "lbrace");
302 png_name.replace('}', "rbrace");
303 png_name.replace('|', "bars");
304 png_name.replace(',', "thinspace");
305 png_name.replace(':', "mediumspace");
306 png_name.replace(';', "thickspace");
307 png_name.replace('!', "negthinspace");
310 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
311 << "Looking for math PNG called \"" << png_name << '"');
318 QString iconName(FuncRequest const & f, bool unknown)
320 initializeResources();
324 switch (f.action()) {
325 case LFUN_MATH_INSERT:
326 if (!f.argument().empty()) {
328 name1 = findPng(toqstr(f.argument()).mid(1));
331 case LFUN_MATH_DELIM:
332 case LFUN_MATH_BIGDELIM:
334 name1 = findPng(toqstr(f.argument()));
338 name1 = toqstr(f.argument());
340 case LFUN_COMMAND_ALTERNATIVES: {
341 // use the first of the alternative commands
343 docstring dummy = split(f.argument(), firstcom, ';');
344 name1 = toqstr(firstcom);
345 // FIXME: we should rename the icons to tabular-xxx instead of
346 // "tabular-feature-xxx"
347 name1.replace("inset-modify tabular", "tabular-feature");
348 name1.replace(' ', '_');
351 case LFUN_INSET_MODIFY: {
352 // FIXME: we should rename the icons to tabular-xxx instead of
353 // "tabular-feature-xxx" and generalize this naming to all
354 // insets, not to tabular using ones.
356 string const command = split(to_utf8(f.argument()), inset_name, ' ');
357 if (insetCode(inset_name) == TABULAR_CODE) {
358 name1 = "tabular-feature "+ toqstr(command);
359 name1.replace(' ', '_');
364 name2 = toqstr(lyxaction.getActionName(f.action()));
367 if (!f.argument().empty()) {
368 name1 = name2 + ' ' + toqstr(f.argument());
369 name1.replace(' ', '_');
370 name1.replace('\\', "backslash");
374 QString imagedir = "images/" + path;
375 FileName fname = imageLibFileSearch(imagedir, name1, "png");
377 return toqstr(fname.absFileName());
379 fname = imageLibFileSearch(imagedir, name2, "png");
381 return toqstr(fname.absFileName());
383 path = ":/images/" + path;
386 LYXERR0("Directory " << path << " not found in resource!");
390 if (res.exists(name1))
394 if (res.exists(name2))
397 LYXERR(Debug::GUI, "Cannot find icon with filename "
398 << "\"" << name1 << "\""
400 << "\"" << name2 << "\""
402 << lyxaction.getActionName(f.action())
403 << '(' << to_utf8(f.argument()) << ")\"");
406 imagedir = "images/";
407 fname = imageLibFileSearch(imagedir, "unknown", "png");
409 return toqstr(fname.absFileName());
410 return QString(":/images/unknown.png");
416 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
419 QString imagedir = path;
420 FileName fname = imageLibFileSearch(imagedir, name, ext);
421 QString path1 = toqstr(fname.absFileName());
422 QString path2 = ":/" + path + name + "." + ext;
424 if (pixmap.load(path1)) {
427 else if (pixmap.load(path2)) {
431 LYXERR0("Cannot load pixmap \""
432 << path << name << '.' << ext
433 << "\", please verify resource system!");
438 QIcon getIcon(FuncRequest const & f, bool unknown)
440 QString icon = iconName(f, unknown);
444 //LYXERR(Debug::GUI, "Found icon: " << icon);
446 if (!pm.load(icon)) {
447 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
455 ////////////////////////////////////////////////////////////////////////
457 // LyX server support code.
459 ////////////////////////////////////////////////////////////////////////
461 class SocketNotifier : public QSocketNotifier
464 /// connect a connection notification from the LyXServerSocket
465 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
466 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
470 /// The callback function
471 Application::SocketCallback func_;
475 ////////////////////////////////////////////////////////////////////////
477 // Mac specific stuff goes here...
479 ////////////////////////////////////////////////////////////////////////
481 class MenuTranslator : public QTranslator
484 MenuTranslator(QObject * parent)
485 : QTranslator(parent)
488 QString translate(const char * /*context*/,
489 const char * sourceText,
490 const char * /*comment*/ = 0)
492 string const s = sourceText;
493 if (s == N_("About %1") || s == N_("Preferences")
494 || s == N_("Reconfigure") || s == N_("Quit %1"))
501 class GlobalMenuBar : public QMenuBar
505 GlobalMenuBar() : QMenuBar(0) {}
508 bool event(QEvent * e)
510 if (e->type() == QEvent::ShortcutOverride) {
511 // && activeWindow() == 0) {
512 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
514 setKeySymbol(&sym, ke);
515 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
524 // QMacPasteboardMimeGraphics can only be compiled on Mac.
526 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
529 QMacPasteboardMimeGraphics()
530 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
533 QString convertorName() { return "Graphics"; }
535 QString flavorFor(QString const & mime)
537 LYXERR(Debug::ACTION, "flavorFor " << mime);
538 if (mime == pdfMimeType())
539 return QLatin1String("com.adobe.pdf");
543 QString mimeFor(QString flav)
545 LYXERR(Debug::ACTION, "mimeFor " << flav);
546 if (flav == QLatin1String("com.adobe.pdf"))
547 return pdfMimeType();
551 bool canConvert(QString const & mime, QString flav)
553 return mimeFor(flav) == mime;
556 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
560 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
564 QList<QByteArray> convertFromMime(QString const & /*mime*/,
565 QVariant data, QString /*flav*/)
567 QList<QByteArray> ret;
568 ret.append(data.toByteArray());
574 ///////////////////////////////////////////////////////////////
576 // You can find more platform specific stuff at the end of this file...
578 ///////////////////////////////////////////////////////////////
580 ////////////////////////////////////////////////////////////////////////
581 // Windows specific stuff goes here...
584 // QWindowsMimeMetafile can only be compiled on Windows.
586 static FORMATETC cfFromMime(QString const & mimetype)
589 if (mimetype == emfMimeType()) {
590 formatetc.cfFormat = CF_ENHMETAFILE;
591 formatetc.tymed = TYMED_ENHMF;
592 } else if (mimetype == wmfMimeType()) {
593 formatetc.cfFormat = CF_METAFILEPICT;
594 formatetc.tymed = TYMED_MFPICT;
597 formatetc.dwAspect = DVASPECT_CONTENT;
598 formatetc.lindex = -1;
603 class QWindowsMimeMetafile : public QWindowsMime {
605 QWindowsMimeMetafile() {}
607 bool canConvertFromMime(FORMATETC const & formatetc,
608 QMimeData const * mimedata) const
613 bool canConvertToMime(QString const & mimetype,
614 IDataObject * pDataObj) const
616 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
618 FORMATETC formatetc = cfFromMime(mimetype);
619 return pDataObj->QueryGetData(&formatetc) == S_OK;
622 bool convertFromMime(FORMATETC const & formatetc,
623 const QMimeData * mimedata, STGMEDIUM * pmedium) const
628 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
629 QVariant::Type preferredType) const
632 if (!canConvertToMime(mimetype, pDataObj))
635 FORMATETC formatetc = cfFromMime(mimetype);
637 if (pDataObj->GetData(&formatetc, &s) != S_OK)
641 if (s.tymed == TYMED_ENHMF) {
642 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
643 data.resize(dataSize);
644 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
645 (LPBYTE)data.data());
646 } else if (s.tymed == TYMED_MFPICT) {
647 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
648 data.resize(dataSize);
649 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
650 (LPBYTE)data.data());
653 ReleaseStgMedium(&s);
659 QVector<FORMATETC> formatsForMime(QString const & mimetype,
660 QMimeData const * mimedata) const
662 QVector<FORMATETC> formats;
663 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
664 formats += cfFromMime(mimetype);
668 QString mimeForFormat(FORMATETC const & formatetc) const
670 switch (formatetc.cfFormat) {
672 return emfMimeType();
673 case CF_METAFILEPICT:
674 return wmfMimeType();
683 /// Allows to check whether ESC was pressed during a long operation
684 class KeyChecker : public QObject {
693 QCoreApplication::instance()->installEventFilter(this);
698 QCoreApplication::instance()->removeEventFilter(this);
702 QCoreApplication::processEvents();
705 bool started() const {
708 bool eventFilter(QObject *obj, QEvent *event) {
709 LYXERR(Debug::ACTION, "Event Type: " << event->type());
710 switch (event->type()) {
714 return QObject::eventFilter(obj, event);
716 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
717 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
725 ////////////////////////////////////////////////////////////////////////
726 // GuiApplication::Private definition and implementation.
727 ////////////////////////////////////////////////////////////////////////
729 struct GuiApplication::Private
731 Private(): language_model_(0), meta_fake_bit(NoModifier),
735 /// WMF Mime handler for Windows clipboard.
736 wmf_mime_ = new QWindowsMimeMetafile();
738 initKeySequences(&theTopLevelKeymap());
741 void initKeySequences(KeyMap * kb)
743 keyseq = KeySequence(kb, kb);
744 cancel_meta_seq = KeySequence(kb, kb);
748 QSortFilterProxyModel * language_model_;
750 GuiClipboard clipboard_;
752 GuiSelection selection_;
754 FontLoader font_loader_;
756 ColorCache color_cache_;
758 QTranslator qt_trans_;
760 QHash<int, SocketNotifier *> socket_notifiers_;
764 /// The global instance
767 /// this timer is used for any regular events one wants to
768 /// perform. at present it is used to check if forked processes
770 QTimer general_timer_;
772 /// delayed FuncRequests
773 std::queue<FuncRequest> func_request_queue_;
778 KeySequence cancel_meta_seq;
780 KeyModifier meta_fake_bit;
782 /// Multiple views container.
784 * Warning: This must not be a smart pointer as the destruction of the
785 * object is handled by Qt when the view is closed
786 * \sa Qt::WA_DeleteOnClose attribute.
788 QHash<int, GuiView *> views_;
790 /// Only used on mac.
791 GlobalMenuBar * global_menubar_;
794 /// Linkback mime handler for MacOSX.
795 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
799 /// WMF Mime handler for Windows clipboard.
800 QWindowsMimeMetafile * wmf_mime_;
803 /// Allows to check whether ESC was pressed during a long operation
804 KeyChecker key_checker_;
808 GuiApplication * guiApp;
810 GuiApplication::~GuiApplication()
813 closeAllLinkBackLinks();
819 GuiApplication::GuiApplication(int & argc, char ** argv)
820 : QApplication(argc, argv), current_view_(0),
821 d(new GuiApplication::Private)
823 QString app_name = "LyX";
824 QCoreApplication::setOrganizationName(app_name);
825 QCoreApplication::setOrganizationDomain("lyx.org");
826 QCoreApplication::setApplicationName(lyx_package);
828 // Install translator for GUI elements.
829 installTranslator(&d->qt_trans_);
831 // FIXME: quitOnLastWindowClosed is true by default. We should have a
832 // lyxrc setting for this in order to let the application stay resident.
833 // But then we need some kind of dock icon, at least on Windows.
835 if (lyxrc.quit_on_last_window_closed)
836 setQuitOnLastWindowClosed(false);
839 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
840 // seems to be the default case for applications like LyX.
841 setQuitOnLastWindowClosed(false);
842 // This allows to translate the strings that appear in the LyX menu.
843 /// A translator suitable for the entries in the LyX menu.
844 /// Only needed with Qt/Mac.
845 installTranslator(new MenuTranslator(this));
849 // doubleClickInterval() is 400 ms on X11 which is just too long.
850 // On Windows and Mac OS X, the operating system's value is used.
851 // On Microsoft Windows, calling this function sets the double
852 // click interval for all applications. So we don't!
853 QApplication::setDoubleClickInterval(300);
856 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
858 // needs to be done before reading lyxrc
860 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
864 // Set the cache to 5120 kilobytes which corresponds to screen size of
865 // 1280 by 1024 pixels with a color depth of 32 bits.
866 QPixmapCache::setCacheLimit(5120);
868 // Initialize RC Fonts
869 if (lyxrc.roman_font_name.empty())
870 lyxrc.roman_font_name = fromqstr(romanFontName());
872 if (lyxrc.sans_font_name.empty())
873 lyxrc.sans_font_name = fromqstr(sansFontName());
875 if (lyxrc.typewriter_font_name.empty())
876 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
878 d->general_timer_.setInterval(500);
879 connect(&d->general_timer_, SIGNAL(timeout()),
880 this, SLOT(handleRegularEvents()));
881 d->general_timer_.start();
883 #if QT_VERSION >= 0x040400
884 // maxThreadCount() defaults in general to 2 on single or dual-processor.
885 // This is clearly not enough in a time where we use threads for
886 // document preview and/or export. 20 should be OK.
887 QThreadPool::globalInstance()->setMaxThreadCount(20);
892 GuiApplication * theGuiApp()
894 return dynamic_cast<GuiApplication *>(theApp());
898 void GuiApplication::clearSession()
905 docstring Application::iconName(FuncRequest const & f, bool unknown)
907 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
911 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
916 BufferView * doc_bv = 0;
918 if (cmd.action() == LFUN_NOACTION) {
919 status.message(from_utf8(N_("Nothing to do")));
920 status.setEnabled(false);
923 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
924 status.setUnknown(true);
925 status.message(from_utf8(N_("Unknown action")));
926 status.setEnabled(false);
929 // Does the GuiApplication know something?
930 else if (getStatus(cmd, status)) { }
932 // If we do not have a GuiView, then other functions are disabled
933 else if (!current_view_)
934 status.setEnabled(false);
936 // Does the GuiView know something?
937 else if (current_view_->getStatus(cmd, status)) { }
939 // In LyX/Mac, when a dialog is open, the menus of the
940 // application can still be accessed without giving focus to
941 // the main window. In this case, we want to disable the menu
942 // entries that are buffer or view-related.
943 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
945 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
946 status.setEnabled(false);
949 // If we do not have a BufferView, then other functions are disabled
950 else if (!(bv = current_view_->currentBufferView()))
951 status.setEnabled(false);
953 // Does the current BufferView know something?
954 else if (bv->getStatus(cmd, status)) { }
956 // Does the current Buffer know something?
957 else if (bv->buffer().getStatus(cmd, status)) { }
959 // If we do not have a document BufferView, different from the
960 // current BufferView, then other functions are disabled
961 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
962 status.setEnabled(false);
964 // Does the document Buffer know something?
965 else if (doc_bv->buffer().getStatus(cmd, status)) { }
968 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
969 status.message(from_utf8(N_("Command not handled")));
970 status.setEnabled(false);
973 // the default error message if we disable the command
974 if (!status.enabled() && status.message().empty())
975 status.message(from_utf8(N_("Command disabled")));
981 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
983 // I would really like to avoid having this switch and rather try to
984 // encode this in the function itself.
985 // -- And I'd rather let an inset decide which LFUNs it is willing
986 // to handle (Andre')
988 switch (cmd.action()) {
990 // This could be used for the no-GUI version. The GUI version is handled in
991 // GuiView::getStatus(). See above.
993 case LFUN_BUFFER_WRITE:
994 case LFUN_BUFFER_WRITE_AS: {
995 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
996 enable = b && (b->isUnnamed() || !b->isClean());
1001 case LFUN_BOOKMARK_GOTO: {
1002 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1003 enable = theSession().bookmarks().isValid(num);
1007 case LFUN_BOOKMARK_CLEAR:
1008 enable = theSession().bookmarks().hasValid();
1011 // this one is difficult to get right. As a half-baked
1012 // solution, we consider only the first action of the sequence
1013 case LFUN_COMMAND_SEQUENCE: {
1014 // argument contains ';'-terminated commands
1015 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1016 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1017 func.setOrigin(cmd.origin());
1018 flag = getStatus(func);
1022 // we want to check if at least one of these is enabled
1023 case LFUN_COMMAND_ALTERNATIVES: {
1024 // argument contains ';'-terminated commands
1025 string arg = to_utf8(cmd.argument());
1026 while (!arg.empty()) {
1028 arg = split(arg, first, ';');
1029 FuncRequest func(lyxaction.lookupFunc(first));
1030 func.setOrigin(cmd.origin());
1031 flag = getStatus(func);
1032 // if this one is enabled, the whole thing is
1041 string name = to_utf8(cmd.argument());
1042 if (theTopLevelCmdDef().lock(name, func)) {
1043 func.setOrigin(cmd.origin());
1044 flag = getStatus(func);
1045 theTopLevelCmdDef().release(name);
1047 // catch recursion or unknown command
1048 // definition. all operations until the
1049 // recursion or unknown command definition
1050 // occurs are performed, so set the state to
1057 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1059 case LFUN_PREFERENCES_SAVE:
1060 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1061 case LFUN_DEBUG_LEVEL_SET:
1062 // these are handled in our dispatch()
1065 case LFUN_WINDOW_CLOSE:
1066 enable = d->views_.size() > 0;
1069 case LFUN_BUFFER_NEW:
1070 case LFUN_BUFFER_NEW_TEMPLATE:
1071 case LFUN_FILE_OPEN:
1072 case LFUN_HELP_OPEN:
1073 case LFUN_SCREEN_FONT_UPDATE:
1074 case LFUN_SET_COLOR:
1075 case LFUN_WINDOW_NEW:
1077 case LFUN_LYXRC_APPLY:
1078 case LFUN_COMMAND_PREFIX:
1080 case LFUN_META_PREFIX:
1081 case LFUN_RECONFIGURE:
1082 case LFUN_SERVER_GET_FILENAME:
1083 case LFUN_SERVER_NOTIFY:
1087 case LFUN_BUFFER_FORALL: {
1088 if (!currentView() || !currentView()->currentBufferView() || !¤tView()->currentBufferView()->buffer()) {
1089 flag.message(from_utf8(N_("Command not allowed without any visible document in the active window")));
1090 flag.setEnabled(false);
1101 flag.setEnabled(false);
1105 /// make a post-dispatch status message
1106 static docstring makeDispatchMessage(docstring const & msg,
1107 FuncRequest const & cmd)
1109 const bool verbose = (cmd.origin() == FuncRequest::MENU
1110 || cmd.origin() == FuncRequest::TOOLBAR
1111 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1113 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1114 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1118 docstring dispatch_msg = msg;
1119 if (!dispatch_msg.empty())
1120 dispatch_msg += ' ';
1122 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1124 bool argsadded = false;
1126 if (!cmd.argument().empty()) {
1127 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1128 comname += ' ' + cmd.argument();
1132 docstring const shortcuts = theTopLevelKeymap().
1133 printBindings(cmd, KeySequence::ForGui);
1135 if (!shortcuts.empty())
1136 comname += ": " + shortcuts;
1137 else if (!argsadded && !cmd.argument().empty())
1138 comname += ' ' + cmd.argument();
1140 if (!comname.empty()) {
1141 comname = rtrim(comname);
1142 dispatch_msg += '(' + rtrim(comname) + ')';
1144 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1145 return dispatch_msg;
1149 void GuiApplication::dispatch(FuncRequest const & cmd)
1151 Buffer * buffer = 0;
1152 if (current_view_ && current_view_->currentBufferView()) {
1153 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1154 buffer = ¤t_view_->currentBufferView()->buffer();
1156 buffer->undo().beginUndoGroup();
1160 // redraw the screen at the end (first of the two drawing steps).
1161 // This is done unless explicitly requested otherwise
1162 dr.screenUpdate(Update::FitCursor);
1164 updateCurrentView(cmd, dr);
1166 // the buffer may have been closed by one action
1167 if (theBufferList().isLoaded(buffer))
1168 buffer->undo().endUndoGroup();
1172 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1177 BufferView * bv = current_view_->currentBufferView();
1179 if (dr.needBufferUpdate()) {
1180 bv->cursor().clearBufferUpdate();
1181 bv->buffer().updateBuffer();
1183 // BufferView::update() updates the ViewMetricsInfo and
1184 // also initializes the position cache for all insets in
1185 // (at least partially) visible top-level paragraphs.
1186 // We will redraw the screen only if needed.
1187 bv->processUpdateFlags(dr.screenUpdate());
1189 // Do we have a selection?
1190 theSelection().haveSelection(bv->cursor().selection());
1193 current_view_->restartCursor();
1195 if (dr.needMessageUpdate()) {
1196 // Some messages may already be translated, so we cannot use _()
1197 current_view_->message(makeDispatchMessage(
1198 translateIfPossible(dr.message()), cmd));
1203 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1204 bool switchToBuffer)
1206 if (!theSession().bookmarks().isValid(idx))
1208 BookmarksSection::Bookmark const & bm =
1209 theSession().bookmarks().bookmark(idx);
1210 LASSERT(!bm.filename.empty(), /**/);
1211 string const file = bm.filename.absFileName();
1212 // if the file is not opened, open it.
1213 if (!theBufferList().exists(bm.filename)) {
1215 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1219 // open may fail, so we need to test it again
1220 if (!theBufferList().exists(bm.filename))
1223 // bm can be changed when saving
1224 BookmarksSection::Bookmark tmp = bm;
1226 // Special case idx == 0 used for back-from-back jump navigation
1228 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1230 // if the current buffer is not that one, switch to it.
1231 BufferView * doc_bv = current_view_ ?
1232 current_view_->documentBufferView() : 0;
1233 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1234 if (switchToBuffer) {
1235 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1238 doc_bv = current_view_->documentBufferView();
1243 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1244 if (!doc_bv->moveToPosition(
1245 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1252 // Cursor jump succeeded!
1253 Cursor const & cur = doc_bv->cursor();
1254 pit_type new_pit = cur.pit();
1255 pos_type new_pos = cur.pos();
1256 int new_id = cur.paragraph().id();
1258 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1259 // see http://www.lyx.org/trac/ticket/3092
1260 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1261 || bm.top_id != new_id) {
1262 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1263 new_pit, new_pos, new_id);
1267 // This function runs "configure" and then rereads lyx.defaults to
1268 // reconfigure the automatic settings.
1269 void GuiApplication::reconfigure(string const & option)
1271 // emit message signal.
1273 current_view_->message(_("Running configure..."));
1275 // Run configure in user lyx directory
1276 PathChanger p(package().user_support());
1277 string configure_command = package().configure_command();
1278 configure_command += option;
1280 int ret = one.startscript(Systemcall::Wait, configure_command);
1282 // emit message signal.
1284 current_view_->message(_("Reloading configuration..."));
1285 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1286 // Re-read packages.lst
1287 LaTeXPackages::getAvailable();
1290 Alert::information(_("System reconfiguration failed"),
1291 _("The system reconfiguration has failed.\n"
1292 "Default textclass is used but LyX may "
1293 "not be able to work properly.\n"
1294 "Please reconfigure again if needed."));
1296 Alert::information(_("System reconfigured"),
1297 _("The system has been reconfigured.\n"
1298 "You need to restart LyX to make use of any\n"
1299 "updated document class specifications."));
1302 void GuiApplication::validateCurrentView()
1304 if (!d->views_.empty() && !current_view_) {
1305 // currently at least one view exists but no view has the focus.
1306 // choose the last view to make it current.
1307 // a view without any open document is preferred.
1308 GuiView * candidate = 0;
1309 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1310 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1311 for (; it != end; ++it) {
1313 if (!candidate->documentBufferView())
1316 setCurrentView(candidate);
1320 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1322 string const argument = to_utf8(cmd.argument());
1323 FuncCode const action = cmd.action();
1325 LYXERR(Debug::ACTION, "cmd: " << cmd);
1327 // we have not done anything wrong yet.
1330 FuncStatus const flag = getStatus(cmd);
1331 if (!flag.enabled()) {
1332 // We cannot use this function here
1333 LYXERR(Debug::ACTION, "action "
1334 << lyxaction.getActionName(action)
1335 << " [" << action << "] is disabled at this location");
1336 dr.setMessage(flag.message());
1338 dr.dispatched(false);
1339 dr.screenUpdate(Update::None);
1340 dr.clearBufferUpdate();
1344 if (cmd.origin() == FuncRequest::LYXSERVER) {
1345 if (current_view_ && current_view_->currentBufferView())
1346 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1347 // we will also need to redraw the screen at the end
1348 dr.screenUpdate(Update::FitCursor);
1351 // Assumes that the action will be dispatched.
1352 dr.dispatched(true);
1354 switch (cmd.action()) {
1356 case LFUN_WINDOW_NEW:
1357 createView(toqstr(cmd.argument()));
1360 case LFUN_WINDOW_CLOSE:
1361 // update bookmark pit of the current buffer before window close
1362 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1363 gotoBookmark(i+1, false, false);
1364 // clear the last opened list, because
1365 // maybe this will end the session
1366 theSession().lastOpened().clear();
1367 // check for valid current_view_
1368 validateCurrentView();
1370 current_view_->closeScheduled();
1374 // quitting is triggered by the gui code
1375 // (leaving the event loop).
1377 current_view_->message(from_utf8(N_("Exiting.")));
1378 if (closeAllViews())
1382 case LFUN_SCREEN_FONT_UPDATE: {
1383 // handle the screen font changes.
1384 d->font_loader_.update();
1385 // Backup current_view_
1386 GuiView * view = current_view_;
1387 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1388 // to skip the refresh.
1390 theBufferList().changed(false);
1391 // Restore current_view_
1392 current_view_ = view;
1396 case LFUN_BUFFER_NEW:
1397 validateCurrentView();
1398 if (d->views_.empty()
1399 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1400 createView(QString(), false); // keep hidden
1401 current_view_->newDocument(to_utf8(cmd.argument()), false);
1402 current_view_->show();
1403 setActiveWindow(current_view_);
1405 current_view_->newDocument(to_utf8(cmd.argument()), false);
1409 case LFUN_BUFFER_NEW_TEMPLATE:
1410 validateCurrentView();
1411 if (d->views_.empty()
1412 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1414 current_view_->newDocument(to_utf8(cmd.argument()), true);
1415 if (!current_view_->documentBufferView())
1416 current_view_->close();
1418 current_view_->newDocument(to_utf8(cmd.argument()), true);
1422 case LFUN_FILE_OPEN: {
1423 validateCurrentView();
1424 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1425 string const fname = to_utf8(cmd.argument());
1426 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1427 && current_view_->documentBufferView() != 0)) {
1428 // We want the ui session to be saved per document and not per
1429 // window number. The filename crc is a good enough identifier.
1430 boost::crc_32_type crc;
1431 crc = for_each(fname.begin(), fname.end(), crc);
1432 createView(crc.checksum());
1433 current_view_->openDocument(fname);
1434 if (current_view_ && !current_view_->documentBufferView())
1435 current_view_->close();
1437 current_view_->openDocument(fname);
1441 case LFUN_HELP_OPEN: {
1442 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1443 if (current_view_ == 0)
1445 string const arg = to_utf8(cmd.argument());
1447 current_view_->message(_("Missing argument"));
1450 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1452 fname = i18nLibFileSearch("examples", arg, "lyx");
1454 if (fname.empty()) {
1455 lyxerr << "LyX: unable to find documentation file `"
1456 << arg << "'. Bad installation?" << endl;
1459 current_view_->message(bformat(_("Opening help file %1$s..."),
1460 makeDisplayPath(fname.absFileName())));
1461 Buffer * buf = current_view_->loadDocument(fname, false);
1463 #ifndef DEVEL_VERSION
1465 buf->setReadonly(true);
1472 case LFUN_SET_COLOR: {
1474 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1475 if (lyx_name.empty() || x11_name.empty()) {
1477 current_view_->message(
1478 _("Syntax: set-color <lyx_name> <x11_name>"));
1483 // FIXME: The graphics cache no longer has a changeDisplay method.
1484 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1485 bool const graphicsbg_changed =
1486 lyx_name == graphicsbg && x11_name != graphicsbg;
1487 if (graphicsbg_changed)
1488 graphics::GCache::get().changeDisplay(true);
1491 if (!lcolor.setColor(lyx_name, x11_name)) {
1493 current_view_->message(
1494 bformat(_("Set-color \"%1$s\" failed "
1495 "- color is undefined or "
1496 "may not be redefined"),
1497 from_utf8(lyx_name)));
1500 // Make sure we don't keep old colors in cache.
1501 d->color_cache_.clear();
1505 case LFUN_LYXRC_APPLY: {
1506 // reset active key sequences, since the bindings
1507 // are updated (bug 6064)
1509 LyXRC const lyxrc_orig = lyxrc;
1511 istringstream ss(to_utf8(cmd.argument()));
1512 bool const success = lyxrc.read(ss);
1515 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1516 << "Unable to read lyxrc data"
1521 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1527 case LFUN_COMMAND_PREFIX:
1528 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1533 d->meta_fake_bit = NoModifier;
1534 GuiView * gv = currentView();
1535 if (gv && gv->currentBufferView())
1536 // cancel any selection
1537 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1538 dr.setMessage(from_ascii(N_("Cancel")));
1541 case LFUN_META_PREFIX:
1542 d->meta_fake_bit = AltModifier;
1543 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1546 // --- Menus -----------------------------------------------
1547 case LFUN_RECONFIGURE:
1548 // argument is any additional parameter to the configure.py command
1549 reconfigure(to_utf8(cmd.argument()));
1552 // --- lyxserver commands ----------------------------
1553 case LFUN_SERVER_GET_FILENAME: {
1554 if (current_view_ && current_view_->documentBufferView()) {
1555 docstring const fname = from_utf8(
1556 current_view_->documentBufferView()->buffer().absFileName());
1557 dr.setMessage(fname);
1558 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1560 dr.setMessage(docstring());
1561 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1566 case LFUN_SERVER_NOTIFY: {
1567 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1568 dr.setMessage(dispatch_buffer);
1569 theServer().notifyClient(to_utf8(dispatch_buffer));
1573 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1574 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1580 string rest = split(argument, countstr, ' ');
1581 istringstream is(countstr);
1584 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1585 for (int i = 0; i < count; ++i)
1586 dispatch(lyxaction.lookupFunc(rest));
1590 case LFUN_COMMAND_SEQUENCE: {
1591 // argument contains ';'-terminated commands
1592 string arg = argument;
1593 // FIXME: this LFUN should also work without any view.
1594 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1595 ? &(current_view_->documentBufferView()->buffer()) : 0;
1597 buffer->undo().beginUndoGroup();
1598 while (!arg.empty()) {
1600 arg = split(arg, first, ';');
1601 FuncRequest func(lyxaction.lookupFunc(first));
1602 func.setOrigin(cmd.origin());
1605 // the buffer may have been closed by one action
1606 if (theBufferList().isLoaded(buffer))
1607 buffer->undo().endUndoGroup();
1611 case LFUN_BUFFER_FORALL: {
1612 GuiView * gv = currentView();
1613 Buffer * const buf = &gv->currentBufferView()->buffer();
1615 bool processVisible = true;
1616 bool processHidden = false;
1617 docstring msg = _("Applied the following command to all visible buffers in the active window: ");
1618 string commandToRun = argument;
1619 if (cmd.getArg(0) == "both") {
1620 processHidden = true;
1621 msg = _("Applied the following command to all visible and hidden buffers in the active window: ");
1622 commandToRun = cmd.getLongArg(1);
1623 } else if (cmd.getArg(0) == "visible") {
1624 commandToRun = cmd.getLongArg(1);
1625 } else if (cmd.getArg(0) == "hidden") {
1626 processHidden = true;
1627 processVisible = false;
1628 commandToRun = cmd.getLongArg(1);
1629 msg = _("Applied the following command to all hidden buffers in the active window: ");
1631 FuncRequest const funcToRun = lyxaction.lookupFunc(commandToRun);
1632 dr.setMessage(bformat(_("%1$s%2$s"), msg, from_utf8(commandToRun)));
1634 Buffer * const last = theBufferList().last();
1635 Buffer * b = theBufferList().first();
1636 Buffer * nextBuf = 0;
1637 // We cannot use a for loop as the buffer list cycles.
1640 nextBuf = theBufferList().next(b); //get next now bc LFUN might close current
1642 bool const hidden = !(gv && gv->workArea(*b));
1644 if (processHidden) {
1646 lyx::dispatch(funcToRun);
1647 gv->currentWorkArea()->view().hideWorkArea(gv->currentWorkArea());
1652 if (processVisible) {
1654 lyx::dispatch(funcToRun);
1663 if (theBufferList().isLoaded(buf)) //the LFUN might have closed buf
1668 case LFUN_COMMAND_ALTERNATIVES: {
1669 // argument contains ';'-terminated commands
1670 string arg = argument;
1671 while (!arg.empty()) {
1673 arg = split(arg, first, ';');
1674 FuncRequest func(lyxaction.lookupFunc(first));
1675 func.setOrigin(cmd.origin());
1676 FuncStatus const stat = getStatus(func);
1677 if (stat.enabled()) {
1687 if (theTopLevelCmdDef().lock(argument, func)) {
1688 func.setOrigin(cmd.origin());
1690 theTopLevelCmdDef().release(argument);
1692 if (func.action() == LFUN_UNKNOWN_ACTION) {
1693 // unknown command definition
1694 lyxerr << "Warning: unknown command definition `"
1698 // recursion detected
1699 lyxerr << "Warning: Recursion in the command definition `"
1700 << argument << "' detected"
1707 case LFUN_PREFERENCES_SAVE:
1708 lyxrc.write(support::makeAbsPath("preferences",
1709 package().user_support().absFileName()), false);
1712 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1713 string const fname = addName(addPath(package().user_support().absFileName(),
1714 "templates/"), "defaults.lyx");
1715 Buffer defaults(fname);
1717 istringstream ss(argument);
1720 int const unknown_tokens = defaults.readHeader(lex);
1722 if (unknown_tokens != 0) {
1723 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1724 << unknown_tokens << " unknown token"
1725 << (unknown_tokens == 1 ? "" : "s")
1729 if (defaults.writeFile(FileName(defaults.absFileName())))
1730 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1731 makeDisplayPath(fname)));
1734 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1739 case LFUN_BOOKMARK_GOTO:
1740 // go to bookmark, open unopened file and switch to buffer if necessary
1741 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1742 dr.screenUpdate(Update::Force | Update::FitCursor);
1745 case LFUN_BOOKMARK_CLEAR:
1746 theSession().bookmarks().clear();
1749 case LFUN_DEBUG_LEVEL_SET:
1750 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1754 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1757 current_view_->dispatch(cmd, dr);
1761 if (cmd.origin() == FuncRequest::LYXSERVER)
1762 updateCurrentView(cmd, dr);
1766 docstring GuiApplication::viewStatusMessage()
1768 // When meta-fake key is pressed, show the key sequence so far + "M-".
1769 if (d->meta_fake_bit != NoModifier)
1770 return d->keyseq.print(KeySequence::ForGui) + "M-";
1772 // Else, when a non-complete key sequence is pressed,
1773 // show the available options.
1774 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1775 return d->keyseq.printOptions(true);
1781 void GuiApplication::handleKeyFunc(FuncCode action)
1785 if (d->keyseq.length())
1787 GuiView * gv = currentView();
1788 LASSERT(gv && gv->currentBufferView(), return);
1789 BufferView * bv = gv->currentBufferView();
1790 bv->getIntl().getTransManager().deadkey(
1791 c, get_accent(action).accent, bv->cursor().innerText(),
1793 // Need to clear, in case the minibuffer calls these
1796 // copied verbatim from do_accent_char
1797 bv->cursor().resetAnchor();
1801 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1803 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1805 // Do nothing if we have nothing (JMarc)
1806 if (!keysym.isOK()) {
1807 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1809 current_view_->restartCursor();
1813 if (keysym.isModifier()) {
1815 current_view_->restartCursor();
1819 char_type encoded_last_key = keysym.getUCSEncoded();
1821 // Do a one-deep top-level lookup for
1822 // cancel and meta-fake keys. RVDK_PATCH_5
1823 d->cancel_meta_seq.reset();
1825 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1826 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1828 // When not cancel or meta-fake, do the normal lookup.
1829 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1830 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1831 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1832 // remove Caps Lock and Mod2 as a modifiers
1833 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1834 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1837 // Dont remove this unless you know what you are doing.
1838 d->meta_fake_bit = NoModifier;
1840 // Can this happen now ?
1841 if (func.action() == LFUN_NOACTION)
1842 func = FuncRequest(LFUN_COMMAND_PREFIX);
1844 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1845 << d->keyseq.print(KeySequence::Portable) << ']');
1847 // already here we know if it any point in going further
1848 // why not return already here if action == -1 and
1849 // num_bytes == 0? (Lgb)
1851 if (d->keyseq.length() > 1 && current_view_)
1852 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1855 // Maybe user can only reach the key via holding down shift.
1856 // Let's see. But only if shift is the only modifier
1857 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1858 LYXERR(Debug::KEY, "Trying without shift");
1859 func = d->keyseq.addkey(keysym, NoModifier);
1860 LYXERR(Debug::KEY, "Action now " << func.action());
1863 if (func.action() == LFUN_UNKNOWN_ACTION) {
1864 // Hmm, we didn't match any of the keysequences. See
1865 // if it's normal insertable text not already covered
1867 if (keysym.isText() && d->keyseq.length() == 1) {
1868 LYXERR(Debug::KEY, "isText() is true, inserting.");
1869 func = FuncRequest(LFUN_SELF_INSERT,
1870 FuncRequest::KEYBOARD);
1872 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1873 if (current_view_) {
1874 current_view_->message(_("Unknown function."));
1875 current_view_->restartCursor();
1881 if (func.action() == LFUN_SELF_INSERT) {
1882 if (encoded_last_key != 0) {
1883 docstring const arg(1, encoded_last_key);
1884 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1885 FuncRequest::KEYBOARD));
1886 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1889 processFuncRequest(func);
1893 void GuiApplication::processFuncRequest(FuncRequest const & func)
1895 lyx::dispatch(func);
1899 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1901 addToFuncRequestQueue(func);
1902 processFuncRequestQueueAsync();
1906 void GuiApplication::processFuncRequestQueue()
1908 while (!d->func_request_queue_.empty()) {
1909 processFuncRequest(d->func_request_queue_.front());
1910 d->func_request_queue_.pop();
1915 void GuiApplication::processFuncRequestQueueAsync()
1917 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1921 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1923 d->func_request_queue_.push(func);
1927 void GuiApplication::resetGui()
1929 // Set the language defined by the user.
1933 if (!readUIFile(toqstr(lyxrc.ui_file)))
1934 // Gives some error box here.
1937 if (d->global_menubar_)
1938 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1940 QHash<int, GuiView *>::iterator it;
1941 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1944 gv->setLayoutDirection(layoutDirection());
1948 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1952 void GuiApplication::createView(int view_id)
1954 createView(QString(), true, view_id);
1958 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1961 // release the keyboard which might have been grabed by the global
1962 // menubar on Mac to catch shortcuts even without any GuiView.
1963 if (d->global_menubar_)
1964 d->global_menubar_->releaseKeyboard();
1968 while (d->views_.find(id) != d->views_.end())
1971 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1972 GuiView * view = new GuiView(id);
1974 d->views_[id] = view;
1978 setActiveWindow(view);
1981 if (!geometry_arg.isEmpty()) {
1985 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1986 re.indexIn(geometry_arg);
1987 w = re.cap(1).toInt();
1988 h = re.cap(2).toInt();
1989 x = re.cap(3).toInt();
1990 y = re.cap(4).toInt();
1991 view->setGeometry(x, y, w, h);
1998 Clipboard & GuiApplication::clipboard()
2000 return d->clipboard_;
2004 Selection & GuiApplication::selection()
2006 return d->selection_;
2010 FontLoader & GuiApplication::fontLoader()
2012 return d->font_loader_;
2016 Toolbars const & GuiApplication::toolbars() const
2018 return d->toolbars_;
2022 Toolbars & GuiApplication::toolbars()
2024 return d->toolbars_;
2028 Menus const & GuiApplication::menus() const
2034 Menus & GuiApplication::menus()
2040 QList<int> GuiApplication::viewIds() const
2042 return d->views_.keys();
2046 ColorCache & GuiApplication::colorCache()
2048 return d->color_cache_;
2052 int GuiApplication::exec()
2054 // asynchronously handle batch commands. This event will be in
2055 // the event queue in front of other asynchronous events. Hence,
2056 // we can assume in the latter that the gui is setup already.
2057 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2059 return QApplication::exec();
2063 void GuiApplication::exit(int status)
2065 QApplication::exit(status);
2069 void GuiApplication::setGuiLanguage()
2071 QString const default_language = toqstr(getGuiMessages().language());
2072 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2073 QLocale const default_locale(default_language);
2074 QLocale::setDefault(default_locale);
2076 // install translation file for Qt built-in dialogs
2077 QString const language_name = QString("qt_") + default_locale.name();
2079 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2080 // Short-named translator can be loaded from a long name, but not the
2081 // opposite. Therefore, long name should be used without truncation.
2082 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2083 if (!d->qt_trans_.load(language_name,
2084 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2085 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2088 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2092 switch (default_locale.language()) {
2093 case QLocale::Arabic :
2094 case QLocale::Hebrew :
2095 case QLocale::Persian :
2096 case QLocale::Urdu :
2097 setLayoutDirection(Qt::RightToLeft);
2100 setLayoutDirection(Qt::LeftToRight);
2105 void GuiApplication::execBatchCommands()
2110 if (!readUIFile(toqstr(lyxrc.ui_file)))
2111 // Gives some error box here.
2115 #if QT_VERSION > 0x040600
2116 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2118 // Create the global default menubar which is shown for the dialogs
2119 // and if no GuiView is visible.
2120 // This must be done after the session was recovered to know the "last files".
2121 d->global_menubar_ = new GlobalMenuBar();
2122 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2125 lyx::execBatchCommands();
2129 QAbstractItemModel * GuiApplication::languageModel()
2131 if (d->language_model_)
2132 return d->language_model_;
2134 QStandardItemModel * lang_model = new QStandardItemModel(this);
2135 lang_model->insertColumns(0, 3);
2137 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2138 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2139 Languages::const_iterator it = lyx::languages.begin();
2140 Languages::const_iterator end = lyx::languages.end();
2141 for (; it != end; ++it) {
2142 current_row = lang_model->rowCount();
2143 lang_model->insertRows(current_row, 1);
2144 QModelIndex pl_item = lang_model->index(current_row, 0);
2145 QModelIndex sp_item = lang_model->index(current_row, 1);
2146 QModelIndex th_item = lang_model->index(current_row, 2);
2147 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2148 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2149 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2150 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2151 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2152 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2153 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2154 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2155 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2156 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2158 d->language_model_ = new QSortFilterProxyModel(this);
2159 d->language_model_->setSourceModel(lang_model);
2160 #if QT_VERSION >= 0x040300
2161 d->language_model_->setSortLocaleAware(true);
2163 return d->language_model_;
2167 void GuiApplication::restoreGuiSession()
2169 if (!lyxrc.load_session)
2172 Session & session = theSession();
2173 LastOpenedSection::LastOpened const & lastopened =
2174 session.lastOpened().getfiles();
2176 validateCurrentView();
2178 FileName active_file;
2179 // do not add to the lastfile list since these files are restored from
2180 // last session, and should be already there (regular files), or should
2181 // not be added at all (help files).
2182 for (size_t i = 0; i < lastopened.size(); ++i) {
2183 FileName const & file_name = lastopened[i].file_name;
2184 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2185 && current_view_->documentBufferView() != 0)) {
2186 boost::crc_32_type crc;
2187 string const & fname = file_name.absFileName();
2188 crc = for_each(fname.begin(), fname.end(), crc);
2189 createView(crc.checksum());
2191 current_view_->loadDocument(file_name, false);
2193 if (lastopened[i].active)
2194 active_file = file_name;
2197 // Restore last active buffer
2198 Buffer * buffer = theBufferList().getBuffer(active_file);
2199 if (buffer && current_view_)
2200 current_view_->setBuffer(buffer);
2202 // clear this list to save a few bytes of RAM
2203 session.lastOpened().clear();
2207 QString const GuiApplication::romanFontName()
2210 font.setKerning(false);
2211 font.setStyleHint(QFont::Serif);
2212 font.setFamily("serif");
2214 return QFontInfo(font).family();
2218 QString const GuiApplication::sansFontName()
2221 font.setKerning(false);
2222 font.setStyleHint(QFont::SansSerif);
2223 font.setFamily("sans");
2225 return QFontInfo(font).family();
2229 QString const GuiApplication::typewriterFontName()
2232 font.setKerning(false);
2233 font.setStyleHint(QFont::TypeWriter);
2234 font.setFamily("monospace");
2236 return QFontInfo(font).family();
2240 void GuiApplication::handleRegularEvents()
2242 ForkedCallsController::handleCompletedProcesses();
2246 bool GuiApplication::event(QEvent * e)
2249 case QEvent::FileOpen: {
2250 // Open a file; this happens only on Mac OS X for now.
2252 // We do this asynchronously because on startup the batch
2253 // commands are not executed here yet and the gui is not ready
2255 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2256 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2257 processFuncRequestAsync(fr);
2262 return QApplication::event(e);
2267 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2270 return QApplication::notify(receiver, event);
2272 catch (ExceptionMessage const & e) {
2274 case ErrorException:
2276 setQuitOnLastWindowClosed(false);
2278 Alert::error(e.title_, e.details_);
2280 // Properly crash in debug mode in order to get a useful backtrace.
2283 // In release mode, try to exit gracefully.
2286 case BufferException: {
2287 if (!current_view_ || !current_view_->documentBufferView())
2289 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2290 docstring details = e.details_ + '\n';
2291 details += buf->emergencyWrite();
2292 theBufferList().release(buf);
2293 details += "\n" + _("The current document was closed.");
2294 Alert::error(e.title_, details);
2297 case WarningException:
2298 Alert::warning(e.title_, e.details_);
2302 catch (exception const & e) {
2303 docstring s = _("LyX has caught an exception, it will now "
2304 "attempt to save all unsaved documents and exit."
2306 s += from_ascii(e.what());
2307 Alert::error(_("Software exception Detected"), s);
2311 docstring s = _("LyX has caught some really weird exception, it will "
2312 "now attempt to save all unsaved documents and exit.");
2313 Alert::error(_("Software exception Detected"), s);
2321 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2323 QColor const & qcol = d->color_cache_.get(col);
2324 if (!qcol.isValid()) {
2330 rgbcol.r = qcol.red();
2331 rgbcol.g = qcol.green();
2332 rgbcol.b = qcol.blue();
2337 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2339 QColor const qcol(lcolor.getX11Name(col).c_str());
2340 if (!qcol.isValid()) {
2346 rgbcol.r = qcol.red();
2347 rgbcol.g = qcol.green();
2348 rgbcol.b = qcol.blue();
2353 string const GuiApplication::hexName(ColorCode col)
2355 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2359 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2361 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2362 d->socket_notifiers_[fd] = sn;
2363 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2367 void GuiApplication::socketDataReceived(int fd)
2369 d->socket_notifiers_[fd]->func_();
2373 void GuiApplication::unregisterSocketCallback(int fd)
2375 d->socket_notifiers_.take(fd)->setEnabled(false);
2379 void GuiApplication::commitData(QSessionManager & sm)
2381 /// The implementation is required to avoid an application exit
2382 /// when session state save is triggered by session manager.
2383 /// The default implementation sends a close event to all
2384 /// visible top level widgets when session managment allows
2386 /// We are changing that to close all wiew one by one.
2387 /// FIXME: verify if the default implementation is enough now.
2388 #ifdef QT_NO_SESSIONMANAGER
2390 #warning Qt is compiled without session manager
2392 #pragma message("warning: Qt is compiled without session manager")
2396 if (sm.allowsInteraction() && !closeAllViews())
2402 void GuiApplication::unregisterView(GuiView * gv)
2404 LASSERT(d->views_[gv->id()] == gv, /**/);
2405 d->views_.remove(gv->id());
2406 if (current_view_ == gv)
2411 bool GuiApplication::closeAllViews()
2413 if (d->views_.empty())
2416 // When a view/window was closed before without quitting LyX, there
2417 // are already entries in the lastOpened list.
2418 theSession().lastOpened().clear();
2420 QList<GuiView *> views = d->views_.values();
2421 foreach (GuiView * view, views) {
2422 if (!view->closeScheduled())
2431 GuiView & GuiApplication::view(int id) const
2433 LASSERT(d->views_.contains(id), /**/);
2434 return *d->views_.value(id);
2438 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2440 QList<GuiView *> views = d->views_.values();
2441 foreach (GuiView * view, views)
2442 view->hideDialog(name, inset);
2446 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2448 Buffer const * buffer_ = 0;
2449 QHash<int, GuiView *>::iterator end = d->views_.end();
2450 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2451 if (Buffer const * ptr = (*it)->updateInset(inset))
2458 bool GuiApplication::searchMenu(FuncRequest const & func,
2459 docstring_list & names) const
2461 return d->menus_.searchMenu(func, names);
2465 // Ensure that a file is read only once (prevents include loops)
2466 static QStringList uifiles;
2467 // store which ui files define Toolbars
2468 static QStringList toolbar_uifiles;
2471 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2482 LexerKeyword uitags[] = {
2483 { "format", ui_format },
2484 { "include", ui_include },
2485 { "menuset", ui_menuset },
2486 { "toolbars", ui_toolbars },
2487 { "toolbarset", ui_toolbarset }
2491 lex.setFile(ui_path);
2493 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2497 if (lyxerr.debugging(Debug::PARSER))
2498 lex.printTable(lyxerr);
2501 // format before introduction of format tag
2502 unsigned int format = 0;
2503 while (lex.isOK()) {
2504 int const status = lex.lex();
2506 // we have to do this check here, outside the switch,
2507 // because otherwise we would start reading include files,
2508 // e.g., if the first tag we hit was an include tag.
2509 if (status == ui_format)
2511 format = lex.getInteger();
2515 // this will trigger unless the first tag we hit is a format
2516 // tag, with the right format.
2517 if (format != LFUN_FORMAT)
2518 return FormatMismatch;
2521 case Lexer::LEX_FEOF:
2526 QString const file = toqstr(lex.getString());
2527 bool const success = readUIFile(file, true);
2529 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2536 d->menus_.read(lex);
2540 d->toolbars_.readToolbars(lex);
2544 d->toolbars_.readToolbarSettings(lex);
2545 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2549 if (!rtrim(lex.getString()).empty())
2550 lex.printError("LyX::ReadUIFile: "
2551 "Unknown menu tag: `$$Token'");
2553 LYXERR0("Error with status: " << status);
2559 return (error ? ReadError : ReadOK);
2563 bool GuiApplication::readUIFile(QString const & name, bool include)
2565 LYXERR(Debug::INIT, "About to read " << name << "...");
2569 ui_path = libFileSearch("ui", name, "inc");
2570 if (ui_path.empty())
2571 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2573 ui_path = libFileSearch("ui", name, "ui");
2576 if (ui_path.empty()) {
2577 static const QString defaultUIFile = "default";
2578 LYXERR(Debug::INIT, "Could not find " << name);
2580 Alert::warning(_("Could not find UI definition file"),
2581 bformat(_("Error while reading the included file\n%1$s\n"
2582 "Please check your installation."), qstring_to_ucs4(name)));
2585 if (name == defaultUIFile) {
2586 LYXERR(Debug::INIT, "Could not find default UI file!!");
2587 Alert::warning(_("Could not find default UI file"),
2588 _("LyX could not find the default UI file!\n"
2589 "Please check your installation."));
2592 Alert::warning(_("Could not find UI definition file"),
2593 bformat(_("Error while reading the configuration file\n%1$s\n"
2594 "Falling back to default.\n"
2595 "Please look under Tools>Preferences>User Interface and\n"
2596 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2597 return readUIFile(defaultUIFile, false);
2600 QString const uifile = toqstr(ui_path.absFileName());
2601 if (uifiles.contains(uifile)) {
2603 // We are reading again the top uifile so reset the safeguard:
2606 d->toolbars_.reset();
2608 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2609 << "Is this an include loop?");
2613 uifiles.push_back(uifile);
2615 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2617 ReturnValues retval = readUIFile(ui_path);
2619 if (retval == FormatMismatch) {
2620 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2621 FileName const tempfile = FileName::tempName("convert_ui");
2622 bool const success = prefs2prefs(ui_path, tempfile, true);
2624 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2625 " to format " << LFUN_FORMAT << ".");
2627 retval = readUIFile(tempfile);
2628 tempfile.removeFile();
2632 if (retval != ReadOK) {
2633 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2641 settings.beginGroup("ui_files");
2642 bool touched = false;
2643 for (int i = 0; i != uifiles.size(); ++i) {
2644 QFileInfo fi(uifiles[i]);
2645 QDateTime const date_value = fi.lastModified();
2646 QString const name_key = QString::number(i);
2647 // if an ui file which defines Toolbars has changed,
2648 // we have to reset the settings
2649 if (toolbar_uifiles.contains(uifiles[i])
2650 && (!settings.contains(name_key)
2651 || settings.value(name_key).toString() != uifiles[i]
2652 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2654 settings.setValue(name_key, uifiles[i]);
2655 settings.setValue(name_key + "/date", date_value);
2658 settings.endGroup();
2660 settings.remove("views");
2666 void GuiApplication::onLastWindowClosed()
2668 if (d->global_menubar_)
2669 d->global_menubar_->grabKeyboard();
2673 void GuiApplication::startLongOperation() {
2674 d->key_checker_.start();
2678 bool GuiApplication::longOperationCancelled() {
2679 return d->key_checker_.pressed();
2683 void GuiApplication::stopLongOperation() {
2684 d->key_checker_.stop();
2688 bool GuiApplication::longOperationStarted() {
2689 return d->key_checker_.started();
2693 ////////////////////////////////////////////////////////////////////////
2695 // X11 specific stuff goes here...
2698 bool GuiApplication::x11EventFilter(XEvent * xev)
2703 switch (xev->type) {
2704 case SelectionRequest: {
2705 if (xev->xselectionrequest.selection != XA_PRIMARY)
2707 LYXERR(Debug::SELECTION, "X requested selection.");
2708 BufferView * bv = current_view_->currentBufferView();
2710 docstring const sel = bv->requestSelection();
2712 d->selection_.put(sel);
2716 case SelectionClear: {
2717 if (xev->xselectionclear.selection != XA_PRIMARY)
2719 LYXERR(Debug::SELECTION, "Lost selection.");
2720 BufferView * bv = current_view_->currentBufferView();
2722 bv->clearSelection();
2730 } // namespace frontend
2733 void hideDialogs(std::string const & name, Inset * inset)
2736 frontend::guiApp->hideDialogs(name, inset);
2740 ////////////////////////////////////////////////////////////////////
2744 ////////////////////////////////////////////////////////////////////
2746 frontend::FontLoader & theFontLoader()
2748 LASSERT(frontend::guiApp, /**/);
2749 return frontend::guiApp->fontLoader();
2753 frontend::FontMetrics const & theFontMetrics(Font const & f)
2755 return theFontMetrics(f.fontInfo());
2759 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2761 LASSERT(frontend::guiApp, /**/);
2762 return frontend::guiApp->fontLoader().metrics(f);
2766 ////////////////////////////////////////////////////////////////////
2770 ////////////////////////////////////////////////////////////////////
2772 frontend::Clipboard & theClipboard()
2774 LASSERT(frontend::guiApp, /**/);
2775 return frontend::guiApp->clipboard();
2779 frontend::Selection & theSelection()
2781 LASSERT(frontend::guiApp, /**/);
2782 return frontend::guiApp->selection();
2788 #include "moc_GuiApplication.cpp"