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 {
692 QCoreApplication::instance()->installEventFilter(this);
696 QCoreApplication::instance()->removeEventFilter(this);
699 QCoreApplication::processEvents();
702 bool eventFilter(QObject *obj, QEvent *event) {
703 LYXERR(Debug::ACTION, "Event Type: " << event->type());
704 switch (event->type()) {
708 return QObject::eventFilter(obj, event);
710 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
711 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
719 ////////////////////////////////////////////////////////////////////////
720 // GuiApplication::Private definition and implementation.
721 ////////////////////////////////////////////////////////////////////////
723 struct GuiApplication::Private
725 Private(): language_model_(0), meta_fake_bit(NoModifier),
729 /// WMF Mime handler for Windows clipboard.
730 wmf_mime_ = new QWindowsMimeMetafile();
732 initKeySequences(&theTopLevelKeymap());
735 void initKeySequences(KeyMap * kb)
737 keyseq = KeySequence(kb, kb);
738 cancel_meta_seq = KeySequence(kb, kb);
742 QSortFilterProxyModel * language_model_;
744 GuiClipboard clipboard_;
746 GuiSelection selection_;
748 FontLoader font_loader_;
750 ColorCache color_cache_;
752 QTranslator qt_trans_;
754 QHash<int, SocketNotifier *> socket_notifiers_;
758 /// The global instance
761 /// this timer is used for any regular events one wants to
762 /// perform. at present it is used to check if forked processes
764 QTimer general_timer_;
766 /// delayed FuncRequests
767 std::queue<FuncRequest> func_request_queue_;
772 KeySequence cancel_meta_seq;
774 KeyModifier meta_fake_bit;
776 /// Multiple views container.
778 * Warning: This must not be a smart pointer as the destruction of the
779 * object is handled by Qt when the view is closed
780 * \sa Qt::WA_DeleteOnClose attribute.
782 QHash<int, GuiView *> views_;
784 /// Only used on mac.
785 GlobalMenuBar * global_menubar_;
788 /// Linkback mime handler for MacOSX.
789 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
793 /// WMF Mime handler for Windows clipboard.
794 QWindowsMimeMetafile * wmf_mime_;
797 /// Allows to check whether ESC was pressed during a long operation
798 KeyChecker key_checker_;
802 GuiApplication * guiApp;
804 GuiApplication::~GuiApplication()
807 closeAllLinkBackLinks();
813 GuiApplication::GuiApplication(int & argc, char ** argv)
814 : QApplication(argc, argv), current_view_(0),
815 d(new GuiApplication::Private)
817 QString app_name = "LyX";
818 QCoreApplication::setOrganizationName(app_name);
819 QCoreApplication::setOrganizationDomain("lyx.org");
820 QCoreApplication::setApplicationName(lyx_package);
822 // Install translator for GUI elements.
823 installTranslator(&d->qt_trans_);
825 // FIXME: quitOnLastWindowClosed is true by default. We should have a
826 // lyxrc setting for this in order to let the application stay resident.
827 // But then we need some kind of dock icon, at least on Windows.
829 if (lyxrc.quit_on_last_window_closed)
830 setQuitOnLastWindowClosed(false);
833 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
834 // seems to be the default case for applications like LyX.
835 setQuitOnLastWindowClosed(false);
836 // This allows to translate the strings that appear in the LyX menu.
837 /// A translator suitable for the entries in the LyX menu.
838 /// Only needed with Qt/Mac.
839 installTranslator(new MenuTranslator(this));
843 // doubleClickInterval() is 400 ms on X11 which is just too long.
844 // On Windows and Mac OS X, the operating system's value is used.
845 // On Microsoft Windows, calling this function sets the double
846 // click interval for all applications. So we don't!
847 QApplication::setDoubleClickInterval(300);
850 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
852 // needs to be done before reading lyxrc
854 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
858 // Set the cache to 5120 kilobytes which corresponds to screen size of
859 // 1280 by 1024 pixels with a color depth of 32 bits.
860 QPixmapCache::setCacheLimit(5120);
862 // Initialize RC Fonts
863 if (lyxrc.roman_font_name.empty())
864 lyxrc.roman_font_name = fromqstr(romanFontName());
866 if (lyxrc.sans_font_name.empty())
867 lyxrc.sans_font_name = fromqstr(sansFontName());
869 if (lyxrc.typewriter_font_name.empty())
870 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
872 d->general_timer_.setInterval(500);
873 connect(&d->general_timer_, SIGNAL(timeout()),
874 this, SLOT(handleRegularEvents()));
875 d->general_timer_.start();
877 #if QT_VERSION >= 0x040400
878 // maxThreadCount() defaults in general to 2 on single or dual-processor.
879 // This is clearly not enough in a time where we use threads for
880 // document preview and/or export. 20 should be OK.
881 QThreadPool::globalInstance()->setMaxThreadCount(20);
886 GuiApplication * theGuiApp()
888 return dynamic_cast<GuiApplication *>(theApp());
892 void GuiApplication::clearSession()
899 docstring Application::iconName(FuncRequest const & f, bool unknown)
901 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
905 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
910 BufferView * doc_bv = 0;
912 if (cmd.action() == LFUN_NOACTION) {
913 status.message(from_utf8(N_("Nothing to do")));
914 status.setEnabled(false);
917 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
918 status.setUnknown(true);
919 status.message(from_utf8(N_("Unknown action")));
920 status.setEnabled(false);
923 // Does the GuiApplication know something?
924 else if (getStatus(cmd, status)) { }
926 // If we do not have a GuiView, then other functions are disabled
927 else if (!current_view_)
928 status.setEnabled(false);
930 // Does the GuiView know something?
931 else if (current_view_->getStatus(cmd, status)) { }
933 // In LyX/Mac, when a dialog is open, the menus of the
934 // application can still be accessed without giving focus to
935 // the main window. In this case, we want to disable the menu
936 // entries that are buffer or view-related.
937 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
939 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
940 status.setEnabled(false);
943 // If we do not have a BufferView, then other functions are disabled
944 else if (!(bv = current_view_->currentBufferView()))
945 status.setEnabled(false);
947 // Does the current BufferView know something?
948 else if (bv->getStatus(cmd, status)) { }
950 // Does the current Buffer know something?
951 else if (bv->buffer().getStatus(cmd, status)) { }
953 // If we do not have a document BufferView, different from the
954 // current BufferView, then other functions are disabled
955 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
956 status.setEnabled(false);
958 // Does the document Buffer know something?
959 else if (doc_bv->buffer().getStatus(cmd, status)) { }
962 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
963 status.message(from_utf8(N_("Command not handled")));
964 status.setEnabled(false);
967 // the default error message if we disable the command
968 if (!status.enabled() && status.message().empty())
969 status.message(from_utf8(N_("Command disabled")));
975 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
977 // I would really like to avoid having this switch and rather try to
978 // encode this in the function itself.
979 // -- And I'd rather let an inset decide which LFUNs it is willing
980 // to handle (Andre')
982 switch (cmd.action()) {
984 // This could be used for the no-GUI version. The GUI version is handled in
985 // GuiView::getStatus(). See above.
987 case LFUN_BUFFER_WRITE:
988 case LFUN_BUFFER_WRITE_AS: {
989 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
990 enable = b && (b->isUnnamed() || !b->isClean());
995 case LFUN_BOOKMARK_GOTO: {
996 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
997 enable = theSession().bookmarks().isValid(num);
1001 case LFUN_BOOKMARK_CLEAR:
1002 enable = theSession().bookmarks().hasValid();
1005 // this one is difficult to get right. As a half-baked
1006 // solution, we consider only the first action of the sequence
1007 case LFUN_COMMAND_SEQUENCE: {
1008 // argument contains ';'-terminated commands
1009 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1010 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1011 func.setOrigin(cmd.origin());
1012 flag = getStatus(func);
1016 // we want to check if at least one of these is enabled
1017 case LFUN_COMMAND_ALTERNATIVES: {
1018 // argument contains ';'-terminated commands
1019 string arg = to_utf8(cmd.argument());
1020 while (!arg.empty()) {
1022 arg = split(arg, first, ';');
1023 FuncRequest func(lyxaction.lookupFunc(first));
1024 func.setOrigin(cmd.origin());
1025 flag = getStatus(func);
1026 // if this one is enabled, the whole thing is
1035 string name = to_utf8(cmd.argument());
1036 if (theTopLevelCmdDef().lock(name, func)) {
1037 func.setOrigin(cmd.origin());
1038 flag = getStatus(func);
1039 theTopLevelCmdDef().release(name);
1041 // catch recursion or unknown command
1042 // definition. all operations until the
1043 // recursion or unknown command definition
1044 // occurs are performed, so set the state to
1051 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1053 case LFUN_PREFERENCES_SAVE:
1054 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1055 case LFUN_DEBUG_LEVEL_SET:
1056 // these are handled in our dispatch()
1059 case LFUN_WINDOW_CLOSE:
1060 enable = d->views_.size() > 0;
1063 case LFUN_BUFFER_NEW:
1064 case LFUN_BUFFER_NEW_TEMPLATE:
1065 case LFUN_FILE_OPEN:
1066 case LFUN_HELP_OPEN:
1067 case LFUN_SCREEN_FONT_UPDATE:
1068 case LFUN_SET_COLOR:
1069 case LFUN_WINDOW_NEW:
1071 case LFUN_LYXRC_APPLY:
1072 case LFUN_COMMAND_PREFIX:
1074 case LFUN_META_PREFIX:
1075 case LFUN_RECONFIGURE:
1076 case LFUN_SERVER_GET_FILENAME:
1077 case LFUN_SERVER_NOTIFY:
1081 case LFUN_BUFFER_FORALL: {
1082 if (!currentView() || !currentView()->currentBufferView() || !¤tView()->currentBufferView()->buffer()) {
1083 flag.message(from_utf8(N_("Command not allowed without any visible document in the active window")));
1084 flag.setEnabled(false);
1095 flag.setEnabled(false);
1099 /// make a post-dispatch status message
1100 static docstring makeDispatchMessage(docstring const & msg,
1101 FuncRequest const & cmd)
1103 const bool verbose = (cmd.origin() == FuncRequest::MENU
1104 || cmd.origin() == FuncRequest::TOOLBAR
1105 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1107 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1108 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1112 docstring dispatch_msg = msg;
1113 if (!dispatch_msg.empty())
1114 dispatch_msg += ' ';
1116 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1118 bool argsadded = false;
1120 if (!cmd.argument().empty()) {
1121 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1122 comname += ' ' + cmd.argument();
1126 docstring const shortcuts = theTopLevelKeymap().
1127 printBindings(cmd, KeySequence::ForGui);
1129 if (!shortcuts.empty())
1130 comname += ": " + shortcuts;
1131 else if (!argsadded && !cmd.argument().empty())
1132 comname += ' ' + cmd.argument();
1134 if (!comname.empty()) {
1135 comname = rtrim(comname);
1136 dispatch_msg += '(' + rtrim(comname) + ')';
1138 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1139 return dispatch_msg;
1143 void GuiApplication::dispatch(FuncRequest const & cmd)
1145 Buffer * buffer = 0;
1146 if (current_view_ && current_view_->currentBufferView()) {
1147 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1148 buffer = ¤t_view_->currentBufferView()->buffer();
1150 buffer->undo().beginUndoGroup();
1154 // redraw the screen at the end (first of the two drawing steps).
1155 // This is done unless explicitly requested otherwise
1156 dr.screenUpdate(Update::FitCursor);
1158 updateCurrentView(cmd, dr);
1160 // the buffer may have been closed by one action
1161 if (theBufferList().isLoaded(buffer))
1162 buffer->undo().endUndoGroup();
1166 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1171 BufferView * bv = current_view_->currentBufferView();
1173 if (dr.needBufferUpdate()) {
1174 bv->cursor().clearBufferUpdate();
1175 bv->buffer().updateBuffer();
1177 // BufferView::update() updates the ViewMetricsInfo and
1178 // also initializes the position cache for all insets in
1179 // (at least partially) visible top-level paragraphs.
1180 // We will redraw the screen only if needed.
1181 bv->processUpdateFlags(dr.screenUpdate());
1183 // Do we have a selection?
1184 theSelection().haveSelection(bv->cursor().selection());
1187 current_view_->restartCursor();
1189 if (dr.needMessageUpdate()) {
1190 // Some messages may already be translated, so we cannot use _()
1191 current_view_->message(makeDispatchMessage(
1192 translateIfPossible(dr.message()), cmd));
1197 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1198 bool switchToBuffer)
1200 if (!theSession().bookmarks().isValid(idx))
1202 BookmarksSection::Bookmark const & bm =
1203 theSession().bookmarks().bookmark(idx);
1204 LASSERT(!bm.filename.empty(), /**/);
1205 string const file = bm.filename.absFileName();
1206 // if the file is not opened, open it.
1207 if (!theBufferList().exists(bm.filename)) {
1209 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1213 // open may fail, so we need to test it again
1214 if (!theBufferList().exists(bm.filename))
1217 // bm can be changed when saving
1218 BookmarksSection::Bookmark tmp = bm;
1220 // Special case idx == 0 used for back-from-back jump navigation
1222 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1224 // if the current buffer is not that one, switch to it.
1225 BufferView * doc_bv = current_view_ ?
1226 current_view_->documentBufferView() : 0;
1227 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1228 if (switchToBuffer) {
1229 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1232 doc_bv = current_view_->documentBufferView();
1237 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1238 if (!doc_bv->moveToPosition(
1239 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1246 // Cursor jump succeeded!
1247 Cursor const & cur = doc_bv->cursor();
1248 pit_type new_pit = cur.pit();
1249 pos_type new_pos = cur.pos();
1250 int new_id = cur.paragraph().id();
1252 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1253 // see http://www.lyx.org/trac/ticket/3092
1254 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1255 || bm.top_id != new_id) {
1256 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1257 new_pit, new_pos, new_id);
1261 // This function runs "configure" and then rereads lyx.defaults to
1262 // reconfigure the automatic settings.
1263 void GuiApplication::reconfigure(string const & option)
1265 // emit message signal.
1267 current_view_->message(_("Running configure..."));
1269 // Run configure in user lyx directory
1270 PathChanger p(package().user_support());
1271 string configure_command = package().configure_command();
1272 configure_command += option;
1274 int ret = one.startscript(Systemcall::Wait, configure_command);
1276 // emit message signal.
1278 current_view_->message(_("Reloading configuration..."));
1279 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1280 // Re-read packages.lst
1281 LaTeXPackages::getAvailable();
1284 Alert::information(_("System reconfiguration failed"),
1285 _("The system reconfiguration has failed.\n"
1286 "Default textclass is used but LyX may "
1287 "not be able to work properly.\n"
1288 "Please reconfigure again if needed."));
1290 Alert::information(_("System reconfigured"),
1291 _("The system has been reconfigured.\n"
1292 "You need to restart LyX to make use of any\n"
1293 "updated document class specifications."));
1296 void GuiApplication::validateCurrentView()
1298 if (!d->views_.empty() && !current_view_) {
1299 // currently at least one view exists but no view has the focus.
1300 // choose the last view to make it current.
1301 // a view without any open document is preferred.
1302 GuiView * candidate = 0;
1303 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1304 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1305 for (; it != end; ++it) {
1307 if (!candidate->documentBufferView())
1310 setCurrentView(candidate);
1314 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1316 string const argument = to_utf8(cmd.argument());
1317 FuncCode const action = cmd.action();
1319 LYXERR(Debug::ACTION, "cmd: " << cmd);
1321 // we have not done anything wrong yet.
1324 FuncStatus const flag = getStatus(cmd);
1325 if (!flag.enabled()) {
1326 // We cannot use this function here
1327 LYXERR(Debug::ACTION, "action "
1328 << lyxaction.getActionName(action)
1329 << " [" << action << "] is disabled at this location");
1330 dr.setMessage(flag.message());
1332 dr.dispatched(false);
1333 dr.screenUpdate(Update::None);
1334 dr.clearBufferUpdate();
1338 if (cmd.origin() == FuncRequest::LYXSERVER) {
1339 if (current_view_ && current_view_->currentBufferView())
1340 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1341 // we will also need to redraw the screen at the end
1342 dr.screenUpdate(Update::FitCursor);
1345 // Assumes that the action will be dispatched.
1346 dr.dispatched(true);
1348 switch (cmd.action()) {
1350 case LFUN_WINDOW_NEW:
1351 createView(toqstr(cmd.argument()));
1354 case LFUN_WINDOW_CLOSE:
1355 // update bookmark pit of the current buffer before window close
1356 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1357 gotoBookmark(i+1, false, false);
1358 // clear the last opened list, because
1359 // maybe this will end the session
1360 theSession().lastOpened().clear();
1361 // check for valid current_view_
1362 validateCurrentView();
1364 current_view_->closeScheduled();
1368 // quitting is triggered by the gui code
1369 // (leaving the event loop).
1371 current_view_->message(from_utf8(N_("Exiting.")));
1372 if (closeAllViews())
1376 case LFUN_SCREEN_FONT_UPDATE: {
1377 // handle the screen font changes.
1378 d->font_loader_.update();
1379 // Backup current_view_
1380 GuiView * view = current_view_;
1381 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1382 // to skip the refresh.
1384 theBufferList().changed(false);
1385 // Restore current_view_
1386 current_view_ = view;
1390 case LFUN_BUFFER_NEW:
1391 validateCurrentView();
1392 if (d->views_.empty()
1393 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1394 createView(QString(), false); // keep hidden
1395 current_view_->newDocument(to_utf8(cmd.argument()), false);
1396 current_view_->show();
1397 setActiveWindow(current_view_);
1399 current_view_->newDocument(to_utf8(cmd.argument()), false);
1403 case LFUN_BUFFER_NEW_TEMPLATE:
1404 validateCurrentView();
1405 if (d->views_.empty()
1406 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1408 current_view_->newDocument(to_utf8(cmd.argument()), true);
1409 if (!current_view_->documentBufferView())
1410 current_view_->close();
1412 current_view_->newDocument(to_utf8(cmd.argument()), true);
1416 case LFUN_FILE_OPEN: {
1417 validateCurrentView();
1418 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1419 string const fname = to_utf8(cmd.argument());
1420 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1421 && current_view_->documentBufferView() != 0)) {
1422 // We want the ui session to be saved per document and not per
1423 // window number. The filename crc is a good enough identifier.
1424 boost::crc_32_type crc;
1425 crc = for_each(fname.begin(), fname.end(), crc);
1426 createView(crc.checksum());
1427 current_view_->openDocument(fname);
1428 if (current_view_ && !current_view_->documentBufferView())
1429 current_view_->close();
1431 current_view_->openDocument(fname);
1435 case LFUN_HELP_OPEN: {
1436 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1437 if (current_view_ == 0)
1439 string const arg = to_utf8(cmd.argument());
1441 current_view_->message(_("Missing argument"));
1444 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1446 fname = i18nLibFileSearch("examples", arg, "lyx");
1448 if (fname.empty()) {
1449 lyxerr << "LyX: unable to find documentation file `"
1450 << arg << "'. Bad installation?" << endl;
1453 current_view_->message(bformat(_("Opening help file %1$s..."),
1454 makeDisplayPath(fname.absFileName())));
1455 Buffer * buf = current_view_->loadDocument(fname, false);
1457 #ifndef DEVEL_VERSION
1459 buf->setReadonly(true);
1466 case LFUN_SET_COLOR: {
1468 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1469 if (lyx_name.empty() || x11_name.empty()) {
1471 current_view_->message(
1472 _("Syntax: set-color <lyx_name> <x11_name>"));
1477 // FIXME: The graphics cache no longer has a changeDisplay method.
1478 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1479 bool const graphicsbg_changed =
1480 lyx_name == graphicsbg && x11_name != graphicsbg;
1481 if (graphicsbg_changed)
1482 graphics::GCache::get().changeDisplay(true);
1485 if (!lcolor.setColor(lyx_name, x11_name)) {
1487 current_view_->message(
1488 bformat(_("Set-color \"%1$s\" failed "
1489 "- color is undefined or "
1490 "may not be redefined"),
1491 from_utf8(lyx_name)));
1494 // Make sure we don't keep old colors in cache.
1495 d->color_cache_.clear();
1499 case LFUN_LYXRC_APPLY: {
1500 // reset active key sequences, since the bindings
1501 // are updated (bug 6064)
1503 LyXRC const lyxrc_orig = lyxrc;
1505 istringstream ss(to_utf8(cmd.argument()));
1506 bool const success = lyxrc.read(ss);
1509 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1510 << "Unable to read lyxrc data"
1515 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1521 case LFUN_COMMAND_PREFIX:
1522 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1527 d->meta_fake_bit = NoModifier;
1528 GuiView * gv = currentView();
1529 if (gv && gv->currentBufferView())
1530 // cancel any selection
1531 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1532 dr.setMessage(from_ascii(N_("Cancel")));
1535 case LFUN_META_PREFIX:
1536 d->meta_fake_bit = AltModifier;
1537 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1540 // --- Menus -----------------------------------------------
1541 case LFUN_RECONFIGURE:
1542 // argument is any additional parameter to the configure.py command
1543 reconfigure(to_utf8(cmd.argument()));
1546 // --- lyxserver commands ----------------------------
1547 case LFUN_SERVER_GET_FILENAME: {
1548 if (current_view_ && current_view_->documentBufferView()) {
1549 docstring const fname = from_utf8(
1550 current_view_->documentBufferView()->buffer().absFileName());
1551 dr.setMessage(fname);
1552 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1554 dr.setMessage(docstring());
1555 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1560 case LFUN_SERVER_NOTIFY: {
1561 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1562 dr.setMessage(dispatch_buffer);
1563 theServer().notifyClient(to_utf8(dispatch_buffer));
1567 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1568 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1574 string rest = split(argument, countstr, ' ');
1575 istringstream is(countstr);
1578 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1579 for (int i = 0; i < count; ++i)
1580 dispatch(lyxaction.lookupFunc(rest));
1584 case LFUN_COMMAND_SEQUENCE: {
1585 // argument contains ';'-terminated commands
1586 string arg = argument;
1587 // FIXME: this LFUN should also work without any view.
1588 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1589 ? &(current_view_->documentBufferView()->buffer()) : 0;
1591 buffer->undo().beginUndoGroup();
1592 while (!arg.empty()) {
1594 arg = split(arg, first, ';');
1595 FuncRequest func(lyxaction.lookupFunc(first));
1596 func.setOrigin(cmd.origin());
1599 // the buffer may have been closed by one action
1600 if (theBufferList().isLoaded(buffer))
1601 buffer->undo().endUndoGroup();
1605 case LFUN_BUFFER_FORALL: {
1606 GuiView * gv = currentView();
1607 Buffer * const buf = &gv->currentBufferView()->buffer();
1609 bool processVisible = true;
1610 bool processHidden = false;
1611 docstring msg = _("Applied the following command to all visible buffers in the active window: ");
1612 string commandToRun = argument;
1613 if (cmd.getArg(0) == "both") {
1614 processHidden = true;
1615 msg = _("Applied the following command to all visible and hidden buffers in the active window: ");
1616 commandToRun = cmd.getLongArg(1);
1617 } else if (cmd.getArg(0) == "visible") {
1618 commandToRun = cmd.getLongArg(1);
1619 } else if (cmd.getArg(0) == "hidden") {
1620 processHidden = true;
1621 processVisible = false;
1622 commandToRun = cmd.getLongArg(1);
1623 msg = _("Applied the following command to all hidden buffers in the active window: ");
1625 FuncRequest const funcToRun = lyxaction.lookupFunc(commandToRun);
1626 dr.setMessage(bformat(_("%1$s%2$s"), msg, from_utf8(commandToRun)));
1628 Buffer * const last = theBufferList().last();
1629 Buffer * b = theBufferList().first();
1630 Buffer * nextBuf = 0;
1631 // We cannot use a for loop as the buffer list cycles.
1634 nextBuf = theBufferList().next(b); //get next now bc LFUN might close current
1636 bool const hidden = !(gv && gv->workArea(*b));
1638 if (processHidden) {
1640 lyx::dispatch(funcToRun);
1641 gv->currentWorkArea()->view().hideWorkArea(gv->currentWorkArea());
1646 if (processVisible) {
1648 lyx::dispatch(funcToRun);
1657 if (theBufferList().isLoaded(buf)) //the LFUN might have closed buf
1662 case LFUN_COMMAND_ALTERNATIVES: {
1663 // argument contains ';'-terminated commands
1664 string arg = argument;
1665 while (!arg.empty()) {
1667 arg = split(arg, first, ';');
1668 FuncRequest func(lyxaction.lookupFunc(first));
1669 func.setOrigin(cmd.origin());
1670 FuncStatus const stat = getStatus(func);
1671 if (stat.enabled()) {
1681 if (theTopLevelCmdDef().lock(argument, func)) {
1682 func.setOrigin(cmd.origin());
1684 theTopLevelCmdDef().release(argument);
1686 if (func.action() == LFUN_UNKNOWN_ACTION) {
1687 // unknown command definition
1688 lyxerr << "Warning: unknown command definition `"
1692 // recursion detected
1693 lyxerr << "Warning: Recursion in the command definition `"
1694 << argument << "' detected"
1701 case LFUN_PREFERENCES_SAVE:
1702 lyxrc.write(support::makeAbsPath("preferences",
1703 package().user_support().absFileName()), false);
1706 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1707 string const fname = addName(addPath(package().user_support().absFileName(),
1708 "templates/"), "defaults.lyx");
1709 Buffer defaults(fname);
1711 istringstream ss(argument);
1714 int const unknown_tokens = defaults.readHeader(lex);
1716 if (unknown_tokens != 0) {
1717 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1718 << unknown_tokens << " unknown token"
1719 << (unknown_tokens == 1 ? "" : "s")
1723 if (defaults.writeFile(FileName(defaults.absFileName())))
1724 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1725 makeDisplayPath(fname)));
1728 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1733 case LFUN_BOOKMARK_GOTO:
1734 // go to bookmark, open unopened file and switch to buffer if necessary
1735 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1736 dr.screenUpdate(Update::Force | Update::FitCursor);
1739 case LFUN_BOOKMARK_CLEAR:
1740 theSession().bookmarks().clear();
1743 case LFUN_DEBUG_LEVEL_SET:
1744 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1748 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1751 current_view_->dispatch(cmd, dr);
1755 if (cmd.origin() == FuncRequest::LYXSERVER)
1756 updateCurrentView(cmd, dr);
1760 docstring GuiApplication::viewStatusMessage()
1762 // When meta-fake key is pressed, show the key sequence so far + "M-".
1763 if (d->meta_fake_bit != NoModifier)
1764 return d->keyseq.print(KeySequence::ForGui) + "M-";
1766 // Else, when a non-complete key sequence is pressed,
1767 // show the available options.
1768 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1769 return d->keyseq.printOptions(true);
1775 void GuiApplication::handleKeyFunc(FuncCode action)
1779 if (d->keyseq.length())
1781 GuiView * gv = currentView();
1782 LASSERT(gv && gv->currentBufferView(), return);
1783 BufferView * bv = gv->currentBufferView();
1784 bv->getIntl().getTransManager().deadkey(
1785 c, get_accent(action).accent, bv->cursor().innerText(),
1787 // Need to clear, in case the minibuffer calls these
1790 // copied verbatim from do_accent_char
1791 bv->cursor().resetAnchor();
1795 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1797 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1799 // Do nothing if we have nothing (JMarc)
1800 if (!keysym.isOK()) {
1801 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1803 current_view_->restartCursor();
1807 if (keysym.isModifier()) {
1809 current_view_->restartCursor();
1813 char_type encoded_last_key = keysym.getUCSEncoded();
1815 // Do a one-deep top-level lookup for
1816 // cancel and meta-fake keys. RVDK_PATCH_5
1817 d->cancel_meta_seq.reset();
1819 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1820 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1822 // When not cancel or meta-fake, do the normal lookup.
1823 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1824 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1825 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1826 // remove Caps Lock and Mod2 as a modifiers
1827 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1828 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1831 // Dont remove this unless you know what you are doing.
1832 d->meta_fake_bit = NoModifier;
1834 // Can this happen now ?
1835 if (func.action() == LFUN_NOACTION)
1836 func = FuncRequest(LFUN_COMMAND_PREFIX);
1838 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1839 << d->keyseq.print(KeySequence::Portable) << ']');
1841 // already here we know if it any point in going further
1842 // why not return already here if action == -1 and
1843 // num_bytes == 0? (Lgb)
1845 if (d->keyseq.length() > 1 && current_view_)
1846 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1849 // Maybe user can only reach the key via holding down shift.
1850 // Let's see. But only if shift is the only modifier
1851 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1852 LYXERR(Debug::KEY, "Trying without shift");
1853 func = d->keyseq.addkey(keysym, NoModifier);
1854 LYXERR(Debug::KEY, "Action now " << func.action());
1857 if (func.action() == LFUN_UNKNOWN_ACTION) {
1858 // Hmm, we didn't match any of the keysequences. See
1859 // if it's normal insertable text not already covered
1861 if (keysym.isText() && d->keyseq.length() == 1) {
1862 LYXERR(Debug::KEY, "isText() is true, inserting.");
1863 func = FuncRequest(LFUN_SELF_INSERT,
1864 FuncRequest::KEYBOARD);
1866 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1867 if (current_view_) {
1868 current_view_->message(_("Unknown function."));
1869 current_view_->restartCursor();
1875 if (func.action() == LFUN_SELF_INSERT) {
1876 if (encoded_last_key != 0) {
1877 docstring const arg(1, encoded_last_key);
1878 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1879 FuncRequest::KEYBOARD));
1880 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1883 processFuncRequest(func);
1887 void GuiApplication::processFuncRequest(FuncRequest const & func)
1889 lyx::dispatch(func);
1893 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1895 addToFuncRequestQueue(func);
1896 processFuncRequestQueueAsync();
1900 void GuiApplication::processFuncRequestQueue()
1902 while (!d->func_request_queue_.empty()) {
1903 processFuncRequest(d->func_request_queue_.front());
1904 d->func_request_queue_.pop();
1909 void GuiApplication::processFuncRequestQueueAsync()
1911 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1915 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1917 d->func_request_queue_.push(func);
1921 void GuiApplication::resetGui()
1923 // Set the language defined by the user.
1927 if (!readUIFile(toqstr(lyxrc.ui_file)))
1928 // Gives some error box here.
1931 if (d->global_menubar_)
1932 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1934 QHash<int, GuiView *>::iterator it;
1935 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1938 gv->setLayoutDirection(layoutDirection());
1942 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1946 void GuiApplication::createView(int view_id)
1948 createView(QString(), true, view_id);
1952 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1955 // release the keyboard which might have been grabed by the global
1956 // menubar on Mac to catch shortcuts even without any GuiView.
1957 if (d->global_menubar_)
1958 d->global_menubar_->releaseKeyboard();
1962 while (d->views_.find(id) != d->views_.end())
1965 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1966 GuiView * view = new GuiView(id);
1968 d->views_[id] = view;
1972 setActiveWindow(view);
1975 if (!geometry_arg.isEmpty()) {
1979 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1980 re.indexIn(geometry_arg);
1981 w = re.cap(1).toInt();
1982 h = re.cap(2).toInt();
1983 x = re.cap(3).toInt();
1984 y = re.cap(4).toInt();
1985 view->setGeometry(x, y, w, h);
1992 Clipboard & GuiApplication::clipboard()
1994 return d->clipboard_;
1998 Selection & GuiApplication::selection()
2000 return d->selection_;
2004 FontLoader & GuiApplication::fontLoader()
2006 return d->font_loader_;
2010 Toolbars const & GuiApplication::toolbars() const
2012 return d->toolbars_;
2016 Toolbars & GuiApplication::toolbars()
2018 return d->toolbars_;
2022 Menus const & GuiApplication::menus() const
2028 Menus & GuiApplication::menus()
2034 QList<int> GuiApplication::viewIds() const
2036 return d->views_.keys();
2040 ColorCache & GuiApplication::colorCache()
2042 return d->color_cache_;
2046 int GuiApplication::exec()
2048 // asynchronously handle batch commands. This event will be in
2049 // the event queue in front of other asynchronous events. Hence,
2050 // we can assume in the latter that the gui is setup already.
2051 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2053 return QApplication::exec();
2057 void GuiApplication::exit(int status)
2059 QApplication::exit(status);
2063 void GuiApplication::setGuiLanguage()
2065 QString const default_language = toqstr(getGuiMessages().language());
2066 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2067 QLocale const default_locale(default_language);
2068 QLocale::setDefault(default_locale);
2070 // install translation file for Qt built-in dialogs
2071 QString const language_name = QString("qt_") + default_locale.name();
2073 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2074 // Short-named translator can be loaded from a long name, but not the
2075 // opposite. Therefore, long name should be used without truncation.
2076 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2077 if (!d->qt_trans_.load(language_name,
2078 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2079 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2082 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2086 switch (default_locale.language()) {
2087 case QLocale::Arabic :
2088 case QLocale::Hebrew :
2089 case QLocale::Persian :
2090 case QLocale::Urdu :
2091 setLayoutDirection(Qt::RightToLeft);
2094 setLayoutDirection(Qt::LeftToRight);
2099 void GuiApplication::execBatchCommands()
2104 if (!readUIFile(toqstr(lyxrc.ui_file)))
2105 // Gives some error box here.
2109 #if QT_VERSION > 0x040600
2110 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2112 // Create the global default menubar which is shown for the dialogs
2113 // and if no GuiView is visible.
2114 // This must be done after the session was recovered to know the "last files".
2115 d->global_menubar_ = new GlobalMenuBar();
2116 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2119 lyx::execBatchCommands();
2123 QAbstractItemModel * GuiApplication::languageModel()
2125 if (d->language_model_)
2126 return d->language_model_;
2128 QStandardItemModel * lang_model = new QStandardItemModel(this);
2129 lang_model->insertColumns(0, 3);
2131 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2132 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2133 Languages::const_iterator it = lyx::languages.begin();
2134 Languages::const_iterator end = lyx::languages.end();
2135 for (; it != end; ++it) {
2136 current_row = lang_model->rowCount();
2137 lang_model->insertRows(current_row, 1);
2138 QModelIndex pl_item = lang_model->index(current_row, 0);
2139 QModelIndex sp_item = lang_model->index(current_row, 1);
2140 QModelIndex th_item = lang_model->index(current_row, 2);
2141 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2142 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2143 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2144 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2145 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2146 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2147 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2148 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2149 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2150 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2152 d->language_model_ = new QSortFilterProxyModel(this);
2153 d->language_model_->setSourceModel(lang_model);
2154 #if QT_VERSION >= 0x040300
2155 d->language_model_->setSortLocaleAware(true);
2157 return d->language_model_;
2161 void GuiApplication::restoreGuiSession()
2163 if (!lyxrc.load_session)
2166 Session & session = theSession();
2167 LastOpenedSection::LastOpened const & lastopened =
2168 session.lastOpened().getfiles();
2170 validateCurrentView();
2172 FileName active_file;
2173 // do not add to the lastfile list since these files are restored from
2174 // last session, and should be already there (regular files), or should
2175 // not be added at all (help files).
2176 for (size_t i = 0; i < lastopened.size(); ++i) {
2177 FileName const & file_name = lastopened[i].file_name;
2178 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2179 && current_view_->documentBufferView() != 0)) {
2180 boost::crc_32_type crc;
2181 string const & fname = file_name.absFileName();
2182 crc = for_each(fname.begin(), fname.end(), crc);
2183 createView(crc.checksum());
2185 current_view_->loadDocument(file_name, false);
2187 if (lastopened[i].active)
2188 active_file = file_name;
2191 // Restore last active buffer
2192 Buffer * buffer = theBufferList().getBuffer(active_file);
2193 if (buffer && current_view_)
2194 current_view_->setBuffer(buffer);
2196 // clear this list to save a few bytes of RAM
2197 session.lastOpened().clear();
2201 QString const GuiApplication::romanFontName()
2204 font.setKerning(false);
2205 font.setStyleHint(QFont::Serif);
2206 font.setFamily("serif");
2208 return QFontInfo(font).family();
2212 QString const GuiApplication::sansFontName()
2215 font.setKerning(false);
2216 font.setStyleHint(QFont::SansSerif);
2217 font.setFamily("sans");
2219 return QFontInfo(font).family();
2223 QString const GuiApplication::typewriterFontName()
2226 font.setKerning(false);
2227 font.setStyleHint(QFont::TypeWriter);
2228 font.setFamily("monospace");
2230 return QFontInfo(font).family();
2234 void GuiApplication::handleRegularEvents()
2236 ForkedCallsController::handleCompletedProcesses();
2240 bool GuiApplication::event(QEvent * e)
2243 case QEvent::FileOpen: {
2244 // Open a file; this happens only on Mac OS X for now.
2246 // We do this asynchronously because on startup the batch
2247 // commands are not executed here yet and the gui is not ready
2249 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2250 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2251 processFuncRequestAsync(fr);
2256 return QApplication::event(e);
2261 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2264 return QApplication::notify(receiver, event);
2266 catch (ExceptionMessage const & e) {
2268 case ErrorException:
2270 setQuitOnLastWindowClosed(false);
2272 Alert::error(e.title_, e.details_);
2274 // Properly crash in debug mode in order to get a useful backtrace.
2277 // In release mode, try to exit gracefully.
2280 case BufferException: {
2281 if (!current_view_ || !current_view_->documentBufferView())
2283 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2284 docstring details = e.details_ + '\n';
2285 details += buf->emergencyWrite();
2286 theBufferList().release(buf);
2287 details += "\n" + _("The current document was closed.");
2288 Alert::error(e.title_, details);
2291 case WarningException:
2292 Alert::warning(e.title_, e.details_);
2296 catch (exception const & e) {
2297 docstring s = _("LyX has caught an exception, it will now "
2298 "attempt to save all unsaved documents and exit."
2300 s += from_ascii(e.what());
2301 Alert::error(_("Software exception Detected"), s);
2305 docstring s = _("LyX has caught some really weird exception, it will "
2306 "now attempt to save all unsaved documents and exit.");
2307 Alert::error(_("Software exception Detected"), s);
2315 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2317 QColor const & qcol = d->color_cache_.get(col);
2318 if (!qcol.isValid()) {
2324 rgbcol.r = qcol.red();
2325 rgbcol.g = qcol.green();
2326 rgbcol.b = qcol.blue();
2331 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2333 QColor const qcol(lcolor.getX11Name(col).c_str());
2334 if (!qcol.isValid()) {
2340 rgbcol.r = qcol.red();
2341 rgbcol.g = qcol.green();
2342 rgbcol.b = qcol.blue();
2347 string const GuiApplication::hexName(ColorCode col)
2349 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2353 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2355 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2356 d->socket_notifiers_[fd] = sn;
2357 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2361 void GuiApplication::socketDataReceived(int fd)
2363 d->socket_notifiers_[fd]->func_();
2367 void GuiApplication::unregisterSocketCallback(int fd)
2369 d->socket_notifiers_.take(fd)->setEnabled(false);
2373 void GuiApplication::commitData(QSessionManager & sm)
2375 /// The implementation is required to avoid an application exit
2376 /// when session state save is triggered by session manager.
2377 /// The default implementation sends a close event to all
2378 /// visible top level widgets when session managment allows
2380 /// We are changing that to close all wiew one by one.
2381 /// FIXME: verify if the default implementation is enough now.
2382 #ifdef QT_NO_SESSIONMANAGER
2384 #warning Qt is compiled without session manager
2386 #pragma message("warning: Qt is compiled without session manager")
2390 if (sm.allowsInteraction() && !closeAllViews())
2396 void GuiApplication::unregisterView(GuiView * gv)
2398 LASSERT(d->views_[gv->id()] == gv, /**/);
2399 d->views_.remove(gv->id());
2400 if (current_view_ == gv)
2405 bool GuiApplication::closeAllViews()
2407 if (d->views_.empty())
2410 // When a view/window was closed before without quitting LyX, there
2411 // are already entries in the lastOpened list.
2412 theSession().lastOpened().clear();
2414 QList<GuiView *> views = d->views_.values();
2415 foreach (GuiView * view, views) {
2416 if (!view->closeScheduled())
2425 GuiView & GuiApplication::view(int id) const
2427 LASSERT(d->views_.contains(id), /**/);
2428 return *d->views_.value(id);
2432 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2434 QList<GuiView *> views = d->views_.values();
2435 foreach (GuiView * view, views)
2436 view->hideDialog(name, inset);
2440 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2442 Buffer const * buffer_ = 0;
2443 QHash<int, GuiView *>::iterator end = d->views_.end();
2444 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2445 if (Buffer const * ptr = (*it)->updateInset(inset))
2452 bool GuiApplication::searchMenu(FuncRequest const & func,
2453 docstring_list & names) const
2455 return d->menus_.searchMenu(func, names);
2459 // Ensure that a file is read only once (prevents include loops)
2460 static QStringList uifiles;
2461 // store which ui files define Toolbars
2462 static QStringList toolbar_uifiles;
2465 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2476 LexerKeyword uitags[] = {
2477 { "format", ui_format },
2478 { "include", ui_include },
2479 { "menuset", ui_menuset },
2480 { "toolbars", ui_toolbars },
2481 { "toolbarset", ui_toolbarset }
2485 lex.setFile(ui_path);
2487 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2491 if (lyxerr.debugging(Debug::PARSER))
2492 lex.printTable(lyxerr);
2495 // format before introduction of format tag
2496 unsigned int format = 0;
2497 while (lex.isOK()) {
2498 int const status = lex.lex();
2500 // we have to do this check here, outside the switch,
2501 // because otherwise we would start reading include files,
2502 // e.g., if the first tag we hit was an include tag.
2503 if (status == ui_format)
2505 format = lex.getInteger();
2509 // this will trigger unless the first tag we hit is a format
2510 // tag, with the right format.
2511 if (format != LFUN_FORMAT)
2512 return FormatMismatch;
2515 case Lexer::LEX_FEOF:
2520 QString const file = toqstr(lex.getString());
2521 bool const success = readUIFile(file, true);
2523 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2530 d->menus_.read(lex);
2534 d->toolbars_.readToolbars(lex);
2538 d->toolbars_.readToolbarSettings(lex);
2539 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2543 if (!rtrim(lex.getString()).empty())
2544 lex.printError("LyX::ReadUIFile: "
2545 "Unknown menu tag: `$$Token'");
2547 LYXERR0("Error with status: " << status);
2553 return (error ? ReadError : ReadOK);
2557 bool GuiApplication::readUIFile(QString const & name, bool include)
2559 LYXERR(Debug::INIT, "About to read " << name << "...");
2563 ui_path = libFileSearch("ui", name, "inc");
2564 if (ui_path.empty())
2565 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2567 ui_path = libFileSearch("ui", name, "ui");
2570 if (ui_path.empty()) {
2571 static const QString defaultUIFile = "default";
2572 LYXERR(Debug::INIT, "Could not find " << name);
2574 Alert::warning(_("Could not find UI definition file"),
2575 bformat(_("Error while reading the included file\n%1$s\n"
2576 "Please check your installation."), qstring_to_ucs4(name)));
2579 if (name == defaultUIFile) {
2580 LYXERR(Debug::INIT, "Could not find default UI file!!");
2581 Alert::warning(_("Could not find default UI file"),
2582 _("LyX could not find the default UI file!\n"
2583 "Please check your installation."));
2586 Alert::warning(_("Could not find UI definition file"),
2587 bformat(_("Error while reading the configuration file\n%1$s\n"
2588 "Falling back to default.\n"
2589 "Please look under Tools>Preferences>User Interface and\n"
2590 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2591 return readUIFile(defaultUIFile, false);
2594 QString const uifile = toqstr(ui_path.absFileName());
2595 if (uifiles.contains(uifile)) {
2597 // We are reading again the top uifile so reset the safeguard:
2600 d->toolbars_.reset();
2602 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2603 << "Is this an include loop?");
2607 uifiles.push_back(uifile);
2609 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2611 ReturnValues retval = readUIFile(ui_path);
2613 if (retval == FormatMismatch) {
2614 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2615 FileName const tempfile = FileName::tempName("convert_ui");
2616 bool const success = prefs2prefs(ui_path, tempfile, true);
2618 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2619 " to format " << LFUN_FORMAT << ".");
2621 retval = readUIFile(tempfile);
2622 tempfile.removeFile();
2626 if (retval != ReadOK) {
2627 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2635 settings.beginGroup("ui_files");
2636 bool touched = false;
2637 for (int i = 0; i != uifiles.size(); ++i) {
2638 QFileInfo fi(uifiles[i]);
2639 QDateTime const date_value = fi.lastModified();
2640 QString const name_key = QString::number(i);
2641 // if an ui file which defines Toolbars has changed,
2642 // we have to reset the settings
2643 if (toolbar_uifiles.contains(uifiles[i])
2644 && (!settings.contains(name_key)
2645 || settings.value(name_key).toString() != uifiles[i]
2646 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2648 settings.setValue(name_key, uifiles[i]);
2649 settings.setValue(name_key + "/date", date_value);
2652 settings.endGroup();
2654 settings.remove("views");
2660 void GuiApplication::onLastWindowClosed()
2662 if (d->global_menubar_)
2663 d->global_menubar_->grabKeyboard();
2667 void GuiApplication::startLongOperation() {
2668 d->key_checker_.start();
2672 bool GuiApplication::longOperationCancelled() {
2673 return d->key_checker_.pressed();
2677 void GuiApplication::stopLongOperation() {
2678 d->key_checker_.stop();
2682 ////////////////////////////////////////////////////////////////////////
2684 // X11 specific stuff goes here...
2687 bool GuiApplication::x11EventFilter(XEvent * xev)
2692 switch (xev->type) {
2693 case SelectionRequest: {
2694 if (xev->xselectionrequest.selection != XA_PRIMARY)
2696 LYXERR(Debug::SELECTION, "X requested selection.");
2697 BufferView * bv = current_view_->currentBufferView();
2699 docstring const sel = bv->requestSelection();
2701 d->selection_.put(sel);
2705 case SelectionClear: {
2706 if (xev->xselectionclear.selection != XA_PRIMARY)
2708 LYXERR(Debug::SELECTION, "Lost selection.");
2709 BufferView * bv = current_view_->currentBufferView();
2711 bv->clearSelection();
2719 } // namespace frontend
2722 void hideDialogs(std::string const & name, Inset * inset)
2725 frontend::guiApp->hideDialogs(name, inset);
2729 ////////////////////////////////////////////////////////////////////
2733 ////////////////////////////////////////////////////////////////////
2735 frontend::FontLoader & theFontLoader()
2737 LASSERT(frontend::guiApp, /**/);
2738 return frontend::guiApp->fontLoader();
2742 frontend::FontMetrics const & theFontMetrics(Font const & f)
2744 return theFontMetrics(f.fontInfo());
2748 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2750 LASSERT(frontend::guiApp, /**/);
2751 return frontend::guiApp->fontLoader().metrics(f);
2755 ////////////////////////////////////////////////////////////////////
2759 ////////////////////////////////////////////////////////////////////
2761 frontend::Clipboard & theClipboard()
2763 LASSERT(frontend::guiApp, /**/);
2764 return frontend::guiApp->clipboard();
2768 frontend::Selection & theSelection()
2770 LASSERT(frontend::guiApp, /**/);
2771 return frontend::guiApp->selection();
2777 #include "moc_GuiApplication.cpp"