2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
44 #include "LaTeXFeatures.h"
47 #include "LyXAction.h"
49 #include "Paragraph.h"
52 #include "SpellChecker.h"
53 #include "Thesaurus.h"
56 #include "support/convert.h"
57 #include "support/debug.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/FileName.h"
60 #include "support/filetools.h"
61 #include "support/foreach.h"
62 #include "support/ForkedCalls.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/lyxalgo.h" // sorted
67 #include "support/Messages.h"
68 #include "support/os.h"
69 #include "support/Package.h"
70 #include "support/Path.h"
71 #include "support/Systemcall.h"
74 #include "support/linkback/LinkBackProxy.h"
84 #include <QFileOpenEvent>
88 #include <QImageReader>
90 #include <QLibraryInfo>
92 #include <QMacPasteboardMime>
97 #include <QPixmapCache>
99 #include <QSessionManager>
101 #include <QSocketNotifier>
102 #include <QSortFilterProxyModel>
103 #include <QStandardItemModel>
104 #include <QTextCodec>
106 #include <QTranslator>
107 #if QT_VERSION >= 0x040400
108 #include <QThreadPool>
113 #include <X11/Xatom.h>
114 #include <X11/Xlib.h>
120 #include <QWindowsMime>
127 #include "support/bind.h"
128 #include <boost/crc.hpp>
135 using namespace lyx::support;
138 static void initializeResources()
140 static bool initialized = false;
142 Q_INIT_RESOURCE(Resources);
150 frontend::Application * createApplication(int & argc, char * argv[])
153 // prune -geometry argument(s) by shifting
154 // the following ones 2 places down.
155 for (int i = 0 ; i < argc ; ++i) {
156 if (strcmp(argv[i], "-geometry") == 0) {
157 int const remove = (i+1) < argc ? 2 : 1;
159 for (int j = i; j < argc; ++j)
160 argv[j] = argv[j + remove];
165 return new frontend::GuiApplication(argc, argv);
171 /// Return the list of loadable formats.
172 vector<string> loadableImageFormats()
176 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
178 LYXERR(Debug::GRAPHICS,
179 "\nThe image loader can load the following directly:\n");
181 if (qt_formats.empty())
182 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
184 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
186 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
188 string ext = ascii_lowercase((const char *) *it);
199 ////////////////////////////////////////////////////////////////////////
201 // Icon loading support code
203 ////////////////////////////////////////////////////////////////////////
213 bool operator<(PngMap const & lhs, PngMap const & rhs)
215 return lhs.key < rhs.key;
221 CompareKey(QString const & name) : name_(name) {}
222 bool operator()(PngMap const & other) const { return other.key == name_; }
228 // this must be sorted alphabetically
229 // Upper case comes before lower case
230 PngMap sorted_png_map[] = {
231 { "Bumpeq", "bumpeq2" },
234 { "Delta", "delta2" },
235 { "Diamond", "diamond2" },
236 { "Downarrow", "downarrow2" },
237 { "Gamma", "gamma2" },
238 { "Lambda", "lambda2" },
239 { "Leftarrow", "leftarrow2" },
240 { "Leftrightarrow", "leftrightarrow2" },
241 { "Longleftarrow", "longleftarrow2" },
242 { "Longleftrightarrow", "longleftrightarrow2" },
243 { "Longrightarrow", "longrightarrow2" },
244 { "Omega", "omega2" },
248 { "Rightarrow", "rightarrow2" },
249 { "Sigma", "sigma2" },
250 { "Subset", "subset2" },
251 { "Supset", "supset2" },
252 { "Theta", "theta2" },
253 { "Uparrow", "uparrow2" },
254 { "Updownarrow", "updownarrow2" },
255 { "Upsilon", "upsilon2" },
256 { "Vdash", "vdash3" },
259 { "nLeftarrow", "nleftarrow2" },
260 { "nLeftrightarrow", "nleftrightarrow2" },
261 { "nRightarrow", "nrightarrow2" },
262 { "nVDash", "nvdash3" },
263 { "nvDash", "nvdash2" },
264 { "textrm \\AA", "textrm_AA"},
265 { "textrm \\O", "textrm_O"},
266 { "vDash", "vdash2" }
269 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
272 QString findPng(QString const & name)
274 PngMap const * const begin = sorted_png_map;
275 PngMap const * const end = begin + nr_sorted_png_map;
276 LASSERT(sorted(begin, end), /**/);
278 PngMap const * const it = find_if(begin, end, CompareKey(name));
282 png_name = it->value;
285 png_name.replace('_', "underscore");
286 png_name.replace(' ', '_');
288 // This way we can have "math-delim { }" on the toolbar.
289 png_name.replace('(', "lparen");
290 png_name.replace(')', "rparen");
291 png_name.replace('[', "lbracket");
292 png_name.replace(']', "rbracket");
293 png_name.replace('{', "lbrace");
294 png_name.replace('}', "rbrace");
295 png_name.replace('|', "bars");
296 png_name.replace(',', "thinspace");
297 png_name.replace(':', "mediumspace");
298 png_name.replace(';', "thickspace");
299 png_name.replace('!', "negthinspace");
302 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
303 << "Looking for math PNG called \"" << png_name << '"');
310 QString iconName(FuncRequest const & f, bool unknown)
312 initializeResources();
316 switch (f.action()) {
317 case LFUN_MATH_INSERT:
318 if (!f.argument().empty()) {
320 name1 = findPng(toqstr(f.argument()).mid(1));
323 case LFUN_MATH_DELIM:
324 case LFUN_MATH_BIGDELIM:
326 name1 = findPng(toqstr(f.argument()));
330 name1 = toqstr(f.argument());
332 case LFUN_COMMAND_ALTERNATIVES: {
333 // use the first of the alternative commands
335 docstring dummy = split(f.argument(), firstcom, ';');
336 name1 = toqstr(firstcom);
337 // FIXME: we should rename the icons to tabular-xxx instead of
338 // "tabular-feature-xxx"
339 name1.replace("inset-modify tabular", "tabular-feature");
340 name1.replace(' ', '_');
343 case LFUN_INSET_MODIFY: {
344 // FIXME: we should rename the icons to tabular-xxx instead of
345 // "tabular-feature-xxx" and generalize this naming to all
346 // insets, not to tabular using ones.
348 string const command = split(to_utf8(f.argument()), inset_name, ' ');
349 if (insetCode(inset_name) == TABULAR_CODE) {
350 name1 = "tabular-feature "+ toqstr(command);
351 name1.replace(' ', '_');
356 name2 = toqstr(lyxaction.getActionName(f.action()));
359 if (!f.argument().empty()) {
360 name1 = name2 + ' ' + toqstr(f.argument());
361 name1.replace(' ', '_');
362 name1.replace('\\', "backslash");
366 FileName fname = libFileSearch("images/" + path, name1, "png");
368 return toqstr(fname.absFileName());
370 fname = libFileSearch("images/" + path, name2, "png");
372 return toqstr(fname.absFileName());
374 path = ":/images/" + path;
377 LYXERR0("Directory " << path << " not found in resource!");
381 if (res.exists(name1))
385 if (res.exists(name2))
388 LYXERR(Debug::GUI, "Cannot find icon with filename "
389 << "\"" << name1 << "\""
391 << "\"" << name2 << "\""
393 << lyxaction.getActionName(f.action())
394 << '(' << to_utf8(f.argument()) << ")\"");
397 fname = libFileSearch(QString("images/"), "unknown", "png");
399 return toqstr(fname.absFileName());
400 return QString(":/images/unknown.png");
406 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
409 FileName fname = libFileSearch(path, name, ext);
410 QString path1 = toqstr(fname.absFileName());
411 QString path2 = ":/" + path + name + "." + ext;
413 if (pixmap.load(path1)) {
416 else if (pixmap.load(path2)) {
420 LYXERR0("Cannot load pixmap \""
421 << path << name << '.' << ext
422 << "\", please verify resource system!");
427 QIcon getIcon(FuncRequest const & f, bool unknown)
429 QString icon = iconName(f, unknown);
433 //LYXERR(Debug::GUI, "Found icon: " << icon);
435 if (!pm.load(icon)) {
436 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
444 ////////////////////////////////////////////////////////////////////////
446 // LyX server support code.
448 ////////////////////////////////////////////////////////////////////////
450 class SocketNotifier : public QSocketNotifier
453 /// connect a connection notification from the LyXServerSocket
454 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
455 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
459 /// The callback function
460 Application::SocketCallback func_;
464 ////////////////////////////////////////////////////////////////////////
466 // Mac specific stuff goes here...
468 ////////////////////////////////////////////////////////////////////////
470 class MenuTranslator : public QTranslator
473 MenuTranslator(QObject * parent)
474 : QTranslator(parent)
477 QString translate(const char * /*context*/,
478 const char * sourceText,
479 const char * /*comment*/ = 0)
481 string const s = sourceText;
482 if (s == N_("About %1") || s == N_("Preferences")
483 || s == N_("Reconfigure") || s == N_("Quit %1"))
490 class GlobalMenuBar : public QMenuBar
494 GlobalMenuBar() : QMenuBar(0) {}
497 bool event(QEvent * e)
499 if (e->type() == QEvent::ShortcutOverride) {
500 // && activeWindow() == 0) {
501 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
503 setKeySymbol(&sym, ke);
504 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
513 // QMacPasteboardMimeGraphics can only be compiled on Mac.
515 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
518 QMacPasteboardMimeGraphics()
519 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
522 QString convertorName() { return "Graphics"; }
524 QString flavorFor(QString const & mime)
526 LYXERR(Debug::ACTION, "flavorFor " << mime);
527 if (mime == pdfMimeType())
528 return QLatin1String("com.adobe.pdf");
532 QString mimeFor(QString flav)
534 LYXERR(Debug::ACTION, "mimeFor " << flav);
535 if (flav == QLatin1String("com.adobe.pdf"))
536 return pdfMimeType();
540 bool canConvert(QString const & mime, QString flav)
542 return mimeFor(flav) == mime;
545 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
549 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
553 QList<QByteArray> convertFromMime(QString const & /*mime*/,
554 QVariant data, QString /*flav*/)
556 QList<QByteArray> ret;
557 ret.append(data.toByteArray());
563 ///////////////////////////////////////////////////////////////
565 // You can find more platform specific stuff at the end of this file...
567 ///////////////////////////////////////////////////////////////
569 ////////////////////////////////////////////////////////////////////////
570 // Windows specific stuff goes here...
573 // QWindowsMimeMetafile can only be compiled on Windows.
575 static FORMATETC cfFromMime(QString const & mimetype)
578 if (mimetype == emfMimeType()) {
579 formatetc.cfFormat = CF_ENHMETAFILE;
580 formatetc.tymed = TYMED_ENHMF;
581 } else if (mimetype == wmfMimeType()) {
582 formatetc.cfFormat = CF_METAFILEPICT;
583 formatetc.tymed = TYMED_MFPICT;
586 formatetc.dwAspect = DVASPECT_CONTENT;
587 formatetc.lindex = -1;
592 class QWindowsMimeMetafile : public QWindowsMime {
594 QWindowsMimeMetafile() {}
596 bool canConvertFromMime(FORMATETC const & formatetc,
597 QMimeData const * mimedata) const
602 bool canConvertToMime(QString const & mimetype,
603 IDataObject * pDataObj) const
605 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
607 FORMATETC formatetc = cfFromMime(mimetype);
608 return pDataObj->QueryGetData(&formatetc) == S_OK;
611 bool convertFromMime(FORMATETC const & formatetc,
612 const QMimeData * mimedata, STGMEDIUM * pmedium) const
617 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
618 QVariant::Type preferredType) const
621 if (!canConvertToMime(mimetype, pDataObj))
624 FORMATETC formatetc = cfFromMime(mimetype);
626 if (pDataObj->GetData(&formatetc, &s) != S_OK)
630 if (s.tymed == TYMED_ENHMF) {
631 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
632 data.resize(dataSize);
633 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
634 (LPBYTE)data.data());
635 } else if (s.tymed == TYMED_MFPICT) {
636 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
637 data.resize(dataSize);
638 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
639 (LPBYTE)data.data());
642 ReleaseStgMedium(&s);
648 QVector<FORMATETC> formatsForMime(QString const & mimetype,
649 QMimeData const * mimedata) const
651 QVector<FORMATETC> formats;
652 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
653 formats += cfFromMime(mimetype);
657 QString mimeForFormat(FORMATETC const & formatetc) const
659 switch (formatetc.cfFormat) {
661 return emfMimeType();
662 case CF_METAFILEPICT:
663 return wmfMimeType();
671 ////////////////////////////////////////////////////////////////////////
672 // GuiApplication::Private definition and implementation.
673 ////////////////////////////////////////////////////////////////////////
675 struct GuiApplication::Private
677 Private(): language_model_(0), meta_fake_bit(NoModifier),
681 /// WMF Mime handler for Windows clipboard.
682 wmf_mime_ = new QWindowsMimeMetafile();
684 initKeySequences(&theTopLevelKeymap());
687 void initKeySequences(KeyMap * kb)
689 keyseq = KeySequence(kb, kb);
690 cancel_meta_seq = KeySequence(kb, kb);
694 QSortFilterProxyModel * language_model_;
696 GuiClipboard clipboard_;
698 GuiSelection selection_;
700 FontLoader font_loader_;
702 ColorCache color_cache_;
704 QTranslator qt_trans_;
706 QHash<int, SocketNotifier *> socket_notifiers_;
710 /// The global instance
713 /// this timer is used for any regular events one wants to
714 /// perform. at present it is used to check if forked processes
716 QTimer general_timer_;
718 /// delayed FuncRequests
719 std::queue<FuncRequest> func_request_queue_;
724 KeySequence cancel_meta_seq;
726 KeyModifier meta_fake_bit;
728 /// Multiple views container.
730 * Warning: This must not be a smart pointer as the destruction of the
731 * object is handled by Qt when the view is closed
732 * \sa Qt::WA_DeleteOnClose attribute.
734 QHash<int, GuiView *> views_;
736 /// Only used on mac.
737 GlobalMenuBar * global_menubar_;
740 /// Linkback mime handler for MacOSX.
741 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
745 /// WMF Mime handler for Windows clipboard.
746 QWindowsMimeMetafile * wmf_mime_;
751 GuiApplication * guiApp;
753 GuiApplication::~GuiApplication()
756 closeAllLinkBackLinks();
763 void setColor(ColorCode code, QPalette const & pal, QPalette::ColorRole cr)
765 lcolor.setColor(code, fromqstr(pal.brush(QPalette::Active, cr).color().name()));
769 GuiApplication::GuiApplication(int & argc, char ** argv)
770 : QApplication(argc, argv), current_view_(0),
771 d(new GuiApplication::Private)
773 QString app_name = "LyX";
774 QCoreApplication::setOrganizationName(app_name);
775 QCoreApplication::setOrganizationDomain("lyx.org");
776 QCoreApplication::setApplicationName(lyx_package);
778 // Install translator for GUI elements.
779 installTranslator(&d->qt_trans_);
781 // FIXME: quitOnLastWindowClosed is true by default. We should have a
782 // lyxrc setting for this in order to let the application stay resident.
783 // But then we need some kind of dock icon, at least on Windows.
785 if (lyxrc.quit_on_last_window_closed)
786 setQuitOnLastWindowClosed(false);
789 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
790 // seems to be the default case for applications like LyX.
791 setQuitOnLastWindowClosed(false);
792 // setAttribute(Qt::AA_MacDontSwapCtrlAndMeta);
794 // This allows to translate the strings that appear in the LyX menu.
795 /// A translator suitable for the entries in the LyX menu.
796 /// Only needed with Qt/Mac.
797 installTranslator(new MenuTranslator(this));
801 // doubleClickInterval() is 400 ms on X11 which is just too long.
802 // On Windows and Mac OS X, the operating system's value is used.
803 // On Microsoft Windows, calling this function sets the double
804 // click interval for all applications. So we don't!
805 QApplication::setDoubleClickInterval(300);
808 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
810 // needs to be done before reading lyxrc
812 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
816 // Set the cache to 5120 kilobytes which corresponds to screen size of
817 // 1280 by 1024 pixels with a color depth of 32 bits.
818 QPixmapCache::setCacheLimit(5120);
820 // Initialize RC Fonts
821 if (lyxrc.roman_font_name.empty())
822 lyxrc.roman_font_name = fromqstr(romanFontName());
824 if (lyxrc.sans_font_name.empty())
825 lyxrc.sans_font_name = fromqstr(sansFontName());
827 if (lyxrc.typewriter_font_name.empty())
828 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
831 setColor(Color_background, palette(), QPalette::Window);
832 setColor(Color_foreground, palette(), QPalette::WindowText);
833 setColor(Color_selection, palette(), QPalette::Highlight);
834 setColor(Color_selectiontext, palette(), QPalette::HighlightedText);
836 d->general_timer_.setInterval(500);
837 connect(&d->general_timer_, SIGNAL(timeout()),
838 this, SLOT(handleRegularEvents()));
839 d->general_timer_.start();
841 #if QT_VERSION >= 0x040400
842 // maxThreadCount() defaults in general to 2 on single or dual-processor.
843 // This is clearly not enough in a time where we use threads for
844 // document preview and/or export. 20 should be OK.
845 QThreadPool::globalInstance()->setMaxThreadCount(20);
850 GuiApplication * theGuiApp()
852 return dynamic_cast<GuiApplication *>(theApp());
856 void GuiApplication::clearSession()
863 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
865 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
869 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
874 BufferView * doc_bv = 0;
876 if (cmd.action() == LFUN_NOACTION) {
877 status.message(from_utf8(N_("Nothing to do")));
878 status.setEnabled(false);
881 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
882 status.setUnknown(true);
883 status.message(from_utf8(N_("Unknown action")));
884 status.setEnabled(false);
887 // Does the GuiApplication know something?
888 else if (getStatus(cmd, status)) { }
890 // If we do not have a GuiView, then other functions are disabled
891 else if (!current_view_)
892 status.setEnabled(false);
894 // Does the GuiView know something?
895 else if (current_view_->getStatus(cmd, status)) { }
897 // In LyX/Mac, when a dialog is open, the menus of the
898 // application can still be accessed without giving focus to
899 // the main window. In this case, we want to disable the menu
900 // entries that are buffer or view-related.
901 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
903 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
904 status.setEnabled(false);
907 // If we do not have a BufferView, then other functions are disabled
908 else if (!(bv = current_view_->currentBufferView()))
909 status.setEnabled(false);
911 // Does the current BufferView know something?
912 else if (bv->getStatus(cmd, status)) { }
914 // Does the current Buffer know something?
915 else if (bv->buffer().getStatus(cmd, status)) { }
917 // If we do not have a document BufferView, different from the
918 // current BufferView, then other functions are disabled
919 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
920 status.setEnabled(false);
922 // Does the document Buffer know something?
923 else if (doc_bv->buffer().getStatus(cmd, status)) { }
926 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
927 status.message(from_utf8(N_("Command not handled")));
928 status.setEnabled(false);
931 // the default error message if we disable the command
932 if (!status.enabled() && status.message().empty())
933 status.message(from_utf8(N_("Command disabled")));
939 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
941 // I would really like to avoid having this switch and rather try to
942 // encode this in the function itself.
943 // -- And I'd rather let an inset decide which LFUNs it is willing
944 // to handle (Andre')
946 switch (cmd.action()) {
948 // This could be used for the no-GUI version. The GUI version is handled in
949 // GuiView::getStatus(). See above.
951 case LFUN_BUFFER_WRITE:
952 case LFUN_BUFFER_WRITE_AS: {
953 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
954 enable = b && (b->isUnnamed() || !b->isClean());
959 case LFUN_BOOKMARK_GOTO: {
960 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
961 enable = theSession().bookmarks().isValid(num);
965 case LFUN_BOOKMARK_CLEAR:
966 enable = theSession().bookmarks().hasValid();
969 // this one is difficult to get right. As a half-baked
970 // solution, we consider only the first action of the sequence
971 case LFUN_COMMAND_SEQUENCE: {
972 // argument contains ';'-terminated commands
973 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
974 FuncRequest func(lyxaction.lookupFunc(firstcmd));
975 func.setOrigin(cmd.origin());
976 flag = getStatus(func);
980 // we want to check if at least one of these is enabled
981 case LFUN_COMMAND_ALTERNATIVES: {
982 // argument contains ';'-terminated commands
983 string arg = to_utf8(cmd.argument());
984 while (!arg.empty()) {
986 arg = split(arg, first, ';');
987 FuncRequest func(lyxaction.lookupFunc(first));
988 func.setOrigin(cmd.origin());
989 flag = getStatus(func);
990 // if this one is enabled, the whole thing is
999 string name = to_utf8(cmd.argument());
1000 if (theTopLevelCmdDef().lock(name, func)) {
1001 func.setOrigin(cmd.origin());
1002 flag = getStatus(func);
1003 theTopLevelCmdDef().release(name);
1005 // catch recursion or unknown command
1006 // definition. all operations until the
1007 // recursion or unknown command definition
1008 // occurs are performed, so set the state to
1015 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1017 case LFUN_PREFERENCES_SAVE:
1018 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1019 case LFUN_DEBUG_LEVEL_SET:
1020 // these are handled in our dispatch()
1023 case LFUN_WINDOW_CLOSE:
1024 enable = d->views_.size() > 0;
1027 case LFUN_BUFFER_NEW:
1028 case LFUN_BUFFER_NEW_TEMPLATE:
1029 case LFUN_FILE_OPEN:
1030 case LFUN_HELP_OPEN:
1031 case LFUN_SCREEN_FONT_UPDATE:
1032 case LFUN_SET_COLOR:
1033 case LFUN_WINDOW_NEW:
1035 case LFUN_LYXRC_APPLY:
1036 case LFUN_COMMAND_PREFIX:
1038 case LFUN_META_PREFIX:
1039 case LFUN_RECONFIGURE:
1040 case LFUN_SERVER_GET_FILENAME:
1041 case LFUN_SERVER_NOTIFY:
1050 flag.setEnabled(false);
1054 /// make a post-dispatch status message
1055 static docstring makeDispatchMessage(docstring const & msg,
1056 FuncRequest const & cmd)
1058 const bool verbose = (cmd.origin() == FuncRequest::MENU
1059 || cmd.origin() == FuncRequest::TOOLBAR
1060 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1062 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1063 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1067 docstring dispatch_msg = msg;
1068 if (!dispatch_msg.empty())
1069 dispatch_msg += ' ';
1071 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1073 bool argsadded = false;
1075 if (!cmd.argument().empty()) {
1076 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1077 comname += ' ' + cmd.argument();
1081 docstring const shortcuts = theTopLevelKeymap().
1082 printBindings(cmd, KeySequence::ForGui);
1084 if (!shortcuts.empty())
1085 comname += ": " + shortcuts;
1086 else if (!argsadded && !cmd.argument().empty())
1087 comname += ' ' + cmd.argument();
1089 if (!comname.empty()) {
1090 comname = rtrim(comname);
1091 dispatch_msg += '(' + rtrim(comname) + ')';
1093 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1094 return dispatch_msg;
1098 void GuiApplication::dispatch(FuncRequest const & cmd)
1100 if (current_view_ && current_view_->currentBufferView())
1101 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1104 // redraw the screen at the end (first of the two drawing steps).
1105 //This is done unless explicitly requested otherwise
1106 dr.update(Update::FitCursor);
1112 BufferView * bv = current_view_->currentBufferView();
1114 if (dr.needBufferUpdate()) {
1115 bv->cursor().clearBufferUpdate();
1116 bv->buffer().updateBuffer();
1118 // BufferView::update() updates the ViewMetricsInfo and
1119 // also initializes the position cache for all insets in
1120 // (at least partially) visible top-level paragraphs.
1121 // We will redraw the screen only if needed.
1122 bv->processUpdateFlags(dr.update());
1124 // Do we have a selection?
1125 theSelection().haveSelection(bv->cursor().selection());
1128 current_view_->restartCursor();
1130 // Some messages may already be translated, so we cannot use _()
1131 current_view_->message(makeDispatchMessage(
1132 translateIfPossible(dr.message()), cmd));
1136 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile, bool switchToBuffer)
1138 LASSERT(current_view_, /**/);
1139 if (!theSession().bookmarks().isValid(idx))
1141 BookmarksSection::Bookmark const & bm = theSession().bookmarks().bookmark(idx);
1142 LASSERT(!bm.filename.empty(), /**/);
1143 string const file = bm.filename.absFileName();
1144 // if the file is not opened, open it.
1145 if (!theBufferList().exists(bm.filename)) {
1147 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1151 // open may fail, so we need to test it again
1152 if (!theBufferList().exists(bm.filename))
1155 // bm can be changed when saving
1156 BookmarksSection::Bookmark tmp = bm;
1158 // Special case idx == 0 used for back-from-back jump navigation
1160 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1162 // if the current buffer is not that one, switch to it.
1163 if (!current_view_->documentBufferView()
1164 || current_view_->documentBufferView()->buffer().fileName() != tmp.filename) {
1165 if (!switchToBuffer)
1167 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1170 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1171 if (!current_view_->documentBufferView()->moveToPosition(
1172 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1179 // Cursor jump succeeded!
1180 Cursor const & cur = current_view_->documentBufferView()->cursor();
1181 pit_type new_pit = cur.pit();
1182 pos_type new_pos = cur.pos();
1183 int new_id = cur.paragraph().id();
1185 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1186 // see http://www.lyx.org/trac/ticket/3092
1187 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1188 || bm.top_id != new_id) {
1189 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1190 new_pit, new_pos, new_id);
1194 // This function runs "configure" and then rereads lyx.defaults to
1195 // reconfigure the automatic settings.
1196 void GuiApplication::reconfigure(string const & option)
1198 // emit message signal.
1200 current_view_->message(_("Running configure..."));
1202 // Run configure in user lyx directory
1203 PathChanger p(package().user_support());
1204 string configure_command = package().configure_command();
1205 configure_command += option;
1207 int ret = one.startscript(Systemcall::Wait, configure_command);
1209 // emit message signal.
1211 current_view_->message(_("Reloading configuration..."));
1212 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1213 // Re-read packages.lst
1214 LaTeXFeatures::getAvailable();
1217 Alert::information(_("System reconfiguration failed"),
1218 _("The system reconfiguration has failed.\n"
1219 "Default textclass is used but LyX may "
1220 "not be able to work properly.\n"
1221 "Please reconfigure again if needed."));
1223 Alert::information(_("System reconfigured"),
1224 _("The system has been reconfigured.\n"
1225 "You need to restart LyX to make use of any\n"
1226 "updated document class specifications."));
1230 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1232 string const argument = to_utf8(cmd.argument());
1233 FuncCode const action = cmd.action();
1235 LYXERR(Debug::ACTION, "cmd: " << cmd);
1237 // we have not done anything wrong yet.
1240 FuncStatus const flag = getStatus(cmd);
1241 if (!flag.enabled()) {
1242 // We cannot use this function here
1243 LYXERR(Debug::ACTION, "action "
1244 << lyxaction.getActionName(action)
1245 << " [" << action << "] is disabled at this location");
1247 current_view_->restartCursor();
1248 dr.setMessage(flag.message());
1250 dr.dispatched(false);
1251 dr.update(Update::None);
1252 dr.clearBufferUpdate();
1256 // Assumes that the action will be dispatched.
1257 dr.dispatched(true);
1259 switch (cmd.action()) {
1261 case LFUN_WINDOW_NEW:
1262 createView(toqstr(cmd.argument()));
1265 case LFUN_WINDOW_CLOSE:
1266 // update bookmark pit of the current buffer before window close
1267 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1268 gotoBookmark(i+1, false, false);
1269 // clear the last opened list, because
1270 // maybe this will end the session
1271 theSession().lastOpened().clear();
1272 current_view_->closeScheduled();
1276 // quitting is triggered by the gui code
1277 // (leaving the event loop).
1279 current_view_->message(from_utf8(N_("Exiting.")));
1280 if (closeAllViews())
1284 case LFUN_SCREEN_FONT_UPDATE: {
1285 // handle the screen font changes.
1286 d->font_loader_.update();
1287 // Backup current_view_
1288 GuiView * view = current_view_;
1289 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1290 // to skip the refresh.
1292 theBufferList().changed(false);
1293 // Restore current_view_
1294 current_view_ = view;
1298 case LFUN_BUFFER_NEW:
1299 if (d->views_.empty()
1300 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1301 createView(QString(), false); // keep hidden
1302 current_view_->newDocument(to_utf8(cmd.argument()), false);
1303 current_view_->show();
1304 setActiveWindow(current_view_);
1306 current_view_->newDocument(to_utf8(cmd.argument()), false);
1310 case LFUN_BUFFER_NEW_TEMPLATE:
1311 if (d->views_.empty()
1312 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1314 current_view_->newDocument(to_utf8(cmd.argument()), true);
1315 if (!current_view_->documentBufferView())
1316 current_view_->close();
1318 current_view_->newDocument(to_utf8(cmd.argument()), true);
1322 case LFUN_FILE_OPEN:
1323 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1324 if (d->views_.empty()
1325 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1326 string const fname = to_utf8(cmd.argument());
1327 // We want the ui session to be saved per document and not per
1328 // window number. The filename crc is a good enough identifier.
1329 boost::crc_32_type crc;
1330 crc = for_each(fname.begin(), fname.end(), crc);
1331 createView(crc.checksum());
1332 current_view_->openDocument(fname);
1333 if (current_view_ && !current_view_->documentBufferView())
1334 current_view_->close();
1336 current_view_->openDocument(to_utf8(cmd.argument()));
1339 case LFUN_HELP_OPEN: {
1340 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1341 if (current_view_ == 0)
1343 string const arg = to_utf8(cmd.argument());
1345 current_view_->message(_("Missing argument"));
1348 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1350 fname = i18nLibFileSearch("examples", arg, "lyx");
1352 if (fname.empty()) {
1353 lyxerr << "LyX: unable to find documentation file `"
1354 << arg << "'. Bad installation?" << endl;
1357 current_view_->message(bformat(_("Opening help file %1$s..."),
1358 makeDisplayPath(fname.absFileName())));
1359 Buffer * buf = current_view_->loadDocument(fname, false);
1361 current_view_->setBuffer(buf);
1362 #ifndef DEVEL_VERSION
1363 buf->setReadonly(true);
1365 buf->errors("Parse");
1370 case LFUN_SET_COLOR: {
1372 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1373 if (lyx_name.empty() || x11_name.empty()) {
1374 current_view_->message(
1375 _("Syntax: set-color <lyx_name> <x11_name>"));
1379 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1380 bool const graphicsbg_changed =
1381 lyx_name == graphicsbg && x11_name != graphicsbg;
1382 if (graphicsbg_changed) {
1383 // FIXME: The graphics cache no longer has a changeDisplay method.
1385 graphics::GCache::get().changeDisplay(true);
1389 if (!lcolor.setColor(lyx_name, x11_name)) {
1390 current_view_->message(
1391 bformat(_("Set-color \"%1$s\" failed "
1392 "- color is undefined or "
1393 "may not be redefined"),
1394 from_utf8(lyx_name)));
1397 // Make sure we don't keep old colors in cache.
1398 d->color_cache_.clear();
1402 case LFUN_LYXRC_APPLY: {
1403 // reset active key sequences, since the bindings
1404 // are updated (bug 6064)
1406 LyXRC const lyxrc_orig = lyxrc;
1408 istringstream ss(to_utf8(cmd.argument()));
1409 bool const success = lyxrc.read(ss) == 0;
1412 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1413 << "Unable to read lyxrc data"
1418 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1425 case LFUN_COMMAND_PREFIX:
1426 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1431 d->meta_fake_bit = NoModifier;
1432 GuiView * gv = currentView();
1433 if (gv && gv->currentBufferView())
1434 // cancel any selection
1435 lyx::dispatch(FuncRequest(LFUN_MARK_OFF));
1436 dr.setMessage(from_ascii(N_("Cancel")));
1439 case LFUN_META_PREFIX:
1440 d->meta_fake_bit = AltModifier;
1441 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1444 // --- Menus -----------------------------------------------
1445 case LFUN_RECONFIGURE:
1446 // argument is any additional parameter to the configure.py command
1447 reconfigure(to_utf8(cmd.argument()));
1450 // --- lyxserver commands ----------------------------
1451 case LFUN_SERVER_GET_FILENAME: {
1452 LASSERT(current_view_ && current_view_->documentBufferView(), return);
1453 docstring const fname = from_utf8(
1454 current_view_->documentBufferView()->buffer().absFileName());
1455 dr.setMessage(fname);
1456 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1459 case LFUN_SERVER_NOTIFY: {
1460 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1461 dr.setMessage(dispatch_buffer);
1462 theServer().notifyClient(to_utf8(dispatch_buffer));
1466 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1467 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1473 string rest = split(argument, countstr, ' ');
1474 istringstream is(countstr);
1477 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1478 for (int i = 0; i < count; ++i)
1479 dispatch(lyxaction.lookupFunc(rest));
1483 case LFUN_COMMAND_SEQUENCE: {
1484 // argument contains ';'-terminated commands
1485 string arg = argument;
1486 // FIXME: this LFUN should also work without any view.
1487 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1488 ? &(current_view_->documentBufferView()->buffer()) : 0;
1490 buffer->undo().beginUndoGroup();
1491 while (!arg.empty()) {
1493 arg = split(arg, first, ';');
1494 FuncRequest func(lyxaction.lookupFunc(first));
1495 func.setOrigin(cmd.origin());
1498 // the buffer may have been closed by one action
1499 if (theBufferList().isLoaded(buffer))
1500 buffer->undo().endUndoGroup();
1504 case LFUN_COMMAND_ALTERNATIVES: {
1505 // argument contains ';'-terminated commands
1506 string arg = argument;
1507 while (!arg.empty()) {
1509 arg = split(arg, first, ';');
1510 FuncRequest func(lyxaction.lookupFunc(first));
1511 func.setOrigin(cmd.origin());
1512 FuncStatus const stat = getStatus(func);
1513 if (stat.enabled()) {
1523 if (theTopLevelCmdDef().lock(argument, func)) {
1524 func.setOrigin(cmd.origin());
1526 theTopLevelCmdDef().release(argument);
1528 if (func.action() == LFUN_UNKNOWN_ACTION) {
1529 // unknown command definition
1530 lyxerr << "Warning: unknown command definition `"
1534 // recursion detected
1535 lyxerr << "Warning: Recursion in the command definition `"
1536 << argument << "' detected"
1543 case LFUN_PREFERENCES_SAVE:
1544 lyxrc.write(support::makeAbsPath("preferences",
1545 package().user_support().absFileName()), false);
1548 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1549 string const fname = addName(addPath(package().user_support().absFileName(),
1550 "templates/"), "defaults.lyx");
1551 Buffer defaults(fname);
1553 istringstream ss(argument);
1556 int const unknown_tokens = defaults.readHeader(lex);
1558 if (unknown_tokens != 0) {
1559 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1560 << unknown_tokens << " unknown token"
1561 << (unknown_tokens == 1 ? "" : "s")
1565 if (defaults.writeFile(FileName(defaults.absFileName())))
1566 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1567 makeDisplayPath(fname)));
1570 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1575 case LFUN_BOOKMARK_GOTO:
1576 // go to bookmark, open unopened file and switch to buffer if necessary
1577 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1578 dr.update(Update::Force | Update::FitCursor);
1581 case LFUN_BOOKMARK_CLEAR:
1582 theSession().bookmarks().clear();
1585 case LFUN_DEBUG_LEVEL_SET:
1586 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1590 // Everything below is only for active window
1591 if (current_view_ == 0)
1594 // Let the current GuiView dispatch its own actions.
1595 current_view_->dispatch(cmd, dr);
1597 if (dr.dispatched())
1600 BufferView * bv = current_view_->currentBufferView();
1603 // Let the current BufferView dispatch its own actions.
1604 bv->dispatch(cmd, dr);
1605 if (dr.dispatched())
1608 BufferView * doc_bv = current_view_->documentBufferView();
1609 // Try with the document BufferView dispatch if any.
1611 doc_bv->dispatch(cmd, dr);
1612 if (dr.dispatched())
1616 // OK, so try the current Buffer itself...
1617 bv->buffer().dispatch(cmd, dr);
1618 if (dr.dispatched())
1621 // and with the document Buffer.
1623 doc_bv->buffer().dispatch(cmd, dr);
1624 if (dr.dispatched())
1628 // Let the current Cursor dispatch its own actions.
1629 Cursor old = bv->cursor();
1630 bv->cursor().dispatch(cmd);
1632 // notify insets we just left
1633 if (bv->cursor() != old) {
1635 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1637 bv->cursor().fixIfBroken();
1640 // update completion. We do it here and not in
1641 // processKeySym to avoid another redraw just for a
1642 // changed inline completion
1643 if (cmd.origin() == FuncRequest::KEYBOARD) {
1644 if (cmd.action() == LFUN_SELF_INSERT
1645 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1646 current_view_->updateCompletion(bv->cursor(), true, true);
1647 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
1648 current_view_->updateCompletion(bv->cursor(), false, true);
1650 current_view_->updateCompletion(bv->cursor(), false, false);
1653 dr = bv->cursor().result();
1656 // if we executed a mutating lfun, mark the buffer as dirty
1657 Buffer * doc_buffer = (current_view_ && current_view_->documentBufferView())
1658 ? &(current_view_->documentBufferView()->buffer()) : 0;
1659 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1661 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1662 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1663 current_view_->currentBufferView()->buffer().markDirty();
1667 docstring GuiApplication::viewStatusMessage()
1669 // When meta-fake key is pressed, show the key sequence so far + "M-".
1670 if (d->meta_fake_bit != NoModifier)
1671 return d->keyseq.print(KeySequence::ForGui) + "M-";
1673 // Else, when a non-complete key sequence is pressed,
1674 // show the available options.
1675 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1676 return d->keyseq.printOptions(true);
1682 void GuiApplication::handleKeyFunc(FuncCode action)
1686 if (d->keyseq.length())
1688 GuiView * gv = currentView();
1689 LASSERT(gv && gv->currentBufferView(), return);
1690 BufferView * bv = gv->currentBufferView();
1691 bv->getIntl().getTransManager().deadkey(
1692 c, get_accent(action).accent, bv->cursor().innerText(),
1694 // Need to clear, in case the minibuffer calls these
1697 // copied verbatim from do_accent_char
1698 bv->cursor().resetAnchor();
1699 bv->processUpdateFlags(Update::FitCursor);
1703 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1705 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1707 // Do nothing if we have nothing (JMarc)
1708 if (!keysym.isOK()) {
1709 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1710 current_view_->restartCursor();
1714 if (keysym.isModifier()) {
1715 LYXERR(Debug::KEY, "isModifier true");
1717 current_view_->restartCursor();
1721 char_type encoded_last_key = keysym.getUCSEncoded();
1723 // Do a one-deep top-level lookup for
1724 // cancel and meta-fake keys. RVDK_PATCH_5
1725 d->cancel_meta_seq.reset();
1727 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1728 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1730 // When not cancel or meta-fake, do the normal lookup.
1731 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1732 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1733 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1734 // remove Caps Lock and Mod2 as a modifiers
1735 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1736 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1739 // Dont remove this unless you know what you are doing.
1740 d->meta_fake_bit = NoModifier;
1742 // Can this happen now ?
1743 if (func.action() == LFUN_NOACTION)
1744 func = FuncRequest(LFUN_COMMAND_PREFIX);
1746 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1747 << d->keyseq.print(KeySequence::Portable) << ']');
1749 // already here we know if it any point in going further
1750 // why not return already here if action == -1 and
1751 // num_bytes == 0? (Lgb)
1753 if (d->keyseq.length() > 1)
1754 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1757 // Maybe user can only reach the key via holding down shift.
1758 // Let's see. But only if shift is the only modifier
1759 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1760 LYXERR(Debug::KEY, "Trying without shift");
1761 func = d->keyseq.addkey(keysym, NoModifier);
1762 LYXERR(Debug::KEY, "Action now " << func.action());
1765 if (func.action() == LFUN_UNKNOWN_ACTION) {
1766 // Hmm, we didn't match any of the keysequences. See
1767 // if it's normal insertable text not already covered
1769 if (keysym.isText() && d->keyseq.length() == 1) {
1770 LYXERR(Debug::KEY, "isText() is true, inserting.");
1771 func = FuncRequest(LFUN_SELF_INSERT,
1772 FuncRequest::KEYBOARD);
1774 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1775 current_view_->message(_("Unknown function."));
1776 current_view_->restartCursor();
1781 if (func.action() == LFUN_SELF_INSERT) {
1782 if (encoded_last_key != 0) {
1783 docstring const arg(1, encoded_last_key);
1784 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, arg,
1785 FuncRequest::KEYBOARD));
1786 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1789 lyx::dispatch(func);
1793 void GuiApplication::dispatchDelayed(FuncRequest const & func)
1795 d->func_request_queue_.push(func);
1796 QTimer::singleShot(0, this, SLOT(processFuncRequestQueue()));
1800 void GuiApplication::resetGui()
1802 // Set the language defined by the user.
1806 if (!readUIFile(toqstr(lyxrc.ui_file)))
1807 // Gives some error box here.
1810 if (d->global_menubar_)
1811 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1813 QHash<int, GuiView *>::iterator it;
1814 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1817 gv->setLayoutDirection(layoutDirection());
1821 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1825 void GuiApplication::createView(int view_id)
1827 createView(QString(), true, view_id);
1831 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1834 // release the keyboard which might have been grabed by the global
1835 // menubar on Mac to catch shortcuts even without any GuiView.
1836 if (d->global_menubar_)
1837 d->global_menubar_->releaseKeyboard();
1841 while (d->views_.find(id) != d->views_.end())
1844 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1845 GuiView * view = new GuiView(id);
1847 d->views_[id] = view;
1851 setActiveWindow(view);
1854 if (!geometry_arg.isEmpty()) {
1858 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1859 re.indexIn(geometry_arg);
1860 w = re.cap(1).toInt();
1861 h = re.cap(2).toInt();
1862 x = re.cap(3).toInt();
1863 y = re.cap(4).toInt();
1864 view->setGeometry(x, y, w, h);
1871 Clipboard & GuiApplication::clipboard()
1873 return d->clipboard_;
1877 Selection & GuiApplication::selection()
1879 return d->selection_;
1883 FontLoader & GuiApplication::fontLoader()
1885 return d->font_loader_;
1889 Toolbars const & GuiApplication::toolbars() const
1891 return d->toolbars_;
1895 Toolbars & GuiApplication::toolbars()
1897 return d->toolbars_;
1901 Menus const & GuiApplication::menus() const
1907 Menus & GuiApplication::menus()
1913 QList<int> GuiApplication::viewIds() const
1915 return d->views_.keys();
1919 ColorCache & GuiApplication::colorCache()
1921 return d->color_cache_;
1925 int GuiApplication::exec()
1927 // asynchronously handle batch commands. This event will be in
1928 // the event queue in front of other asynchronous events. Hence,
1929 // we can assume in the latter that the gui is setup already.
1930 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1932 return QApplication::exec();
1936 void GuiApplication::exit(int status)
1938 QApplication::exit(status);
1942 void GuiApplication::setGuiLanguage()
1944 // Set the language defined by the user.
1947 QString const default_language = toqstr(Messages::defaultLanguage());
1948 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1949 QLocale const default_locale(default_language);
1950 QLocale::setDefault(default_locale);
1952 // install translation file for Qt built-in dialogs
1953 QString const language_name = QString("qt_") + default_locale.name();
1955 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1956 // Short-named translator can be loaded from a long name, but not the
1957 // opposite. Therefore, long name should be used without truncation.
1958 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1959 if (!d->qt_trans_.load(language_name,
1960 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1961 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1964 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1968 switch (default_locale.language()) {
1969 case QLocale::Arabic :
1970 case QLocale::Hebrew :
1971 case QLocale::Persian :
1972 case QLocale::Urdu :
1973 setLayoutDirection(Qt::RightToLeft);
1976 setLayoutDirection(Qt::LeftToRight);
1981 void GuiApplication::processFuncRequestQueue()
1983 while (!d->func_request_queue_.empty()) {
1984 lyx::dispatch(d->func_request_queue_.back());
1985 d->func_request_queue_.pop();
1990 void GuiApplication::execBatchCommands()
1995 if (!readUIFile(toqstr(lyxrc.ui_file)))
1996 // Gives some error box here.
2000 // Create the global default menubar which is shown for the dialogs
2001 // and if no GuiView is visible.
2002 // This must be done after the session was recovered to know the "last files".
2003 d->global_menubar_ = new GlobalMenuBar();
2004 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2007 lyx::execBatchCommands();
2011 QAbstractItemModel * GuiApplication::languageModel()
2013 if (d->language_model_)
2014 return d->language_model_;
2016 QStandardItemModel * lang_model = new QStandardItemModel(this);
2017 lang_model->insertColumns(0, 3);
2019 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2020 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2021 Languages::const_iterator it = lyx::languages.begin();
2022 Languages::const_iterator end = lyx::languages.end();
2023 for (; it != end; ++it) {
2024 current_row = lang_model->rowCount();
2025 lang_model->insertRows(current_row, 1);
2026 QModelIndex pl_item = lang_model->index(current_row, 0);
2027 QModelIndex sp_item = lang_model->index(current_row, 1);
2028 QModelIndex th_item = lang_model->index(current_row, 2);
2029 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2030 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2031 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2032 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2033 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2034 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2035 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2036 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2037 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2038 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2040 d->language_model_ = new QSortFilterProxyModel(this);
2041 d->language_model_->setSourceModel(lang_model);
2042 #if QT_VERSION >= 0x040300
2043 d->language_model_->setSortLocaleAware(true);
2045 return d->language_model_;
2049 void GuiApplication::restoreGuiSession()
2051 if (!lyxrc.load_session)
2054 Session & session = theSession();
2055 LastOpenedSection::LastOpened const & lastopened =
2056 session.lastOpened().getfiles();
2058 FileName active_file;
2059 // do not add to the lastfile list since these files are restored from
2060 // last session, and should be already there (regular files), or should
2061 // not be added at all (help files).
2062 for (size_t i = 0; i < lastopened.size(); ++i) {
2063 FileName const & file_name = lastopened[i].file_name;
2064 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2065 && current_view_->documentBufferView() != 0)) {
2066 boost::crc_32_type crc;
2067 string const & fname = file_name.absFileName();
2068 crc = for_each(fname.begin(), fname.end(), crc);
2069 createView(crc.checksum());
2071 current_view_->loadDocument(file_name, false);
2073 if (lastopened[i].active)
2074 active_file = file_name;
2077 // Restore last active buffer
2078 Buffer * buffer = theBufferList().getBuffer(active_file);
2080 current_view_->setBuffer(buffer);
2082 // clear this list to save a few bytes of RAM
2083 session.lastOpened().clear();
2087 QString const GuiApplication::romanFontName()
2090 font.setKerning(false);
2091 font.setStyleHint(QFont::Serif);
2092 font.setFamily("serif");
2094 return QFontInfo(font).family();
2098 QString const GuiApplication::sansFontName()
2101 font.setKerning(false);
2102 font.setStyleHint(QFont::SansSerif);
2103 font.setFamily("sans");
2105 return QFontInfo(font).family();
2109 QString const GuiApplication::typewriterFontName()
2112 font.setKerning(false);
2113 font.setStyleHint(QFont::TypeWriter);
2114 font.setFamily("monospace");
2116 return QFontInfo(font).family();
2120 void GuiApplication::handleRegularEvents()
2122 ForkedCallsController::handleCompletedProcesses();
2126 bool GuiApplication::event(QEvent * e)
2129 case QEvent::FileOpen: {
2130 // Open a file; this happens only on Mac OS X for now.
2132 // We do this asynchronously because on startup the batch
2133 // commands are not executed here yet and the gui is not ready
2135 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2136 dispatchDelayed(FuncRequest(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file())));
2141 return QApplication::event(e);
2146 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2149 return QApplication::notify(receiver, event);
2151 catch (ExceptionMessage const & e) {
2153 case ErrorException:
2155 setQuitOnLastWindowClosed(false);
2157 Alert::error(e.title_, e.details_);
2159 // Properly crash in debug mode in order to get a useful backtrace.
2162 // In release mode, try to exit gracefully.
2165 case BufferException: {
2166 if (!current_view_->documentBufferView())
2168 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2169 docstring details = e.details_ + '\n';
2170 details += buf->emergencyWrite();
2171 theBufferList().release(buf);
2172 details += "\n" + _("The current document was closed.");
2173 Alert::error(e.title_, details);
2176 case WarningException:
2177 Alert::warning(e.title_, e.details_);
2181 catch (exception const & e) {
2182 docstring s = _("LyX has caught an exception, it will now "
2183 "attempt to save all unsaved documents and exit."
2185 s += from_ascii(e.what());
2186 Alert::error(_("Software exception Detected"), s);
2190 docstring s = _("LyX has caught some really weird exception, it will "
2191 "now attempt to save all unsaved documents and exit.");
2192 Alert::error(_("Software exception Detected"), s);
2200 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2202 QColor const & qcol = d->color_cache_.get(col);
2203 if (!qcol.isValid()) {
2209 rgbcol.r = qcol.red();
2210 rgbcol.g = qcol.green();
2211 rgbcol.b = qcol.blue();
2216 string const GuiApplication::hexName(ColorCode col)
2218 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2222 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2224 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2225 d->socket_notifiers_[fd] = sn;
2226 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2230 void GuiApplication::socketDataReceived(int fd)
2232 d->socket_notifiers_[fd]->func_();
2236 void GuiApplication::unregisterSocketCallback(int fd)
2238 d->socket_notifiers_.take(fd)->setEnabled(false);
2242 void GuiApplication::commitData(QSessionManager & sm)
2244 /// The implementation is required to avoid an application exit
2245 /// when session state save is triggered by session manager.
2246 /// The default implementation sends a close event to all
2247 /// visible top level widgets when session managment allows
2249 /// We are changing that to close all wiew one by one.
2250 /// FIXME: verify if the default implementation is enough now.
2251 if (sm.allowsInteraction() && !closeAllViews())
2256 void GuiApplication::unregisterView(GuiView * gv)
2258 LASSERT(d->views_[gv->id()] == gv, /**/);
2259 d->views_.remove(gv->id());
2260 if (current_view_ == gv)
2265 bool GuiApplication::closeAllViews()
2267 if (d->views_.empty())
2270 // When a view/window was closed before without quitting LyX, there
2271 // are already entries in the lastOpened list.
2272 theSession().lastOpened().clear();
2274 QList<GuiView *> views = d->views_.values();
2275 foreach (GuiView * view, views) {
2276 if (!view->closeScheduled())
2285 GuiView & GuiApplication::view(int id) const
2287 LASSERT(d->views_.contains(id), /**/);
2288 return *d->views_.value(id);
2292 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2294 QList<GuiView *> views = d->views_.values();
2295 foreach (GuiView * view, views)
2296 view->hideDialog(name, inset);
2300 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2302 Buffer const * buffer_ = 0;
2303 QHash<int, GuiView *>::iterator end = d->views_.end();
2304 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2305 if (Buffer const * ptr = (*it)->updateInset(inset))
2312 bool GuiApplication::searchMenu(FuncRequest const & func,
2313 docstring_list & names) const
2315 return d->menus_.searchMenu(func, names);
2319 bool GuiApplication::readUIFile(QString const & name, bool include)
2321 LYXERR(Debug::INIT, "About to read " << name << "...");
2325 ui_path = libFileSearch("ui", name, "inc");
2326 if (ui_path.empty())
2327 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2329 ui_path = libFileSearch("ui", name, "ui");
2332 if (ui_path.empty()) {
2333 static const QString defaultUIFile = "default";
2334 LYXERR(Debug::INIT, "Could not find " << name);
2336 Alert::warning(_("Could not find UI definition file"),
2337 bformat(_("Error while reading the included file\n%1$s\n"
2338 "Please check your installation."), qstring_to_ucs4(name)));
2341 if (name == defaultUIFile) {
2342 LYXERR(Debug::INIT, "Could not find default UI file!!");
2343 Alert::warning(_("Could not find default UI file"),
2344 _("LyX could not find the default UI file!\n"
2345 "Please check your installation."));
2348 Alert::warning(_("Could not find UI definition file"),
2349 bformat(_("Error while reading the configuration file\n%1$s\n"
2350 "Falling back to default.\n"
2351 "Please look under Tools>Preferences>User Interface and\n"
2352 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2353 return readUIFile(defaultUIFile, false);
2356 // Ensure that a file is read only once (prevents include loops)
2357 static QStringList uifiles;
2358 QString const uifile = toqstr(ui_path.absFileName());
2359 if (uifiles.contains(uifile)) {
2361 // We are reading again the top uifile so reset the safeguard:
2364 d->toolbars_.reset();
2366 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2367 << "Is this an include loop?");
2371 uifiles.push_back(uifile);
2373 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2383 LexerKeyword uitags[] = {
2384 { "include", ui_include },
2385 { "menuset", ui_menuset },
2386 { "toolbars", ui_toolbars },
2387 { "toolbarset", ui_toolbarset }
2391 lex.setFile(ui_path);
2393 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2397 if (lyxerr.debugging(Debug::PARSER))
2398 lex.printTable(lyxerr);
2400 // store which ui files define Toolbars
2401 static QStringList toolbar_uifiles;
2403 while (lex.isOK()) {
2404 switch (lex.lex()) {
2407 QString const file = toqstr(lex.getString());
2408 if (!readUIFile(file, true))
2413 d->menus_.read(lex);
2417 d->toolbars_.readToolbars(lex);
2421 d->toolbars_.readToolbarSettings(lex);
2422 toolbar_uifiles.push_back(uifile);
2426 if (!rtrim(lex.getString()).empty())
2427 lex.printError("LyX::ReadUIFile: "
2428 "Unknown menu tag: `$$Token'");
2437 settings.beginGroup("ui_files");
2438 bool touched = false;
2439 for (int i = 0; i != uifiles.size(); ++i) {
2440 QFileInfo fi(uifiles[i]);
2441 QDateTime const date_value = fi.lastModified();
2442 QString const name_key = QString::number(i);
2443 // if an ui file which defines Toolbars has changed,
2444 // we have to reset the settings
2445 if (toolbar_uifiles.contains(uifiles[i])
2446 && (!settings.contains(name_key)
2447 || settings.value(name_key).toString() != uifiles[i]
2448 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2450 settings.setValue(name_key, uifiles[i]);
2451 settings.setValue(name_key + "/date", date_value);
2454 settings.endGroup();
2456 settings.remove("views");
2462 void GuiApplication::onLastWindowClosed()
2464 if (d->global_menubar_)
2465 d->global_menubar_->grabKeyboard();
2469 ////////////////////////////////////////////////////////////////////////
2471 // X11 specific stuff goes here...
2474 bool GuiApplication::x11EventFilter(XEvent * xev)
2479 switch (xev->type) {
2480 case SelectionRequest: {
2481 if (xev->xselectionrequest.selection != XA_PRIMARY)
2483 LYXERR(Debug::SELECTION, "X requested selection.");
2484 BufferView * bv = current_view_->currentBufferView();
2486 docstring const sel = bv->requestSelection();
2488 d->selection_.put(sel);
2492 case SelectionClear: {
2493 if (xev->xselectionclear.selection != XA_PRIMARY)
2495 LYXERR(Debug::SELECTION, "Lost selection.");
2496 BufferView * bv = current_view_->currentBufferView();
2498 bv->clearSelection();
2506 } // namespace frontend
2509 void hideDialogs(std::string const & name, Inset * inset)
2512 frontend::guiApp->hideDialogs(name, inset);
2516 ////////////////////////////////////////////////////////////////////
2520 ////////////////////////////////////////////////////////////////////
2522 frontend::FontLoader & theFontLoader()
2524 LASSERT(frontend::guiApp, /**/);
2525 return frontend::guiApp->fontLoader();
2529 frontend::FontMetrics const & theFontMetrics(Font const & f)
2531 return theFontMetrics(f.fontInfo());
2535 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2537 LASSERT(frontend::guiApp, /**/);
2538 return frontend::guiApp->fontLoader().metrics(f);
2542 ////////////////////////////////////////////////////////////////////
2546 ////////////////////////////////////////////////////////////////////
2548 frontend::Clipboard & theClipboard()
2550 LASSERT(frontend::guiApp, /**/);
2551 return frontend::guiApp->clipboard();
2555 frontend::Selection & theSelection()
2557 LASSERT(frontend::guiApp, /**/);
2558 return frontend::guiApp->selection();
2564 #include "moc_GuiApplication.cpp"