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 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
166 // I'd rather do that in the constructor, but I do not think that
167 // the palette is accessible there.
168 guiApp->colorCache().setPalette(guiApp->palette());
175 /// Return the list of loadable formats.
176 vector<string> loadableImageFormats()
180 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
182 LYXERR(Debug::GRAPHICS,
183 "\nThe image loader can load the following directly:\n");
185 if (qt_formats.empty())
186 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
188 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
190 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
192 string ext = ascii_lowercase((const char *) *it);
203 ////////////////////////////////////////////////////////////////////////
205 // Icon loading support code
207 ////////////////////////////////////////////////////////////////////////
217 bool operator<(PngMap const & lhs, PngMap const & rhs)
219 return lhs.key < rhs.key;
225 CompareKey(QString const & name) : name_(name) {}
226 bool operator()(PngMap const & other) const { return other.key == name_; }
232 // this must be sorted alphabetically
233 // Upper case comes before lower case
234 PngMap sorted_png_map[] = {
235 { "Bumpeq", "bumpeq2" },
238 { "Delta", "delta2" },
239 { "Diamond", "diamond2" },
240 { "Downarrow", "downarrow2" },
241 { "Gamma", "gamma2" },
242 { "Lambda", "lambda2" },
243 { "Leftarrow", "leftarrow2" },
244 { "Leftrightarrow", "leftrightarrow2" },
245 { "Longleftarrow", "longleftarrow2" },
246 { "Longleftrightarrow", "longleftrightarrow2" },
247 { "Longrightarrow", "longrightarrow2" },
248 { "Omega", "omega2" },
252 { "Rightarrow", "rightarrow2" },
253 { "Sigma", "sigma2" },
254 { "Subset", "subset2" },
255 { "Supset", "supset2" },
256 { "Theta", "theta2" },
257 { "Uparrow", "uparrow2" },
258 { "Updownarrow", "updownarrow2" },
259 { "Upsilon", "upsilon2" },
260 { "Vdash", "vdash3" },
263 { "nLeftarrow", "nleftarrow2" },
264 { "nLeftrightarrow", "nleftrightarrow2" },
265 { "nRightarrow", "nrightarrow2" },
266 { "nVDash", "nvdash3" },
267 { "nvDash", "nvdash2" },
268 { "textrm \\AA", "textrm_AA"},
269 { "textrm \\O", "textrm_O"},
270 { "vDash", "vdash2" },
271 { "varPhi", "varphi2" },
272 { "varPi", "varpi2" },
273 { "varSigma", "varsigma2" },
274 { "varTheta", "vartheta2" }
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 FileName fname = libFileSearch("images/" + path, name1, "png");
376 return toqstr(fname.absFileName());
378 fname = libFileSearch("images/" + path, name2, "png");
380 return toqstr(fname.absFileName());
382 path = ":/images/" + path;
385 LYXERR0("Directory " << path << " not found in resource!");
389 if (res.exists(name1))
393 if (res.exists(name2))
396 LYXERR(Debug::GUI, "Cannot find icon with filename "
397 << "\"" << name1 << "\""
399 << "\"" << name2 << "\""
401 << lyxaction.getActionName(f.action())
402 << '(' << to_utf8(f.argument()) << ")\"");
405 fname = libFileSearch(QString("images/"), "unknown", "png");
407 return toqstr(fname.absFileName());
408 return QString(":/images/unknown.png");
414 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
417 FileName fname = libFileSearch(path, name, ext);
418 QString path1 = toqstr(fname.absFileName());
419 QString path2 = ":/" + path + name + "." + ext;
421 if (pixmap.load(path1)) {
424 else if (pixmap.load(path2)) {
428 LYXERR0("Cannot load pixmap \""
429 << path << name << '.' << ext
430 << "\", please verify resource system!");
435 QIcon getIcon(FuncRequest const & f, bool unknown)
437 QString icon = iconName(f, unknown);
441 //LYXERR(Debug::GUI, "Found icon: " << icon);
443 if (!pm.load(icon)) {
444 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
452 ////////////////////////////////////////////////////////////////////////
454 // LyX server support code.
456 ////////////////////////////////////////////////////////////////////////
458 class SocketNotifier : public QSocketNotifier
461 /// connect a connection notification from the LyXServerSocket
462 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
463 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
467 /// The callback function
468 Application::SocketCallback func_;
472 ////////////////////////////////////////////////////////////////////////
474 // Mac specific stuff goes here...
476 ////////////////////////////////////////////////////////////////////////
478 class MenuTranslator : public QTranslator
481 MenuTranslator(QObject * parent)
482 : QTranslator(parent)
485 QString translate(const char * /*context*/,
486 const char * sourceText,
487 const char * /*comment*/ = 0)
489 string const s = sourceText;
490 if (s == N_("About %1") || s == N_("Preferences")
491 || s == N_("Reconfigure") || s == N_("Quit %1"))
498 class GlobalMenuBar : public QMenuBar
502 GlobalMenuBar() : QMenuBar(0) {}
505 bool event(QEvent * e)
507 if (e->type() == QEvent::ShortcutOverride) {
508 // && activeWindow() == 0) {
509 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
511 setKeySymbol(&sym, ke);
512 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
521 // QMacPasteboardMimeGraphics can only be compiled on Mac.
523 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
526 QMacPasteboardMimeGraphics()
527 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
530 QString convertorName() { return "Graphics"; }
532 QString flavorFor(QString const & mime)
534 LYXERR(Debug::ACTION, "flavorFor " << mime);
535 if (mime == pdfMimeType())
536 return QLatin1String("com.adobe.pdf");
540 QString mimeFor(QString flav)
542 LYXERR(Debug::ACTION, "mimeFor " << flav);
543 if (flav == QLatin1String("com.adobe.pdf"))
544 return pdfMimeType();
548 bool canConvert(QString const & mime, QString flav)
550 return mimeFor(flav) == mime;
553 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
557 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
561 QList<QByteArray> convertFromMime(QString const & /*mime*/,
562 QVariant data, QString /*flav*/)
564 QList<QByteArray> ret;
565 ret.append(data.toByteArray());
571 ///////////////////////////////////////////////////////////////
573 // You can find more platform specific stuff at the end of this file...
575 ///////////////////////////////////////////////////////////////
577 ////////////////////////////////////////////////////////////////////////
578 // Windows specific stuff goes here...
581 // QWindowsMimeMetafile can only be compiled on Windows.
583 static FORMATETC cfFromMime(QString const & mimetype)
586 if (mimetype == emfMimeType()) {
587 formatetc.cfFormat = CF_ENHMETAFILE;
588 formatetc.tymed = TYMED_ENHMF;
589 } else if (mimetype == wmfMimeType()) {
590 formatetc.cfFormat = CF_METAFILEPICT;
591 formatetc.tymed = TYMED_MFPICT;
594 formatetc.dwAspect = DVASPECT_CONTENT;
595 formatetc.lindex = -1;
600 class QWindowsMimeMetafile : public QWindowsMime {
602 QWindowsMimeMetafile() {}
604 bool canConvertFromMime(FORMATETC const & formatetc,
605 QMimeData const * mimedata) const
610 bool canConvertToMime(QString const & mimetype,
611 IDataObject * pDataObj) const
613 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
615 FORMATETC formatetc = cfFromMime(mimetype);
616 return pDataObj->QueryGetData(&formatetc) == S_OK;
619 bool convertFromMime(FORMATETC const & formatetc,
620 const QMimeData * mimedata, STGMEDIUM * pmedium) const
625 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
626 QVariant::Type preferredType) const
629 if (!canConvertToMime(mimetype, pDataObj))
632 FORMATETC formatetc = cfFromMime(mimetype);
634 if (pDataObj->GetData(&formatetc, &s) != S_OK)
638 if (s.tymed == TYMED_ENHMF) {
639 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
640 data.resize(dataSize);
641 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
642 (LPBYTE)data.data());
643 } else if (s.tymed == TYMED_MFPICT) {
644 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
645 data.resize(dataSize);
646 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
647 (LPBYTE)data.data());
650 ReleaseStgMedium(&s);
656 QVector<FORMATETC> formatsForMime(QString const & mimetype,
657 QMimeData const * mimedata) const
659 QVector<FORMATETC> formats;
660 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
661 formats += cfFromMime(mimetype);
665 QString mimeForFormat(FORMATETC const & formatetc) const
667 switch (formatetc.cfFormat) {
669 return emfMimeType();
670 case CF_METAFILEPICT:
671 return wmfMimeType();
679 ////////////////////////////////////////////////////////////////////////
680 // GuiApplication::Private definition and implementation.
681 ////////////////////////////////////////////////////////////////////////
683 struct GuiApplication::Private
685 Private(): language_model_(0), meta_fake_bit(NoModifier),
689 /// WMF Mime handler for Windows clipboard.
690 wmf_mime_ = new QWindowsMimeMetafile();
692 initKeySequences(&theTopLevelKeymap());
695 void initKeySequences(KeyMap * kb)
697 keyseq = KeySequence(kb, kb);
698 cancel_meta_seq = KeySequence(kb, kb);
702 QSortFilterProxyModel * language_model_;
704 GuiClipboard clipboard_;
706 GuiSelection selection_;
708 FontLoader font_loader_;
710 ColorCache color_cache_;
712 QTranslator qt_trans_;
714 QHash<int, SocketNotifier *> socket_notifiers_;
718 /// The global instance
721 /// this timer is used for any regular events one wants to
722 /// perform. at present it is used to check if forked processes
724 QTimer general_timer_;
726 /// delayed FuncRequests
727 std::queue<FuncRequest> func_request_queue_;
732 KeySequence cancel_meta_seq;
734 KeyModifier meta_fake_bit;
736 /// Multiple views container.
738 * Warning: This must not be a smart pointer as the destruction of the
739 * object is handled by Qt when the view is closed
740 * \sa Qt::WA_DeleteOnClose attribute.
742 QHash<int, GuiView *> views_;
744 /// Only used on mac.
745 GlobalMenuBar * global_menubar_;
748 /// Linkback mime handler for MacOSX.
749 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
753 /// WMF Mime handler for Windows clipboard.
754 QWindowsMimeMetafile * wmf_mime_;
759 GuiApplication * guiApp;
761 GuiApplication::~GuiApplication()
764 closeAllLinkBackLinks();
770 GuiApplication::GuiApplication(int & argc, char ** argv)
771 : QApplication(argc, argv), current_view_(0),
772 d(new GuiApplication::Private)
774 QString app_name = "LyX";
775 QCoreApplication::setOrganizationName(app_name);
776 QCoreApplication::setOrganizationDomain("lyx.org");
777 QCoreApplication::setApplicationName(lyx_package);
779 // Install translator for GUI elements.
780 installTranslator(&d->qt_trans_);
782 // FIXME: quitOnLastWindowClosed is true by default. We should have a
783 // lyxrc setting for this in order to let the application stay resident.
784 // But then we need some kind of dock icon, at least on Windows.
786 if (lyxrc.quit_on_last_window_closed)
787 setQuitOnLastWindowClosed(false);
790 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
791 // seems to be the default case for applications like LyX.
792 setQuitOnLastWindowClosed(false);
793 // This allows to translate the strings that appear in the LyX menu.
794 /// A translator suitable for the entries in the LyX menu.
795 /// Only needed with Qt/Mac.
796 installTranslator(new MenuTranslator(this));
800 // doubleClickInterval() is 400 ms on X11 which is just too long.
801 // On Windows and Mac OS X, the operating system's value is used.
802 // On Microsoft Windows, calling this function sets the double
803 // click interval for all applications. So we don't!
804 QApplication::setDoubleClickInterval(300);
807 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
809 // needs to be done before reading lyxrc
811 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
815 // Set the cache to 5120 kilobytes which corresponds to screen size of
816 // 1280 by 1024 pixels with a color depth of 32 bits.
817 QPixmapCache::setCacheLimit(5120);
819 // Initialize RC Fonts
820 if (lyxrc.roman_font_name.empty())
821 lyxrc.roman_font_name = fromqstr(romanFontName());
823 if (lyxrc.sans_font_name.empty())
824 lyxrc.sans_font_name = fromqstr(sansFontName());
826 if (lyxrc.typewriter_font_name.empty())
827 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
829 d->general_timer_.setInterval(500);
830 connect(&d->general_timer_, SIGNAL(timeout()),
831 this, SLOT(handleRegularEvents()));
832 d->general_timer_.start();
834 #if QT_VERSION >= 0x040400
835 // maxThreadCount() defaults in general to 2 on single or dual-processor.
836 // This is clearly not enough in a time where we use threads for
837 // document preview and/or export. 20 should be OK.
838 QThreadPool::globalInstance()->setMaxThreadCount(20);
843 GuiApplication * theGuiApp()
845 return dynamic_cast<GuiApplication *>(theApp());
849 void GuiApplication::clearSession()
856 docstring GuiApplication::iconName(FuncRequest const & f, bool unknown)
858 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
862 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
867 BufferView * doc_bv = 0;
869 if (cmd.action() == LFUN_NOACTION) {
870 status.message(from_utf8(N_("Nothing to do")));
871 status.setEnabled(false);
874 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
875 status.setUnknown(true);
876 status.message(from_utf8(N_("Unknown action")));
877 status.setEnabled(false);
880 // Does the GuiApplication know something?
881 else if (getStatus(cmd, status)) { }
883 // If we do not have a GuiView, then other functions are disabled
884 else if (!current_view_)
885 status.setEnabled(false);
887 // Does the GuiView know something?
888 else if (current_view_->getStatus(cmd, status)) { }
890 // In LyX/Mac, when a dialog is open, the menus of the
891 // application can still be accessed without giving focus to
892 // the main window. In this case, we want to disable the menu
893 // entries that are buffer or view-related.
894 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
896 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
897 status.setEnabled(false);
900 // If we do not have a BufferView, then other functions are disabled
901 else if (!(bv = current_view_->currentBufferView()))
902 status.setEnabled(false);
904 // Does the current BufferView know something?
905 else if (bv->getStatus(cmd, status)) { }
907 // Does the current Buffer know something?
908 else if (bv->buffer().getStatus(cmd, status)) { }
910 // If we do not have a document BufferView, different from the
911 // current BufferView, then other functions are disabled
912 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
913 status.setEnabled(false);
915 // Does the document Buffer know something?
916 else if (doc_bv->buffer().getStatus(cmd, status)) { }
919 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
920 status.message(from_utf8(N_("Command not handled")));
921 status.setEnabled(false);
924 // the default error message if we disable the command
925 if (!status.enabled() && status.message().empty())
926 status.message(from_utf8(N_("Command disabled")));
932 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
934 // I would really like to avoid having this switch and rather try to
935 // encode this in the function itself.
936 // -- And I'd rather let an inset decide which LFUNs it is willing
937 // to handle (Andre')
939 switch (cmd.action()) {
941 // This could be used for the no-GUI version. The GUI version is handled in
942 // GuiView::getStatus(). See above.
944 case LFUN_BUFFER_WRITE:
945 case LFUN_BUFFER_WRITE_AS: {
946 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
947 enable = b && (b->isUnnamed() || !b->isClean());
952 case LFUN_BOOKMARK_GOTO: {
953 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
954 enable = theSession().bookmarks().isValid(num);
958 case LFUN_BOOKMARK_CLEAR:
959 enable = theSession().bookmarks().hasValid();
962 // this one is difficult to get right. As a half-baked
963 // solution, we consider only the first action of the sequence
964 case LFUN_COMMAND_SEQUENCE: {
965 // argument contains ';'-terminated commands
966 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
967 FuncRequest func(lyxaction.lookupFunc(firstcmd));
968 func.setOrigin(cmd.origin());
969 flag = getStatus(func);
973 // we want to check if at least one of these is enabled
974 case LFUN_COMMAND_ALTERNATIVES: {
975 // argument contains ';'-terminated commands
976 string arg = to_utf8(cmd.argument());
977 while (!arg.empty()) {
979 arg = split(arg, first, ';');
980 FuncRequest func(lyxaction.lookupFunc(first));
981 func.setOrigin(cmd.origin());
982 flag = getStatus(func);
983 // if this one is enabled, the whole thing is
992 string name = to_utf8(cmd.argument());
993 if (theTopLevelCmdDef().lock(name, func)) {
994 func.setOrigin(cmd.origin());
995 flag = getStatus(func);
996 theTopLevelCmdDef().release(name);
998 // catch recursion or unknown command
999 // definition. all operations until the
1000 // recursion or unknown command definition
1001 // occurs are performed, so set the state to
1008 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1010 case LFUN_PREFERENCES_SAVE:
1011 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1012 case LFUN_DEBUG_LEVEL_SET:
1013 // these are handled in our dispatch()
1016 case LFUN_WINDOW_CLOSE:
1017 enable = d->views_.size() > 0;
1020 case LFUN_BUFFER_NEW:
1021 case LFUN_BUFFER_NEW_TEMPLATE:
1022 case LFUN_FILE_OPEN:
1023 case LFUN_HELP_OPEN:
1024 case LFUN_SCREEN_FONT_UPDATE:
1025 case LFUN_SET_COLOR:
1026 case LFUN_WINDOW_NEW:
1028 case LFUN_LYXRC_APPLY:
1029 case LFUN_COMMAND_PREFIX:
1031 case LFUN_META_PREFIX:
1032 case LFUN_RECONFIGURE:
1033 case LFUN_SERVER_GET_FILENAME:
1034 case LFUN_SERVER_NOTIFY:
1043 flag.setEnabled(false);
1047 /// make a post-dispatch status message
1048 static docstring makeDispatchMessage(docstring const & msg,
1049 FuncRequest const & cmd)
1051 const bool verbose = (cmd.origin() == FuncRequest::MENU
1052 || cmd.origin() == FuncRequest::TOOLBAR
1053 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1055 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1056 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1060 docstring dispatch_msg = msg;
1061 if (!dispatch_msg.empty())
1062 dispatch_msg += ' ';
1064 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1066 bool argsadded = false;
1068 if (!cmd.argument().empty()) {
1069 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1070 comname += ' ' + cmd.argument();
1074 docstring const shortcuts = theTopLevelKeymap().
1075 printBindings(cmd, KeySequence::ForGui);
1077 if (!shortcuts.empty())
1078 comname += ": " + shortcuts;
1079 else if (!argsadded && !cmd.argument().empty())
1080 comname += ' ' + cmd.argument();
1082 if (!comname.empty()) {
1083 comname = rtrim(comname);
1084 dispatch_msg += '(' + rtrim(comname) + ')';
1086 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1087 return dispatch_msg;
1091 void GuiApplication::dispatch(FuncRequest const & cmd)
1093 if (current_view_ && current_view_->currentBufferView())
1094 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1097 // redraw the screen at the end (first of the two drawing steps).
1098 // This is done unless explicitly requested otherwise
1099 dr.screenUpdate(Update::FitCursor);
1105 BufferView * bv = current_view_->currentBufferView();
1107 Cursor & cursor = bv->cursor();
1108 Buffer & buf = bv->buffer();
1111 // This check out to be done somewhere else. It got moved here
1112 // from TextMetrics.cpp, where it definitely didn't need to be.
1113 // Actually, this test ought not to be done at all, since the
1114 // whole InsetBibitem business is a mess. But that is a different
1116 if (cursor.inTexted()) {
1117 int const moveCursor = cursor.paragraph().checkBiblio(buf);
1119 cursor.posForward();
1120 else if (moveCursor < 0 && cursor.pos() >= -moveCursor)
1121 cursor.posBackward();
1123 if (moveCursor != 0 || dr.needBufferUpdate()) {
1124 cursor.clearBufferUpdate();
1128 // BufferView::update() updates the ViewMetricsInfo and
1129 // also initializes the position cache for all insets in
1130 // (at least partially) visible top-level paragraphs.
1131 // We will redraw the screen only if needed.
1132 bv->processUpdateFlags(dr.screenUpdate());
1134 // Do we have a selection?
1135 theSelection().haveSelection(bv->cursor().selection());
1138 current_view_->restartCursor();
1140 if (dr.needMessageUpdate()) {
1141 // Some messages may already be translated, so we cannot use _()
1142 current_view_->message(makeDispatchMessage(
1143 translateIfPossible(dr.message()), cmd));
1148 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1149 bool switchToBuffer)
1151 if (!theSession().bookmarks().isValid(idx))
1153 BookmarksSection::Bookmark const & bm =
1154 theSession().bookmarks().bookmark(idx);
1155 LASSERT(!bm.filename.empty(), /**/);
1156 string const file = bm.filename.absFileName();
1157 // if the file is not opened, open it.
1158 if (!theBufferList().exists(bm.filename)) {
1160 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1164 // open may fail, so we need to test it again
1165 if (!theBufferList().exists(bm.filename))
1168 // bm can be changed when saving
1169 BookmarksSection::Bookmark tmp = bm;
1171 // Special case idx == 0 used for back-from-back jump navigation
1173 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1175 // if the current buffer is not that one, switch to it.
1176 BufferView * doc_bv = current_view_->documentBufferView();
1177 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1178 if (switchToBuffer) {
1179 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1180 doc_bv = current_view_->documentBufferView();
1185 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1186 if (!doc_bv->moveToPosition(
1187 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1194 // Cursor jump succeeded!
1195 Cursor const & cur = doc_bv->cursor();
1196 pit_type new_pit = cur.pit();
1197 pos_type new_pos = cur.pos();
1198 int new_id = cur.paragraph().id();
1200 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1201 // see http://www.lyx.org/trac/ticket/3092
1202 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1203 || bm.top_id != new_id) {
1204 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1205 new_pit, new_pos, new_id);
1209 // This function runs "configure" and then rereads lyx.defaults to
1210 // reconfigure the automatic settings.
1211 void GuiApplication::reconfigure(string const & option)
1213 // emit message signal.
1215 current_view_->message(_("Running configure..."));
1217 // Run configure in user lyx directory
1218 PathChanger p(package().user_support());
1219 string configure_command = package().configure_command();
1220 configure_command += option;
1222 int ret = one.startscript(Systemcall::Wait, configure_command);
1224 // emit message signal.
1226 current_view_->message(_("Reloading configuration..."));
1227 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"));
1228 // Re-read packages.lst
1229 LaTeXFeatures::getAvailable();
1232 Alert::information(_("System reconfiguration failed"),
1233 _("The system reconfiguration has failed.\n"
1234 "Default textclass is used but LyX may "
1235 "not be able to work properly.\n"
1236 "Please reconfigure again if needed."));
1238 Alert::information(_("System reconfigured"),
1239 _("The system has been reconfigured.\n"
1240 "You need to restart LyX to make use of any\n"
1241 "updated document class specifications."));
1245 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1247 string const argument = to_utf8(cmd.argument());
1248 FuncCode const action = cmd.action();
1250 LYXERR(Debug::ACTION, "cmd: " << cmd);
1252 // we have not done anything wrong yet.
1255 FuncStatus const flag = getStatus(cmd);
1256 if (!flag.enabled()) {
1257 // We cannot use this function here
1258 LYXERR(Debug::ACTION, "action "
1259 << lyxaction.getActionName(action)
1260 << " [" << action << "] is disabled at this location");
1262 current_view_->restartCursor();
1263 dr.setMessage(flag.message());
1265 dr.dispatched(false);
1266 dr.screenUpdate(Update::None);
1267 dr.clearBufferUpdate();
1271 // Assumes that the action will be dispatched.
1272 dr.dispatched(true);
1274 switch (cmd.action()) {
1276 case LFUN_WINDOW_NEW:
1277 createView(toqstr(cmd.argument()));
1280 case LFUN_WINDOW_CLOSE:
1281 // update bookmark pit of the current buffer before window close
1282 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1283 gotoBookmark(i+1, false, false);
1284 // clear the last opened list, because
1285 // maybe this will end the session
1286 theSession().lastOpened().clear();
1287 current_view_->closeScheduled();
1291 // quitting is triggered by the gui code
1292 // (leaving the event loop).
1294 current_view_->message(from_utf8(N_("Exiting.")));
1295 if (closeAllViews())
1299 case LFUN_SCREEN_FONT_UPDATE: {
1300 // handle the screen font changes.
1301 d->font_loader_.update();
1302 // Backup current_view_
1303 GuiView * view = current_view_;
1304 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1305 // to skip the refresh.
1307 theBufferList().changed(false);
1308 // Restore current_view_
1309 current_view_ = view;
1313 case LFUN_BUFFER_NEW:
1314 if (d->views_.empty()
1315 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1316 createView(QString(), false); // keep hidden
1317 current_view_->newDocument(to_utf8(cmd.argument()), false);
1318 current_view_->show();
1319 setActiveWindow(current_view_);
1321 current_view_->newDocument(to_utf8(cmd.argument()), false);
1325 case LFUN_BUFFER_NEW_TEMPLATE:
1326 if (d->views_.empty()
1327 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1329 current_view_->newDocument(to_utf8(cmd.argument()), true);
1330 if (!current_view_->documentBufferView())
1331 current_view_->close();
1333 current_view_->newDocument(to_utf8(cmd.argument()), true);
1337 case LFUN_FILE_OPEN: {
1338 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1339 string const fname = to_utf8(cmd.argument());
1340 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1341 && current_view_->documentBufferView() != 0)) {
1342 // We want the ui session to be saved per document and not per
1343 // window number. The filename crc is a good enough identifier.
1344 boost::crc_32_type crc;
1345 crc = for_each(fname.begin(), fname.end(), crc);
1346 createView(crc.checksum());
1347 current_view_->openDocument(fname);
1348 if (current_view_ && !current_view_->documentBufferView())
1349 current_view_->close();
1351 current_view_->openDocument(fname);
1355 case LFUN_HELP_OPEN: {
1356 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1357 if (current_view_ == 0)
1359 string const arg = to_utf8(cmd.argument());
1361 current_view_->message(_("Missing argument"));
1364 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1366 fname = i18nLibFileSearch("examples", arg, "lyx");
1368 if (fname.empty()) {
1369 lyxerr << "LyX: unable to find documentation file `"
1370 << arg << "'. Bad installation?" << endl;
1373 current_view_->message(bformat(_("Opening help file %1$s..."),
1374 makeDisplayPath(fname.absFileName())));
1375 Buffer * buf = current_view_->loadDocument(fname, false);
1377 #ifndef DEVEL_VERSION
1379 buf->setReadonly(true);
1386 case LFUN_SET_COLOR: {
1388 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1389 if (lyx_name.empty() || x11_name.empty()) {
1391 current_view_->message(
1392 _("Syntax: set-color <lyx_name> <x11_name>"));
1396 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1397 bool const graphicsbg_changed =
1398 lyx_name == graphicsbg && x11_name != graphicsbg;
1399 if (graphicsbg_changed) {
1400 // FIXME: The graphics cache no longer has a changeDisplay method.
1402 graphics::GCache::get().changeDisplay(true);
1406 if (!lcolor.setColor(lyx_name, x11_name)) {
1407 current_view_->message(
1408 bformat(_("Set-color \"%1$s\" failed "
1409 "- color is undefined or "
1410 "may not be redefined"),
1411 from_utf8(lyx_name)));
1414 // Make sure we don't keep old colors in cache.
1415 d->color_cache_.clear();
1419 case LFUN_LYXRC_APPLY: {
1420 // reset active key sequences, since the bindings
1421 // are updated (bug 6064)
1423 LyXRC const lyxrc_orig = lyxrc;
1425 istringstream ss(to_utf8(cmd.argument()));
1426 bool const success = lyxrc.read(ss) == 0;
1429 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1430 << "Unable to read lyxrc data"
1435 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1442 case LFUN_COMMAND_PREFIX:
1443 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1448 d->meta_fake_bit = NoModifier;
1449 GuiView * gv = currentView();
1450 if (gv && gv->currentBufferView())
1451 // cancel any selection
1452 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1453 dr.setMessage(from_ascii(N_("Cancel")));
1456 case LFUN_META_PREFIX:
1457 d->meta_fake_bit = AltModifier;
1458 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1461 // --- Menus -----------------------------------------------
1462 case LFUN_RECONFIGURE:
1463 // argument is any additional parameter to the configure.py command
1464 reconfigure(to_utf8(cmd.argument()));
1467 // --- lyxserver commands ----------------------------
1468 case LFUN_SERVER_GET_FILENAME: {
1469 LASSERT(current_view_ && current_view_->documentBufferView(), return);
1470 docstring const fname = from_utf8(
1471 current_view_->documentBufferView()->buffer().absFileName());
1472 dr.setMessage(fname);
1473 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1476 case LFUN_SERVER_NOTIFY: {
1477 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1478 dr.setMessage(dispatch_buffer);
1479 theServer().notifyClient(to_utf8(dispatch_buffer));
1483 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1484 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1490 string rest = split(argument, countstr, ' ');
1491 istringstream is(countstr);
1494 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1495 for (int i = 0; i < count; ++i)
1496 dispatch(lyxaction.lookupFunc(rest));
1500 case LFUN_COMMAND_SEQUENCE: {
1501 // argument contains ';'-terminated commands
1502 string arg = argument;
1503 // FIXME: this LFUN should also work without any view.
1504 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1505 ? &(current_view_->documentBufferView()->buffer()) : 0;
1507 buffer->undo().beginUndoGroup();
1508 while (!arg.empty()) {
1510 arg = split(arg, first, ';');
1511 FuncRequest func(lyxaction.lookupFunc(first));
1512 func.setOrigin(cmd.origin());
1515 // the buffer may have been closed by one action
1516 if (theBufferList().isLoaded(buffer))
1517 buffer->undo().endUndoGroup();
1521 case LFUN_COMMAND_ALTERNATIVES: {
1522 // argument contains ';'-terminated commands
1523 string arg = argument;
1524 while (!arg.empty()) {
1526 arg = split(arg, first, ';');
1527 FuncRequest func(lyxaction.lookupFunc(first));
1528 func.setOrigin(cmd.origin());
1529 FuncStatus const stat = getStatus(func);
1530 if (stat.enabled()) {
1540 if (theTopLevelCmdDef().lock(argument, func)) {
1541 func.setOrigin(cmd.origin());
1543 theTopLevelCmdDef().release(argument);
1545 if (func.action() == LFUN_UNKNOWN_ACTION) {
1546 // unknown command definition
1547 lyxerr << "Warning: unknown command definition `"
1551 // recursion detected
1552 lyxerr << "Warning: Recursion in the command definition `"
1553 << argument << "' detected"
1560 case LFUN_PREFERENCES_SAVE:
1561 lyxrc.write(support::makeAbsPath("preferences",
1562 package().user_support().absFileName()), false);
1565 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1566 string const fname = addName(addPath(package().user_support().absFileName(),
1567 "templates/"), "defaults.lyx");
1568 Buffer defaults(fname);
1570 istringstream ss(argument);
1573 int const unknown_tokens = defaults.readHeader(lex);
1575 if (unknown_tokens != 0) {
1576 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1577 << unknown_tokens << " unknown token"
1578 << (unknown_tokens == 1 ? "" : "s")
1582 if (defaults.writeFile(FileName(defaults.absFileName())))
1583 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1584 makeDisplayPath(fname)));
1587 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1592 case LFUN_BOOKMARK_GOTO:
1593 // go to bookmark, open unopened file and switch to buffer if necessary
1594 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1595 dr.screenUpdate(Update::Force | Update::FitCursor);
1598 case LFUN_BOOKMARK_CLEAR:
1599 theSession().bookmarks().clear();
1602 case LFUN_DEBUG_LEVEL_SET:
1603 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1607 // Everything below is only for active window
1608 if (current_view_ == 0)
1611 // Let the current GuiView dispatch its own actions.
1612 current_view_->dispatch(cmd, dr);
1614 if (dr.dispatched())
1617 BufferView * bv = current_view_->currentBufferView();
1620 // Let the current BufferView dispatch its own actions.
1621 bv->dispatch(cmd, dr);
1622 if (dr.dispatched())
1625 BufferView * doc_bv = current_view_->documentBufferView();
1626 // Try with the document BufferView dispatch if any.
1628 doc_bv->dispatch(cmd, dr);
1629 if (dr.dispatched())
1633 // OK, so try the current Buffer itself...
1634 bv->buffer().dispatch(cmd, dr);
1635 if (dr.dispatched())
1638 // and with the document Buffer.
1640 doc_bv->buffer().dispatch(cmd, dr);
1641 if (dr.dispatched())
1645 // Let the current Cursor dispatch its own actions.
1646 Cursor old = bv->cursor();
1647 bv->cursor().dispatch(cmd);
1649 // notify insets we just left
1650 // FIXME: move this code to Cursor::dispatch
1651 if (bv->cursor() != old) {
1652 old.beginUndoGroup();
1654 bool badcursor = notifyCursorLeavesOrEnters(old, bv->cursor());
1656 bv->cursor().fixIfBroken();
1657 bv->fixInlineCompletionPos();
1662 // update completion. We do it here and not in
1663 // processKeySym to avoid another redraw just for a
1664 // changed inline completion
1665 if (cmd.origin() == FuncRequest::KEYBOARD) {
1666 if (cmd.action() == LFUN_SELF_INSERT
1667 || (cmd.action() == LFUN_ERT_INSERT && bv->cursor().inMathed()))
1668 current_view_->updateCompletion(bv->cursor(), true, true);
1669 else if (cmd.action() == LFUN_CHAR_DELETE_BACKWARD)
1670 current_view_->updateCompletion(bv->cursor(), false, true);
1672 current_view_->updateCompletion(bv->cursor(), false, false);
1675 dr = bv->cursor().result();
1678 // if we executed a mutating lfun, mark the buffer as dirty
1679 Buffer * doc_buffer = (current_view_ && current_view_->documentBufferView())
1680 ? &(current_view_->documentBufferView()->buffer()) : 0;
1681 if (doc_buffer && theBufferList().isLoaded(doc_buffer)
1683 && !lyxaction.funcHasFlag(action, LyXAction::NoBuffer)
1684 && !lyxaction.funcHasFlag(action, LyXAction::ReadOnly))
1685 current_view_->currentBufferView()->buffer().markDirty();
1689 docstring GuiApplication::viewStatusMessage()
1691 // When meta-fake key is pressed, show the key sequence so far + "M-".
1692 if (d->meta_fake_bit != NoModifier)
1693 return d->keyseq.print(KeySequence::ForGui) + "M-";
1695 // Else, when a non-complete key sequence is pressed,
1696 // show the available options.
1697 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1698 return d->keyseq.printOptions(true);
1704 void GuiApplication::handleKeyFunc(FuncCode action)
1708 if (d->keyseq.length())
1710 GuiView * gv = currentView();
1711 LASSERT(gv && gv->currentBufferView(), return);
1712 BufferView * bv = gv->currentBufferView();
1713 bv->getIntl().getTransManager().deadkey(
1714 c, get_accent(action).accent, bv->cursor().innerText(),
1716 // Need to clear, in case the minibuffer calls these
1719 // copied verbatim from do_accent_char
1720 bv->cursor().resetAnchor();
1724 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1726 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1728 // Do nothing if we have nothing (JMarc)
1729 if (!keysym.isOK()) {
1730 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1732 current_view_->restartCursor();
1736 if (keysym.isModifier()) {
1737 LYXERR(Debug::KEY, "isModifier true");
1739 current_view_->restartCursor();
1743 char_type encoded_last_key = keysym.getUCSEncoded();
1745 // Do a one-deep top-level lookup for
1746 // cancel and meta-fake keys. RVDK_PATCH_5
1747 d->cancel_meta_seq.reset();
1749 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1750 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1752 // When not cancel or meta-fake, do the normal lookup.
1753 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1754 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1755 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1756 // remove Caps Lock and Mod2 as a modifiers
1757 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1758 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1761 // Dont remove this unless you know what you are doing.
1762 d->meta_fake_bit = NoModifier;
1764 // Can this happen now ?
1765 if (func.action() == LFUN_NOACTION)
1766 func = FuncRequest(LFUN_COMMAND_PREFIX);
1768 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1769 << d->keyseq.print(KeySequence::Portable) << ']');
1771 // already here we know if it any point in going further
1772 // why not return already here if action == -1 and
1773 // num_bytes == 0? (Lgb)
1775 if (d->keyseq.length() > 1 && current_view_)
1776 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1779 // Maybe user can only reach the key via holding down shift.
1780 // Let's see. But only if shift is the only modifier
1781 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1782 LYXERR(Debug::KEY, "Trying without shift");
1783 func = d->keyseq.addkey(keysym, NoModifier);
1784 LYXERR(Debug::KEY, "Action now " << func.action());
1787 if (func.action() == LFUN_UNKNOWN_ACTION) {
1788 // Hmm, we didn't match any of the keysequences. See
1789 // if it's normal insertable text not already covered
1791 if (keysym.isText() && d->keyseq.length() == 1) {
1792 LYXERR(Debug::KEY, "isText() is true, inserting.");
1793 func = FuncRequest(LFUN_SELF_INSERT,
1794 FuncRequest::KEYBOARD);
1796 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1797 if (current_view_) {
1798 current_view_->message(_("Unknown function."));
1799 current_view_->restartCursor();
1805 if (func.action() == LFUN_SELF_INSERT) {
1806 if (encoded_last_key != 0) {
1807 docstring const arg(1, encoded_last_key);
1808 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1809 FuncRequest::KEYBOARD));
1810 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1813 processFuncRequest(func);
1817 void GuiApplication::processFuncRequest(FuncRequest const & func)
1819 lyx::dispatch(func);
1823 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1825 addToFuncRequestQueue(func);
1826 processFuncRequestQueueAsync();
1830 void GuiApplication::processFuncRequestQueue()
1832 while (!d->func_request_queue_.empty()) {
1833 processFuncRequest(d->func_request_queue_.front());
1834 d->func_request_queue_.pop();
1839 void GuiApplication::processFuncRequestQueueAsync()
1841 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1845 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1847 d->func_request_queue_.push(func);
1851 void GuiApplication::resetGui()
1853 // Set the language defined by the user.
1857 if (!readUIFile(toqstr(lyxrc.ui_file)))
1858 // Gives some error box here.
1861 if (d->global_menubar_)
1862 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1864 QHash<int, GuiView *>::iterator it;
1865 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1868 gv->setLayoutDirection(layoutDirection());
1872 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1876 void GuiApplication::createView(int view_id)
1878 createView(QString(), true, view_id);
1882 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1885 // release the keyboard which might have been grabed by the global
1886 // menubar on Mac to catch shortcuts even without any GuiView.
1887 if (d->global_menubar_)
1888 d->global_menubar_->releaseKeyboard();
1892 while (d->views_.find(id) != d->views_.end())
1895 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1896 GuiView * view = new GuiView(id);
1898 d->views_[id] = view;
1902 setActiveWindow(view);
1905 if (!geometry_arg.isEmpty()) {
1909 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1910 re.indexIn(geometry_arg);
1911 w = re.cap(1).toInt();
1912 h = re.cap(2).toInt();
1913 x = re.cap(3).toInt();
1914 y = re.cap(4).toInt();
1915 view->setGeometry(x, y, w, h);
1922 Clipboard & GuiApplication::clipboard()
1924 return d->clipboard_;
1928 Selection & GuiApplication::selection()
1930 return d->selection_;
1934 FontLoader & GuiApplication::fontLoader()
1936 return d->font_loader_;
1940 Toolbars const & GuiApplication::toolbars() const
1942 return d->toolbars_;
1946 Toolbars & GuiApplication::toolbars()
1948 return d->toolbars_;
1952 Menus const & GuiApplication::menus() const
1958 Menus & GuiApplication::menus()
1964 QList<int> GuiApplication::viewIds() const
1966 return d->views_.keys();
1970 ColorCache & GuiApplication::colorCache()
1972 return d->color_cache_;
1976 int GuiApplication::exec()
1978 // asynchronously handle batch commands. This event will be in
1979 // the event queue in front of other asynchronous events. Hence,
1980 // we can assume in the latter that the gui is setup already.
1981 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1983 return QApplication::exec();
1987 void GuiApplication::exit(int status)
1989 QApplication::exit(status);
1993 void GuiApplication::setGuiLanguage()
1995 // Set the language defined by the user.
1998 QString const default_language = toqstr(Messages::defaultLanguage());
1999 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2000 QLocale const default_locale(default_language);
2001 QLocale::setDefault(default_locale);
2003 // install translation file for Qt built-in dialogs
2004 QString const language_name = QString("qt_") + default_locale.name();
2006 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2007 // Short-named translator can be loaded from a long name, but not the
2008 // opposite. Therefore, long name should be used without truncation.
2009 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2010 if (!d->qt_trans_.load(language_name,
2011 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2012 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2015 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2019 switch (default_locale.language()) {
2020 case QLocale::Arabic :
2021 case QLocale::Hebrew :
2022 case QLocale::Persian :
2023 case QLocale::Urdu :
2024 setLayoutDirection(Qt::RightToLeft);
2027 setLayoutDirection(Qt::LeftToRight);
2032 void GuiApplication::execBatchCommands()
2037 if (!readUIFile(toqstr(lyxrc.ui_file)))
2038 // Gives some error box here.
2042 #if QT_VERSION > 0x040600
2043 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2045 // Create the global default menubar which is shown for the dialogs
2046 // and if no GuiView is visible.
2047 // This must be done after the session was recovered to know the "last files".
2048 d->global_menubar_ = new GlobalMenuBar();
2049 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2052 lyx::execBatchCommands();
2056 QAbstractItemModel * GuiApplication::languageModel()
2058 if (d->language_model_)
2059 return d->language_model_;
2061 QStandardItemModel * lang_model = new QStandardItemModel(this);
2062 lang_model->insertColumns(0, 3);
2064 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2065 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2066 Languages::const_iterator it = lyx::languages.begin();
2067 Languages::const_iterator end = lyx::languages.end();
2068 for (; it != end; ++it) {
2069 current_row = lang_model->rowCount();
2070 lang_model->insertRows(current_row, 1);
2071 QModelIndex pl_item = lang_model->index(current_row, 0);
2072 QModelIndex sp_item = lang_model->index(current_row, 1);
2073 QModelIndex th_item = lang_model->index(current_row, 2);
2074 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2075 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2076 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2077 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2078 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2079 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2080 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2081 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2082 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2083 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2085 d->language_model_ = new QSortFilterProxyModel(this);
2086 d->language_model_->setSourceModel(lang_model);
2087 #if QT_VERSION >= 0x040300
2088 d->language_model_->setSortLocaleAware(true);
2090 return d->language_model_;
2094 void GuiApplication::restoreGuiSession()
2096 if (!lyxrc.load_session)
2099 Session & session = theSession();
2100 LastOpenedSection::LastOpened const & lastopened =
2101 session.lastOpened().getfiles();
2103 FileName active_file;
2104 // do not add to the lastfile list since these files are restored from
2105 // last session, and should be already there (regular files), or should
2106 // not be added at all (help files).
2107 for (size_t i = 0; i < lastopened.size(); ++i) {
2108 FileName const & file_name = lastopened[i].file_name;
2109 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2110 && current_view_->documentBufferView() != 0)) {
2111 boost::crc_32_type crc;
2112 string const & fname = file_name.absFileName();
2113 crc = for_each(fname.begin(), fname.end(), crc);
2114 createView(crc.checksum());
2116 current_view_->loadDocument(file_name, false);
2118 if (lastopened[i].active)
2119 active_file = file_name;
2122 // Restore last active buffer
2123 Buffer * buffer = theBufferList().getBuffer(active_file);
2125 current_view_->setBuffer(buffer);
2127 // clear this list to save a few bytes of RAM
2128 session.lastOpened().clear();
2132 QString const GuiApplication::romanFontName()
2135 font.setKerning(false);
2136 font.setStyleHint(QFont::Serif);
2137 font.setFamily("serif");
2139 return QFontInfo(font).family();
2143 QString const GuiApplication::sansFontName()
2146 font.setKerning(false);
2147 font.setStyleHint(QFont::SansSerif);
2148 font.setFamily("sans");
2150 return QFontInfo(font).family();
2154 QString const GuiApplication::typewriterFontName()
2157 font.setKerning(false);
2158 font.setStyleHint(QFont::TypeWriter);
2159 font.setFamily("monospace");
2161 return QFontInfo(font).family();
2165 void GuiApplication::handleRegularEvents()
2167 ForkedCallsController::handleCompletedProcesses();
2171 bool GuiApplication::event(QEvent * e)
2174 case QEvent::FileOpen: {
2175 // Open a file; this happens only on Mac OS X for now.
2177 // We do this asynchronously because on startup the batch
2178 // commands are not executed here yet and the gui is not ready
2180 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2181 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2182 processFuncRequestAsync(fr);
2187 return QApplication::event(e);
2192 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2195 return QApplication::notify(receiver, event);
2197 catch (ExceptionMessage const & e) {
2199 case ErrorException:
2201 setQuitOnLastWindowClosed(false);
2203 Alert::error(e.title_, e.details_);
2205 // Properly crash in debug mode in order to get a useful backtrace.
2208 // In release mode, try to exit gracefully.
2211 case BufferException: {
2212 if (!current_view_->documentBufferView())
2214 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2215 docstring details = e.details_ + '\n';
2216 details += buf->emergencyWrite();
2217 theBufferList().release(buf);
2218 details += "\n" + _("The current document was closed.");
2219 Alert::error(e.title_, details);
2222 case WarningException:
2223 Alert::warning(e.title_, e.details_);
2227 catch (exception const & e) {
2228 docstring s = _("LyX has caught an exception, it will now "
2229 "attempt to save all unsaved documents and exit."
2231 s += from_ascii(e.what());
2232 Alert::error(_("Software exception Detected"), s);
2236 docstring s = _("LyX has caught some really weird exception, it will "
2237 "now attempt to save all unsaved documents and exit.");
2238 Alert::error(_("Software exception Detected"), s);
2246 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2248 QColor const & qcol = d->color_cache_.get(col);
2249 if (!qcol.isValid()) {
2255 rgbcol.r = qcol.red();
2256 rgbcol.g = qcol.green();
2257 rgbcol.b = qcol.blue();
2262 string const GuiApplication::hexName(ColorCode col)
2264 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2268 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2270 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2271 d->socket_notifiers_[fd] = sn;
2272 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2276 void GuiApplication::socketDataReceived(int fd)
2278 d->socket_notifiers_[fd]->func_();
2282 void GuiApplication::unregisterSocketCallback(int fd)
2284 d->socket_notifiers_.take(fd)->setEnabled(false);
2288 void GuiApplication::commitData(QSessionManager & sm)
2290 /// The implementation is required to avoid an application exit
2291 /// when session state save is triggered by session manager.
2292 /// The default implementation sends a close event to all
2293 /// visible top level widgets when session managment allows
2295 /// We are changing that to close all wiew one by one.
2296 /// FIXME: verify if the default implementation is enough now.
2297 #ifdef QT_NO_SESSIONMANAGER
2298 #warning Qt is compiled without session manager
2301 if (sm.allowsInteraction() && !closeAllViews())
2307 void GuiApplication::unregisterView(GuiView * gv)
2309 LASSERT(d->views_[gv->id()] == gv, /**/);
2310 d->views_.remove(gv->id());
2311 if (current_view_ == gv)
2316 bool GuiApplication::closeAllViews()
2318 if (d->views_.empty())
2321 // When a view/window was closed before without quitting LyX, there
2322 // are already entries in the lastOpened list.
2323 theSession().lastOpened().clear();
2325 QList<GuiView *> views = d->views_.values();
2326 foreach (GuiView * view, views) {
2327 if (!view->closeScheduled())
2336 GuiView & GuiApplication::view(int id) const
2338 LASSERT(d->views_.contains(id), /**/);
2339 return *d->views_.value(id);
2343 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2345 QList<GuiView *> views = d->views_.values();
2346 foreach (GuiView * view, views)
2347 view->hideDialog(name, inset);
2351 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2353 Buffer const * buffer_ = 0;
2354 QHash<int, GuiView *>::iterator end = d->views_.end();
2355 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2356 if (Buffer const * ptr = (*it)->updateInset(inset))
2363 bool GuiApplication::searchMenu(FuncRequest const & func,
2364 docstring_list & names) const
2366 return d->menus_.searchMenu(func, names);
2370 bool GuiApplication::readUIFile(QString const & name, bool include)
2372 LYXERR(Debug::INIT, "About to read " << name << "...");
2376 ui_path = libFileSearch("ui", name, "inc");
2377 if (ui_path.empty())
2378 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2380 ui_path = libFileSearch("ui", name, "ui");
2383 if (ui_path.empty()) {
2384 static const QString defaultUIFile = "default";
2385 LYXERR(Debug::INIT, "Could not find " << name);
2387 Alert::warning(_("Could not find UI definition file"),
2388 bformat(_("Error while reading the included file\n%1$s\n"
2389 "Please check your installation."), qstring_to_ucs4(name)));
2392 if (name == defaultUIFile) {
2393 LYXERR(Debug::INIT, "Could not find default UI file!!");
2394 Alert::warning(_("Could not find default UI file"),
2395 _("LyX could not find the default UI file!\n"
2396 "Please check your installation."));
2399 Alert::warning(_("Could not find UI definition file"),
2400 bformat(_("Error while reading the configuration file\n%1$s\n"
2401 "Falling back to default.\n"
2402 "Please look under Tools>Preferences>User Interface and\n"
2403 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2404 return readUIFile(defaultUIFile, false);
2407 // Ensure that a file is read only once (prevents include loops)
2408 static QStringList uifiles;
2409 QString const uifile = toqstr(ui_path.absFileName());
2410 if (uifiles.contains(uifile)) {
2412 // We are reading again the top uifile so reset the safeguard:
2415 d->toolbars_.reset();
2417 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2418 << "Is this an include loop?");
2422 uifiles.push_back(uifile);
2424 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2434 LexerKeyword uitags[] = {
2435 { "include", ui_include },
2436 { "menuset", ui_menuset },
2437 { "toolbars", ui_toolbars },
2438 { "toolbarset", ui_toolbarset }
2442 lex.setFile(ui_path);
2444 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2448 if (lyxerr.debugging(Debug::PARSER))
2449 lex.printTable(lyxerr);
2451 // store which ui files define Toolbars
2452 static QStringList toolbar_uifiles;
2454 while (lex.isOK()) {
2455 switch (lex.lex()) {
2458 QString const file = toqstr(lex.getString());
2459 if (!readUIFile(file, true))
2464 d->menus_.read(lex);
2468 d->toolbars_.readToolbars(lex);
2472 d->toolbars_.readToolbarSettings(lex);
2473 toolbar_uifiles.push_back(uifile);
2477 if (!rtrim(lex.getString()).empty())
2478 lex.printError("LyX::ReadUIFile: "
2479 "Unknown menu tag: `$$Token'");
2488 settings.beginGroup("ui_files");
2489 bool touched = false;
2490 for (int i = 0; i != uifiles.size(); ++i) {
2491 QFileInfo fi(uifiles[i]);
2492 QDateTime const date_value = fi.lastModified();
2493 QString const name_key = QString::number(i);
2494 // if an ui file which defines Toolbars has changed,
2495 // we have to reset the settings
2496 if (toolbar_uifiles.contains(uifiles[i])
2497 && (!settings.contains(name_key)
2498 || settings.value(name_key).toString() != uifiles[i]
2499 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2501 settings.setValue(name_key, uifiles[i]);
2502 settings.setValue(name_key + "/date", date_value);
2505 settings.endGroup();
2507 settings.remove("views");
2513 void GuiApplication::onLastWindowClosed()
2515 if (d->global_menubar_)
2516 d->global_menubar_->grabKeyboard();
2520 ////////////////////////////////////////////////////////////////////////
2522 // X11 specific stuff goes here...
2525 bool GuiApplication::x11EventFilter(XEvent * xev)
2530 switch (xev->type) {
2531 case SelectionRequest: {
2532 if (xev->xselectionrequest.selection != XA_PRIMARY)
2534 LYXERR(Debug::SELECTION, "X requested selection.");
2535 BufferView * bv = current_view_->currentBufferView();
2537 docstring const sel = bv->requestSelection();
2539 d->selection_.put(sel);
2543 case SelectionClear: {
2544 if (xev->xselectionclear.selection != XA_PRIMARY)
2546 LYXERR(Debug::SELECTION, "Lost selection.");
2547 BufferView * bv = current_view_->currentBufferView();
2549 bv->clearSelection();
2557 } // namespace frontend
2560 void hideDialogs(std::string const & name, Inset * inset)
2563 frontend::guiApp->hideDialogs(name, inset);
2567 ////////////////////////////////////////////////////////////////////
2571 ////////////////////////////////////////////////////////////////////
2573 frontend::FontLoader & theFontLoader()
2575 LASSERT(frontend::guiApp, /**/);
2576 return frontend::guiApp->fontLoader();
2580 frontend::FontMetrics const & theFontMetrics(Font const & f)
2582 return theFontMetrics(f.fontInfo());
2586 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2588 LASSERT(frontend::guiApp, /**/);
2589 return frontend::guiApp->fontLoader().metrics(f);
2593 ////////////////////////////////////////////////////////////////////
2597 ////////////////////////////////////////////////////////////////////
2599 frontend::Clipboard & theClipboard()
2601 LASSERT(frontend::guiApp, /**/);
2602 return frontend::guiApp->clipboard();
2606 frontend::Selection & theSelection()
2608 LASSERT(frontend::guiApp, /**/);
2609 return frontend::guiApp->selection();
2615 #include "moc_GuiApplication.cpp"