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 "LaTeXPackages.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"
85 #include <QFileOpenEvent>
89 #include <QImageReader>
92 #include <QLibraryInfo>
94 #include <QMacPasteboardMime>
99 #include <QPixmapCache>
101 #include <QSessionManager>
103 #include <QShowEvent>
104 #include <QSocketNotifier>
105 #include <QSortFilterProxyModel>
106 #include <QStandardItemModel>
107 #include <QTextCodec>
109 #include <QTranslator>
110 #if QT_VERSION >= 0x040400
111 #include <QThreadPool>
116 #include <X11/Xatom.h>
117 #include <X11/Xlib.h>
123 #include <QWindowsMime>
130 #include "support/bind.h"
131 #include <boost/crc.hpp>
138 using namespace lyx::support;
141 static void initializeResources()
143 static bool initialized = false;
145 Q_INIT_RESOURCE(Resources);
153 frontend::Application * createApplication(int & argc, char * argv[])
156 // prune -geometry argument(s) by shifting
157 // the following ones 2 places down.
158 for (int i = 0 ; i < argc ; ++i) {
159 if (strcmp(argv[i], "-geometry") == 0) {
160 int const remove = (i+1) < argc ? 2 : 1;
162 for (int j = i; j < argc; ++j)
163 argv[j] = argv[j + remove];
168 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
169 // I'd rather do that in the constructor, but I do not think that
170 // the palette is accessible there.
171 guiApp->colorCache().setPalette(guiApp->palette());
178 /// Return the list of loadable formats.
179 vector<string> loadableImageFormats()
183 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
185 LYXERR(Debug::GRAPHICS,
186 "\nThe image loader can load the following directly:\n");
188 if (qt_formats.empty())
189 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
191 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
193 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
195 string ext = ascii_lowercase((const char *) *it);
206 ////////////////////////////////////////////////////////////////////////
208 // Icon loading support code
210 ////////////////////////////////////////////////////////////////////////
220 bool operator<(PngMap const & lhs, PngMap const & rhs)
222 return lhs.key < rhs.key;
228 CompareKey(QString const & name) : name_(name) {}
229 bool operator()(PngMap const & other) const { return other.key == name_; }
235 // this must be sorted alphabetically
236 // Upper case comes before lower case
237 PngMap sorted_png_map[] = {
238 { "Bumpeq", "bumpeq2" },
241 { "Delta", "delta2" },
242 { "Diamond", "diamond2" },
243 { "Downarrow", "downarrow2" },
244 { "Gamma", "gamma2" },
245 { "Lambda", "lambda2" },
246 { "Leftarrow", "leftarrow2" },
247 { "Leftrightarrow", "leftrightarrow2" },
248 { "Longleftarrow", "longleftarrow2" },
249 { "Longleftrightarrow", "longleftrightarrow2" },
250 { "Longrightarrow", "longrightarrow2" },
251 { "Omega", "omega2" },
255 { "Rightarrow", "rightarrow2" },
256 { "Sigma", "sigma2" },
257 { "Subset", "subset2" },
258 { "Supset", "supset2" },
259 { "Theta", "theta2" },
260 { "Uparrow", "uparrow2" },
261 { "Updownarrow", "updownarrow2" },
262 { "Upsilon", "upsilon2" },
263 { "Vdash", "vdash3" },
266 { "nLeftarrow", "nleftarrow2" },
267 { "nLeftrightarrow", "nleftrightarrow2" },
268 { "nRightarrow", "nrightarrow2" },
269 { "nVDash", "nvdash3" },
270 { "nvDash", "nvdash2" },
271 { "textrm \\AA", "textrm_AA"},
272 { "textrm \\O", "textrm_O"},
273 { "vDash", "vdash2" }
276 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
279 QString findPng(QString const & name)
281 PngMap const * const begin = sorted_png_map;
282 PngMap const * const end = begin + nr_sorted_png_map;
283 LASSERT(sorted(begin, end), /**/);
285 PngMap const * const it = find_if(begin, end, CompareKey(name));
289 png_name = it->value;
292 png_name.replace('_', "underscore");
293 png_name.replace(' ', '_');
295 // This way we can have "math-delim { }" on the toolbar.
296 png_name.replace('(', "lparen");
297 png_name.replace(')', "rparen");
298 png_name.replace('[', "lbracket");
299 png_name.replace(']', "rbracket");
300 png_name.replace('{', "lbrace");
301 png_name.replace('}', "rbrace");
302 png_name.replace('|', "bars");
303 png_name.replace(',', "thinspace");
304 png_name.replace(':', "mediumspace");
305 png_name.replace(';', "thickspace");
306 png_name.replace('!', "negthinspace");
309 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
310 << "Looking for math PNG called \"" << png_name << '"');
317 QString iconName(FuncRequest const & f, bool unknown)
319 initializeResources();
323 switch (f.action()) {
324 case LFUN_MATH_INSERT:
325 if (!f.argument().empty()) {
327 name1 = findPng(toqstr(f.argument()).mid(1));
330 case LFUN_MATH_DELIM:
331 case LFUN_MATH_BIGDELIM:
333 name1 = findPng(toqstr(f.argument()));
337 name1 = toqstr(f.argument());
339 case LFUN_COMMAND_ALTERNATIVES: {
340 // use the first of the alternative commands
342 docstring dummy = split(f.argument(), firstcom, ';');
343 name1 = toqstr(firstcom);
344 // FIXME: we should rename the icons to tabular-xxx instead of
345 // "tabular-feature-xxx"
346 name1.replace("inset-modify tabular", "tabular-feature");
347 name1.replace(' ', '_');
350 case LFUN_INSET_MODIFY: {
351 // FIXME: we should rename the icons to tabular-xxx instead of
352 // "tabular-feature-xxx" and generalize this naming to all
353 // insets, not to tabular using ones.
355 string const command = split(to_utf8(f.argument()), inset_name, ' ');
356 if (insetCode(inset_name) == TABULAR_CODE) {
357 name1 = "tabular-feature "+ toqstr(command);
358 name1.replace(' ', '_');
363 name2 = toqstr(lyxaction.getActionName(f.action()));
366 if (!f.argument().empty()) {
367 name1 = name2 + ' ' + toqstr(f.argument());
368 name1.replace(' ', '_');
369 name1.replace('\\', "backslash");
373 QString imagedir = "images/" + path;
374 FileName fname = imageLibFileSearch(imagedir, name1, "png");
376 return toqstr(fname.absFileName());
378 fname = imageLibFileSearch(imagedir, 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 imagedir = "images/";
406 fname = imageLibFileSearch(imagedir, "unknown", "png");
408 return toqstr(fname.absFileName());
409 return QString(":/images/unknown.png");
415 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
418 QString imagedir = path;
419 FileName fname = imageLibFileSearch(imagedir, name, ext);
420 QString path1 = toqstr(fname.absFileName());
421 QString path2 = ":/" + path + name + "." + ext;
423 if (pixmap.load(path1)) {
426 else if (pixmap.load(path2)) {
430 LYXERR0("Cannot load pixmap \""
431 << path << name << '.' << ext
432 << "\", please verify resource system!");
437 QIcon getIcon(FuncRequest const & f, bool unknown)
439 QString icon = iconName(f, unknown);
443 //LYXERR(Debug::GUI, "Found icon: " << icon);
445 if (!pm.load(icon)) {
446 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
454 ////////////////////////////////////////////////////////////////////////
456 // LyX server support code.
458 ////////////////////////////////////////////////////////////////////////
460 class SocketNotifier : public QSocketNotifier
463 /// connect a connection notification from the LyXServerSocket
464 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
465 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
469 /// The callback function
470 Application::SocketCallback func_;
474 ////////////////////////////////////////////////////////////////////////
476 // Mac specific stuff goes here...
478 ////////////////////////////////////////////////////////////////////////
480 class MenuTranslator : public QTranslator
483 MenuTranslator(QObject * parent)
484 : QTranslator(parent)
487 QString translate(const char * /*context*/,
488 const char * sourceText,
489 const char * /*comment*/ = 0)
491 string const s = sourceText;
492 if (s == N_("About %1") || s == N_("Preferences")
493 || s == N_("Reconfigure") || s == N_("Quit %1"))
500 class GlobalMenuBar : public QMenuBar
504 GlobalMenuBar() : QMenuBar(0) {}
507 bool event(QEvent * e)
509 if (e->type() == QEvent::ShortcutOverride) {
510 // && activeWindow() == 0) {
511 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
513 setKeySymbol(&sym, ke);
514 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
523 // QMacPasteboardMimeGraphics can only be compiled on Mac.
525 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
528 QMacPasteboardMimeGraphics()
529 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
532 QString convertorName() { return "Graphics"; }
534 QString flavorFor(QString const & mime)
536 LYXERR(Debug::ACTION, "flavorFor " << mime);
537 if (mime == pdfMimeType())
538 return QLatin1String("com.adobe.pdf");
542 QString mimeFor(QString flav)
544 LYXERR(Debug::ACTION, "mimeFor " << flav);
545 if (flav == QLatin1String("com.adobe.pdf"))
546 return pdfMimeType();
550 bool canConvert(QString const & mime, QString flav)
552 return mimeFor(flav) == mime;
555 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
559 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
563 QList<QByteArray> convertFromMime(QString const & /*mime*/,
564 QVariant data, QString /*flav*/)
566 QList<QByteArray> ret;
567 ret.append(data.toByteArray());
573 ///////////////////////////////////////////////////////////////
575 // You can find more platform specific stuff at the end of this file...
577 ///////////////////////////////////////////////////////////////
579 ////////////////////////////////////////////////////////////////////////
580 // Windows specific stuff goes here...
583 // QWindowsMimeMetafile can only be compiled on Windows.
585 static FORMATETC cfFromMime(QString const & mimetype)
588 if (mimetype == emfMimeType()) {
589 formatetc.cfFormat = CF_ENHMETAFILE;
590 formatetc.tymed = TYMED_ENHMF;
591 } else if (mimetype == wmfMimeType()) {
592 formatetc.cfFormat = CF_METAFILEPICT;
593 formatetc.tymed = TYMED_MFPICT;
596 formatetc.dwAspect = DVASPECT_CONTENT;
597 formatetc.lindex = -1;
602 class QWindowsMimeMetafile : public QWindowsMime {
604 QWindowsMimeMetafile() {}
606 bool canConvertFromMime(FORMATETC const & formatetc,
607 QMimeData const * mimedata) const
612 bool canConvertToMime(QString const & mimetype,
613 IDataObject * pDataObj) const
615 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
617 FORMATETC formatetc = cfFromMime(mimetype);
618 return pDataObj->QueryGetData(&formatetc) == S_OK;
621 bool convertFromMime(FORMATETC const & formatetc,
622 const QMimeData * mimedata, STGMEDIUM * pmedium) const
627 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
628 QVariant::Type preferredType) const
631 if (!canConvertToMime(mimetype, pDataObj))
634 FORMATETC formatetc = cfFromMime(mimetype);
636 if (pDataObj->GetData(&formatetc, &s) != S_OK)
640 if (s.tymed == TYMED_ENHMF) {
641 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
642 data.resize(dataSize);
643 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
644 (LPBYTE)data.data());
645 } else if (s.tymed == TYMED_MFPICT) {
646 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
647 data.resize(dataSize);
648 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
649 (LPBYTE)data.data());
652 ReleaseStgMedium(&s);
658 QVector<FORMATETC> formatsForMime(QString const & mimetype,
659 QMimeData const * mimedata) const
661 QVector<FORMATETC> formats;
662 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
663 formats += cfFromMime(mimetype);
667 QString mimeForFormat(FORMATETC const & formatetc) const
669 switch (formatetc.cfFormat) {
671 return emfMimeType();
672 case CF_METAFILEPICT:
673 return wmfMimeType();
682 /// Allows to check whether ESC was pressed during a long operation
683 class KeyChecker : public QObject {
691 QCoreApplication::instance()->installEventFilter(this);
695 QCoreApplication::instance()->removeEventFilter(this);
698 QCoreApplication::processEvents();
701 bool eventFilter(QObject *obj, QEvent *event) {
702 LYXERR(Debug::ACTION, "Event Type: " << event->type());
703 switch (event->type()) {
707 return QObject::eventFilter(obj, event);
709 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
710 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
718 ////////////////////////////////////////////////////////////////////////
719 // GuiApplication::Private definition and implementation.
720 ////////////////////////////////////////////////////////////////////////
722 struct GuiApplication::Private
724 Private(): language_model_(0), meta_fake_bit(NoModifier),
728 /// WMF Mime handler for Windows clipboard.
729 wmf_mime_ = new QWindowsMimeMetafile();
731 initKeySequences(&theTopLevelKeymap());
734 void initKeySequences(KeyMap * kb)
736 keyseq = KeySequence(kb, kb);
737 cancel_meta_seq = KeySequence(kb, kb);
741 QSortFilterProxyModel * language_model_;
743 GuiClipboard clipboard_;
745 GuiSelection selection_;
747 FontLoader font_loader_;
749 ColorCache color_cache_;
751 QTranslator qt_trans_;
753 QHash<int, SocketNotifier *> socket_notifiers_;
757 /// The global instance
760 /// this timer is used for any regular events one wants to
761 /// perform. at present it is used to check if forked processes
763 QTimer general_timer_;
765 /// delayed FuncRequests
766 std::queue<FuncRequest> func_request_queue_;
771 KeySequence cancel_meta_seq;
773 KeyModifier meta_fake_bit;
775 /// Multiple views container.
777 * Warning: This must not be a smart pointer as the destruction of the
778 * object is handled by Qt when the view is closed
779 * \sa Qt::WA_DeleteOnClose attribute.
781 QHash<int, GuiView *> views_;
783 /// Only used on mac.
784 GlobalMenuBar * global_menubar_;
787 /// Linkback mime handler for MacOSX.
788 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
792 /// WMF Mime handler for Windows clipboard.
793 QWindowsMimeMetafile * wmf_mime_;
796 /// Allows to check whether ESC was pressed during a long operation
797 KeyChecker key_checker_;
801 GuiApplication * guiApp;
803 GuiApplication::~GuiApplication()
806 closeAllLinkBackLinks();
812 GuiApplication::GuiApplication(int & argc, char ** argv)
813 : QApplication(argc, argv), current_view_(0),
814 d(new GuiApplication::Private)
816 QString app_name = "LyX";
817 QCoreApplication::setOrganizationName(app_name);
818 QCoreApplication::setOrganizationDomain("lyx.org");
819 QCoreApplication::setApplicationName(lyx_package);
821 // Install translator for GUI elements.
822 installTranslator(&d->qt_trans_);
824 // FIXME: quitOnLastWindowClosed is true by default. We should have a
825 // lyxrc setting for this in order to let the application stay resident.
826 // But then we need some kind of dock icon, at least on Windows.
828 if (lyxrc.quit_on_last_window_closed)
829 setQuitOnLastWindowClosed(false);
832 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
833 // seems to be the default case for applications like LyX.
834 setQuitOnLastWindowClosed(false);
835 // This allows to translate the strings that appear in the LyX menu.
836 /// A translator suitable for the entries in the LyX menu.
837 /// Only needed with Qt/Mac.
838 installTranslator(new MenuTranslator(this));
842 // doubleClickInterval() is 400 ms on X11 which is just too long.
843 // On Windows and Mac OS X, the operating system's value is used.
844 // On Microsoft Windows, calling this function sets the double
845 // click interval for all applications. So we don't!
846 QApplication::setDoubleClickInterval(300);
849 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
851 // needs to be done before reading lyxrc
853 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
857 // Set the cache to 5120 kilobytes which corresponds to screen size of
858 // 1280 by 1024 pixels with a color depth of 32 bits.
859 QPixmapCache::setCacheLimit(5120);
861 // Initialize RC Fonts
862 if (lyxrc.roman_font_name.empty())
863 lyxrc.roman_font_name = fromqstr(romanFontName());
865 if (lyxrc.sans_font_name.empty())
866 lyxrc.sans_font_name = fromqstr(sansFontName());
868 if (lyxrc.typewriter_font_name.empty())
869 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
871 d->general_timer_.setInterval(500);
872 connect(&d->general_timer_, SIGNAL(timeout()),
873 this, SLOT(handleRegularEvents()));
874 d->general_timer_.start();
876 #if QT_VERSION >= 0x040400
877 // maxThreadCount() defaults in general to 2 on single or dual-processor.
878 // This is clearly not enough in a time where we use threads for
879 // document preview and/or export. 20 should be OK.
880 QThreadPool::globalInstance()->setMaxThreadCount(20);
885 GuiApplication * theGuiApp()
887 return dynamic_cast<GuiApplication *>(theApp());
891 void GuiApplication::clearSession()
898 docstring Application::iconName(FuncRequest const & f, bool unknown)
900 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
904 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
909 BufferView * doc_bv = 0;
911 if (cmd.action() == LFUN_NOACTION) {
912 status.message(from_utf8(N_("Nothing to do")));
913 status.setEnabled(false);
916 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
917 status.setUnknown(true);
918 status.message(from_utf8(N_("Unknown action")));
919 status.setEnabled(false);
922 // Does the GuiApplication know something?
923 else if (getStatus(cmd, status)) { }
925 // If we do not have a GuiView, then other functions are disabled
926 else if (!current_view_)
927 status.setEnabled(false);
929 // Does the GuiView know something?
930 else if (current_view_->getStatus(cmd, status)) { }
932 // In LyX/Mac, when a dialog is open, the menus of the
933 // application can still be accessed without giving focus to
934 // the main window. In this case, we want to disable the menu
935 // entries that are buffer or view-related.
936 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
938 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
939 status.setEnabled(false);
942 // If we do not have a BufferView, then other functions are disabled
943 else if (!(bv = current_view_->currentBufferView()))
944 status.setEnabled(false);
946 // Does the current BufferView know something?
947 else if (bv->getStatus(cmd, status)) { }
949 // Does the current Buffer know something?
950 else if (bv->buffer().getStatus(cmd, status)) { }
952 // If we do not have a document BufferView, different from the
953 // current BufferView, then other functions are disabled
954 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
955 status.setEnabled(false);
957 // Does the document Buffer know something?
958 else if (doc_bv->buffer().getStatus(cmd, status)) { }
961 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
962 status.message(from_utf8(N_("Command not handled")));
963 status.setEnabled(false);
966 // the default error message if we disable the command
967 if (!status.enabled() && status.message().empty())
968 status.message(from_utf8(N_("Command disabled")));
974 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
976 // I would really like to avoid having this switch and rather try to
977 // encode this in the function itself.
978 // -- And I'd rather let an inset decide which LFUNs it is willing
979 // to handle (Andre')
981 switch (cmd.action()) {
983 // This could be used for the no-GUI version. The GUI version is handled in
984 // GuiView::getStatus(). See above.
986 case LFUN_BUFFER_WRITE:
987 case LFUN_BUFFER_WRITE_AS: {
988 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
989 enable = b && (b->isUnnamed() || !b->isClean());
994 case LFUN_BOOKMARK_GOTO: {
995 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
996 enable = theSession().bookmarks().isValid(num);
1000 case LFUN_BOOKMARK_CLEAR:
1001 enable = theSession().bookmarks().hasValid();
1004 // this one is difficult to get right. As a half-baked
1005 // solution, we consider only the first action of the sequence
1006 case LFUN_COMMAND_SEQUENCE: {
1007 // argument contains ';'-terminated commands
1008 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1009 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1010 func.setOrigin(cmd.origin());
1011 flag = getStatus(func);
1015 // we want to check if at least one of these is enabled
1016 case LFUN_COMMAND_ALTERNATIVES: {
1017 // argument contains ';'-terminated commands
1018 string arg = to_utf8(cmd.argument());
1019 while (!arg.empty()) {
1021 arg = split(arg, first, ';');
1022 FuncRequest func(lyxaction.lookupFunc(first));
1023 func.setOrigin(cmd.origin());
1024 flag = getStatus(func);
1025 // if this one is enabled, the whole thing is
1034 string name = to_utf8(cmd.argument());
1035 if (theTopLevelCmdDef().lock(name, func)) {
1036 func.setOrigin(cmd.origin());
1037 flag = getStatus(func);
1038 theTopLevelCmdDef().release(name);
1040 // catch recursion or unknown command
1041 // definition. all operations until the
1042 // recursion or unknown command definition
1043 // occurs are performed, so set the state to
1050 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1052 case LFUN_PREFERENCES_SAVE:
1053 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1054 case LFUN_DEBUG_LEVEL_SET:
1055 // these are handled in our dispatch()
1058 case LFUN_WINDOW_CLOSE:
1059 enable = d->views_.size() > 0;
1062 case LFUN_BUFFER_NEW:
1063 case LFUN_BUFFER_NEW_TEMPLATE:
1064 case LFUN_FILE_OPEN:
1065 case LFUN_HELP_OPEN:
1066 case LFUN_SCREEN_FONT_UPDATE:
1067 case LFUN_SET_COLOR:
1068 case LFUN_WINDOW_NEW:
1070 case LFUN_LYXRC_APPLY:
1071 case LFUN_COMMAND_PREFIX:
1073 case LFUN_META_PREFIX:
1074 case LFUN_RECONFIGURE:
1075 case LFUN_SERVER_GET_FILENAME:
1076 case LFUN_SERVER_NOTIFY:
1085 flag.setEnabled(false);
1089 /// make a post-dispatch status message
1090 static docstring makeDispatchMessage(docstring const & msg,
1091 FuncRequest const & cmd)
1093 const bool verbose = (cmd.origin() == FuncRequest::MENU
1094 || cmd.origin() == FuncRequest::TOOLBAR
1095 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1097 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1098 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1102 docstring dispatch_msg = msg;
1103 if (!dispatch_msg.empty())
1104 dispatch_msg += ' ';
1106 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1108 bool argsadded = false;
1110 if (!cmd.argument().empty()) {
1111 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1112 comname += ' ' + cmd.argument();
1116 docstring const shortcuts = theTopLevelKeymap().
1117 printBindings(cmd, KeySequence::ForGui);
1119 if (!shortcuts.empty())
1120 comname += ": " + shortcuts;
1121 else if (!argsadded && !cmd.argument().empty())
1122 comname += ' ' + cmd.argument();
1124 if (!comname.empty()) {
1125 comname = rtrim(comname);
1126 dispatch_msg += '(' + rtrim(comname) + ')';
1128 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1129 return dispatch_msg;
1133 void GuiApplication::dispatch(FuncRequest const & cmd)
1135 if (current_view_ && current_view_->currentBufferView())
1136 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1139 // redraw the screen at the end (first of the two drawing steps).
1140 // This is done unless explicitly requested otherwise
1141 dr.screenUpdate(Update::FitCursor);
1147 BufferView * bv = current_view_->currentBufferView();
1149 if (dr.needBufferUpdate()) {
1150 bv->cursor().clearBufferUpdate();
1151 bv->buffer().updateBuffer();
1153 // BufferView::update() updates the ViewMetricsInfo and
1154 // also initializes the position cache for all insets in
1155 // (at least partially) visible top-level paragraphs.
1156 // We will redraw the screen only if needed.
1157 bv->processUpdateFlags(dr.screenUpdate());
1159 // Do we have a selection?
1160 theSelection().haveSelection(bv->cursor().selection());
1163 current_view_->restartCursor();
1165 if (dr.needMessageUpdate()) {
1166 // Some messages may already be translated, so we cannot use _()
1167 current_view_->message(makeDispatchMessage(
1168 translateIfPossible(dr.message()), cmd));
1173 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1174 bool switchToBuffer)
1176 if (!theSession().bookmarks().isValid(idx))
1178 BookmarksSection::Bookmark const & bm =
1179 theSession().bookmarks().bookmark(idx);
1180 LASSERT(!bm.filename.empty(), /**/);
1181 string const file = bm.filename.absFileName();
1182 // if the file is not opened, open it.
1183 if (!theBufferList().exists(bm.filename)) {
1185 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1189 // open may fail, so we need to test it again
1190 if (!theBufferList().exists(bm.filename))
1193 // bm can be changed when saving
1194 BookmarksSection::Bookmark tmp = bm;
1196 // Special case idx == 0 used for back-from-back jump navigation
1198 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1200 // if the current buffer is not that one, switch to it.
1201 BufferView * doc_bv = current_view_ ?
1202 current_view_->documentBufferView() : 0;
1203 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1204 if (switchToBuffer) {
1205 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1208 doc_bv = current_view_->documentBufferView();
1213 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1214 if (!doc_bv->moveToPosition(
1215 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1222 // Cursor jump succeeded!
1223 Cursor const & cur = doc_bv->cursor();
1224 pit_type new_pit = cur.pit();
1225 pos_type new_pos = cur.pos();
1226 int new_id = cur.paragraph().id();
1228 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1229 // see http://www.lyx.org/trac/ticket/3092
1230 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1231 || bm.top_id != new_id) {
1232 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1233 new_pit, new_pos, new_id);
1237 // This function runs "configure" and then rereads lyx.defaults to
1238 // reconfigure the automatic settings.
1239 void GuiApplication::reconfigure(string const & option)
1241 // emit message signal.
1243 current_view_->message(_("Running configure..."));
1245 // Run configure in user lyx directory
1246 PathChanger p(package().user_support());
1247 string configure_command = package().configure_command();
1248 configure_command += option;
1250 int ret = one.startscript(Systemcall::Wait, configure_command);
1252 // emit message signal.
1254 current_view_->message(_("Reloading configuration..."));
1255 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1256 // Re-read packages.lst
1257 LaTeXPackages::getAvailable();
1260 Alert::information(_("System reconfiguration failed"),
1261 _("The system reconfiguration has failed.\n"
1262 "Default textclass is used but LyX may "
1263 "not be able to work properly.\n"
1264 "Please reconfigure again if needed."));
1266 Alert::information(_("System reconfigured"),
1267 _("The system has been reconfigured.\n"
1268 "You need to restart LyX to make use of any\n"
1269 "updated document class specifications."));
1272 void GuiApplication::validateCurrentView()
1274 if (!d->views_.empty() && !current_view_) {
1275 // currently at least one view exists but no view has the focus.
1276 // choose the last view to make it current.
1277 // a view without any open document is preferred.
1278 GuiView * candidate = 0;
1279 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1280 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1281 for (; it != end; ++it) {
1283 if (!candidate->documentBufferView())
1286 setCurrentView(candidate);
1290 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1292 string const argument = to_utf8(cmd.argument());
1293 FuncCode const action = cmd.action();
1295 LYXERR(Debug::ACTION, "cmd: " << cmd);
1297 // we have not done anything wrong yet.
1300 FuncStatus const flag = getStatus(cmd);
1301 if (!flag.enabled()) {
1302 // We cannot use this function here
1303 LYXERR(Debug::ACTION, "action "
1304 << lyxaction.getActionName(action)
1305 << " [" << action << "] is disabled at this location");
1306 dr.setMessage(flag.message());
1308 dr.dispatched(false);
1309 dr.screenUpdate(Update::None);
1310 dr.clearBufferUpdate();
1314 // Assumes that the action will be dispatched.
1315 dr.dispatched(true);
1317 switch (cmd.action()) {
1319 case LFUN_WINDOW_NEW:
1320 createView(toqstr(cmd.argument()));
1323 case LFUN_WINDOW_CLOSE:
1324 // update bookmark pit of the current buffer before window close
1325 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1326 gotoBookmark(i+1, false, false);
1327 // clear the last opened list, because
1328 // maybe this will end the session
1329 theSession().lastOpened().clear();
1330 // check for valid current_view_
1331 validateCurrentView();
1333 current_view_->closeScheduled();
1337 // quitting is triggered by the gui code
1338 // (leaving the event loop).
1340 current_view_->message(from_utf8(N_("Exiting.")));
1341 if (closeAllViews())
1345 case LFUN_SCREEN_FONT_UPDATE: {
1346 // handle the screen font changes.
1347 d->font_loader_.update();
1348 // Backup current_view_
1349 GuiView * view = current_view_;
1350 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1351 // to skip the refresh.
1353 theBufferList().changed(false);
1354 // Restore current_view_
1355 current_view_ = view;
1359 case LFUN_BUFFER_NEW:
1360 validateCurrentView();
1361 if (d->views_.empty()
1362 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1363 createView(QString(), false); // keep hidden
1364 current_view_->newDocument(to_utf8(cmd.argument()), false);
1365 current_view_->show();
1366 setActiveWindow(current_view_);
1368 current_view_->newDocument(to_utf8(cmd.argument()), false);
1372 case LFUN_BUFFER_NEW_TEMPLATE:
1373 validateCurrentView();
1374 if (d->views_.empty()
1375 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1377 current_view_->newDocument(to_utf8(cmd.argument()), true);
1378 if (!current_view_->documentBufferView())
1379 current_view_->close();
1381 current_view_->newDocument(to_utf8(cmd.argument()), true);
1385 case LFUN_FILE_OPEN: {
1386 validateCurrentView();
1387 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1388 string const fname = to_utf8(cmd.argument());
1389 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1390 && current_view_->documentBufferView() != 0)) {
1391 // We want the ui session to be saved per document and not per
1392 // window number. The filename crc is a good enough identifier.
1393 boost::crc_32_type crc;
1394 crc = for_each(fname.begin(), fname.end(), crc);
1395 createView(crc.checksum());
1396 current_view_->openDocument(fname);
1397 if (current_view_ && !current_view_->documentBufferView())
1398 current_view_->close();
1400 current_view_->openDocument(fname);
1404 case LFUN_HELP_OPEN: {
1405 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1406 if (current_view_ == 0)
1408 string const arg = to_utf8(cmd.argument());
1410 current_view_->message(_("Missing argument"));
1413 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1415 fname = i18nLibFileSearch("examples", arg, "lyx");
1417 if (fname.empty()) {
1418 lyxerr << "LyX: unable to find documentation file `"
1419 << arg << "'. Bad installation?" << endl;
1422 current_view_->message(bformat(_("Opening help file %1$s..."),
1423 makeDisplayPath(fname.absFileName())));
1424 Buffer * buf = current_view_->loadDocument(fname, false);
1426 #ifndef DEVEL_VERSION
1428 buf->setReadonly(true);
1435 case LFUN_SET_COLOR: {
1437 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1438 if (lyx_name.empty() || x11_name.empty()) {
1440 current_view_->message(
1441 _("Syntax: set-color <lyx_name> <x11_name>"));
1446 // FIXME: The graphics cache no longer has a changeDisplay method.
1447 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1448 bool const graphicsbg_changed =
1449 lyx_name == graphicsbg && x11_name != graphicsbg;
1450 if (graphicsbg_changed)
1451 graphics::GCache::get().changeDisplay(true);
1454 if (!lcolor.setColor(lyx_name, x11_name)) {
1456 current_view_->message(
1457 bformat(_("Set-color \"%1$s\" failed "
1458 "- color is undefined or "
1459 "may not be redefined"),
1460 from_utf8(lyx_name)));
1463 // Make sure we don't keep old colors in cache.
1464 d->color_cache_.clear();
1468 case LFUN_LYXRC_APPLY: {
1469 // reset active key sequences, since the bindings
1470 // are updated (bug 6064)
1472 LyXRC const lyxrc_orig = lyxrc;
1474 istringstream ss(to_utf8(cmd.argument()));
1475 bool const success = lyxrc.read(ss);
1478 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1479 << "Unable to read lyxrc data"
1484 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1490 case LFUN_COMMAND_PREFIX:
1491 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1496 d->meta_fake_bit = NoModifier;
1497 GuiView * gv = currentView();
1498 if (gv && gv->currentBufferView())
1499 // cancel any selection
1500 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1501 dr.setMessage(from_ascii(N_("Cancel")));
1504 case LFUN_META_PREFIX:
1505 d->meta_fake_bit = AltModifier;
1506 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1509 // --- Menus -----------------------------------------------
1510 case LFUN_RECONFIGURE:
1511 // argument is any additional parameter to the configure.py command
1512 reconfigure(to_utf8(cmd.argument()));
1515 // --- lyxserver commands ----------------------------
1516 case LFUN_SERVER_GET_FILENAME: {
1517 if (current_view_ && current_view_->documentBufferView()) {
1518 docstring const fname = from_utf8(
1519 current_view_->documentBufferView()->buffer().absFileName());
1520 dr.setMessage(fname);
1521 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1523 dr.setMessage(docstring());
1524 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1529 case LFUN_SERVER_NOTIFY: {
1530 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1531 dr.setMessage(dispatch_buffer);
1532 theServer().notifyClient(to_utf8(dispatch_buffer));
1536 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1537 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1543 string rest = split(argument, countstr, ' ');
1544 istringstream is(countstr);
1547 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1548 for (int i = 0; i < count; ++i)
1549 dispatch(lyxaction.lookupFunc(rest));
1553 case LFUN_COMMAND_SEQUENCE: {
1554 // argument contains ';'-terminated commands
1555 string arg = argument;
1556 // FIXME: this LFUN should also work without any view.
1557 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1558 ? &(current_view_->documentBufferView()->buffer()) : 0;
1560 buffer->undo().beginUndoGroup();
1561 while (!arg.empty()) {
1563 arg = split(arg, first, ';');
1564 FuncRequest func(lyxaction.lookupFunc(first));
1565 func.setOrigin(cmd.origin());
1568 // the buffer may have been closed by one action
1569 if (theBufferList().isLoaded(buffer))
1570 buffer->undo().endUndoGroup();
1574 case LFUN_COMMAND_ALTERNATIVES: {
1575 // argument contains ';'-terminated commands
1576 string arg = argument;
1577 while (!arg.empty()) {
1579 arg = split(arg, first, ';');
1580 FuncRequest func(lyxaction.lookupFunc(first));
1581 func.setOrigin(cmd.origin());
1582 FuncStatus const stat = getStatus(func);
1583 if (stat.enabled()) {
1593 if (theTopLevelCmdDef().lock(argument, func)) {
1594 func.setOrigin(cmd.origin());
1596 theTopLevelCmdDef().release(argument);
1598 if (func.action() == LFUN_UNKNOWN_ACTION) {
1599 // unknown command definition
1600 lyxerr << "Warning: unknown command definition `"
1604 // recursion detected
1605 lyxerr << "Warning: Recursion in the command definition `"
1606 << argument << "' detected"
1613 case LFUN_PREFERENCES_SAVE:
1614 lyxrc.write(support::makeAbsPath("preferences",
1615 package().user_support().absFileName()), false);
1618 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1619 string const fname = addName(addPath(package().user_support().absFileName(),
1620 "templates/"), "defaults.lyx");
1621 Buffer defaults(fname);
1623 istringstream ss(argument);
1626 int const unknown_tokens = defaults.readHeader(lex);
1628 if (unknown_tokens != 0) {
1629 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1630 << unknown_tokens << " unknown token"
1631 << (unknown_tokens == 1 ? "" : "s")
1635 if (defaults.writeFile(FileName(defaults.absFileName())))
1636 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1637 makeDisplayPath(fname)));
1640 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1645 case LFUN_BOOKMARK_GOTO:
1646 // go to bookmark, open unopened file and switch to buffer if necessary
1647 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1648 dr.screenUpdate(Update::Force | Update::FitCursor);
1651 case LFUN_BOOKMARK_CLEAR:
1652 theSession().bookmarks().clear();
1655 case LFUN_DEBUG_LEVEL_SET:
1656 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1660 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1663 current_view_->dispatch(cmd, dr);
1669 docstring GuiApplication::viewStatusMessage()
1671 // When meta-fake key is pressed, show the key sequence so far + "M-".
1672 if (d->meta_fake_bit != NoModifier)
1673 return d->keyseq.print(KeySequence::ForGui) + "M-";
1675 // Else, when a non-complete key sequence is pressed,
1676 // show the available options.
1677 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1678 return d->keyseq.printOptions(true);
1684 void GuiApplication::handleKeyFunc(FuncCode action)
1688 if (d->keyseq.length())
1690 GuiView * gv = currentView();
1691 LASSERT(gv && gv->currentBufferView(), return);
1692 BufferView * bv = gv->currentBufferView();
1693 bv->getIntl().getTransManager().deadkey(
1694 c, get_accent(action).accent, bv->cursor().innerText(),
1696 // Need to clear, in case the minibuffer calls these
1699 // copied verbatim from do_accent_char
1700 bv->cursor().resetAnchor();
1704 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1706 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1708 // Do nothing if we have nothing (JMarc)
1709 if (!keysym.isOK()) {
1710 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1712 current_view_->restartCursor();
1716 if (keysym.isModifier()) {
1718 current_view_->restartCursor();
1722 char_type encoded_last_key = keysym.getUCSEncoded();
1724 // Do a one-deep top-level lookup for
1725 // cancel and meta-fake keys. RVDK_PATCH_5
1726 d->cancel_meta_seq.reset();
1728 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1729 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1731 // When not cancel or meta-fake, do the normal lookup.
1732 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1733 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1734 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1735 // remove Caps Lock and Mod2 as a modifiers
1736 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1737 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1740 // Dont remove this unless you know what you are doing.
1741 d->meta_fake_bit = NoModifier;
1743 // Can this happen now ?
1744 if (func.action() == LFUN_NOACTION)
1745 func = FuncRequest(LFUN_COMMAND_PREFIX);
1747 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1748 << d->keyseq.print(KeySequence::Portable) << ']');
1750 // already here we know if it any point in going further
1751 // why not return already here if action == -1 and
1752 // num_bytes == 0? (Lgb)
1754 if (d->keyseq.length() > 1 && current_view_)
1755 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1758 // Maybe user can only reach the key via holding down shift.
1759 // Let's see. But only if shift is the only modifier
1760 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1761 LYXERR(Debug::KEY, "Trying without shift");
1762 func = d->keyseq.addkey(keysym, NoModifier);
1763 LYXERR(Debug::KEY, "Action now " << func.action());
1766 if (func.action() == LFUN_UNKNOWN_ACTION) {
1767 // Hmm, we didn't match any of the keysequences. See
1768 // if it's normal insertable text not already covered
1770 if (keysym.isText() && d->keyseq.length() == 1) {
1771 LYXERR(Debug::KEY, "isText() is true, inserting.");
1772 func = FuncRequest(LFUN_SELF_INSERT,
1773 FuncRequest::KEYBOARD);
1775 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1776 if (current_view_) {
1777 current_view_->message(_("Unknown function."));
1778 current_view_->restartCursor();
1784 if (func.action() == LFUN_SELF_INSERT) {
1785 if (encoded_last_key != 0) {
1786 docstring const arg(1, encoded_last_key);
1787 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1788 FuncRequest::KEYBOARD));
1789 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1792 processFuncRequest(func);
1796 void GuiApplication::processFuncRequest(FuncRequest const & func)
1798 lyx::dispatch(func);
1802 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1804 addToFuncRequestQueue(func);
1805 processFuncRequestQueueAsync();
1809 void GuiApplication::processFuncRequestQueue()
1811 while (!d->func_request_queue_.empty()) {
1812 processFuncRequest(d->func_request_queue_.front());
1813 d->func_request_queue_.pop();
1818 void GuiApplication::processFuncRequestQueueAsync()
1820 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1824 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1826 d->func_request_queue_.push(func);
1830 void GuiApplication::resetGui()
1832 // Set the language defined by the user.
1836 if (!readUIFile(toqstr(lyxrc.ui_file)))
1837 // Gives some error box here.
1840 if (d->global_menubar_)
1841 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1843 QHash<int, GuiView *>::iterator it;
1844 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1847 gv->setLayoutDirection(layoutDirection());
1851 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1855 void GuiApplication::createView(int view_id)
1857 createView(QString(), true, view_id);
1861 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1864 // release the keyboard which might have been grabed by the global
1865 // menubar on Mac to catch shortcuts even without any GuiView.
1866 if (d->global_menubar_)
1867 d->global_menubar_->releaseKeyboard();
1871 while (d->views_.find(id) != d->views_.end())
1874 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1875 GuiView * view = new GuiView(id);
1877 d->views_[id] = view;
1881 setActiveWindow(view);
1884 if (!geometry_arg.isEmpty()) {
1888 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1889 re.indexIn(geometry_arg);
1890 w = re.cap(1).toInt();
1891 h = re.cap(2).toInt();
1892 x = re.cap(3).toInt();
1893 y = re.cap(4).toInt();
1894 view->setGeometry(x, y, w, h);
1901 Clipboard & GuiApplication::clipboard()
1903 return d->clipboard_;
1907 Selection & GuiApplication::selection()
1909 return d->selection_;
1913 FontLoader & GuiApplication::fontLoader()
1915 return d->font_loader_;
1919 Toolbars const & GuiApplication::toolbars() const
1921 return d->toolbars_;
1925 Toolbars & GuiApplication::toolbars()
1927 return d->toolbars_;
1931 Menus const & GuiApplication::menus() const
1937 Menus & GuiApplication::menus()
1943 QList<int> GuiApplication::viewIds() const
1945 return d->views_.keys();
1949 ColorCache & GuiApplication::colorCache()
1951 return d->color_cache_;
1955 int GuiApplication::exec()
1957 // asynchronously handle batch commands. This event will be in
1958 // the event queue in front of other asynchronous events. Hence,
1959 // we can assume in the latter that the gui is setup already.
1960 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
1962 return QApplication::exec();
1966 void GuiApplication::exit(int status)
1968 QApplication::exit(status);
1972 void GuiApplication::setGuiLanguage()
1974 // Set the language defined by the user.
1977 QString const default_language = toqstr(Messages::defaultLanguage());
1978 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
1979 QLocale const default_locale(default_language);
1980 QLocale::setDefault(default_locale);
1982 // install translation file for Qt built-in dialogs
1983 QString const language_name = QString("qt_") + default_locale.name();
1985 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
1986 // Short-named translator can be loaded from a long name, but not the
1987 // opposite. Therefore, long name should be used without truncation.
1988 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
1989 if (!d->qt_trans_.load(language_name,
1990 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1991 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
1994 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
1998 switch (default_locale.language()) {
1999 case QLocale::Arabic :
2000 case QLocale::Hebrew :
2001 case QLocale::Persian :
2002 case QLocale::Urdu :
2003 setLayoutDirection(Qt::RightToLeft);
2006 setLayoutDirection(Qt::LeftToRight);
2011 void GuiApplication::execBatchCommands()
2016 if (!readUIFile(toqstr(lyxrc.ui_file)))
2017 // Gives some error box here.
2021 #if QT_VERSION > 0x040600
2022 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2024 // Create the global default menubar which is shown for the dialogs
2025 // and if no GuiView is visible.
2026 // This must be done after the session was recovered to know the "last files".
2027 d->global_menubar_ = new GlobalMenuBar();
2028 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2031 lyx::execBatchCommands();
2035 QAbstractItemModel * GuiApplication::languageModel()
2037 if (d->language_model_)
2038 return d->language_model_;
2040 QStandardItemModel * lang_model = new QStandardItemModel(this);
2041 lang_model->insertColumns(0, 3);
2043 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2044 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2045 Languages::const_iterator it = lyx::languages.begin();
2046 Languages::const_iterator end = lyx::languages.end();
2047 for (; it != end; ++it) {
2048 current_row = lang_model->rowCount();
2049 lang_model->insertRows(current_row, 1);
2050 QModelIndex pl_item = lang_model->index(current_row, 0);
2051 QModelIndex sp_item = lang_model->index(current_row, 1);
2052 QModelIndex th_item = lang_model->index(current_row, 2);
2053 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2054 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2055 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2056 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2057 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2058 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2059 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2060 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2061 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2062 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2064 d->language_model_ = new QSortFilterProxyModel(this);
2065 d->language_model_->setSourceModel(lang_model);
2066 #if QT_VERSION >= 0x040300
2067 d->language_model_->setSortLocaleAware(true);
2069 return d->language_model_;
2073 void GuiApplication::restoreGuiSession()
2075 if (!lyxrc.load_session)
2078 Session & session = theSession();
2079 LastOpenedSection::LastOpened const & lastopened =
2080 session.lastOpened().getfiles();
2082 validateCurrentView();
2084 FileName active_file;
2085 // do not add to the lastfile list since these files are restored from
2086 // last session, and should be already there (regular files), or should
2087 // not be added at all (help files).
2088 for (size_t i = 0; i < lastopened.size(); ++i) {
2089 FileName const & file_name = lastopened[i].file_name;
2090 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2091 && current_view_->documentBufferView() != 0)) {
2092 boost::crc_32_type crc;
2093 string const & fname = file_name.absFileName();
2094 crc = for_each(fname.begin(), fname.end(), crc);
2095 createView(crc.checksum());
2097 current_view_->loadDocument(file_name, false);
2099 if (lastopened[i].active)
2100 active_file = file_name;
2103 // Restore last active buffer
2104 Buffer * buffer = theBufferList().getBuffer(active_file);
2105 if (buffer && current_view_)
2106 current_view_->setBuffer(buffer);
2108 // clear this list to save a few bytes of RAM
2109 session.lastOpened().clear();
2113 QString const GuiApplication::romanFontName()
2116 font.setKerning(false);
2117 font.setStyleHint(QFont::Serif);
2118 font.setFamily("serif");
2120 return QFontInfo(font).family();
2124 QString const GuiApplication::sansFontName()
2127 font.setKerning(false);
2128 font.setStyleHint(QFont::SansSerif);
2129 font.setFamily("sans");
2131 return QFontInfo(font).family();
2135 QString const GuiApplication::typewriterFontName()
2138 font.setKerning(false);
2139 font.setStyleHint(QFont::TypeWriter);
2140 font.setFamily("monospace");
2142 return QFontInfo(font).family();
2146 void GuiApplication::handleRegularEvents()
2148 ForkedCallsController::handleCompletedProcesses();
2152 bool GuiApplication::event(QEvent * e)
2155 case QEvent::FileOpen: {
2156 // Open a file; this happens only on Mac OS X for now.
2158 // We do this asynchronously because on startup the batch
2159 // commands are not executed here yet and the gui is not ready
2161 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2162 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2163 processFuncRequestAsync(fr);
2168 return QApplication::event(e);
2173 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2176 return QApplication::notify(receiver, event);
2178 catch (ExceptionMessage const & e) {
2180 case ErrorException:
2182 setQuitOnLastWindowClosed(false);
2184 Alert::error(e.title_, e.details_);
2186 // Properly crash in debug mode in order to get a useful backtrace.
2189 // In release mode, try to exit gracefully.
2192 case BufferException: {
2193 if (!current_view_ || !current_view_->documentBufferView())
2195 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2196 docstring details = e.details_ + '\n';
2197 details += buf->emergencyWrite();
2198 theBufferList().release(buf);
2199 details += "\n" + _("The current document was closed.");
2200 Alert::error(e.title_, details);
2203 case WarningException:
2204 Alert::warning(e.title_, e.details_);
2208 catch (exception const & e) {
2209 docstring s = _("LyX has caught an exception, it will now "
2210 "attempt to save all unsaved documents and exit."
2212 s += from_ascii(e.what());
2213 Alert::error(_("Software exception Detected"), s);
2217 docstring s = _("LyX has caught some really weird exception, it will "
2218 "now attempt to save all unsaved documents and exit.");
2219 Alert::error(_("Software exception Detected"), s);
2227 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2229 QColor const & qcol = d->color_cache_.get(col);
2230 if (!qcol.isValid()) {
2236 rgbcol.r = qcol.red();
2237 rgbcol.g = qcol.green();
2238 rgbcol.b = qcol.blue();
2243 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2245 QColor const qcol(lcolor.getX11Name(col).c_str());
2246 if (!qcol.isValid()) {
2252 rgbcol.r = qcol.red();
2253 rgbcol.g = qcol.green();
2254 rgbcol.b = qcol.blue();
2259 string const GuiApplication::hexName(ColorCode col)
2261 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2265 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2267 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2268 d->socket_notifiers_[fd] = sn;
2269 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2273 void GuiApplication::socketDataReceived(int fd)
2275 d->socket_notifiers_[fd]->func_();
2279 void GuiApplication::unregisterSocketCallback(int fd)
2281 d->socket_notifiers_.take(fd)->setEnabled(false);
2285 void GuiApplication::commitData(QSessionManager & sm)
2287 /// The implementation is required to avoid an application exit
2288 /// when session state save is triggered by session manager.
2289 /// The default implementation sends a close event to all
2290 /// visible top level widgets when session managment allows
2292 /// We are changing that to close all wiew one by one.
2293 /// FIXME: verify if the default implementation is enough now.
2294 #ifdef QT_NO_SESSIONMANAGER
2296 #warning Qt is compiled without session manager
2298 #pragma message("warning: Qt is compiled without session manager")
2302 if (sm.allowsInteraction() && !closeAllViews())
2308 void GuiApplication::unregisterView(GuiView * gv)
2310 LASSERT(d->views_[gv->id()] == gv, /**/);
2311 d->views_.remove(gv->id());
2312 if (current_view_ == gv)
2317 bool GuiApplication::closeAllViews()
2319 if (d->views_.empty())
2322 // When a view/window was closed before without quitting LyX, there
2323 // are already entries in the lastOpened list.
2324 theSession().lastOpened().clear();
2326 QList<GuiView *> views = d->views_.values();
2327 foreach (GuiView * view, views) {
2328 if (!view->closeScheduled())
2337 GuiView & GuiApplication::view(int id) const
2339 LASSERT(d->views_.contains(id), /**/);
2340 return *d->views_.value(id);
2344 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2346 QList<GuiView *> views = d->views_.values();
2347 foreach (GuiView * view, views)
2348 view->hideDialog(name, inset);
2352 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2354 Buffer const * buffer_ = 0;
2355 QHash<int, GuiView *>::iterator end = d->views_.end();
2356 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2357 if (Buffer const * ptr = (*it)->updateInset(inset))
2364 bool GuiApplication::searchMenu(FuncRequest const & func,
2365 docstring_list & names) const
2367 return d->menus_.searchMenu(func, names);
2371 // Ensure that a file is read only once (prevents include loops)
2372 static QStringList uifiles;
2373 // store which ui files define Toolbars
2374 static QStringList toolbar_uifiles;
2377 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2388 LexerKeyword uitags[] = {
2389 { "format", ui_format },
2390 { "include", ui_include },
2391 { "menuset", ui_menuset },
2392 { "toolbars", ui_toolbars },
2393 { "toolbarset", ui_toolbarset }
2397 lex.setFile(ui_path);
2399 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2403 if (lyxerr.debugging(Debug::PARSER))
2404 lex.printTable(lyxerr);
2407 // format before introduction of format tag
2408 unsigned int format = 0;
2409 while (lex.isOK()) {
2410 int const status = lex.lex();
2412 // we have to do this check here, outside the switch,
2413 // because otherwise we would start reading include files,
2414 // e.g., if the first tag we hit was an include tag.
2415 if (status == ui_format)
2417 format = lex.getInteger();
2421 // this will trigger unless the first tag we hit is a format
2422 // tag, with the right format.
2423 if (format != LFUN_FORMAT)
2424 return FormatMismatch;
2427 case Lexer::LEX_FEOF:
2432 QString const file = toqstr(lex.getString());
2433 bool const success = readUIFile(file, true);
2435 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2442 d->menus_.read(lex);
2446 d->toolbars_.readToolbars(lex);
2450 d->toolbars_.readToolbarSettings(lex);
2451 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2455 if (!rtrim(lex.getString()).empty())
2456 lex.printError("LyX::ReadUIFile: "
2457 "Unknown menu tag: `$$Token'");
2459 LYXERR0("Error with status: " << status);
2465 return (error ? ReadError : ReadOK);
2469 bool GuiApplication::readUIFile(QString const & name, bool include)
2471 LYXERR(Debug::INIT, "About to read " << name << "...");
2475 ui_path = libFileSearch("ui", name, "inc");
2476 if (ui_path.empty())
2477 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2479 ui_path = libFileSearch("ui", name, "ui");
2482 if (ui_path.empty()) {
2483 static const QString defaultUIFile = "default";
2484 LYXERR(Debug::INIT, "Could not find " << name);
2486 Alert::warning(_("Could not find UI definition file"),
2487 bformat(_("Error while reading the included file\n%1$s\n"
2488 "Please check your installation."), qstring_to_ucs4(name)));
2491 if (name == defaultUIFile) {
2492 LYXERR(Debug::INIT, "Could not find default UI file!!");
2493 Alert::warning(_("Could not find default UI file"),
2494 _("LyX could not find the default UI file!\n"
2495 "Please check your installation."));
2498 Alert::warning(_("Could not find UI definition file"),
2499 bformat(_("Error while reading the configuration file\n%1$s\n"
2500 "Falling back to default.\n"
2501 "Please look under Tools>Preferences>User Interface and\n"
2502 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2503 return readUIFile(defaultUIFile, false);
2506 QString const uifile = toqstr(ui_path.absFileName());
2507 if (uifiles.contains(uifile)) {
2509 // We are reading again the top uifile so reset the safeguard:
2512 d->toolbars_.reset();
2514 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2515 << "Is this an include loop?");
2519 uifiles.push_back(uifile);
2521 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2523 ReturnValues retval = readUIFile(ui_path);
2525 if (retval == FormatMismatch) {
2526 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2527 FileName const tempfile = FileName::tempName("convert_ui");
2528 bool const success = prefs2prefs(ui_path, tempfile, true);
2530 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2531 " to format " << LFUN_FORMAT << ".");
2533 retval = readUIFile(tempfile);
2534 tempfile.removeFile();
2538 if (retval != ReadOK) {
2539 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2547 settings.beginGroup("ui_files");
2548 bool touched = false;
2549 for (int i = 0; i != uifiles.size(); ++i) {
2550 QFileInfo fi(uifiles[i]);
2551 QDateTime const date_value = fi.lastModified();
2552 QString const name_key = QString::number(i);
2553 // if an ui file which defines Toolbars has changed,
2554 // we have to reset the settings
2555 if (toolbar_uifiles.contains(uifiles[i])
2556 && (!settings.contains(name_key)
2557 || settings.value(name_key).toString() != uifiles[i]
2558 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2560 settings.setValue(name_key, uifiles[i]);
2561 settings.setValue(name_key + "/date", date_value);
2564 settings.endGroup();
2566 settings.remove("views");
2572 void GuiApplication::onLastWindowClosed()
2574 if (d->global_menubar_)
2575 d->global_menubar_->grabKeyboard();
2579 void GuiApplication::startLongOperation() {
2580 d->key_checker_.start();
2584 bool GuiApplication::longOperationCancelled() {
2585 return d->key_checker_.pressed();
2589 void GuiApplication::stopLongOperation() {
2590 d->key_checker_.stop();
2594 ////////////////////////////////////////////////////////////////////////
2596 // X11 specific stuff goes here...
2599 bool GuiApplication::x11EventFilter(XEvent * xev)
2604 switch (xev->type) {
2605 case SelectionRequest: {
2606 if (xev->xselectionrequest.selection != XA_PRIMARY)
2608 LYXERR(Debug::SELECTION, "X requested selection.");
2609 BufferView * bv = current_view_->currentBufferView();
2611 docstring const sel = bv->requestSelection();
2613 d->selection_.put(sel);
2617 case SelectionClear: {
2618 if (xev->xselectionclear.selection != XA_PRIMARY)
2620 LYXERR(Debug::SELECTION, "Lost selection.");
2621 BufferView * bv = current_view_->currentBufferView();
2623 bv->clearSelection();
2631 } // namespace frontend
2634 void hideDialogs(std::string const & name, Inset * inset)
2637 frontend::guiApp->hideDialogs(name, inset);
2641 ////////////////////////////////////////////////////////////////////
2645 ////////////////////////////////////////////////////////////////////
2647 frontend::FontLoader & theFontLoader()
2649 LASSERT(frontend::guiApp, /**/);
2650 return frontend::guiApp->fontLoader();
2654 frontend::FontMetrics const & theFontMetrics(Font const & f)
2656 return theFontMetrics(f.fontInfo());
2660 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2662 LASSERT(frontend::guiApp, /**/);
2663 return frontend::guiApp->fontLoader().metrics(f);
2667 ////////////////////////////////////////////////////////////////////
2671 ////////////////////////////////////////////////////////////////////
2673 frontend::Clipboard & theClipboard()
2675 LASSERT(frontend::guiApp, /**/);
2676 return frontend::guiApp->clipboard();
2680 frontend::Selection & theSelection()
2682 LASSERT(frontend::guiApp, /**/);
2683 return frontend::guiApp->selection();
2689 #include "moc_GuiApplication.cpp"