2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ColorCache.h"
19 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferView.h"
39 #include "FuncRequest.h"
40 #include "FuncStatus.h"
41 #include "GuiWorkArea.h"
45 #include "LaTeXPackages.h"
48 #include "LyXAction.h"
50 #include "Paragraph.h"
53 #include "SpellChecker.h"
54 #include "Thesaurus.h"
57 #include "support/convert.h"
58 #include "support/debug.h"
59 #include "support/ExceptionMessage.h"
60 #include "support/FileName.h"
61 #include "support/filetools.h"
62 #include "support/foreach.h"
63 #include "support/ForkedCalls.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/lyxalgo.h" // sorted
68 #include "support/Messages.h"
69 #include "support/os.h"
70 #include "support/Package.h"
71 #include "support/Path.h"
72 #include "support/Systemcall.h"
75 #include "support/AppleScript.h"
76 #include "support/linkback/LinkBackProxy.h"
87 #include <QFileOpenEvent>
91 #include <QImageReader>
94 #include <QLibraryInfo>
96 #include <QMacPasteboardMime>
101 #include <QPixmapCache>
103 #include <QSessionManager>
105 #include <QShowEvent>
106 #include <QSocketNotifier>
107 #include <QSortFilterProxyModel>
108 #include <QStandardItemModel>
109 #include <QTextCodec>
111 #include <QTranslator>
112 #if QT_VERSION >= 0x040400
113 #include <QThreadPool>
118 #include <X11/Xatom.h>
119 #include <X11/Xlib.h>
125 #include <QWindowsMime>
132 #include "support/bind.h"
133 #include <boost/crc.hpp>
140 using namespace lyx::support;
143 static void initializeResources()
145 static bool initialized = false;
147 Q_INIT_RESOURCE(Resources);
155 frontend::Application * createApplication(int & argc, char * argv[])
158 // prune -geometry argument(s) by shifting
159 // the following ones 2 places down.
160 for (int i = 0 ; i < argc ; ++i) {
161 if (strcmp(argv[i], "-geometry") == 0) {
162 int const remove = (i+1) < argc ? 2 : 1;
164 for (int j = i; j < argc; ++j)
165 argv[j] = argv[j + remove];
170 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
171 // I'd rather do that in the constructor, but I do not think that
172 // the palette is accessible there.
173 guiApp->colorCache().setPalette(guiApp->palette());
180 /// Return the list of loadable formats.
181 vector<string> loadableImageFormats()
185 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
187 LYXERR(Debug::GRAPHICS,
188 "\nThe image loader can load the following directly:\n");
190 if (qt_formats.empty())
191 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
193 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
195 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
197 string ext = ascii_lowercase((const char *) *it);
208 ////////////////////////////////////////////////////////////////////////
210 // Icon loading support code
212 ////////////////////////////////////////////////////////////////////////
222 bool operator<(PngMap const & lhs, PngMap const & rhs)
224 return lhs.key < rhs.key;
230 CompareKey(QString const & name) : name_(name) {}
231 bool operator()(PngMap const & other) const { return other.key == name_; }
237 // this must be sorted alphabetically
238 // Upper case comes before lower case
239 PngMap sorted_png_map[] = {
240 { "Bumpeq", "bumpeq2" },
243 { "Delta", "delta2" },
244 { "Diamond", "diamond2" },
245 { "Downarrow", "downarrow2" },
246 { "Gamma", "gamma2" },
247 { "Lambda", "lambda2" },
248 { "Leftarrow", "leftarrow2" },
249 { "Leftrightarrow", "leftrightarrow2" },
250 { "Longleftarrow", "longleftarrow2" },
251 { "Longleftrightarrow", "longleftrightarrow2" },
252 { "Longrightarrow", "longrightarrow2" },
253 { "Omega", "omega2" },
257 { "Rightarrow", "rightarrow2" },
258 { "Sigma", "sigma2" },
259 { "Subset", "subset2" },
260 { "Supset", "supset2" },
261 { "Theta", "theta2" },
262 { "Uparrow", "uparrow2" },
263 { "Updownarrow", "updownarrow2" },
264 { "Upsilon", "upsilon2" },
265 { "Vdash", "vdash3" },
268 { "nLeftarrow", "nleftarrow2" },
269 { "nLeftrightarrow", "nleftrightarrow2" },
270 { "nRightarrow", "nrightarrow2" },
271 { "nVDash", "nvdash3" },
272 { "nvDash", "nvdash2" },
273 { "textrm \\AA", "textrm_AA"},
274 { "textrm \\O", "textrm_O"},
275 { "vDash", "vdash2" }
278 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
281 QString findPng(QString const & name)
283 PngMap const * const begin = sorted_png_map;
284 PngMap const * const end = begin + nr_sorted_png_map;
285 LASSERT(sorted(begin, end), /**/);
287 PngMap const * const it = find_if(begin, end, CompareKey(name));
291 png_name = it->value;
294 png_name.replace('_', "underscore");
295 png_name.replace(' ', '_');
297 // This way we can have "math-delim { }" on the toolbar.
298 png_name.replace('(', "lparen");
299 png_name.replace(')', "rparen");
300 png_name.replace('[', "lbracket");
301 png_name.replace(']', "rbracket");
302 png_name.replace('{', "lbrace");
303 png_name.replace('}', "rbrace");
304 png_name.replace('|', "bars");
305 png_name.replace(',', "thinspace");
306 png_name.replace(':', "mediumspace");
307 png_name.replace(';', "thickspace");
308 png_name.replace('!', "negthinspace");
311 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
312 << "Looking for math PNG called \"" << png_name << '"');
319 QString iconName(FuncRequest const & f, bool unknown)
321 initializeResources();
325 switch (f.action()) {
326 case LFUN_MATH_INSERT:
327 if (!f.argument().empty()) {
329 name1 = findPng(toqstr(f.argument()).mid(1));
332 case LFUN_MATH_DELIM:
333 case LFUN_MATH_BIGDELIM:
335 name1 = findPng(toqstr(f.argument()));
339 name1 = toqstr(f.argument());
341 case LFUN_COMMAND_ALTERNATIVES: {
342 // use the first of the alternative commands
344 docstring dummy = split(f.argument(), firstcom, ';');
345 name1 = toqstr(firstcom);
346 // FIXME: we should rename the icons to tabular-xxx instead of
347 // "tabular-feature-xxx"
348 name1.replace("inset-modify tabular", "tabular-feature");
349 name1.replace(' ', '_');
352 case LFUN_INSET_MODIFY: {
353 // FIXME: we should rename the icons to tabular-xxx instead of
354 // "tabular-feature-xxx" and generalize this naming to all
355 // insets, not to tabular using ones.
357 string const command = split(to_utf8(f.argument()), inset_name, ' ');
358 if (insetCode(inset_name) == TABULAR_CODE) {
359 name1 = "tabular-feature "+ toqstr(command);
360 name1.replace(' ', '_');
365 name2 = toqstr(lyxaction.getActionName(f.action()));
368 if (!f.argument().empty()) {
369 name1 = name2 + ' ' + toqstr(f.argument());
370 name1.replace(' ', '_');
371 name1.replace('\\', "backslash");
375 QStringList imagedirs;
376 imagedirs << "images/" << "images/ipa/";
377 for (int i = 0; i < imagedirs.size(); ++i) {
378 QString imagedir = imagedirs.at(i) + path;
379 FileName fname = imageLibFileSearch(imagedir, name1, "png");
381 return toqstr(fname.absFileName());
383 fname = imageLibFileSearch(imagedir, name2, "png");
385 return toqstr(fname.absFileName());
388 path = ":/images/" + path;
391 LYXERR0("Directory " << path << " not found in resource!");
395 if (res.exists(name1))
399 if (res.exists(name2))
402 LYXERR(Debug::GUI, "Cannot find icon with filename "
403 << "\"" << name1 << "\""
405 << "\"" << name2 << "\""
407 << lyxaction.getActionName(f.action())
408 << '(' << to_utf8(f.argument()) << ")\"");
411 QString imagedir = "images/";
412 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
414 return toqstr(fname.absFileName());
415 return QString(":/images/unknown.png");
421 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
424 QString imagedir = path;
425 FileName fname = imageLibFileSearch(imagedir, name, ext);
426 QString path1 = toqstr(fname.absFileName());
427 QString path2 = ":/" + path + name + "." + ext;
429 if (pixmap.load(path1)) {
432 else if (pixmap.load(path2)) {
436 LYXERR0("Cannot load pixmap \""
437 << path << name << '.' << ext
438 << "\", please verify resource system!");
443 QIcon getIcon(FuncRequest const & f, bool unknown)
445 QString icon = iconName(f, unknown);
449 //LYXERR(Debug::GUI, "Found icon: " << icon);
451 if (!pm.load(icon)) {
452 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
460 ////////////////////////////////////////////////////////////////////////
462 // LyX server support code.
464 ////////////////////////////////////////////////////////////////////////
466 class SocketNotifier : public QSocketNotifier
469 /// connect a connection notification from the LyXServerSocket
470 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
471 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
475 /// The callback function
476 Application::SocketCallback func_;
480 ////////////////////////////////////////////////////////////////////////
482 // Mac specific stuff goes here...
484 ////////////////////////////////////////////////////////////////////////
486 class MenuTranslator : public QTranslator
489 MenuTranslator(QObject * parent)
490 : QTranslator(parent)
493 QString translate(const char * /*context*/,
494 const char * sourceText,
495 const char * /*comment*/ = 0)
497 string const s = sourceText;
498 if (s == N_("About %1") || s == N_("Preferences")
499 || s == N_("Reconfigure") || s == N_("Quit %1"))
506 class GlobalMenuBar : public QMenuBar
510 GlobalMenuBar() : QMenuBar(0) {}
513 bool event(QEvent * e)
515 if (e->type() == QEvent::ShortcutOverride) {
516 // && activeWindow() == 0) {
517 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
519 setKeySymbol(&sym, ke);
520 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
529 // QMacPasteboardMimeGraphics can only be compiled on Mac.
531 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
534 QMacPasteboardMimeGraphics()
535 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
538 QString convertorName() { return "Graphics"; }
540 QString flavorFor(QString const & mime)
542 LYXERR(Debug::ACTION, "flavorFor " << mime);
543 if (mime == pdfMimeType())
544 return QLatin1String("com.adobe.pdf");
548 QString mimeFor(QString flav)
550 LYXERR(Debug::ACTION, "mimeFor " << flav);
551 if (flav == QLatin1String("com.adobe.pdf"))
552 return pdfMimeType();
556 bool canConvert(QString const & mime, QString flav)
558 return mimeFor(flav) == mime;
561 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
565 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
569 QList<QByteArray> convertFromMime(QString const & /*mime*/,
570 QVariant data, QString /*flav*/)
572 QList<QByteArray> ret;
573 ret.append(data.toByteArray());
579 ///////////////////////////////////////////////////////////////
581 // You can find more platform specific stuff at the end of this file...
583 ///////////////////////////////////////////////////////////////
585 ////////////////////////////////////////////////////////////////////////
586 // Windows specific stuff goes here...
589 // QWindowsMimeMetafile can only be compiled on Windows.
591 static FORMATETC cfFromMime(QString const & mimetype)
594 if (mimetype == emfMimeType()) {
595 formatetc.cfFormat = CF_ENHMETAFILE;
596 formatetc.tymed = TYMED_ENHMF;
597 } else if (mimetype == wmfMimeType()) {
598 formatetc.cfFormat = CF_METAFILEPICT;
599 formatetc.tymed = TYMED_MFPICT;
602 formatetc.dwAspect = DVASPECT_CONTENT;
603 formatetc.lindex = -1;
608 class QWindowsMimeMetafile : public QWindowsMime {
610 QWindowsMimeMetafile() {}
612 bool canConvertFromMime(FORMATETC const & formatetc,
613 QMimeData const * mimedata) const
618 bool canConvertToMime(QString const & mimetype,
619 IDataObject * pDataObj) const
621 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
623 FORMATETC formatetc = cfFromMime(mimetype);
624 return pDataObj->QueryGetData(&formatetc) == S_OK;
627 bool convertFromMime(FORMATETC const & formatetc,
628 const QMimeData * mimedata, STGMEDIUM * pmedium) const
633 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
634 QVariant::Type preferredType) const
637 if (!canConvertToMime(mimetype, pDataObj))
640 FORMATETC formatetc = cfFromMime(mimetype);
642 if (pDataObj->GetData(&formatetc, &s) != S_OK)
646 if (s.tymed == TYMED_ENHMF) {
647 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
648 data.resize(dataSize);
649 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
650 (LPBYTE)data.data());
651 } else if (s.tymed == TYMED_MFPICT) {
652 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
653 data.resize(dataSize);
654 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
655 (LPBYTE)data.data());
658 ReleaseStgMedium(&s);
664 QVector<FORMATETC> formatsForMime(QString const & mimetype,
665 QMimeData const * mimedata) const
667 QVector<FORMATETC> formats;
668 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
669 formats += cfFromMime(mimetype);
673 QString mimeForFormat(FORMATETC const & formatetc) const
675 switch (formatetc.cfFormat) {
677 return emfMimeType();
678 case CF_METAFILEPICT:
679 return wmfMimeType();
688 /// Allows to check whether ESC was pressed during a long operation
689 class KeyChecker : public QObject {
694 KeyChecker() : pressed_(false), started_(false) {}
697 QCoreApplication::instance()->installEventFilter(this);
702 QCoreApplication::instance()->removeEventFilter(this);
706 QCoreApplication::processEvents();
709 bool started() const {
712 bool eventFilter(QObject *obj, QEvent *event) {
713 LYXERR(Debug::ACTION, "Event Type: " << event->type());
714 switch (event->type()) {
718 return QObject::eventFilter(obj, event);
720 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
721 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
729 ////////////////////////////////////////////////////////////////////////
730 // GuiApplication::Private definition and implementation.
731 ////////////////////////////////////////////////////////////////////////
733 struct GuiApplication::Private
735 Private(): language_model_(0), meta_fake_bit(NoModifier),
739 /// WMF Mime handler for Windows clipboard.
740 wmf_mime_ = new QWindowsMimeMetafile();
742 initKeySequences(&theTopLevelKeymap());
745 void initKeySequences(KeyMap * kb)
747 keyseq = KeySequence(kb, kb);
748 cancel_meta_seq = KeySequence(kb, kb);
752 QSortFilterProxyModel * language_model_;
754 GuiClipboard clipboard_;
756 GuiSelection selection_;
758 FontLoader font_loader_;
760 ColorCache color_cache_;
762 QTranslator qt_trans_;
764 QHash<int, SocketNotifier *> socket_notifiers_;
768 /// The global instance
771 /// this timer is used for any regular events one wants to
772 /// perform. at present it is used to check if forked processes
774 QTimer general_timer_;
776 /// delayed FuncRequests
777 std::queue<FuncRequest> func_request_queue_;
782 KeySequence cancel_meta_seq;
784 KeyModifier meta_fake_bit;
786 /// Multiple views container.
788 * Warning: This must not be a smart pointer as the destruction of the
789 * object is handled by Qt when the view is closed
790 * \sa Qt::WA_DeleteOnClose attribute.
792 QHash<int, GuiView *> views_;
794 /// Only used on mac.
795 GlobalMenuBar * global_menubar_;
798 /// Linkback mime handler for MacOSX.
799 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
803 /// WMF Mime handler for Windows clipboard.
804 QWindowsMimeMetafile * wmf_mime_;
807 /// Allows to check whether ESC was pressed during a long operation
808 KeyChecker key_checker_;
812 GuiApplication * guiApp;
814 GuiApplication::~GuiApplication()
817 closeAllLinkBackLinks();
823 GuiApplication::GuiApplication(int & argc, char ** argv)
824 : QApplication(argc, argv), current_view_(0),
825 d(new GuiApplication::Private)
827 QString app_name = "LyX";
828 QCoreApplication::setOrganizationName(app_name);
829 QCoreApplication::setOrganizationDomain("lyx.org");
830 QCoreApplication::setApplicationName(lyx_package);
832 // Install translator for GUI elements.
833 installTranslator(&d->qt_trans_);
835 // FIXME: quitOnLastWindowClosed is true by default. We should have a
836 // lyxrc setting for this in order to let the application stay resident.
837 // But then we need some kind of dock icon, at least on Windows.
839 if (lyxrc.quit_on_last_window_closed)
840 setQuitOnLastWindowClosed(false);
843 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
844 // seems to be the default case for applications like LyX.
845 setQuitOnLastWindowClosed(false);
846 // This allows to translate the strings that appear in the LyX menu.
847 /// A translator suitable for the entries in the LyX menu.
848 /// Only needed with Qt/Mac.
849 installTranslator(new MenuTranslator(this));
855 // doubleClickInterval() is 400 ms on X11 which is just too long.
856 // On Windows and Mac OS X, the operating system's value is used.
857 // On Microsoft Windows, calling this function sets the double
858 // click interval for all applications. So we don't!
859 QApplication::setDoubleClickInterval(300);
862 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
864 // needs to be done before reading lyxrc
866 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
870 // Set the cache to 5120 kilobytes which corresponds to screen size of
871 // 1280 by 1024 pixels with a color depth of 32 bits.
872 QPixmapCache::setCacheLimit(5120);
874 // Initialize RC Fonts
875 if (lyxrc.roman_font_name.empty())
876 lyxrc.roman_font_name = fromqstr(romanFontName());
878 if (lyxrc.sans_font_name.empty())
879 lyxrc.sans_font_name = fromqstr(sansFontName());
881 if (lyxrc.typewriter_font_name.empty())
882 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
884 d->general_timer_.setInterval(500);
885 connect(&d->general_timer_, SIGNAL(timeout()),
886 this, SLOT(handleRegularEvents()));
887 d->general_timer_.start();
889 #if QT_VERSION >= 0x040400
890 // maxThreadCount() defaults in general to 2 on single or dual-processor.
891 // This is clearly not enough in a time where we use threads for
892 // document preview and/or export. 20 should be OK.
893 QThreadPool::globalInstance()->setMaxThreadCount(20);
898 GuiApplication * theGuiApp()
900 return dynamic_cast<GuiApplication *>(theApp());
904 void GuiApplication::clearSession()
911 docstring Application::iconName(FuncRequest const & f, bool unknown)
913 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
917 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
922 BufferView * doc_bv = 0;
924 if (cmd.action() == LFUN_NOACTION) {
925 status.message(from_utf8(N_("Nothing to do")));
926 status.setEnabled(false);
929 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
930 status.setUnknown(true);
931 status.message(from_utf8(N_("Unknown action")));
932 status.setEnabled(false);
935 // Does the GuiApplication know something?
936 else if (getStatus(cmd, status)) { }
938 // If we do not have a GuiView, then other functions are disabled
939 else if (!current_view_)
940 status.setEnabled(false);
942 // Does the GuiView know something?
943 else if (current_view_->getStatus(cmd, status)) { }
945 // In LyX/Mac, when a dialog is open, the menus of the
946 // application can still be accessed without giving focus to
947 // the main window. In this case, we want to disable the menu
948 // entries that are buffer or view-related.
949 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
951 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
952 status.setEnabled(false);
955 // If we do not have a BufferView, then other functions are disabled
956 else if (!(bv = current_view_->currentBufferView()))
957 status.setEnabled(false);
959 // Does the current BufferView know something?
960 else if (bv->getStatus(cmd, status)) { }
962 // Does the current Buffer know something?
963 else if (bv->buffer().getStatus(cmd, status)) { }
965 // If we do not have a document BufferView, different from the
966 // current BufferView, then other functions are disabled
967 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
968 status.setEnabled(false);
970 // Does the document Buffer know something?
971 else if (doc_bv->buffer().getStatus(cmd, status)) { }
974 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
975 status.message(from_utf8(N_("Command not handled")));
976 status.setEnabled(false);
979 // the default error message if we disable the command
980 if (!status.enabled() && status.message().empty())
981 status.message(from_utf8(N_("Command disabled")));
987 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
989 // I would really like to avoid having this switch and rather try to
990 // encode this in the function itself.
991 // -- And I'd rather let an inset decide which LFUNs it is willing
992 // to handle (Andre')
994 switch (cmd.action()) {
996 // This could be used for the no-GUI version. The GUI version is handled in
997 // GuiView::getStatus(). See above.
999 case LFUN_BUFFER_WRITE:
1000 case LFUN_BUFFER_WRITE_AS: {
1001 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1002 enable = b && (b->isUnnamed() || !b->isClean());
1007 case LFUN_BOOKMARK_GOTO: {
1008 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1009 enable = theSession().bookmarks().isValid(num);
1013 case LFUN_BOOKMARK_CLEAR:
1014 enable = theSession().bookmarks().hasValid();
1017 // this one is difficult to get right. As a half-baked
1018 // solution, we consider only the first action of the sequence
1019 case LFUN_COMMAND_SEQUENCE: {
1020 // argument contains ';'-terminated commands
1021 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1022 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1023 func.setOrigin(cmd.origin());
1024 flag = getStatus(func);
1028 // we want to check if at least one of these is enabled
1029 case LFUN_COMMAND_ALTERNATIVES: {
1030 // argument contains ';'-terminated commands
1031 string arg = to_utf8(cmd.argument());
1032 while (!arg.empty()) {
1034 arg = split(arg, first, ';');
1035 FuncRequest func(lyxaction.lookupFunc(first));
1036 func.setOrigin(cmd.origin());
1037 flag = getStatus(func);
1038 // if this one is enabled, the whole thing is
1047 string name = to_utf8(cmd.argument());
1048 if (theTopLevelCmdDef().lock(name, func)) {
1049 func.setOrigin(cmd.origin());
1050 flag = getStatus(func);
1051 theTopLevelCmdDef().release(name);
1053 // catch recursion or unknown command
1054 // definition. all operations until the
1055 // recursion or unknown command definition
1056 // occurs are performed, so set the state to
1063 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1065 case LFUN_PREFERENCES_SAVE:
1066 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1067 case LFUN_DEBUG_LEVEL_SET:
1068 // these are handled in our dispatch()
1071 case LFUN_WINDOW_CLOSE:
1072 enable = d->views_.size() > 0;
1075 case LFUN_BUFFER_NEW:
1076 case LFUN_BUFFER_NEW_TEMPLATE:
1077 case LFUN_FILE_OPEN:
1078 case LFUN_HELP_OPEN:
1079 case LFUN_SCREEN_FONT_UPDATE:
1080 case LFUN_SET_COLOR:
1081 case LFUN_WINDOW_NEW:
1083 case LFUN_LYXRC_APPLY:
1084 case LFUN_COMMAND_PREFIX:
1086 case LFUN_META_PREFIX:
1087 case LFUN_RECONFIGURE:
1088 case LFUN_SERVER_GET_FILENAME:
1089 case LFUN_SERVER_NOTIFY:
1093 case LFUN_BUFFER_FORALL: {
1094 if (!currentView() || !currentView()->currentBufferView() || !¤tView()->currentBufferView()->buffer()) {
1095 flag.message(from_utf8(N_("Command not allowed without any visible document in the active window")));
1096 flag.setEnabled(false);
1107 flag.setEnabled(false);
1111 /// make a post-dispatch status message
1112 static docstring makeDispatchMessage(docstring const & msg,
1113 FuncRequest const & cmd)
1115 const bool verbose = (cmd.origin() == FuncRequest::MENU
1116 || cmd.origin() == FuncRequest::TOOLBAR
1117 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1119 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1120 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1124 docstring dispatch_msg = msg;
1125 if (!dispatch_msg.empty())
1126 dispatch_msg += ' ';
1128 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1130 bool argsadded = false;
1132 if (!cmd.argument().empty()) {
1133 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1134 comname += ' ' + cmd.argument();
1138 docstring const shortcuts = theTopLevelKeymap().
1139 printBindings(cmd, KeySequence::ForGui);
1141 if (!shortcuts.empty())
1142 comname += ": " + shortcuts;
1143 else if (!argsadded && !cmd.argument().empty())
1144 comname += ' ' + cmd.argument();
1146 if (!comname.empty()) {
1147 comname = rtrim(comname);
1148 dispatch_msg += '(' + rtrim(comname) + ')';
1150 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1151 return dispatch_msg;
1155 void GuiApplication::dispatch(FuncRequest const & cmd)
1157 Buffer * buffer = 0;
1158 if (current_view_ && current_view_->currentBufferView()) {
1159 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1160 buffer = ¤t_view_->currentBufferView()->buffer();
1162 buffer->undo().beginUndoGroup();
1166 // redraw the screen at the end (first of the two drawing steps).
1167 // This is done unless explicitly requested otherwise
1168 dr.screenUpdate(Update::FitCursor);
1170 updateCurrentView(cmd, dr);
1172 // the buffer may have been closed by one action
1173 if (theBufferList().isLoaded(buffer))
1174 buffer->undo().endUndoGroup();
1178 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1183 BufferView * bv = current_view_->currentBufferView();
1185 if (dr.needBufferUpdate()) {
1186 bv->cursor().clearBufferUpdate();
1187 bv->buffer().updateBuffer();
1189 // BufferView::update() updates the ViewMetricsInfo and
1190 // also initializes the position cache for all insets in
1191 // (at least partially) visible top-level paragraphs.
1192 // We will redraw the screen only if needed.
1193 bv->processUpdateFlags(dr.screenUpdate());
1195 // Do we have a selection?
1196 theSelection().haveSelection(bv->cursor().selection());
1199 current_view_->restartCursor();
1201 if (dr.needMessageUpdate()) {
1202 // Some messages may already be translated, so we cannot use _()
1203 current_view_->message(makeDispatchMessage(
1204 translateIfPossible(dr.message()), cmd));
1209 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1210 bool switchToBuffer)
1212 if (!theSession().bookmarks().isValid(idx))
1214 BookmarksSection::Bookmark const & bm =
1215 theSession().bookmarks().bookmark(idx);
1216 LASSERT(!bm.filename.empty(), /**/);
1217 string const file = bm.filename.absFileName();
1218 // if the file is not opened, open it.
1219 if (!theBufferList().exists(bm.filename)) {
1221 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1225 // open may fail, so we need to test it again
1226 if (!theBufferList().exists(bm.filename))
1229 // bm can be changed when saving
1230 BookmarksSection::Bookmark tmp = bm;
1232 // Special case idx == 0 used for back-from-back jump navigation
1234 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1236 // if the current buffer is not that one, switch to it.
1237 BufferView * doc_bv = current_view_ ?
1238 current_view_->documentBufferView() : 0;
1239 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1240 if (switchToBuffer) {
1241 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1244 doc_bv = current_view_->documentBufferView();
1249 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1250 if (!doc_bv->moveToPosition(
1251 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1258 // Cursor jump succeeded!
1259 Cursor const & cur = doc_bv->cursor();
1260 pit_type new_pit = cur.pit();
1261 pos_type new_pos = cur.pos();
1262 int new_id = cur.paragraph().id();
1264 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1265 // see http://www.lyx.org/trac/ticket/3092
1266 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1267 || bm.top_id != new_id) {
1268 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1269 new_pit, new_pos, new_id);
1273 // This function runs "configure" and then rereads lyx.defaults to
1274 // reconfigure the automatic settings.
1275 void GuiApplication::reconfigure(string const & option)
1277 // emit message signal.
1279 current_view_->message(_("Running configure..."));
1281 // Run configure in user lyx directory
1282 PathChanger p(package().user_support());
1283 string configure_command = package().configure_command();
1284 configure_command += option;
1286 int const ret = one.startscript(Systemcall::Wait, configure_command);
1288 // emit message signal.
1290 current_view_->message(_("Reloading configuration..."));
1291 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1292 // Re-read packages.lst
1293 LaTeXPackages::getAvailable();
1296 Alert::information(_("System reconfiguration failed"),
1297 _("The system reconfiguration has failed.\n"
1298 "Default textclass is used but LyX may\n"
1299 "not be able to work properly.\n"
1300 "Please reconfigure again if needed."));
1302 Alert::information(_("System reconfigured"),
1303 _("The system has been reconfigured.\n"
1304 "You need to restart LyX to make use of any\n"
1305 "updated document class specifications."));
1308 void GuiApplication::validateCurrentView()
1310 if (!d->views_.empty() && !current_view_) {
1311 // currently at least one view exists but no view has the focus.
1312 // choose the last view to make it current.
1313 // a view without any open document is preferred.
1314 GuiView * candidate = 0;
1315 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1316 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1317 for (; it != end; ++it) {
1319 if (!candidate->documentBufferView())
1322 setCurrentView(candidate);
1326 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1328 string const argument = to_utf8(cmd.argument());
1329 FuncCode const action = cmd.action();
1331 LYXERR(Debug::ACTION, "cmd: " << cmd);
1333 // we have not done anything wrong yet.
1336 FuncStatus const flag = getStatus(cmd);
1337 if (!flag.enabled()) {
1338 // We cannot use this function here
1339 LYXERR(Debug::ACTION, "action "
1340 << lyxaction.getActionName(action)
1341 << " [" << action << "] is disabled at this location");
1342 dr.setMessage(flag.message());
1344 dr.dispatched(false);
1345 dr.screenUpdate(Update::None);
1346 dr.clearBufferUpdate();
1350 if (cmd.origin() == FuncRequest::LYXSERVER) {
1351 if (current_view_ && current_view_->currentBufferView())
1352 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1353 // we will also need to redraw the screen at the end
1354 dr.screenUpdate(Update::FitCursor);
1357 // Assumes that the action will be dispatched.
1358 dr.dispatched(true);
1360 switch (cmd.action()) {
1362 case LFUN_WINDOW_NEW:
1363 createView(toqstr(cmd.argument()));
1366 case LFUN_WINDOW_CLOSE:
1367 // update bookmark pit of the current buffer before window close
1368 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1369 gotoBookmark(i+1, false, false);
1370 // clear the last opened list, because
1371 // maybe this will end the session
1372 theSession().lastOpened().clear();
1373 // check for valid current_view_
1374 validateCurrentView();
1376 current_view_->closeScheduled();
1380 // quitting is triggered by the gui code
1381 // (leaving the event loop).
1383 current_view_->message(from_utf8(N_("Exiting.")));
1384 if (closeAllViews())
1388 case LFUN_SCREEN_FONT_UPDATE: {
1389 // handle the screen font changes.
1390 d->font_loader_.update();
1391 // Backup current_view_
1392 GuiView * view = current_view_;
1393 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1394 // to skip the refresh.
1396 theBufferList().changed(false);
1397 // Restore current_view_
1398 current_view_ = view;
1402 case LFUN_BUFFER_NEW:
1403 validateCurrentView();
1404 if (d->views_.empty()
1405 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1406 createView(QString(), false); // keep hidden
1407 current_view_->newDocument(to_utf8(cmd.argument()), false);
1408 current_view_->show();
1409 setActiveWindow(current_view_);
1411 current_view_->newDocument(to_utf8(cmd.argument()), false);
1415 case LFUN_BUFFER_NEW_TEMPLATE:
1416 validateCurrentView();
1417 if (d->views_.empty()
1418 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1420 current_view_->newDocument(to_utf8(cmd.argument()), true);
1421 if (!current_view_->documentBufferView())
1422 current_view_->close();
1424 current_view_->newDocument(to_utf8(cmd.argument()), true);
1428 case LFUN_FILE_OPEN: {
1429 validateCurrentView();
1430 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1431 string const fname = to_utf8(cmd.argument());
1432 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1433 && current_view_->documentBufferView() != 0)) {
1434 // We want the ui session to be saved per document and not per
1435 // window number. The filename crc is a good enough identifier.
1436 boost::crc_32_type crc;
1437 crc = for_each(fname.begin(), fname.end(), crc);
1438 createView(crc.checksum());
1439 current_view_->openDocument(fname);
1440 if (current_view_ && !current_view_->documentBufferView())
1441 current_view_->close();
1443 current_view_->openDocument(fname);
1447 case LFUN_HELP_OPEN: {
1448 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1449 if (current_view_ == 0)
1451 string const arg = to_utf8(cmd.argument());
1453 current_view_->message(_("Missing argument"));
1456 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1458 fname = i18nLibFileSearch("examples", arg, "lyx");
1460 if (fname.empty()) {
1461 lyxerr << "LyX: unable to find documentation file `"
1462 << arg << "'. Bad installation?" << endl;
1465 current_view_->message(bformat(_("Opening help file %1$s..."),
1466 makeDisplayPath(fname.absFileName())));
1467 Buffer * buf = current_view_->loadDocument(fname, false);
1469 #ifndef DEVEL_VERSION
1471 buf->setReadonly(true);
1478 case LFUN_SET_COLOR: {
1480 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1481 if (lyx_name.empty() || x11_name.empty()) {
1483 current_view_->message(
1484 _("Syntax: set-color <lyx_name> <x11_name>"));
1489 // FIXME: The graphics cache no longer has a changeDisplay method.
1490 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1491 bool const graphicsbg_changed =
1492 lyx_name == graphicsbg && x11_name != graphicsbg;
1493 if (graphicsbg_changed)
1494 graphics::GCache::get().changeDisplay(true);
1497 if (!lcolor.setColor(lyx_name, x11_name)) {
1499 current_view_->message(
1500 bformat(_("Set-color \"%1$s\" failed "
1501 "- color is undefined or "
1502 "may not be redefined"),
1503 from_utf8(lyx_name)));
1506 // Make sure we don't keep old colors in cache.
1507 d->color_cache_.clear();
1511 case LFUN_LYXRC_APPLY: {
1512 // reset active key sequences, since the bindings
1513 // are updated (bug 6064)
1515 LyXRC const lyxrc_orig = lyxrc;
1517 istringstream ss(to_utf8(cmd.argument()));
1518 bool const success = lyxrc.read(ss);
1521 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1522 << "Unable to read lyxrc data"
1527 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1533 case LFUN_COMMAND_PREFIX:
1534 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1539 d->meta_fake_bit = NoModifier;
1540 GuiView * gv = currentView();
1541 if (gv && gv->currentBufferView())
1542 // cancel any selection
1543 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1544 dr.setMessage(from_ascii(N_("Cancel")));
1547 case LFUN_META_PREFIX:
1548 d->meta_fake_bit = AltModifier;
1549 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1552 // --- Menus -----------------------------------------------
1553 case LFUN_RECONFIGURE:
1554 // argument is any additional parameter to the configure.py command
1555 reconfigure(to_utf8(cmd.argument()));
1558 // --- lyxserver commands ----------------------------
1559 case LFUN_SERVER_GET_FILENAME: {
1560 if (current_view_ && current_view_->documentBufferView()) {
1561 docstring const fname = from_utf8(
1562 current_view_->documentBufferView()->buffer().absFileName());
1563 dr.setMessage(fname);
1564 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1566 dr.setMessage(docstring());
1567 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1572 case LFUN_SERVER_NOTIFY: {
1573 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1574 dr.setMessage(dispatch_buffer);
1575 theServer().notifyClient(to_utf8(dispatch_buffer));
1579 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1580 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1586 string rest = split(argument, countstr, ' ');
1587 istringstream is(countstr);
1590 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1591 for (int i = 0; i < count; ++i)
1592 dispatch(lyxaction.lookupFunc(rest));
1596 case LFUN_COMMAND_SEQUENCE: {
1597 // argument contains ';'-terminated commands
1598 string arg = argument;
1599 // FIXME: this LFUN should also work without any view.
1600 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1601 ? &(current_view_->documentBufferView()->buffer()) : 0;
1603 buffer->undo().beginUndoGroup();
1604 while (!arg.empty()) {
1606 arg = split(arg, first, ';');
1607 FuncRequest func(lyxaction.lookupFunc(first));
1608 func.setOrigin(cmd.origin());
1611 // the buffer may have been closed by one action
1612 if (theBufferList().isLoaded(buffer))
1613 buffer->undo().endUndoGroup();
1617 case LFUN_BUFFER_FORALL: {
1618 GuiView * gv = currentView();
1619 Buffer * const buf = &gv->currentBufferView()->buffer();
1621 bool processVisible = true;
1622 bool processHidden = false;
1623 docstring msg = _("Applied the following command to all visible buffers in the active window: ");
1624 string commandToRun = argument;
1625 if (cmd.getArg(0) == "both") {
1626 processHidden = true;
1627 msg = _("Applied the following command to all visible and hidden buffers in the active window: ");
1628 commandToRun = cmd.getLongArg(1);
1629 } else if (cmd.getArg(0) == "visible") {
1630 commandToRun = cmd.getLongArg(1);
1631 } else if (cmd.getArg(0) == "hidden") {
1632 processHidden = true;
1633 processVisible = false;
1634 commandToRun = cmd.getLongArg(1);
1635 msg = _("Applied the following command to all hidden buffers in the active window: ");
1637 FuncRequest const funcToRun = lyxaction.lookupFunc(commandToRun);
1638 dr.setMessage(bformat(_("%1$s%2$s"), msg, from_utf8(commandToRun)));
1640 Buffer * const last = theBufferList().last();
1641 Buffer * b = theBufferList().first();
1642 Buffer * nextBuf = 0;
1643 // We cannot use a for loop as the buffer list cycles.
1646 nextBuf = theBufferList().next(b); //get next now bc LFUN might close current
1648 bool const hidden = !(gv && gv->workArea(*b));
1650 if (processHidden) {
1652 lyx::dispatch(funcToRun);
1653 gv->currentWorkArea()->view().hideWorkArea(gv->currentWorkArea());
1658 if (processVisible) {
1660 lyx::dispatch(funcToRun);
1669 if (theBufferList().isLoaded(buf)) //the LFUN might have closed buf
1674 case LFUN_COMMAND_ALTERNATIVES: {
1675 // argument contains ';'-terminated commands
1676 string arg = argument;
1677 while (!arg.empty()) {
1679 arg = split(arg, first, ';');
1680 FuncRequest func(lyxaction.lookupFunc(first));
1681 func.setOrigin(cmd.origin());
1682 FuncStatus const stat = getStatus(func);
1683 if (stat.enabled()) {
1693 if (theTopLevelCmdDef().lock(argument, func)) {
1694 func.setOrigin(cmd.origin());
1696 theTopLevelCmdDef().release(argument);
1698 if (func.action() == LFUN_UNKNOWN_ACTION) {
1699 // unknown command definition
1700 lyxerr << "Warning: unknown command definition `"
1704 // recursion detected
1705 lyxerr << "Warning: Recursion in the command definition `"
1706 << argument << "' detected"
1713 case LFUN_PREFERENCES_SAVE:
1714 lyxrc.write(support::makeAbsPath("preferences",
1715 package().user_support().absFileName()), false);
1718 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1719 string const fname = addName(addPath(package().user_support().absFileName(),
1720 "templates/"), "defaults.lyx");
1721 Buffer defaults(fname);
1723 istringstream ss(argument);
1726 int const unknown_tokens = defaults.readHeader(lex);
1728 if (unknown_tokens != 0) {
1729 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1730 << unknown_tokens << " unknown token"
1731 << (unknown_tokens == 1 ? "" : "s")
1735 if (defaults.writeFile(FileName(defaults.absFileName())))
1736 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1737 makeDisplayPath(fname)));
1740 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1745 case LFUN_BOOKMARK_GOTO:
1746 // go to bookmark, open unopened file and switch to buffer if necessary
1747 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1748 dr.screenUpdate(Update::Force | Update::FitCursor);
1751 case LFUN_BOOKMARK_CLEAR:
1752 theSession().bookmarks().clear();
1755 case LFUN_DEBUG_LEVEL_SET:
1756 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1760 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1763 current_view_->dispatch(cmd, dr);
1767 if (cmd.origin() == FuncRequest::LYXSERVER)
1768 updateCurrentView(cmd, dr);
1772 docstring GuiApplication::viewStatusMessage()
1774 // When meta-fake key is pressed, show the key sequence so far + "M-".
1775 if (d->meta_fake_bit != NoModifier)
1776 return d->keyseq.print(KeySequence::ForGui) + "M-";
1778 // Else, when a non-complete key sequence is pressed,
1779 // show the available options.
1780 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1781 return d->keyseq.printOptions(true);
1787 void GuiApplication::handleKeyFunc(FuncCode action)
1791 if (d->keyseq.length())
1793 GuiView * gv = currentView();
1794 LASSERT(gv && gv->currentBufferView(), return);
1795 BufferView * bv = gv->currentBufferView();
1796 bv->getIntl().getTransManager().deadkey(
1797 c, get_accent(action).accent, bv->cursor().innerText(),
1799 // Need to clear, in case the minibuffer calls these
1802 // copied verbatim from do_accent_char
1803 bv->cursor().resetAnchor();
1807 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1809 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1811 // Do nothing if we have nothing (JMarc)
1812 if (!keysym.isOK()) {
1813 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1815 current_view_->restartCursor();
1819 if (keysym.isModifier()) {
1821 current_view_->restartCursor();
1825 char_type encoded_last_key = keysym.getUCSEncoded();
1827 // Do a one-deep top-level lookup for
1828 // cancel and meta-fake keys. RVDK_PATCH_5
1829 d->cancel_meta_seq.reset();
1831 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1832 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1834 // When not cancel or meta-fake, do the normal lookup.
1835 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1836 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1837 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1838 // remove Caps Lock and Mod2 as a modifiers
1839 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1840 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1843 // Dont remove this unless you know what you are doing.
1844 d->meta_fake_bit = NoModifier;
1846 // Can this happen now ?
1847 if (func.action() == LFUN_NOACTION)
1848 func = FuncRequest(LFUN_COMMAND_PREFIX);
1850 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1851 << d->keyseq.print(KeySequence::Portable) << ']');
1853 // already here we know if it any point in going further
1854 // why not return already here if action == -1 and
1855 // num_bytes == 0? (Lgb)
1857 if (d->keyseq.length() > 1 && current_view_)
1858 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1861 // Maybe user can only reach the key via holding down shift.
1862 // Let's see. But only if shift is the only modifier
1863 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1864 LYXERR(Debug::KEY, "Trying without shift");
1865 func = d->keyseq.addkey(keysym, NoModifier);
1866 LYXERR(Debug::KEY, "Action now " << func.action());
1869 if (func.action() == LFUN_UNKNOWN_ACTION) {
1870 // Hmm, we didn't match any of the keysequences. See
1871 // if it's normal insertable text not already covered
1873 if (keysym.isText() && d->keyseq.length() == 1) {
1874 LYXERR(Debug::KEY, "isText() is true, inserting.");
1875 func = FuncRequest(LFUN_SELF_INSERT,
1876 FuncRequest::KEYBOARD);
1878 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1879 if (current_view_) {
1880 current_view_->message(_("Unknown function."));
1881 current_view_->restartCursor();
1887 if (func.action() == LFUN_SELF_INSERT) {
1888 if (encoded_last_key != 0) {
1889 docstring const arg(1, encoded_last_key);
1890 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1891 FuncRequest::KEYBOARD));
1892 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1895 processFuncRequest(func);
1899 void GuiApplication::processFuncRequest(FuncRequest const & func)
1901 lyx::dispatch(func);
1905 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1907 addToFuncRequestQueue(func);
1908 processFuncRequestQueueAsync();
1912 void GuiApplication::processFuncRequestQueue()
1914 while (!d->func_request_queue_.empty()) {
1915 processFuncRequest(d->func_request_queue_.front());
1916 d->func_request_queue_.pop();
1921 void GuiApplication::processFuncRequestQueueAsync()
1923 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1927 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1929 d->func_request_queue_.push(func);
1933 void GuiApplication::resetGui()
1935 // Set the language defined by the user.
1939 if (!readUIFile(toqstr(lyxrc.ui_file)))
1940 // Gives some error box here.
1943 if (d->global_menubar_)
1944 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1946 QHash<int, GuiView *>::iterator it;
1947 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1950 gv->setLayoutDirection(layoutDirection());
1954 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1958 void GuiApplication::createView(int view_id)
1960 createView(QString(), true, view_id);
1964 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1967 // release the keyboard which might have been grabed by the global
1968 // menubar on Mac to catch shortcuts even without any GuiView.
1969 if (d->global_menubar_)
1970 d->global_menubar_->releaseKeyboard();
1974 while (d->views_.find(id) != d->views_.end())
1977 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1978 GuiView * view = new GuiView(id);
1980 d->views_[id] = view;
1984 setActiveWindow(view);
1987 if (!geometry_arg.isEmpty()) {
1991 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
1992 re.indexIn(geometry_arg);
1993 w = re.cap(1).toInt();
1994 h = re.cap(2).toInt();
1995 x = re.cap(3).toInt();
1996 y = re.cap(4).toInt();
1997 view->setGeometry(x, y, w, h);
2004 Clipboard & GuiApplication::clipboard()
2006 return d->clipboard_;
2010 Selection & GuiApplication::selection()
2012 return d->selection_;
2016 FontLoader & GuiApplication::fontLoader()
2018 return d->font_loader_;
2022 Toolbars const & GuiApplication::toolbars() const
2024 return d->toolbars_;
2028 Toolbars & GuiApplication::toolbars()
2030 return d->toolbars_;
2034 Menus const & GuiApplication::menus() const
2040 Menus & GuiApplication::menus()
2046 QList<int> GuiApplication::viewIds() const
2048 return d->views_.keys();
2052 ColorCache & GuiApplication::colorCache()
2054 return d->color_cache_;
2058 int GuiApplication::exec()
2060 // asynchronously handle batch commands. This event will be in
2061 // the event queue in front of other asynchronous events. Hence,
2062 // we can assume in the latter that the gui is setup already.
2063 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2065 return QApplication::exec();
2069 void GuiApplication::exit(int status)
2071 QApplication::exit(status);
2075 void GuiApplication::setGuiLanguage()
2077 QString const default_language = toqstr(getGuiMessages().language());
2078 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2079 QLocale const default_locale(default_language);
2080 QLocale::setDefault(default_locale);
2082 // install translation file for Qt built-in dialogs
2083 QString const language_name = QString("qt_") + default_locale.name();
2085 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2086 // Short-named translator can be loaded from a long name, but not the
2087 // opposite. Therefore, long name should be used without truncation.
2088 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2089 if (!d->qt_trans_.load(language_name,
2090 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2091 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2094 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2098 switch (default_locale.language()) {
2099 case QLocale::Arabic :
2100 case QLocale::Hebrew :
2101 case QLocale::Persian :
2102 case QLocale::Urdu :
2103 setLayoutDirection(Qt::RightToLeft);
2106 setLayoutDirection(Qt::LeftToRight);
2111 void GuiApplication::execBatchCommands()
2116 if (!readUIFile(toqstr(lyxrc.ui_file)))
2117 // Gives some error box here.
2121 #if QT_VERSION > 0x040600
2122 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2124 // Create the global default menubar which is shown for the dialogs
2125 // and if no GuiView is visible.
2126 // This must be done after the session was recovered to know the "last files".
2127 d->global_menubar_ = new GlobalMenuBar();
2128 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2131 lyx::execBatchCommands();
2135 QAbstractItemModel * GuiApplication::languageModel()
2137 if (d->language_model_)
2138 return d->language_model_;
2140 QStandardItemModel * lang_model = new QStandardItemModel(this);
2141 lang_model->insertColumns(0, 3);
2143 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2144 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2145 Languages::const_iterator it = lyx::languages.begin();
2146 Languages::const_iterator end = lyx::languages.end();
2147 for (; it != end; ++it) {
2148 current_row = lang_model->rowCount();
2149 lang_model->insertRows(current_row, 1);
2150 QModelIndex pl_item = lang_model->index(current_row, 0);
2151 QModelIndex sp_item = lang_model->index(current_row, 1);
2152 QModelIndex th_item = lang_model->index(current_row, 2);
2153 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2154 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2155 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2156 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2157 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2158 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2159 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2160 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2161 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2162 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2164 d->language_model_ = new QSortFilterProxyModel(this);
2165 d->language_model_->setSourceModel(lang_model);
2166 #if QT_VERSION >= 0x040300
2167 d->language_model_->setSortLocaleAware(true);
2169 return d->language_model_;
2173 void GuiApplication::restoreGuiSession()
2175 if (!lyxrc.load_session)
2178 Session & session = theSession();
2179 LastOpenedSection::LastOpened const & lastopened =
2180 session.lastOpened().getfiles();
2182 validateCurrentView();
2184 FileName active_file;
2185 // do not add to the lastfile list since these files are restored from
2186 // last session, and should be already there (regular files), or should
2187 // not be added at all (help files).
2188 for (size_t i = 0; i < lastopened.size(); ++i) {
2189 FileName const & file_name = lastopened[i].file_name;
2190 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2191 && current_view_->documentBufferView() != 0)) {
2192 boost::crc_32_type crc;
2193 string const & fname = file_name.absFileName();
2194 crc = for_each(fname.begin(), fname.end(), crc);
2195 createView(crc.checksum());
2197 current_view_->loadDocument(file_name, false);
2199 if (lastopened[i].active)
2200 active_file = file_name;
2203 // Restore last active buffer
2204 Buffer * buffer = theBufferList().getBuffer(active_file);
2205 if (buffer && current_view_)
2206 current_view_->setBuffer(buffer);
2208 // clear this list to save a few bytes of RAM
2209 session.lastOpened().clear();
2213 QString const GuiApplication::romanFontName()
2216 font.setKerning(false);
2217 font.setStyleHint(QFont::Serif);
2218 font.setFamily("serif");
2220 return QFontInfo(font).family();
2224 QString const GuiApplication::sansFontName()
2227 font.setKerning(false);
2228 font.setStyleHint(QFont::SansSerif);
2229 font.setFamily("sans");
2231 return QFontInfo(font).family();
2235 QString const GuiApplication::typewriterFontName()
2238 font.setKerning(false);
2239 font.setStyleHint(QFont::TypeWriter);
2240 font.setFamily("monospace");
2242 return QFontInfo(font).family();
2246 void GuiApplication::handleRegularEvents()
2248 ForkedCallsController::handleCompletedProcesses();
2252 bool GuiApplication::event(QEvent * e)
2255 case QEvent::FileOpen: {
2256 // Open a file; this happens only on Mac OS X for now.
2258 // We do this asynchronously because on startup the batch
2259 // commands are not executed here yet and the gui is not ready
2261 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2262 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2263 processFuncRequestAsync(fr);
2268 return QApplication::event(e);
2273 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2276 return QApplication::notify(receiver, event);
2278 catch (ExceptionMessage const & e) {
2280 case ErrorException:
2282 setQuitOnLastWindowClosed(false);
2284 Alert::error(e.title_, e.details_);
2286 // Properly crash in debug mode in order to get a useful backtrace.
2289 // In release mode, try to exit gracefully.
2292 case BufferException: {
2293 if (!current_view_ || !current_view_->documentBufferView())
2295 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2296 docstring details = e.details_ + '\n';
2297 details += buf->emergencyWrite();
2298 theBufferList().release(buf);
2299 details += "\n" + _("The current document was closed.");
2300 Alert::error(e.title_, details);
2303 case WarningException:
2304 Alert::warning(e.title_, e.details_);
2308 catch (exception const & e) {
2309 docstring s = _("LyX has caught an exception, it will now "
2310 "attempt to save all unsaved documents and exit."
2312 s += from_ascii(e.what());
2313 Alert::error(_("Software exception Detected"), s);
2317 docstring s = _("LyX has caught some really weird exception, it will "
2318 "now attempt to save all unsaved documents and exit.");
2319 Alert::error(_("Software exception Detected"), s);
2327 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2329 QColor const & qcol = d->color_cache_.get(col);
2330 if (!qcol.isValid()) {
2336 rgbcol.r = qcol.red();
2337 rgbcol.g = qcol.green();
2338 rgbcol.b = qcol.blue();
2343 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2345 QColor const qcol(lcolor.getX11Name(col).c_str());
2346 if (!qcol.isValid()) {
2352 rgbcol.r = qcol.red();
2353 rgbcol.g = qcol.green();
2354 rgbcol.b = qcol.blue();
2359 string const GuiApplication::hexName(ColorCode col)
2361 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2365 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2367 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2368 d->socket_notifiers_[fd] = sn;
2369 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2373 void GuiApplication::socketDataReceived(int fd)
2375 d->socket_notifiers_[fd]->func_();
2379 void GuiApplication::unregisterSocketCallback(int fd)
2381 d->socket_notifiers_.take(fd)->setEnabled(false);
2385 void GuiApplication::commitData(QSessionManager & sm)
2387 /// The implementation is required to avoid an application exit
2388 /// when session state save is triggered by session manager.
2389 /// The default implementation sends a close event to all
2390 /// visible top level widgets when session managment allows
2392 /// We are changing that to close all wiew one by one.
2393 /// FIXME: verify if the default implementation is enough now.
2394 #ifdef QT_NO_SESSIONMANAGER
2396 #warning Qt is compiled without session manager
2398 #pragma message("warning: Qt is compiled without session manager")
2402 if (sm.allowsInteraction() && !closeAllViews())
2408 void GuiApplication::unregisterView(GuiView * gv)
2410 LASSERT(d->views_[gv->id()] == gv, /**/);
2411 d->views_.remove(gv->id());
2412 if (current_view_ == gv)
2417 bool GuiApplication::closeAllViews()
2419 if (d->views_.empty())
2422 // When a view/window was closed before without quitting LyX, there
2423 // are already entries in the lastOpened list.
2424 theSession().lastOpened().clear();
2426 QList<GuiView *> const views = d->views_.values();
2427 foreach (GuiView * view, views) {
2428 if (!view->closeScheduled())
2437 GuiView & GuiApplication::view(int id) const
2439 LASSERT(d->views_.contains(id), /**/);
2440 return *d->views_.value(id);
2444 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2446 QList<GuiView *> const views = d->views_.values();
2447 foreach (GuiView * view, views)
2448 view->hideDialog(name, inset);
2452 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2454 Buffer const * buffer_ = 0;
2455 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2456 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2457 if (Buffer const * ptr = (*it)->updateInset(inset))
2464 bool GuiApplication::searchMenu(FuncRequest const & func,
2465 docstring_list & names) const
2467 return d->menus_.searchMenu(func, names);
2471 // Ensure that a file is read only once (prevents include loops)
2472 static QStringList uifiles;
2473 // store which ui files define Toolbars
2474 static QStringList toolbar_uifiles;
2477 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2488 LexerKeyword uitags[] = {
2489 { "format", ui_format },
2490 { "include", ui_include },
2491 { "menuset", ui_menuset },
2492 { "toolbars", ui_toolbars },
2493 { "toolbarset", ui_toolbarset }
2497 lex.setFile(ui_path);
2499 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2503 if (lyxerr.debugging(Debug::PARSER))
2504 lex.printTable(lyxerr);
2507 // format before introduction of format tag
2508 unsigned int format = 0;
2509 while (lex.isOK()) {
2510 int const status = lex.lex();
2512 // we have to do this check here, outside the switch,
2513 // because otherwise we would start reading include files,
2514 // e.g., if the first tag we hit was an include tag.
2515 if (status == ui_format)
2517 format = lex.getInteger();
2521 // this will trigger unless the first tag we hit is a format
2522 // tag, with the right format.
2523 if (format != LFUN_FORMAT)
2524 return FormatMismatch;
2527 case Lexer::LEX_FEOF:
2532 QString const file = toqstr(lex.getString());
2533 bool const success = readUIFile(file, true);
2535 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2542 d->menus_.read(lex);
2546 d->toolbars_.readToolbars(lex);
2550 d->toolbars_.readToolbarSettings(lex);
2551 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2555 if (!rtrim(lex.getString()).empty())
2556 lex.printError("LyX::ReadUIFile: "
2557 "Unknown menu tag: `$$Token'");
2559 LYXERR0("Error with status: " << status);
2565 return (error ? ReadError : ReadOK);
2569 bool GuiApplication::readUIFile(QString const & name, bool include)
2571 LYXERR(Debug::INIT, "About to read " << name << "...");
2575 ui_path = libFileSearch("ui", name, "inc");
2576 if (ui_path.empty())
2577 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2579 ui_path = libFileSearch("ui", name, "ui");
2582 if (ui_path.empty()) {
2583 static const QString defaultUIFile = "default";
2584 LYXERR(Debug::INIT, "Could not find " << name);
2586 Alert::warning(_("Could not find UI definition file"),
2587 bformat(_("Error while reading the included file\n%1$s\n"
2588 "Please check your installation."), qstring_to_ucs4(name)));
2591 if (name == defaultUIFile) {
2592 LYXERR(Debug::INIT, "Could not find default UI file!!");
2593 Alert::warning(_("Could not find default UI file"),
2594 _("LyX could not find the default UI file!\n"
2595 "Please check your installation."));
2598 Alert::warning(_("Could not find UI definition file"),
2599 bformat(_("Error while reading the configuration file\n%1$s\n"
2600 "Falling back to default.\n"
2601 "Please look under Tools>Preferences>User Interface and\n"
2602 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2603 return readUIFile(defaultUIFile, false);
2606 QString const uifile = toqstr(ui_path.absFileName());
2607 if (uifiles.contains(uifile)) {
2609 // We are reading again the top uifile so reset the safeguard:
2612 d->toolbars_.reset();
2614 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2615 << "Is this an include loop?");
2619 uifiles.push_back(uifile);
2621 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2623 ReturnValues retval = readUIFile(ui_path);
2625 if (retval == FormatMismatch) {
2626 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2627 FileName const tempfile = FileName::tempName("convert_ui");
2628 bool const success = prefs2prefs(ui_path, tempfile, true);
2630 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2631 " to format " << LFUN_FORMAT << ".");
2633 retval = readUIFile(tempfile);
2634 tempfile.removeFile();
2638 if (retval != ReadOK) {
2639 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2647 settings.beginGroup("ui_files");
2648 bool touched = false;
2649 for (int i = 0; i != uifiles.size(); ++i) {
2650 QFileInfo fi(uifiles[i]);
2651 QDateTime const date_value = fi.lastModified();
2652 QString const name_key = QString::number(i);
2653 // if an ui file which defines Toolbars has changed,
2654 // we have to reset the settings
2655 if (toolbar_uifiles.contains(uifiles[i])
2656 && (!settings.contains(name_key)
2657 || settings.value(name_key).toString() != uifiles[i]
2658 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2660 settings.setValue(name_key, uifiles[i]);
2661 settings.setValue(name_key + "/date", date_value);
2664 settings.endGroup();
2666 settings.remove("views");
2672 void GuiApplication::onLastWindowClosed()
2674 if (d->global_menubar_)
2675 d->global_menubar_->grabKeyboard();
2679 void GuiApplication::startLongOperation() {
2680 d->key_checker_.start();
2684 bool GuiApplication::longOperationCancelled() {
2685 return d->key_checker_.pressed();
2689 void GuiApplication::stopLongOperation() {
2690 d->key_checker_.stop();
2694 bool GuiApplication::longOperationStarted() {
2695 return d->key_checker_.started();
2699 ////////////////////////////////////////////////////////////////////////
2701 // X11 specific stuff goes here...
2704 bool GuiApplication::x11EventFilter(XEvent * xev)
2709 switch (xev->type) {
2710 case SelectionRequest: {
2711 if (xev->xselectionrequest.selection != XA_PRIMARY)
2713 LYXERR(Debug::SELECTION, "X requested selection.");
2714 BufferView * bv = current_view_->currentBufferView();
2716 docstring const sel = bv->requestSelection();
2718 d->selection_.put(sel);
2722 case SelectionClear: {
2723 if (xev->xselectionclear.selection != XA_PRIMARY)
2725 LYXERR(Debug::SELECTION, "Lost selection.");
2726 BufferView * bv = current_view_->currentBufferView();
2728 bv->clearSelection();
2736 } // namespace frontend
2739 void hideDialogs(std::string const & name, Inset * inset)
2742 frontend::guiApp->hideDialogs(name, inset);
2746 ////////////////////////////////////////////////////////////////////
2750 ////////////////////////////////////////////////////////////////////
2752 frontend::FontLoader & theFontLoader()
2754 LASSERT(frontend::guiApp, /**/);
2755 return frontend::guiApp->fontLoader();
2759 frontend::FontMetrics const & theFontMetrics(Font const & f)
2761 return theFontMetrics(f.fontInfo());
2765 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2767 LASSERT(frontend::guiApp, /**/);
2768 return frontend::guiApp->fontLoader().metrics(f);
2772 ////////////////////////////////////////////////////////////////////
2776 ////////////////////////////////////////////////////////////////////
2778 frontend::Clipboard & theClipboard()
2780 LASSERT(frontend::guiApp, /**/);
2781 return frontend::guiApp->clipboard();
2785 frontend::Selection & theSelection()
2787 LASSERT(frontend::guiApp, /**/);
2788 return frontend::guiApp->selection();
2794 #include "moc_GuiApplication.cpp"