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) const
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 (theBufferList().empty()) {
1095 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1096 flag.setEnabled(false);
1100 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1101 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1102 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1103 flag.setEnabled(false);
1114 flag.setEnabled(false);
1118 /// make a post-dispatch status message
1119 static docstring makeDispatchMessage(docstring const & msg,
1120 FuncRequest const & cmd)
1122 const bool verbose = (cmd.origin() == FuncRequest::MENU
1123 || cmd.origin() == FuncRequest::TOOLBAR
1124 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1126 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1127 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1131 docstring dispatch_msg = msg;
1132 if (!dispatch_msg.empty())
1133 dispatch_msg += ' ';
1135 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1137 bool argsadded = false;
1139 if (!cmd.argument().empty()) {
1140 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1141 comname += ' ' + cmd.argument();
1145 docstring const shortcuts = theTopLevelKeymap().
1146 printBindings(cmd, KeySequence::ForGui);
1148 if (!shortcuts.empty())
1149 comname += ": " + shortcuts;
1150 else if (!argsadded && !cmd.argument().empty())
1151 comname += ' ' + cmd.argument();
1153 if (!comname.empty()) {
1154 comname = rtrim(comname);
1155 dispatch_msg += '(' + rtrim(comname) + ')';
1157 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1158 return dispatch_msg;
1162 void GuiApplication::dispatch(FuncRequest const & cmd)
1164 Buffer * buffer = 0;
1165 if (current_view_ && current_view_->currentBufferView()) {
1166 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1167 buffer = ¤t_view_->currentBufferView()->buffer();
1169 buffer->undo().beginUndoGroup();
1173 // redraw the screen at the end (first of the two drawing steps).
1174 // This is done unless explicitly requested otherwise
1175 dr.screenUpdate(Update::FitCursor);
1177 updateCurrentView(cmd, dr);
1179 // the buffer may have been closed by one action
1180 if (theBufferList().isLoaded(buffer))
1181 buffer->undo().endUndoGroup();
1185 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1190 BufferView * bv = current_view_->currentBufferView();
1192 if (dr.needBufferUpdate()) {
1193 bv->cursor().clearBufferUpdate();
1194 bv->buffer().updateBuffer();
1196 // BufferView::update() updates the ViewMetricsInfo and
1197 // also initializes the position cache for all insets in
1198 // (at least partially) visible top-level paragraphs.
1199 // We will redraw the screen only if needed.
1200 bv->processUpdateFlags(dr.screenUpdate());
1202 // Do we have a selection?
1203 theSelection().haveSelection(bv->cursor().selection());
1206 current_view_->restartCursor();
1208 if (dr.needMessageUpdate()) {
1209 // Some messages may already be translated, so we cannot use _()
1210 current_view_->message(makeDispatchMessage(
1211 translateIfPossible(dr.message()), cmd));
1216 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1217 bool switchToBuffer)
1219 if (!theSession().bookmarks().isValid(idx))
1221 BookmarksSection::Bookmark const & bm =
1222 theSession().bookmarks().bookmark(idx);
1223 LASSERT(!bm.filename.empty(), /**/);
1224 string const file = bm.filename.absFileName();
1225 // if the file is not opened, open it.
1226 if (!theBufferList().exists(bm.filename)) {
1228 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1232 // open may fail, so we need to test it again
1233 if (!theBufferList().exists(bm.filename))
1236 // bm can be changed when saving
1237 BookmarksSection::Bookmark tmp = bm;
1239 // Special case idx == 0 used for back-from-back jump navigation
1241 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1243 // if the current buffer is not that one, switch to it.
1244 BufferView * doc_bv = current_view_ ?
1245 current_view_->documentBufferView() : 0;
1246 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1247 if (switchToBuffer) {
1248 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1251 doc_bv = current_view_->documentBufferView();
1256 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1257 if (!doc_bv->moveToPosition(
1258 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1265 // Cursor jump succeeded!
1266 Cursor const & cur = doc_bv->cursor();
1267 pit_type new_pit = cur.pit();
1268 pos_type new_pos = cur.pos();
1269 int new_id = cur.paragraph().id();
1271 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1272 // see http://www.lyx.org/trac/ticket/3092
1273 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1274 || bm.top_id != new_id) {
1275 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1276 new_pit, new_pos, new_id);
1280 // This function runs "configure" and then rereads lyx.defaults to
1281 // reconfigure the automatic settings.
1282 void GuiApplication::reconfigure(string const & option)
1284 // emit message signal.
1286 current_view_->message(_("Running configure..."));
1288 // Run configure in user lyx directory
1289 PathChanger p(package().user_support());
1290 string configure_command = package().configure_command();
1291 configure_command += option;
1293 int const ret = one.startscript(Systemcall::Wait, configure_command);
1295 // emit message signal.
1297 current_view_->message(_("Reloading configuration..."));
1298 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1299 // Re-read packages.lst
1300 LaTeXPackages::getAvailable();
1303 Alert::information(_("System reconfiguration failed"),
1304 _("The system reconfiguration has failed.\n"
1305 "Default textclass is used but LyX may\n"
1306 "not be able to work properly.\n"
1307 "Please reconfigure again if needed."));
1309 Alert::information(_("System reconfigured"),
1310 _("The system has been reconfigured.\n"
1311 "You need to restart LyX to make use of any\n"
1312 "updated document class specifications."));
1315 void GuiApplication::validateCurrentView()
1317 if (!d->views_.empty() && !current_view_) {
1318 // currently at least one view exists but no view has the focus.
1319 // choose the last view to make it current.
1320 // a view without any open document is preferred.
1321 GuiView * candidate = 0;
1322 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1323 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1324 for (; it != end; ++it) {
1326 if (!candidate->documentBufferView())
1329 setCurrentView(candidate);
1333 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1335 string const argument = to_utf8(cmd.argument());
1336 FuncCode const action = cmd.action();
1338 LYXERR(Debug::ACTION, "cmd: " << cmd);
1340 // we have not done anything wrong yet.
1343 FuncStatus const flag = getStatus(cmd);
1344 if (!flag.enabled()) {
1345 // We cannot use this function here
1346 LYXERR(Debug::ACTION, "action "
1347 << lyxaction.getActionName(action)
1348 << " [" << action << "] is disabled at this location");
1349 dr.setMessage(flag.message());
1351 dr.dispatched(false);
1352 dr.screenUpdate(Update::None);
1353 dr.clearBufferUpdate();
1357 if (cmd.origin() == FuncRequest::LYXSERVER) {
1358 if (current_view_ && current_view_->currentBufferView())
1359 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1360 // we will also need to redraw the screen at the end
1361 dr.screenUpdate(Update::FitCursor);
1364 // Assumes that the action will be dispatched.
1365 dr.dispatched(true);
1367 switch (cmd.action()) {
1369 case LFUN_WINDOW_NEW:
1370 createView(toqstr(cmd.argument()));
1373 case LFUN_WINDOW_CLOSE:
1374 // update bookmark pit of the current buffer before window close
1375 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1376 gotoBookmark(i+1, false, false);
1377 // clear the last opened list, because
1378 // maybe this will end the session
1379 theSession().lastOpened().clear();
1380 // check for valid current_view_
1381 validateCurrentView();
1383 current_view_->closeScheduled();
1387 // quitting is triggered by the gui code
1388 // (leaving the event loop).
1390 current_view_->message(from_utf8(N_("Exiting.")));
1391 if (closeAllViews())
1395 case LFUN_SCREEN_FONT_UPDATE: {
1396 // handle the screen font changes.
1397 d->font_loader_.update();
1398 // Backup current_view_
1399 GuiView * view = current_view_;
1400 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1401 // to skip the refresh.
1403 theBufferList().changed(false);
1404 // Restore current_view_
1405 current_view_ = view;
1409 case LFUN_BUFFER_NEW:
1410 validateCurrentView();
1411 if (d->views_.empty()
1412 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1413 createView(QString(), false); // keep hidden
1414 current_view_->newDocument(to_utf8(cmd.argument()), false);
1415 current_view_->show();
1416 setActiveWindow(current_view_);
1418 current_view_->newDocument(to_utf8(cmd.argument()), false);
1422 case LFUN_BUFFER_NEW_TEMPLATE:
1423 validateCurrentView();
1424 if (d->views_.empty()
1425 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1427 current_view_->newDocument(to_utf8(cmd.argument()), true);
1428 if (!current_view_->documentBufferView())
1429 current_view_->close();
1431 current_view_->newDocument(to_utf8(cmd.argument()), true);
1435 case LFUN_FILE_OPEN: {
1436 validateCurrentView();
1437 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1438 string const fname = to_utf8(cmd.argument());
1439 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1440 && current_view_->documentBufferView() != 0)) {
1441 // We want the ui session to be saved per document and not per
1442 // window number. The filename crc is a good enough identifier.
1443 boost::crc_32_type crc;
1444 crc = for_each(fname.begin(), fname.end(), crc);
1445 createView(crc.checksum());
1446 current_view_->openDocument(fname);
1447 if (current_view_ && !current_view_->documentBufferView())
1448 current_view_->close();
1450 current_view_->openDocument(fname);
1454 case LFUN_HELP_OPEN: {
1455 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1456 if (current_view_ == 0)
1458 string const arg = to_utf8(cmd.argument());
1460 current_view_->message(_("Missing argument"));
1463 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1465 fname = i18nLibFileSearch("examples", arg, "lyx");
1467 if (fname.empty()) {
1468 lyxerr << "LyX: unable to find documentation file `"
1469 << arg << "'. Bad installation?" << endl;
1472 current_view_->message(bformat(_("Opening help file %1$s..."),
1473 makeDisplayPath(fname.absFileName())));
1474 Buffer * buf = current_view_->loadDocument(fname, false);
1476 #ifndef DEVEL_VERSION
1478 buf->setReadonly(true);
1485 case LFUN_SET_COLOR: {
1487 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1488 if (lyx_name.empty() || x11_name.empty()) {
1490 current_view_->message(
1491 _("Syntax: set-color <lyx_name> <x11_name>"));
1496 // FIXME: The graphics cache no longer has a changeDisplay method.
1497 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1498 bool const graphicsbg_changed =
1499 lyx_name == graphicsbg && x11_name != graphicsbg;
1500 if (graphicsbg_changed)
1501 graphics::GCache::get().changeDisplay(true);
1504 if (!lcolor.setColor(lyx_name, x11_name)) {
1506 current_view_->message(
1507 bformat(_("Set-color \"%1$s\" failed "
1508 "- color is undefined or "
1509 "may not be redefined"),
1510 from_utf8(lyx_name)));
1513 // Make sure we don't keep old colors in cache.
1514 d->color_cache_.clear();
1518 case LFUN_LYXRC_APPLY: {
1519 // reset active key sequences, since the bindings
1520 // are updated (bug 6064)
1522 LyXRC const lyxrc_orig = lyxrc;
1524 istringstream ss(to_utf8(cmd.argument()));
1525 bool const success = lyxrc.read(ss);
1528 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1529 << "Unable to read lyxrc data"
1534 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1540 case LFUN_COMMAND_PREFIX:
1541 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1546 d->meta_fake_bit = NoModifier;
1547 GuiView * gv = currentView();
1548 if (gv && gv->currentBufferView())
1549 // cancel any selection
1550 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1551 dr.setMessage(from_ascii(N_("Cancel")));
1554 case LFUN_META_PREFIX:
1555 d->meta_fake_bit = AltModifier;
1556 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1559 // --- Menus -----------------------------------------------
1560 case LFUN_RECONFIGURE:
1561 // argument is any additional parameter to the configure.py command
1562 reconfigure(to_utf8(cmd.argument()));
1565 // --- lyxserver commands ----------------------------
1566 case LFUN_SERVER_GET_FILENAME: {
1567 if (current_view_ && current_view_->documentBufferView()) {
1568 docstring const fname = from_utf8(
1569 current_view_->documentBufferView()->buffer().absFileName());
1570 dr.setMessage(fname);
1571 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1573 dr.setMessage(docstring());
1574 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1579 case LFUN_SERVER_NOTIFY: {
1580 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1581 dr.setMessage(dispatch_buffer);
1582 theServer().notifyClient(to_utf8(dispatch_buffer));
1586 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1587 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1593 string rest = split(argument, countstr, ' ');
1594 istringstream is(countstr);
1597 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1598 for (int i = 0; i < count; ++i)
1599 dispatch(lyxaction.lookupFunc(rest));
1603 case LFUN_COMMAND_SEQUENCE: {
1604 // argument contains ';'-terminated commands
1605 string arg = argument;
1606 // FIXME: this LFUN should also work without any view.
1607 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1608 ? &(current_view_->documentBufferView()->buffer()) : 0;
1610 buffer->undo().beginUndoGroup();
1611 while (!arg.empty()) {
1613 arg = split(arg, first, ';');
1614 FuncRequest func(lyxaction.lookupFunc(first));
1615 func.setOrigin(cmd.origin());
1618 // the buffer may have been closed by one action
1619 if (theBufferList().isLoaded(buffer))
1620 buffer->undo().endUndoGroup();
1624 case LFUN_BUFFER_FORALL: {
1625 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1627 map<Buffer *, GuiView *> views_lVisible;
1628 map<GuiView *, Buffer *> activeBuffers;
1630 QList<GuiView *> allViews = d->views_.values();
1632 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1633 // and on which buffer is active in each view.
1634 Buffer * const last = theBufferList().last();
1635 foreach (GuiView * view, allViews) {
1636 // all of the buffers might be locally hidden. That is, there is no active buffer.
1637 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1638 activeBuffers[view] = 0;
1640 activeBuffers[view] = &view->currentBufferView()->buffer();
1642 // find out if each is locally visible or locally hidden.
1643 // we don't use a for loop as the buffer list cycles.
1644 Buffer * b = theBufferList().first();
1646 bool const locallyVisible = view && view->workArea(*b);
1647 if (locallyVisible) {
1648 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1649 // only need to overwrite/add if we don't already know a buffer is globally
1650 // visible or we do know but we would prefer to dispatch LFUN from the
1651 // current view because of cursor position issues.
1652 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1653 views_lVisible[b] = view;
1657 b = theBufferList().next(b);
1661 GuiView * const homeView = currentView();
1662 Buffer * b = theBufferList().first();
1663 Buffer * nextBuf = 0;
1664 int numProcessed = 0;
1667 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1669 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1671 // first change to a view where b is locally visible, preferably current_view_.
1672 GuiView * const vLv = views_lVisible[b];
1674 lyx::dispatch(funcToRun);
1682 // put things back to how they were (if possible).
1683 foreach (GuiView * view, allViews) {
1684 Buffer * originalBuf = activeBuffers[view];
1685 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1686 if (theBufferList().isLoaded(originalBuf))
1687 view->setBuffer(originalBuf);
1689 homeView->setFocus();
1691 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1695 case LFUN_COMMAND_ALTERNATIVES: {
1696 // argument contains ';'-terminated commands
1697 string arg = argument;
1698 while (!arg.empty()) {
1700 arg = split(arg, first, ';');
1701 FuncRequest func(lyxaction.lookupFunc(first));
1702 func.setOrigin(cmd.origin());
1703 FuncStatus const stat = getStatus(func);
1704 if (stat.enabled()) {
1714 if (theTopLevelCmdDef().lock(argument, func)) {
1715 func.setOrigin(cmd.origin());
1717 theTopLevelCmdDef().release(argument);
1719 if (func.action() == LFUN_UNKNOWN_ACTION) {
1720 // unknown command definition
1721 lyxerr << "Warning: unknown command definition `"
1725 // recursion detected
1726 lyxerr << "Warning: Recursion in the command definition `"
1727 << argument << "' detected"
1734 case LFUN_PREFERENCES_SAVE:
1735 lyxrc.write(support::makeAbsPath("preferences",
1736 package().user_support().absFileName()), false);
1739 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1740 string const fname = addName(addPath(package().user_support().absFileName(),
1741 "templates/"), "defaults.lyx");
1742 Buffer defaults(fname);
1744 istringstream ss(argument);
1747 int const unknown_tokens = defaults.readHeader(lex);
1749 if (unknown_tokens != 0) {
1750 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1751 << unknown_tokens << " unknown token"
1752 << (unknown_tokens == 1 ? "" : "s")
1756 if (defaults.writeFile(FileName(defaults.absFileName())))
1757 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1758 makeDisplayPath(fname)));
1761 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1766 case LFUN_BOOKMARK_GOTO:
1767 // go to bookmark, open unopened file and switch to buffer if necessary
1768 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1769 dr.screenUpdate(Update::Force | Update::FitCursor);
1772 case LFUN_BOOKMARK_CLEAR:
1773 theSession().bookmarks().clear();
1776 case LFUN_DEBUG_LEVEL_SET:
1777 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1781 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1784 current_view_->dispatch(cmd, dr);
1788 if (cmd.origin() == FuncRequest::LYXSERVER)
1789 updateCurrentView(cmd, dr);
1793 docstring GuiApplication::viewStatusMessage()
1795 // When meta-fake key is pressed, show the key sequence so far + "M-".
1796 if (d->meta_fake_bit != NoModifier)
1797 return d->keyseq.print(KeySequence::ForGui) + "M-";
1799 // Else, when a non-complete key sequence is pressed,
1800 // show the available options.
1801 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1802 return d->keyseq.printOptions(true);
1808 void GuiApplication::handleKeyFunc(FuncCode action)
1812 if (d->keyseq.length())
1814 GuiView * gv = currentView();
1815 LASSERT(gv && gv->currentBufferView(), return);
1816 BufferView * bv = gv->currentBufferView();
1817 bv->getIntl().getTransManager().deadkey(
1818 c, get_accent(action).accent, bv->cursor().innerText(),
1820 // Need to clear, in case the minibuffer calls these
1823 // copied verbatim from do_accent_char
1824 bv->cursor().resetAnchor();
1828 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1830 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1832 // Do nothing if we have nothing (JMarc)
1833 if (!keysym.isOK()) {
1834 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1836 current_view_->restartCursor();
1840 if (keysym.isModifier()) {
1842 current_view_->restartCursor();
1846 char_type encoded_last_key = keysym.getUCSEncoded();
1848 // Do a one-deep top-level lookup for
1849 // cancel and meta-fake keys. RVDK_PATCH_5
1850 d->cancel_meta_seq.reset();
1852 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1853 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1855 // When not cancel or meta-fake, do the normal lookup.
1856 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1857 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1858 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1859 // remove Caps Lock and Mod2 as a modifiers
1860 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1861 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1864 // Dont remove this unless you know what you are doing.
1865 d->meta_fake_bit = NoModifier;
1867 // Can this happen now ?
1868 if (func.action() == LFUN_NOACTION)
1869 func = FuncRequest(LFUN_COMMAND_PREFIX);
1871 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1872 << d->keyseq.print(KeySequence::Portable) << ']');
1874 // already here we know if it any point in going further
1875 // why not return already here if action == -1 and
1876 // num_bytes == 0? (Lgb)
1878 if (d->keyseq.length() > 1 && current_view_)
1879 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1882 // Maybe user can only reach the key via holding down shift.
1883 // Let's see. But only if shift is the only modifier
1884 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1885 LYXERR(Debug::KEY, "Trying without shift");
1886 func = d->keyseq.addkey(keysym, NoModifier);
1887 LYXERR(Debug::KEY, "Action now " << func.action());
1890 if (func.action() == LFUN_UNKNOWN_ACTION) {
1891 // Hmm, we didn't match any of the keysequences. See
1892 // if it's normal insertable text not already covered
1894 if (keysym.isText() && d->keyseq.length() == 1) {
1895 LYXERR(Debug::KEY, "isText() is true, inserting.");
1896 func = FuncRequest(LFUN_SELF_INSERT,
1897 FuncRequest::KEYBOARD);
1899 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1900 if (current_view_) {
1901 current_view_->message(_("Unknown function."));
1902 current_view_->restartCursor();
1908 if (func.action() == LFUN_SELF_INSERT) {
1909 if (encoded_last_key != 0) {
1910 docstring const arg(1, encoded_last_key);
1911 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1912 FuncRequest::KEYBOARD));
1913 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1916 processFuncRequest(func);
1920 void GuiApplication::processFuncRequest(FuncRequest const & func)
1922 lyx::dispatch(func);
1926 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1928 addToFuncRequestQueue(func);
1929 processFuncRequestQueueAsync();
1933 void GuiApplication::processFuncRequestQueue()
1935 while (!d->func_request_queue_.empty()) {
1936 processFuncRequest(d->func_request_queue_.front());
1937 d->func_request_queue_.pop();
1942 void GuiApplication::processFuncRequestQueueAsync()
1944 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1948 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1950 d->func_request_queue_.push(func);
1954 void GuiApplication::resetGui()
1956 // Set the language defined by the user.
1960 if (!readUIFile(toqstr(lyxrc.ui_file)))
1961 // Gives some error box here.
1964 if (d->global_menubar_)
1965 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1967 QHash<int, GuiView *>::iterator it;
1968 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1971 gv->setLayoutDirection(layoutDirection());
1975 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1979 void GuiApplication::createView(int view_id)
1981 createView(QString(), true, view_id);
1985 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1988 // release the keyboard which might have been grabed by the global
1989 // menubar on Mac to catch shortcuts even without any GuiView.
1990 if (d->global_menubar_)
1991 d->global_menubar_->releaseKeyboard();
1995 while (d->views_.find(id) != d->views_.end())
1998 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1999 GuiView * view = new GuiView(id);
2001 d->views_[id] = view;
2005 setActiveWindow(view);
2008 if (!geometry_arg.isEmpty()) {
2012 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2013 re.indexIn(geometry_arg);
2014 w = re.cap(1).toInt();
2015 h = re.cap(2).toInt();
2016 x = re.cap(3).toInt();
2017 y = re.cap(4).toInt();
2018 view->setGeometry(x, y, w, h);
2025 Clipboard & GuiApplication::clipboard()
2027 return d->clipboard_;
2031 Selection & GuiApplication::selection()
2033 return d->selection_;
2037 FontLoader & GuiApplication::fontLoader()
2039 return d->font_loader_;
2043 Toolbars const & GuiApplication::toolbars() const
2045 return d->toolbars_;
2049 Toolbars & GuiApplication::toolbars()
2051 return d->toolbars_;
2055 Menus const & GuiApplication::menus() const
2061 Menus & GuiApplication::menus()
2067 QList<int> GuiApplication::viewIds() const
2069 return d->views_.keys();
2073 ColorCache & GuiApplication::colorCache()
2075 return d->color_cache_;
2079 int GuiApplication::exec()
2081 // asynchronously handle batch commands. This event will be in
2082 // the event queue in front of other asynchronous events. Hence,
2083 // we can assume in the latter that the gui is setup already.
2084 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2086 return QApplication::exec();
2090 void GuiApplication::exit(int status)
2092 QApplication::exit(status);
2096 void GuiApplication::setGuiLanguage()
2098 QString const default_language = toqstr(getGuiMessages().language());
2099 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2100 QLocale const default_locale(default_language);
2101 QLocale::setDefault(default_locale);
2103 // install translation file for Qt built-in dialogs
2104 QString const language_name = QString("qt_") + default_locale.name();
2106 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2107 // Short-named translator can be loaded from a long name, but not the
2108 // opposite. Therefore, long name should be used without truncation.
2109 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2110 if (!d->qt_trans_.load(language_name,
2111 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2112 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2115 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2119 switch (default_locale.language()) {
2120 case QLocale::Arabic :
2121 case QLocale::Hebrew :
2122 case QLocale::Persian :
2123 case QLocale::Urdu :
2124 setLayoutDirection(Qt::RightToLeft);
2127 setLayoutDirection(Qt::LeftToRight);
2132 void GuiApplication::execBatchCommands()
2137 if (!readUIFile(toqstr(lyxrc.ui_file)))
2138 // Gives some error box here.
2142 #if QT_VERSION > 0x040600
2143 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2145 // Create the global default menubar which is shown for the dialogs
2146 // and if no GuiView is visible.
2147 // This must be done after the session was recovered to know the "last files".
2148 d->global_menubar_ = new GlobalMenuBar();
2149 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2152 lyx::execBatchCommands();
2156 QAbstractItemModel * GuiApplication::languageModel()
2158 if (d->language_model_)
2159 return d->language_model_;
2161 QStandardItemModel * lang_model = new QStandardItemModel(this);
2162 lang_model->insertColumns(0, 3);
2164 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2165 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2166 Languages::const_iterator it = lyx::languages.begin();
2167 Languages::const_iterator end = lyx::languages.end();
2168 for (; it != end; ++it) {
2169 current_row = lang_model->rowCount();
2170 lang_model->insertRows(current_row, 1);
2171 QModelIndex pl_item = lang_model->index(current_row, 0);
2172 QModelIndex sp_item = lang_model->index(current_row, 1);
2173 QModelIndex th_item = lang_model->index(current_row, 2);
2174 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2175 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2176 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2177 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2178 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2179 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2180 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2181 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2182 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2183 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2185 d->language_model_ = new QSortFilterProxyModel(this);
2186 d->language_model_->setSourceModel(lang_model);
2187 #if QT_VERSION >= 0x040300
2188 d->language_model_->setSortLocaleAware(true);
2190 return d->language_model_;
2194 void GuiApplication::restoreGuiSession()
2196 if (!lyxrc.load_session)
2199 Session & session = theSession();
2200 LastOpenedSection::LastOpened const & lastopened =
2201 session.lastOpened().getfiles();
2203 validateCurrentView();
2205 FileName active_file;
2206 // do not add to the lastfile list since these files are restored from
2207 // last session, and should be already there (regular files), or should
2208 // not be added at all (help files).
2209 for (size_t i = 0; i < lastopened.size(); ++i) {
2210 FileName const & file_name = lastopened[i].file_name;
2211 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2212 && current_view_->documentBufferView() != 0)) {
2213 boost::crc_32_type crc;
2214 string const & fname = file_name.absFileName();
2215 crc = for_each(fname.begin(), fname.end(), crc);
2216 createView(crc.checksum());
2218 current_view_->loadDocument(file_name, false);
2220 if (lastopened[i].active)
2221 active_file = file_name;
2224 // Restore last active buffer
2225 Buffer * buffer = theBufferList().getBuffer(active_file);
2226 if (buffer && current_view_)
2227 current_view_->setBuffer(buffer);
2229 // clear this list to save a few bytes of RAM
2230 session.lastOpened().clear();
2234 QString const GuiApplication::romanFontName()
2237 font.setKerning(false);
2238 font.setStyleHint(QFont::Serif);
2239 font.setFamily("serif");
2241 return QFontInfo(font).family();
2245 QString const GuiApplication::sansFontName()
2248 font.setKerning(false);
2249 font.setStyleHint(QFont::SansSerif);
2250 font.setFamily("sans");
2252 return QFontInfo(font).family();
2256 QString const GuiApplication::typewriterFontName()
2259 font.setKerning(false);
2260 font.setStyleHint(QFont::TypeWriter);
2261 font.setFamily("monospace");
2263 return QFontInfo(font).family();
2267 void GuiApplication::handleRegularEvents()
2269 ForkedCallsController::handleCompletedProcesses();
2273 bool GuiApplication::event(QEvent * e)
2276 case QEvent::FileOpen: {
2277 // Open a file; this happens only on Mac OS X for now.
2279 // We do this asynchronously because on startup the batch
2280 // commands are not executed here yet and the gui is not ready
2282 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2283 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2284 processFuncRequestAsync(fr);
2289 return QApplication::event(e);
2294 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2297 return QApplication::notify(receiver, event);
2299 catch (ExceptionMessage const & e) {
2301 case ErrorException:
2303 setQuitOnLastWindowClosed(false);
2305 Alert::error(e.title_, e.details_);
2307 // Properly crash in debug mode in order to get a useful backtrace.
2310 // In release mode, try to exit gracefully.
2313 case BufferException: {
2314 if (!current_view_ || !current_view_->documentBufferView())
2316 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2317 docstring details = e.details_ + '\n';
2318 details += buf->emergencyWrite();
2319 theBufferList().release(buf);
2320 details += "\n" + _("The current document was closed.");
2321 Alert::error(e.title_, details);
2324 case WarningException:
2325 Alert::warning(e.title_, e.details_);
2329 catch (exception const & e) {
2330 docstring s = _("LyX has caught an exception, it will now "
2331 "attempt to save all unsaved documents and exit."
2333 s += from_ascii(e.what());
2334 Alert::error(_("Software exception Detected"), s);
2338 docstring s = _("LyX has caught some really weird exception, it will "
2339 "now attempt to save all unsaved documents and exit.");
2340 Alert::error(_("Software exception Detected"), s);
2348 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2350 QColor const & qcol = d->color_cache_.get(col);
2351 if (!qcol.isValid()) {
2357 rgbcol.r = qcol.red();
2358 rgbcol.g = qcol.green();
2359 rgbcol.b = qcol.blue();
2364 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2366 QColor const qcol(lcolor.getX11Name(col).c_str());
2367 if (!qcol.isValid()) {
2373 rgbcol.r = qcol.red();
2374 rgbcol.g = qcol.green();
2375 rgbcol.b = qcol.blue();
2380 string const GuiApplication::hexName(ColorCode col)
2382 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2386 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2388 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2389 d->socket_notifiers_[fd] = sn;
2390 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2394 void GuiApplication::socketDataReceived(int fd)
2396 d->socket_notifiers_[fd]->func_();
2400 void GuiApplication::unregisterSocketCallback(int fd)
2402 d->socket_notifiers_.take(fd)->setEnabled(false);
2406 void GuiApplication::commitData(QSessionManager & sm)
2408 /// The implementation is required to avoid an application exit
2409 /// when session state save is triggered by session manager.
2410 /// The default implementation sends a close event to all
2411 /// visible top level widgets when session managment allows
2413 /// We are changing that to close all wiew one by one.
2414 /// FIXME: verify if the default implementation is enough now.
2415 #ifdef QT_NO_SESSIONMANAGER
2417 #warning Qt is compiled without session manager
2419 #pragma message("warning: Qt is compiled without session manager")
2423 if (sm.allowsInteraction() && !closeAllViews())
2429 void GuiApplication::unregisterView(GuiView * gv)
2431 LASSERT(d->views_[gv->id()] == gv, /**/);
2432 d->views_.remove(gv->id());
2433 if (current_view_ == gv)
2438 bool GuiApplication::closeAllViews()
2440 if (d->views_.empty())
2443 // When a view/window was closed before without quitting LyX, there
2444 // are already entries in the lastOpened list.
2445 theSession().lastOpened().clear();
2447 QList<GuiView *> const views = d->views_.values();
2448 foreach (GuiView * view, views) {
2449 if (!view->closeScheduled())
2458 GuiView & GuiApplication::view(int id) const
2460 LASSERT(d->views_.contains(id), /**/);
2461 return *d->views_.value(id);
2465 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2467 QList<GuiView *> const views = d->views_.values();
2468 foreach (GuiView * view, views)
2469 view->hideDialog(name, inset);
2473 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2475 Buffer const * buffer_ = 0;
2476 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2477 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2478 if (Buffer const * ptr = (*it)->updateInset(inset))
2485 bool GuiApplication::searchMenu(FuncRequest const & func,
2486 docstring_list & names) const
2488 return d->menus_.searchMenu(func, names);
2492 // Ensure that a file is read only once (prevents include loops)
2493 static QStringList uifiles;
2494 // store which ui files define Toolbars
2495 static QStringList toolbar_uifiles;
2498 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2509 LexerKeyword uitags[] = {
2510 { "format", ui_format },
2511 { "include", ui_include },
2512 { "menuset", ui_menuset },
2513 { "toolbars", ui_toolbars },
2514 { "toolbarset", ui_toolbarset }
2518 lex.setFile(ui_path);
2520 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2524 if (lyxerr.debugging(Debug::PARSER))
2525 lex.printTable(lyxerr);
2528 // format before introduction of format tag
2529 unsigned int format = 0;
2530 while (lex.isOK()) {
2531 int const status = lex.lex();
2533 // we have to do this check here, outside the switch,
2534 // because otherwise we would start reading include files,
2535 // e.g., if the first tag we hit was an include tag.
2536 if (status == ui_format)
2538 format = lex.getInteger();
2542 // this will trigger unless the first tag we hit is a format
2543 // tag, with the right format.
2544 if (format != LFUN_FORMAT)
2545 return FormatMismatch;
2548 case Lexer::LEX_FEOF:
2553 QString const file = toqstr(lex.getString());
2554 bool const success = readUIFile(file, true);
2556 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2563 d->menus_.read(lex);
2567 d->toolbars_.readToolbars(lex);
2571 d->toolbars_.readToolbarSettings(lex);
2572 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2576 if (!rtrim(lex.getString()).empty())
2577 lex.printError("LyX::ReadUIFile: "
2578 "Unknown menu tag: `$$Token'");
2580 LYXERR0("Error with status: " << status);
2586 return (error ? ReadError : ReadOK);
2590 bool GuiApplication::readUIFile(QString const & name, bool include)
2592 LYXERR(Debug::INIT, "About to read " << name << "...");
2596 ui_path = libFileSearch("ui", name, "inc");
2597 if (ui_path.empty())
2598 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2600 ui_path = libFileSearch("ui", name, "ui");
2603 if (ui_path.empty()) {
2604 static const QString defaultUIFile = "default";
2605 LYXERR(Debug::INIT, "Could not find " << name);
2607 Alert::warning(_("Could not find UI definition file"),
2608 bformat(_("Error while reading the included file\n%1$s\n"
2609 "Please check your installation."), qstring_to_ucs4(name)));
2612 if (name == defaultUIFile) {
2613 LYXERR(Debug::INIT, "Could not find default UI file!!");
2614 Alert::warning(_("Could not find default UI file"),
2615 _("LyX could not find the default UI file!\n"
2616 "Please check your installation."));
2619 Alert::warning(_("Could not find UI definition file"),
2620 bformat(_("Error while reading the configuration file\n%1$s\n"
2621 "Falling back to default.\n"
2622 "Please look under Tools>Preferences>User Interface and\n"
2623 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2624 return readUIFile(defaultUIFile, false);
2627 QString const uifile = toqstr(ui_path.absFileName());
2628 if (uifiles.contains(uifile)) {
2630 // We are reading again the top uifile so reset the safeguard:
2633 d->toolbars_.reset();
2635 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2636 << "Is this an include loop?");
2640 uifiles.push_back(uifile);
2642 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2644 ReturnValues retval = readUIFile(ui_path);
2646 if (retval == FormatMismatch) {
2647 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2648 FileName const tempfile = FileName::tempName("convert_ui");
2649 bool const success = prefs2prefs(ui_path, tempfile, true);
2651 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2652 " to format " << LFUN_FORMAT << ".");
2654 retval = readUIFile(tempfile);
2655 tempfile.removeFile();
2659 if (retval != ReadOK) {
2660 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2668 settings.beginGroup("ui_files");
2669 bool touched = false;
2670 for (int i = 0; i != uifiles.size(); ++i) {
2671 QFileInfo fi(uifiles[i]);
2672 QDateTime const date_value = fi.lastModified();
2673 QString const name_key = QString::number(i);
2674 // if an ui file which defines Toolbars has changed,
2675 // we have to reset the settings
2676 if (toolbar_uifiles.contains(uifiles[i])
2677 && (!settings.contains(name_key)
2678 || settings.value(name_key).toString() != uifiles[i]
2679 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2681 settings.setValue(name_key, uifiles[i]);
2682 settings.setValue(name_key + "/date", date_value);
2685 settings.endGroup();
2687 settings.remove("views");
2693 void GuiApplication::onLastWindowClosed()
2695 if (d->global_menubar_)
2696 d->global_menubar_->grabKeyboard();
2700 void GuiApplication::startLongOperation() {
2701 d->key_checker_.start();
2705 bool GuiApplication::longOperationCancelled() {
2706 return d->key_checker_.pressed();
2710 void GuiApplication::stopLongOperation() {
2711 d->key_checker_.stop();
2715 bool GuiApplication::longOperationStarted() {
2716 return d->key_checker_.started();
2720 ////////////////////////////////////////////////////////////////////////
2722 // X11 specific stuff goes here...
2725 bool GuiApplication::x11EventFilter(XEvent * xev)
2730 switch (xev->type) {
2731 case SelectionRequest: {
2732 if (xev->xselectionrequest.selection != XA_PRIMARY)
2734 LYXERR(Debug::SELECTION, "X requested selection.");
2735 BufferView * bv = current_view_->currentBufferView();
2737 docstring const sel = bv->requestSelection();
2739 d->selection_.put(sel);
2743 case SelectionClear: {
2744 if (xev->xselectionclear.selection != XA_PRIMARY)
2746 LYXERR(Debug::SELECTION, "Lost selection.");
2747 BufferView * bv = current_view_->currentBufferView();
2749 bv->clearSelection();
2757 } // namespace frontend
2760 void hideDialogs(std::string const & name, Inset * inset)
2763 frontend::guiApp->hideDialogs(name, inset);
2767 ////////////////////////////////////////////////////////////////////
2771 ////////////////////////////////////////////////////////////////////
2773 frontend::FontLoader & theFontLoader()
2775 LASSERT(frontend::guiApp, /**/);
2776 return frontend::guiApp->fontLoader();
2780 frontend::FontMetrics const & theFontMetrics(Font const & f)
2782 return theFontMetrics(f.fontInfo());
2786 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2788 LASSERT(frontend::guiApp, /**/);
2789 return frontend::guiApp->fontLoader().metrics(f);
2793 ////////////////////////////////////////////////////////////////////
2797 ////////////////////////////////////////////////////////////////////
2799 frontend::Clipboard & theClipboard()
2801 LASSERT(frontend::guiApp, /**/);
2802 return frontend::guiApp->clipboard();
2806 frontend::Selection & theSelection()
2808 LASSERT(frontend::guiApp, /**/);
2809 return frontend::guiApp->selection();
2815 #include "moc_GuiApplication.cpp"