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 #include <QThreadPool>
116 #include <X11/Xatom.h>
117 #include <X11/Xlib.h>
123 #include <QWindowsMime>
130 #include "support/bind.h"
131 #include <boost/crc.hpp>
138 using namespace lyx::support;
141 static void initializeResources()
143 static bool initialized = false;
145 Q_INIT_RESOURCE(Resources);
153 frontend::Application * createApplication(int & argc, char * argv[])
156 // prune -geometry argument(s) by shifting
157 // the following ones 2 places down.
158 for (int i = 0 ; i < argc ; ++i) {
159 if (strcmp(argv[i], "-geometry") == 0) {
160 int const remove = (i+1) < argc ? 2 : 1;
162 for (int j = i; j < argc; ++j)
163 argv[j] = argv[j + remove];
168 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
169 // I'd rather do that in the constructor, but I do not think that
170 // the palette is accessible there.
171 guiApp->colorCache().setPalette(guiApp->palette());
178 /// Return the list of loadable formats.
179 vector<string> loadableImageFormats()
183 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
185 LYXERR(Debug::GRAPHICS,
186 "\nThe image loader can load the following directly:\n");
188 if (qt_formats.empty())
189 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
191 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
193 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
195 string ext = ascii_lowercase((const char *) *it);
206 ////////////////////////////////////////////////////////////////////////
208 // Icon loading support code
210 ////////////////////////////////////////////////////////////////////////
220 bool operator<(PngMap const & lhs, PngMap const & rhs)
222 return lhs.key < rhs.key;
228 CompareKey(QString const & name) : name_(name) {}
229 bool operator()(PngMap const & other) const { return other.key == name_; }
235 // this must be sorted alphabetically
236 // Upper case comes before lower case
237 PngMap sorted_png_map[] = {
238 { "Bumpeq", "bumpeq2" },
241 { "Delta", "delta2" },
242 { "Diamond", "diamond2" },
243 { "Downarrow", "downarrow2" },
244 { "Gamma", "gamma2" },
245 { "Lambda", "lambda2" },
246 { "Leftarrow", "leftarrow2" },
247 { "Leftrightarrow", "leftrightarrow2" },
248 { "Longleftarrow", "longleftarrow2" },
249 { "Longleftrightarrow", "longleftrightarrow2" },
250 { "Longrightarrow", "longrightarrow2" },
251 { "Omega", "omega2" },
255 { "Rightarrow", "rightarrow2" },
256 { "Sigma", "sigma2" },
257 { "Subset", "subset2" },
258 { "Supset", "supset2" },
259 { "Theta", "theta2" },
260 { "Uparrow", "uparrow2" },
261 { "Updownarrow", "updownarrow2" },
262 { "Upsilon", "upsilon2" },
263 { "Vdash", "vdash3" },
266 { "nLeftarrow", "nleftarrow2" },
267 { "nLeftrightarrow", "nleftrightarrow2" },
268 { "nRightarrow", "nrightarrow2" },
269 { "nVDash", "nvdash3" },
270 { "nvDash", "nvdash2" },
271 { "textrm \\AA", "textrm_AA"},
272 { "textrm \\O", "textrm_O"},
273 { "vDash", "vdash2" }
276 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
279 QString findPng(QString const & name)
281 PngMap const * const begin = sorted_png_map;
282 PngMap const * const end = begin + nr_sorted_png_map;
283 LASSERT(sorted(begin, end), /**/);
285 PngMap const * const it = find_if(begin, end, CompareKey(name));
289 png_name = it->value;
292 png_name.replace('_', "underscore");
293 png_name.replace(' ', '_');
295 // This way we can have "math-delim { }" on the toolbar.
296 png_name.replace('(', "lparen");
297 png_name.replace(')', "rparen");
298 png_name.replace('[', "lbracket");
299 png_name.replace(']', "rbracket");
300 png_name.replace('{', "lbrace");
301 png_name.replace('}', "rbrace");
302 png_name.replace('|', "bars");
303 png_name.replace(',', "thinspace");
304 png_name.replace(':', "mediumspace");
305 png_name.replace(';', "thickspace");
306 png_name.replace('!', "negthinspace");
309 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
310 << "Looking for math PNG called \"" << png_name << '"');
317 QString iconName(FuncRequest const & f, bool unknown)
319 initializeResources();
323 switch (f.action()) {
324 case LFUN_MATH_INSERT:
325 if (!f.argument().empty()) {
327 name1 = findPng(toqstr(f.argument()).mid(1));
330 case LFUN_MATH_DELIM:
331 case LFUN_MATH_BIGDELIM:
333 name1 = findPng(toqstr(f.argument()));
337 name1 = toqstr(f.argument());
339 case LFUN_COMMAND_ALTERNATIVES: {
340 // use the first of the alternative commands
342 docstring dummy = split(f.argument(), firstcom, ';');
343 name1 = toqstr(firstcom);
344 // FIXME: we should rename the icons to tabular-xxx instead of
345 // "tabular-feature-xxx"
346 name1.replace("inset-modify tabular", "tabular-feature");
347 name1.replace(' ', '_');
350 case LFUN_INSET_MODIFY: {
351 // FIXME: we should rename the icons to tabular-xxx instead of
352 // "tabular-feature-xxx" and generalize this naming to all
353 // insets, not to tabular using ones.
355 string const command = split(to_utf8(f.argument()), inset_name, ' ');
356 if (insetCode(inset_name) == TABULAR_CODE) {
357 name1 = "tabular-feature "+ toqstr(command);
358 name1.replace(' ', '_');
363 name2 = toqstr(lyxaction.getActionName(f.action()));
366 if (!f.argument().empty()) {
367 name1 = name2 + ' ' + toqstr(f.argument());
368 name1.replace(' ', '_');
369 name1.replace('\\', "backslash");
373 QStringList imagedirs;
374 imagedirs << "images/" << "images/ipa/";
375 for (int i = 0; i < imagedirs.size(); ++i) {
376 QString imagedir = imagedirs.at(i) + path;
377 FileName fname = imageLibFileSearch(imagedir, name1, "png");
379 return toqstr(fname.absFileName());
381 fname = imageLibFileSearch(imagedir, name2, "png");
383 return toqstr(fname.absFileName());
386 path = ":/images/" + path;
389 LYXERR0("Directory " << path << " not found in resource!");
393 if (res.exists(name1))
397 if (res.exists(name2))
400 LYXERR(Debug::GUI, "Cannot find icon with filename "
401 << "\"" << name1 << "\""
403 << "\"" << name2 << "\""
405 << lyxaction.getActionName(f.action())
406 << '(' << to_utf8(f.argument()) << ")\"");
409 QString imagedir = "images/";
410 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
412 return toqstr(fname.absFileName());
413 return QString(":/images/unknown.png");
419 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
422 QString imagedir = path;
423 FileName fname = imageLibFileSearch(imagedir, name, ext);
424 QString path1 = toqstr(fname.absFileName());
425 QString path2 = ":/" + path + name + "." + ext;
427 if (pixmap.load(path1)) {
430 else if (pixmap.load(path2)) {
434 LYXERR0("Cannot load pixmap \""
435 << path << name << '.' << ext
436 << "\", please verify resource system!");
441 QIcon getIcon(FuncRequest const & f, bool unknown)
443 QString icon = iconName(f, unknown);
447 //LYXERR(Debug::GUI, "Found icon: " << icon);
449 if (!pm.load(icon)) {
450 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
458 ////////////////////////////////////////////////////////////////////////
460 // LyX server support code.
462 ////////////////////////////////////////////////////////////////////////
464 class SocketNotifier : public QSocketNotifier
467 /// connect a connection notification from the LyXServerSocket
468 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
469 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
473 /// The callback function
474 Application::SocketCallback func_;
478 ////////////////////////////////////////////////////////////////////////
480 // Mac specific stuff goes here...
482 ////////////////////////////////////////////////////////////////////////
484 class MenuTranslator : public QTranslator
487 MenuTranslator(QObject * parent)
488 : QTranslator(parent)
491 QString translate(const char * /*context*/,
492 const char * sourceText,
493 const char * /*comment*/ = 0) const
495 string const s = sourceText;
496 if (s == N_("About %1") || s == N_("Preferences")
497 || s == N_("Reconfigure") || s == N_("Quit %1"))
504 class GlobalMenuBar : public QMenuBar
508 GlobalMenuBar() : QMenuBar(0) {}
511 bool event(QEvent * e)
513 if (e->type() == QEvent::ShortcutOverride) {
514 // && activeWindow() == 0) {
515 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
517 setKeySymbol(&sym, ke);
518 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
527 // QMacPasteboardMimeGraphics can only be compiled on Mac.
529 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
532 QMacPasteboardMimeGraphics()
533 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
536 QString convertorName() { return "Graphics"; }
538 QString flavorFor(QString const & mime)
540 LYXERR(Debug::ACTION, "flavorFor " << mime);
541 if (mime == pdfMimeType())
542 return QLatin1String("com.adobe.pdf");
546 QString mimeFor(QString flav)
548 LYXERR(Debug::ACTION, "mimeFor " << flav);
549 if (flav == QLatin1String("com.adobe.pdf"))
550 return pdfMimeType();
554 bool canConvert(QString const & mime, QString flav)
556 return mimeFor(flav) == mime;
559 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
563 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
567 QList<QByteArray> convertFromMime(QString const & /*mime*/,
568 QVariant data, QString /*flav*/)
570 QList<QByteArray> ret;
571 ret.append(data.toByteArray());
577 ///////////////////////////////////////////////////////////////
579 // You can find more platform specific stuff at the end of this file...
581 ///////////////////////////////////////////////////////////////
583 ////////////////////////////////////////////////////////////////////////
584 // Windows specific stuff goes here...
587 // QWindowsMimeMetafile can only be compiled on Windows.
589 static FORMATETC cfFromMime(QString const & mimetype)
592 if (mimetype == emfMimeType()) {
593 formatetc.cfFormat = CF_ENHMETAFILE;
594 formatetc.tymed = TYMED_ENHMF;
595 } else if (mimetype == wmfMimeType()) {
596 formatetc.cfFormat = CF_METAFILEPICT;
597 formatetc.tymed = TYMED_MFPICT;
600 formatetc.dwAspect = DVASPECT_CONTENT;
601 formatetc.lindex = -1;
606 class QWindowsMimeMetafile : public QWindowsMime {
608 QWindowsMimeMetafile() {}
610 bool canConvertFromMime(FORMATETC const & formatetc,
611 QMimeData const * mimedata) const
616 bool canConvertToMime(QString const & mimetype,
617 IDataObject * pDataObj) const
619 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
621 FORMATETC formatetc = cfFromMime(mimetype);
622 return pDataObj->QueryGetData(&formatetc) == S_OK;
625 bool convertFromMime(FORMATETC const & formatetc,
626 const QMimeData * mimedata, STGMEDIUM * pmedium) const
631 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
632 QVariant::Type preferredType) const
635 if (!canConvertToMime(mimetype, pDataObj))
638 FORMATETC formatetc = cfFromMime(mimetype);
640 if (pDataObj->GetData(&formatetc, &s) != S_OK)
644 if (s.tymed == TYMED_ENHMF) {
645 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
646 data.resize(dataSize);
647 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
648 (LPBYTE)data.data());
649 } else if (s.tymed == TYMED_MFPICT) {
650 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
651 data.resize(dataSize);
652 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
653 (LPBYTE)data.data());
656 ReleaseStgMedium(&s);
662 QVector<FORMATETC> formatsForMime(QString const & mimetype,
663 QMimeData const * mimedata) const
665 QVector<FORMATETC> formats;
666 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
667 formats += cfFromMime(mimetype);
671 QString mimeForFormat(FORMATETC const & formatetc) const
673 switch (formatetc.cfFormat) {
675 return emfMimeType();
676 case CF_METAFILEPICT:
677 return wmfMimeType();
686 /// Allows to check whether ESC was pressed during a long operation
687 class KeyChecker : public QObject {
692 KeyChecker() : pressed_(false), started_(false) {}
695 QCoreApplication::instance()->installEventFilter(this);
700 QCoreApplication::instance()->removeEventFilter(this);
704 QCoreApplication::processEvents();
707 bool started() const {
710 bool eventFilter(QObject *obj, QEvent *event) {
711 LYXERR(Debug::ACTION, "Event Type: " << event->type());
712 switch (event->type()) {
716 return QObject::eventFilter(obj, event);
718 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
719 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
727 ////////////////////////////////////////////////////////////////////////
728 // GuiApplication::Private definition and implementation.
729 ////////////////////////////////////////////////////////////////////////
731 struct GuiApplication::Private
733 Private(): language_model_(0), meta_fake_bit(NoModifier),
737 /// WMF Mime handler for Windows clipboard.
738 wmf_mime_ = new QWindowsMimeMetafile;
740 initKeySequences(&theTopLevelKeymap());
743 void initKeySequences(KeyMap * kb)
745 keyseq = KeySequence(kb, kb);
746 cancel_meta_seq = KeySequence(kb, kb);
750 QSortFilterProxyModel * language_model_;
752 GuiClipboard clipboard_;
754 GuiSelection selection_;
756 FontLoader font_loader_;
758 ColorCache color_cache_;
760 QTranslator qt_trans_;
762 QHash<int, SocketNotifier *> socket_notifiers_;
766 /// The global instance
769 /// this timer is used for any regular events one wants to
770 /// perform. at present it is used to check if forked processes
772 QTimer general_timer_;
774 /// delayed FuncRequests
775 std::queue<FuncRequest> func_request_queue_;
780 KeySequence cancel_meta_seq;
782 KeyModifier meta_fake_bit;
784 /// Multiple views container.
786 * Warning: This must not be a smart pointer as the destruction of the
787 * object is handled by Qt when the view is closed
788 * \sa Qt::WA_DeleteOnClose attribute.
790 QHash<int, GuiView *> views_;
792 /// Only used on mac.
793 GlobalMenuBar * global_menubar_;
796 /// Linkback mime handler for MacOSX.
797 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
801 /// WMF Mime handler for Windows clipboard.
802 QWindowsMimeMetafile * wmf_mime_;
805 /// Allows to check whether ESC was pressed during a long operation
806 KeyChecker key_checker_;
810 GuiApplication * guiApp;
812 GuiApplication::~GuiApplication()
815 closeAllLinkBackLinks();
821 GuiApplication::GuiApplication(int & argc, char ** argv)
822 : QApplication(argc, argv), current_view_(0),
823 d(new GuiApplication::Private)
825 QString app_name = "LyX";
826 QCoreApplication::setOrganizationName(app_name);
827 QCoreApplication::setOrganizationDomain("lyx.org");
828 QCoreApplication::setApplicationName(lyx_package);
830 // Install translator for GUI elements.
831 installTranslator(&d->qt_trans_);
833 // FIXME: quitOnLastWindowClosed is true by default. We should have a
834 // lyxrc setting for this in order to let the application stay resident.
835 // But then we need some kind of dock icon, at least on Windows.
837 if (lyxrc.quit_on_last_window_closed)
838 setQuitOnLastWindowClosed(false);
841 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
842 // seems to be the default case for applications like LyX.
843 setQuitOnLastWindowClosed(false);
844 // This allows to translate the strings that appear in the LyX menu.
845 /// A translator suitable for the entries in the LyX menu.
846 /// Only needed with Qt/Mac.
847 installTranslator(new MenuTranslator(this));
853 // doubleClickInterval() is 400 ms on X11 which is just too long.
854 // On Windows and Mac OS X, the operating system's value is used.
855 // On Microsoft Windows, calling this function sets the double
856 // click interval for all applications. So we don't!
857 QApplication::setDoubleClickInterval(300);
860 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
862 // needs to be done before reading lyxrc
864 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
868 // Set the cache to 5120 kilobytes which corresponds to screen size of
869 // 1280 by 1024 pixels with a color depth of 32 bits.
870 QPixmapCache::setCacheLimit(5120);
872 // Initialize RC Fonts
873 if (lyxrc.roman_font_name.empty())
874 lyxrc.roman_font_name = fromqstr(romanFontName());
876 if (lyxrc.sans_font_name.empty())
877 lyxrc.sans_font_name = fromqstr(sansFontName());
879 if (lyxrc.typewriter_font_name.empty())
880 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
882 d->general_timer_.setInterval(500);
883 connect(&d->general_timer_, SIGNAL(timeout()),
884 this, SLOT(handleRegularEvents()));
885 d->general_timer_.start();
887 // maxThreadCount() defaults in general to 2 on single or dual-processor.
888 // This is clearly not enough in a time where we use threads for
889 // document preview and/or export. 20 should be OK.
890 QThreadPool::globalInstance()->setMaxThreadCount(20);
894 GuiApplication * theGuiApp()
896 return dynamic_cast<GuiApplication *>(theApp());
900 void GuiApplication::clearSession()
907 docstring Application::iconName(FuncRequest const & f, bool unknown)
909 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
913 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
918 BufferView * doc_bv = 0;
920 if (cmd.action() == LFUN_NOACTION) {
921 status.message(from_utf8(N_("Nothing to do")));
922 status.setEnabled(false);
925 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
926 status.setUnknown(true);
927 status.message(from_utf8(N_("Unknown action")));
928 status.setEnabled(false);
931 // Does the GuiApplication know something?
932 else if (getStatus(cmd, status)) { }
934 // If we do not have a GuiView, then other functions are disabled
935 else if (!current_view_)
936 status.setEnabled(false);
938 // Does the GuiView know something?
939 else if (current_view_->getStatus(cmd, status)) { }
941 // In LyX/Mac, when a dialog is open, the menus of the
942 // application can still be accessed without giving focus to
943 // the main window. In this case, we want to disable the menu
944 // entries that are buffer or view-related.
945 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
947 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
948 status.setEnabled(false);
951 // If we do not have a BufferView, then other functions are disabled
952 else if (!(bv = current_view_->currentBufferView()))
953 status.setEnabled(false);
955 // Does the current BufferView know something?
956 else if (bv->getStatus(cmd, status)) { }
958 // Does the current Buffer know something?
959 else if (bv->buffer().getStatus(cmd, status)) { }
961 // If we do not have a document BufferView, different from the
962 // current BufferView, then other functions are disabled
963 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
964 status.setEnabled(false);
966 // Does the document Buffer know something?
967 else if (doc_bv->buffer().getStatus(cmd, status)) { }
970 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
971 status.message(from_utf8(N_("Command not handled")));
972 status.setEnabled(false);
975 // the default error message if we disable the command
976 if (!status.enabled() && status.message().empty())
977 status.message(from_utf8(N_("Command disabled")));
983 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
985 // I would really like to avoid having this switch and rather try to
986 // encode this in the function itself.
987 // -- And I'd rather let an inset decide which LFUNs it is willing
988 // to handle (Andre')
990 switch (cmd.action()) {
992 // This could be used for the no-GUI version. The GUI version is handled in
993 // GuiView::getStatus(). See above.
995 case LFUN_BUFFER_WRITE:
996 case LFUN_BUFFER_WRITE_AS: {
997 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
998 enable = b && (b->isUnnamed() || !b->isClean());
1003 case LFUN_BOOKMARK_GOTO: {
1004 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1005 enable = theSession().bookmarks().isValid(num);
1009 case LFUN_BOOKMARK_CLEAR:
1010 enable = theSession().bookmarks().hasValid();
1013 // this one is difficult to get right. As a half-baked
1014 // solution, we consider only the first action of the sequence
1015 case LFUN_COMMAND_SEQUENCE: {
1016 // argument contains ';'-terminated commands
1017 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1018 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1019 func.setOrigin(cmd.origin());
1020 flag = getStatus(func);
1024 // we want to check if at least one of these is enabled
1025 case LFUN_COMMAND_ALTERNATIVES: {
1026 // argument contains ';'-terminated commands
1027 string arg = to_utf8(cmd.argument());
1028 while (!arg.empty()) {
1030 arg = split(arg, first, ';');
1031 FuncRequest func(lyxaction.lookupFunc(first));
1032 func.setOrigin(cmd.origin());
1033 flag = getStatus(func);
1034 // if this one is enabled, the whole thing is
1043 string name = to_utf8(cmd.argument());
1044 if (theTopLevelCmdDef().lock(name, func)) {
1045 func.setOrigin(cmd.origin());
1046 flag = getStatus(func);
1047 theTopLevelCmdDef().release(name);
1049 // catch recursion or unknown command
1050 // definition. all operations until the
1051 // recursion or unknown command definition
1052 // occurs are performed, so set the state to
1059 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1061 case LFUN_PREFERENCES_SAVE:
1062 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1063 case LFUN_DEBUG_LEVEL_SET:
1064 // these are handled in our dispatch()
1067 case LFUN_WINDOW_CLOSE:
1068 enable = d->views_.size() > 0;
1071 case LFUN_BUFFER_NEW:
1072 case LFUN_BUFFER_NEW_TEMPLATE:
1073 case LFUN_FILE_OPEN:
1074 case LFUN_HELP_OPEN:
1075 case LFUN_SCREEN_FONT_UPDATE:
1076 case LFUN_SET_COLOR:
1077 case LFUN_WINDOW_NEW:
1079 case LFUN_LYXRC_APPLY:
1080 case LFUN_COMMAND_PREFIX:
1082 case LFUN_META_PREFIX:
1083 case LFUN_RECONFIGURE:
1084 case LFUN_SERVER_GET_FILENAME:
1085 case LFUN_SERVER_NOTIFY:
1089 case LFUN_BUFFER_FORALL: {
1090 if (theBufferList().empty()) {
1091 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1092 flag.setEnabled(false);
1096 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1097 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1098 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1099 flag.setEnabled(false);
1110 flag.setEnabled(false);
1114 /// make a post-dispatch status message
1115 static docstring makeDispatchMessage(docstring const & msg,
1116 FuncRequest const & cmd)
1118 const bool verbose = (cmd.origin() == FuncRequest::MENU
1119 || cmd.origin() == FuncRequest::TOOLBAR
1120 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1122 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1123 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1127 docstring dispatch_msg = msg;
1128 if (!dispatch_msg.empty())
1129 dispatch_msg += ' ';
1131 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1133 bool argsadded = false;
1135 if (!cmd.argument().empty()) {
1136 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1137 comname += ' ' + cmd.argument();
1141 docstring const shortcuts = theTopLevelKeymap().
1142 printBindings(cmd, KeySequence::ForGui);
1144 if (!shortcuts.empty())
1145 comname += ": " + shortcuts;
1146 else if (!argsadded && !cmd.argument().empty())
1147 comname += ' ' + cmd.argument();
1149 if (!comname.empty()) {
1150 comname = rtrim(comname);
1151 dispatch_msg += '(' + rtrim(comname) + ')';
1153 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1154 return dispatch_msg;
1158 void GuiApplication::dispatch(FuncRequest const & cmd)
1160 Buffer * buffer = 0;
1161 if (current_view_ && current_view_->currentBufferView()) {
1162 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1163 buffer = ¤t_view_->currentBufferView()->buffer();
1165 buffer->undo().beginUndoGroup();
1169 // redraw the screen at the end (first of the two drawing steps).
1170 // This is done unless explicitly requested otherwise
1171 dr.screenUpdate(Update::FitCursor);
1173 updateCurrentView(cmd, dr);
1175 // the buffer may have been closed by one action
1176 if (theBufferList().isLoaded(buffer))
1177 buffer->undo().endUndoGroup();
1181 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1186 BufferView * bv = current_view_->currentBufferView();
1188 if (dr.needBufferUpdate()) {
1189 bv->cursor().clearBufferUpdate();
1190 bv->buffer().updateBuffer();
1192 // BufferView::update() updates the ViewMetricsInfo and
1193 // also initializes the position cache for all insets in
1194 // (at least partially) visible top-level paragraphs.
1195 // We will redraw the screen only if needed.
1196 bv->processUpdateFlags(dr.screenUpdate());
1198 // Do we have a selection?
1199 theSelection().haveSelection(bv->cursor().selection());
1202 current_view_->restartCursor();
1204 if (dr.needMessageUpdate()) {
1205 // Some messages may already be translated, so we cannot use _()
1206 current_view_->message(makeDispatchMessage(
1207 translateIfPossible(dr.message()), cmd));
1212 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1213 bool switchToBuffer)
1215 if (!theSession().bookmarks().isValid(idx))
1217 BookmarksSection::Bookmark const & bm =
1218 theSession().bookmarks().bookmark(idx);
1219 LASSERT(!bm.filename.empty(), /**/);
1220 string const file = bm.filename.absFileName();
1221 // if the file is not opened, open it.
1222 if (!theBufferList().exists(bm.filename)) {
1224 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1228 // open may fail, so we need to test it again
1229 if (!theBufferList().exists(bm.filename))
1232 // bm can be changed when saving
1233 BookmarksSection::Bookmark tmp = bm;
1235 // Special case idx == 0 used for back-from-back jump navigation
1237 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1239 // if the current buffer is not that one, switch to it.
1240 BufferView * doc_bv = current_view_ ?
1241 current_view_->documentBufferView() : 0;
1242 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1243 if (switchToBuffer) {
1244 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1247 doc_bv = current_view_->documentBufferView();
1252 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1253 if (!doc_bv->moveToPosition(
1254 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1261 // Cursor jump succeeded!
1262 Cursor const & cur = doc_bv->cursor();
1263 pit_type new_pit = cur.pit();
1264 pos_type new_pos = cur.pos();
1265 int new_id = cur.paragraph().id();
1267 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1268 // see http://www.lyx.org/trac/ticket/3092
1269 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1270 || bm.top_id != new_id) {
1271 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1272 new_pit, new_pos, new_id);
1276 // This function runs "configure" and then rereads lyx.defaults to
1277 // reconfigure the automatic settings.
1278 void GuiApplication::reconfigure(string const & option)
1280 // emit message signal.
1282 current_view_->message(_("Running configure..."));
1284 // Run configure in user lyx directory
1285 PathChanger p(package().user_support());
1286 string configure_command = package().configure_command();
1287 configure_command += option;
1289 int const ret = one.startscript(Systemcall::Wait, configure_command);
1291 // emit message signal.
1293 current_view_->message(_("Reloading configuration..."));
1294 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1295 // Re-read packages.lst
1296 LaTeXPackages::getAvailable();
1299 Alert::information(_("System reconfiguration failed"),
1300 _("The system reconfiguration has failed.\n"
1301 "Default textclass is used but LyX may\n"
1302 "not be able to work properly.\n"
1303 "Please reconfigure again if needed."));
1305 Alert::information(_("System reconfigured"),
1306 _("The system has been reconfigured.\n"
1307 "You need to restart LyX to make use of any\n"
1308 "updated document class specifications."));
1311 void GuiApplication::validateCurrentView()
1313 if (!d->views_.empty() && !current_view_) {
1314 // currently at least one view exists but no view has the focus.
1315 // choose the last view to make it current.
1316 // a view without any open document is preferred.
1317 GuiView * candidate = 0;
1318 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1319 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1320 for (; it != end; ++it) {
1322 if (!candidate->documentBufferView())
1325 setCurrentView(candidate);
1329 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1331 string const argument = to_utf8(cmd.argument());
1332 FuncCode const action = cmd.action();
1334 LYXERR(Debug::ACTION, "cmd: " << cmd);
1336 // we have not done anything wrong yet.
1339 FuncStatus const flag = getStatus(cmd);
1340 if (!flag.enabled()) {
1341 // We cannot use this function here
1342 LYXERR(Debug::ACTION, "action "
1343 << lyxaction.getActionName(action)
1344 << " [" << action << "] is disabled at this location");
1345 dr.setMessage(flag.message());
1347 dr.dispatched(false);
1348 dr.screenUpdate(Update::None);
1349 dr.clearBufferUpdate();
1353 if (cmd.origin() == FuncRequest::LYXSERVER) {
1354 if (current_view_ && current_view_->currentBufferView())
1355 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1356 // we will also need to redraw the screen at the end
1357 dr.screenUpdate(Update::FitCursor);
1360 // Assumes that the action will be dispatched.
1361 dr.dispatched(true);
1363 switch (cmd.action()) {
1365 case LFUN_WINDOW_NEW:
1366 createView(toqstr(cmd.argument()));
1369 case LFUN_WINDOW_CLOSE:
1370 // update bookmark pit of the current buffer before window close
1371 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1372 gotoBookmark(i+1, false, false);
1373 // clear the last opened list, because
1374 // maybe this will end the session
1375 theSession().lastOpened().clear();
1376 // check for valid current_view_
1377 validateCurrentView();
1379 current_view_->closeScheduled();
1383 // quitting is triggered by the gui code
1384 // (leaving the event loop).
1386 current_view_->message(from_utf8(N_("Exiting.")));
1387 if (closeAllViews())
1391 case LFUN_SCREEN_FONT_UPDATE: {
1392 // handle the screen font changes.
1393 d->font_loader_.update();
1394 // Backup current_view_
1395 GuiView * view = current_view_;
1396 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1397 // to skip the refresh.
1399 theBufferList().changed(false);
1400 // Restore current_view_
1401 current_view_ = view;
1405 case LFUN_BUFFER_NEW:
1406 validateCurrentView();
1407 if (d->views_.empty()
1408 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1409 createView(QString(), false); // keep hidden
1410 current_view_->newDocument(to_utf8(cmd.argument()), false);
1411 current_view_->show();
1412 setActiveWindow(current_view_);
1414 current_view_->newDocument(to_utf8(cmd.argument()), false);
1418 case LFUN_BUFFER_NEW_TEMPLATE:
1419 validateCurrentView();
1420 if (d->views_.empty()
1421 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1423 current_view_->newDocument(to_utf8(cmd.argument()), true);
1424 if (!current_view_->documentBufferView())
1425 current_view_->close();
1427 current_view_->newDocument(to_utf8(cmd.argument()), true);
1431 case LFUN_FILE_OPEN: {
1432 validateCurrentView();
1433 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1434 string const fname = to_utf8(cmd.argument());
1435 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1436 && current_view_->documentBufferView() != 0)) {
1437 // We want the ui session to be saved per document and not per
1438 // window number. The filename crc is a good enough identifier.
1439 boost::crc_32_type crc;
1440 crc = for_each(fname.begin(), fname.end(), crc);
1441 createView(crc.checksum());
1442 current_view_->openDocument(fname);
1443 if (current_view_ && !current_view_->documentBufferView())
1444 current_view_->close();
1446 current_view_->openDocument(fname);
1450 case LFUN_HELP_OPEN: {
1451 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1452 if (current_view_ == 0)
1454 string const arg = to_utf8(cmd.argument());
1456 current_view_->message(_("Missing argument"));
1459 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1461 fname = i18nLibFileSearch("examples", arg, "lyx");
1463 if (fname.empty()) {
1464 lyxerr << "LyX: unable to find documentation file `"
1465 << arg << "'. Bad installation?" << endl;
1468 current_view_->message(bformat(_("Opening help file %1$s..."),
1469 makeDisplayPath(fname.absFileName())));
1470 Buffer * buf = current_view_->loadDocument(fname, false);
1472 #ifndef DEVEL_VERSION
1474 buf->setReadonly(true);
1481 case LFUN_SET_COLOR: {
1483 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1484 if (lyx_name.empty() || x11_name.empty()) {
1486 current_view_->message(
1487 _("Syntax: set-color <lyx_name> <x11_name>"));
1492 // FIXME: The graphics cache no longer has a changeDisplay method.
1493 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1494 bool const graphicsbg_changed =
1495 lyx_name == graphicsbg && x11_name != graphicsbg;
1496 if (graphicsbg_changed)
1497 graphics::GCache::get().changeDisplay(true);
1500 if (!lcolor.setColor(lyx_name, x11_name)) {
1502 current_view_->message(
1503 bformat(_("Set-color \"%1$s\" failed "
1504 "- color is undefined or "
1505 "may not be redefined"),
1506 from_utf8(lyx_name)));
1509 // Make sure we don't keep old colors in cache.
1510 d->color_cache_.clear();
1514 case LFUN_LYXRC_APPLY: {
1515 // reset active key sequences, since the bindings
1516 // are updated (bug 6064)
1518 LyXRC const lyxrc_orig = lyxrc;
1520 istringstream ss(to_utf8(cmd.argument()));
1521 bool const success = lyxrc.read(ss);
1524 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1525 << "Unable to read lyxrc data"
1530 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1536 case LFUN_COMMAND_PREFIX:
1537 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1542 d->meta_fake_bit = NoModifier;
1543 GuiView * gv = currentView();
1544 if (gv && gv->currentBufferView())
1545 // cancel any selection
1546 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1547 dr.setMessage(from_ascii(N_("Cancel")));
1550 case LFUN_META_PREFIX:
1551 d->meta_fake_bit = AltModifier;
1552 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1555 // --- Menus -----------------------------------------------
1556 case LFUN_RECONFIGURE:
1557 // argument is any additional parameter to the configure.py command
1558 reconfigure(to_utf8(cmd.argument()));
1561 // --- lyxserver commands ----------------------------
1562 case LFUN_SERVER_GET_FILENAME: {
1563 if (current_view_ && current_view_->documentBufferView()) {
1564 docstring const fname = from_utf8(
1565 current_view_->documentBufferView()->buffer().absFileName());
1566 dr.setMessage(fname);
1567 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1569 dr.setMessage(docstring());
1570 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1575 case LFUN_SERVER_NOTIFY: {
1576 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1577 dr.setMessage(dispatch_buffer);
1578 theServer().notifyClient(to_utf8(dispatch_buffer));
1582 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1583 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1589 string rest = split(argument, countstr, ' ');
1590 istringstream is(countstr);
1593 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1594 for (int i = 0; i < count; ++i)
1595 dispatch(lyxaction.lookupFunc(rest));
1599 case LFUN_COMMAND_SEQUENCE: {
1600 // argument contains ';'-terminated commands
1601 string arg = argument;
1602 // FIXME: this LFUN should also work without any view.
1603 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1604 ? &(current_view_->documentBufferView()->buffer()) : 0;
1606 buffer->undo().beginUndoGroup();
1607 while (!arg.empty()) {
1609 arg = split(arg, first, ';');
1610 FuncRequest func(lyxaction.lookupFunc(first));
1611 func.setOrigin(cmd.origin());
1614 // the buffer may have been closed by one action
1615 if (theBufferList().isLoaded(buffer))
1616 buffer->undo().endUndoGroup();
1620 case LFUN_BUFFER_FORALL: {
1621 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1623 map<Buffer *, GuiView *> views_lVisible;
1624 map<GuiView *, Buffer *> activeBuffers;
1626 QList<GuiView *> allViews = d->views_.values();
1628 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1629 // and on which buffer is active in each view.
1630 Buffer * const last = theBufferList().last();
1631 foreach (GuiView * view, allViews) {
1632 // all of the buffers might be locally hidden. That is, there is no active buffer.
1633 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1634 activeBuffers[view] = 0;
1636 activeBuffers[view] = &view->currentBufferView()->buffer();
1638 // find out if each is locally visible or locally hidden.
1639 // we don't use a for loop as the buffer list cycles.
1640 Buffer * b = theBufferList().first();
1642 bool const locallyVisible = view && view->workArea(*b);
1643 if (locallyVisible) {
1644 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1645 // only need to overwrite/add if we don't already know a buffer is globally
1646 // visible or we do know but we would prefer to dispatch LFUN from the
1647 // current view because of cursor position issues.
1648 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1649 views_lVisible[b] = view;
1653 b = theBufferList().next(b);
1657 GuiView * const homeView = currentView();
1658 Buffer * b = theBufferList().first();
1659 Buffer * nextBuf = 0;
1660 int numProcessed = 0;
1663 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1665 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1667 // first change to a view where b is locally visible, preferably current_view_.
1668 GuiView * const vLv = views_lVisible[b];
1670 lyx::dispatch(funcToRun);
1678 // put things back to how they were (if possible).
1679 foreach (GuiView * view, allViews) {
1680 Buffer * originalBuf = activeBuffers[view];
1681 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1682 if (theBufferList().isLoaded(originalBuf))
1683 view->setBuffer(originalBuf);
1685 homeView->setFocus();
1687 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1691 case LFUN_COMMAND_ALTERNATIVES: {
1692 // argument contains ';'-terminated commands
1693 string arg = argument;
1694 while (!arg.empty()) {
1696 arg = split(arg, first, ';');
1697 FuncRequest func(lyxaction.lookupFunc(first));
1698 func.setOrigin(cmd.origin());
1699 FuncStatus const stat = getStatus(func);
1700 if (stat.enabled()) {
1710 if (theTopLevelCmdDef().lock(argument, func)) {
1711 func.setOrigin(cmd.origin());
1713 theTopLevelCmdDef().release(argument);
1715 if (func.action() == LFUN_UNKNOWN_ACTION) {
1716 // unknown command definition
1717 lyxerr << "Warning: unknown command definition `"
1721 // recursion detected
1722 lyxerr << "Warning: Recursion in the command definition `"
1723 << argument << "' detected"
1730 case LFUN_PREFERENCES_SAVE:
1731 lyxrc.write(support::makeAbsPath("preferences",
1732 package().user_support().absFileName()), false);
1735 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1736 string const fname = addName(addPath(package().user_support().absFileName(),
1737 "templates/"), "defaults.lyx");
1738 Buffer defaults(fname);
1740 istringstream ss(argument);
1743 int const unknown_tokens = defaults.readHeader(lex);
1745 if (unknown_tokens != 0) {
1746 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1747 << unknown_tokens << " unknown token"
1748 << (unknown_tokens == 1 ? "" : "s")
1752 if (defaults.writeFile(FileName(defaults.absFileName())))
1753 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1754 makeDisplayPath(fname)));
1757 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1762 case LFUN_BOOKMARK_GOTO:
1763 // go to bookmark, open unopened file and switch to buffer if necessary
1764 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1765 dr.screenUpdate(Update::Force | Update::FitCursor);
1768 case LFUN_BOOKMARK_CLEAR:
1769 theSession().bookmarks().clear();
1772 case LFUN_DEBUG_LEVEL_SET:
1773 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1777 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1780 current_view_->dispatch(cmd, dr);
1784 if (cmd.origin() == FuncRequest::LYXSERVER)
1785 updateCurrentView(cmd, dr);
1789 docstring GuiApplication::viewStatusMessage()
1791 // When meta-fake key is pressed, show the key sequence so far + "M-".
1792 if (d->meta_fake_bit != NoModifier)
1793 return d->keyseq.print(KeySequence::ForGui) + "M-";
1795 // Else, when a non-complete key sequence is pressed,
1796 // show the available options.
1797 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1798 return d->keyseq.printOptions(true);
1804 void GuiApplication::handleKeyFunc(FuncCode action)
1808 if (d->keyseq.length())
1810 GuiView * gv = currentView();
1811 LASSERT(gv && gv->currentBufferView(), return);
1812 BufferView * bv = gv->currentBufferView();
1813 bv->getIntl().getTransManager().deadkey(
1814 c, get_accent(action).accent, bv->cursor().innerText(),
1816 // Need to clear, in case the minibuffer calls these
1819 // copied verbatim from do_accent_char
1820 bv->cursor().resetAnchor();
1824 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1826 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1828 // Do nothing if we have nothing (JMarc)
1829 if (!keysym.isOK()) {
1830 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1832 current_view_->restartCursor();
1836 if (keysym.isModifier()) {
1838 current_view_->restartCursor();
1842 char_type encoded_last_key = keysym.getUCSEncoded();
1844 // Do a one-deep top-level lookup for
1845 // cancel and meta-fake keys. RVDK_PATCH_5
1846 d->cancel_meta_seq.reset();
1848 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1849 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1851 // When not cancel or meta-fake, do the normal lookup.
1852 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1853 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1854 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1855 // remove Caps Lock and Mod2 as a modifiers
1856 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1857 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1860 // Dont remove this unless you know what you are doing.
1861 d->meta_fake_bit = NoModifier;
1863 // Can this happen now ?
1864 if (func.action() == LFUN_NOACTION)
1865 func = FuncRequest(LFUN_COMMAND_PREFIX);
1867 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1868 << d->keyseq.print(KeySequence::Portable) << ']');
1870 // already here we know if it any point in going further
1871 // why not return already here if action == -1 and
1872 // num_bytes == 0? (Lgb)
1874 if (d->keyseq.length() > 1 && current_view_)
1875 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1878 // Maybe user can only reach the key via holding down shift.
1879 // Let's see. But only if shift is the only modifier
1880 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1881 LYXERR(Debug::KEY, "Trying without shift");
1882 func = d->keyseq.addkey(keysym, NoModifier);
1883 LYXERR(Debug::KEY, "Action now " << func.action());
1886 if (func.action() == LFUN_UNKNOWN_ACTION) {
1887 // Hmm, we didn't match any of the keysequences. See
1888 // if it's normal insertable text not already covered
1890 if (keysym.isText() && d->keyseq.length() == 1) {
1891 LYXERR(Debug::KEY, "isText() is true, inserting.");
1892 func = FuncRequest(LFUN_SELF_INSERT,
1893 FuncRequest::KEYBOARD);
1895 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1896 if (current_view_) {
1897 current_view_->message(_("Unknown function."));
1898 current_view_->restartCursor();
1904 if (func.action() == LFUN_SELF_INSERT) {
1905 if (encoded_last_key != 0) {
1906 docstring const arg(1, encoded_last_key);
1907 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1908 FuncRequest::KEYBOARD));
1909 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1912 processFuncRequest(func);
1916 void GuiApplication::processFuncRequest(FuncRequest const & func)
1918 lyx::dispatch(func);
1922 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1924 addToFuncRequestQueue(func);
1925 processFuncRequestQueueAsync();
1929 void GuiApplication::processFuncRequestQueue()
1931 while (!d->func_request_queue_.empty()) {
1932 processFuncRequest(d->func_request_queue_.front());
1933 d->func_request_queue_.pop();
1938 void GuiApplication::processFuncRequestQueueAsync()
1940 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1944 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1946 d->func_request_queue_.push(func);
1950 void GuiApplication::resetGui()
1952 // Set the language defined by the user.
1956 if (!readUIFile(toqstr(lyxrc.ui_file)))
1957 // Gives some error box here.
1960 if (d->global_menubar_)
1961 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1963 QHash<int, GuiView *>::iterator it;
1964 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1967 gv->setLayoutDirection(layoutDirection());
1971 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1975 void GuiApplication::createView(int view_id)
1977 createView(QString(), true, view_id);
1981 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1984 // release the keyboard which might have been grabed by the global
1985 // menubar on Mac to catch shortcuts even without any GuiView.
1986 if (d->global_menubar_)
1987 d->global_menubar_->releaseKeyboard();
1991 while (d->views_.find(id) != d->views_.end())
1994 LYXERR(Debug::GUI, "About to create new window with ID " << id);
1995 GuiView * view = new GuiView(id);
1997 d->views_[id] = view;
2001 setActiveWindow(view);
2004 if (!geometry_arg.isEmpty()) {
2008 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2009 re.indexIn(geometry_arg);
2010 w = re.cap(1).toInt();
2011 h = re.cap(2).toInt();
2012 x = re.cap(3).toInt();
2013 y = re.cap(4).toInt();
2014 view->setGeometry(x, y, w, h);
2021 Clipboard & GuiApplication::clipboard()
2023 return d->clipboard_;
2027 Selection & GuiApplication::selection()
2029 return d->selection_;
2033 FontLoader & GuiApplication::fontLoader()
2035 return d->font_loader_;
2039 Toolbars const & GuiApplication::toolbars() const
2041 return d->toolbars_;
2045 Toolbars & GuiApplication::toolbars()
2047 return d->toolbars_;
2051 Menus const & GuiApplication::menus() const
2057 Menus & GuiApplication::menus()
2063 QList<int> GuiApplication::viewIds() const
2065 return d->views_.keys();
2069 ColorCache & GuiApplication::colorCache()
2071 return d->color_cache_;
2075 int GuiApplication::exec()
2077 // asynchronously handle batch commands. This event will be in
2078 // the event queue in front of other asynchronous events. Hence,
2079 // we can assume in the latter that the gui is setup already.
2080 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2082 return QApplication::exec();
2086 void GuiApplication::exit(int status)
2088 QApplication::exit(status);
2092 void GuiApplication::setGuiLanguage()
2094 QString const default_language = toqstr(getGuiMessages().language());
2095 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2096 QLocale const default_locale(default_language);
2097 QLocale::setDefault(default_locale);
2099 // install translation file for Qt built-in dialogs
2100 QString const language_name = QString("qt_") + default_locale.name();
2102 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2103 // Short-named translator can be loaded from a long name, but not the
2104 // opposite. Therefore, long name should be used without truncation.
2105 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2106 if (!d->qt_trans_.load(language_name,
2107 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2108 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2111 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2115 switch (default_locale.language()) {
2116 case QLocale::Arabic :
2117 case QLocale::Hebrew :
2118 case QLocale::Persian :
2119 case QLocale::Urdu :
2120 setLayoutDirection(Qt::RightToLeft);
2123 setLayoutDirection(Qt::LeftToRight);
2128 void GuiApplication::execBatchCommands()
2133 if (!readUIFile(toqstr(lyxrc.ui_file)))
2134 // Gives some error box here.
2138 #if QT_VERSION > 0x040600
2139 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2141 // Create the global default menubar which is shown for the dialogs
2142 // and if no GuiView is visible.
2143 // This must be done after the session was recovered to know the "last files".
2144 d->global_menubar_ = new GlobalMenuBar;
2145 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2148 lyx::execBatchCommands();
2152 QAbstractItemModel * GuiApplication::languageModel()
2154 if (d->language_model_)
2155 return d->language_model_;
2157 QStandardItemModel * lang_model = new QStandardItemModel(this);
2158 lang_model->insertColumns(0, 3);
2160 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2161 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2162 Languages::const_iterator it = lyx::languages.begin();
2163 Languages::const_iterator end = lyx::languages.end();
2164 for (; it != end; ++it) {
2165 current_row = lang_model->rowCount();
2166 lang_model->insertRows(current_row, 1);
2167 QModelIndex pl_item = lang_model->index(current_row, 0);
2168 QModelIndex sp_item = lang_model->index(current_row, 1);
2169 QModelIndex th_item = lang_model->index(current_row, 2);
2170 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2171 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2172 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2173 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2174 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2175 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2176 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2177 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2178 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2179 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2181 d->language_model_ = new QSortFilterProxyModel(this);
2182 d->language_model_->setSourceModel(lang_model);
2183 d->language_model_->setSortLocaleAware(true);
2184 return d->language_model_;
2188 void GuiApplication::restoreGuiSession()
2190 if (!lyxrc.load_session)
2193 Session & session = theSession();
2194 LastOpenedSection::LastOpened const & lastopened =
2195 session.lastOpened().getfiles();
2197 validateCurrentView();
2199 FileName active_file;
2200 // do not add to the lastfile list since these files are restored from
2201 // last session, and should be already there (regular files), or should
2202 // not be added at all (help files).
2203 for (size_t i = 0; i < lastopened.size(); ++i) {
2204 FileName const & file_name = lastopened[i].file_name;
2205 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2206 && current_view_->documentBufferView() != 0)) {
2207 boost::crc_32_type crc;
2208 string const & fname = file_name.absFileName();
2209 crc = for_each(fname.begin(), fname.end(), crc);
2210 createView(crc.checksum());
2212 current_view_->loadDocument(file_name, false);
2214 if (lastopened[i].active)
2215 active_file = file_name;
2218 // Restore last active buffer
2219 Buffer * buffer = theBufferList().getBuffer(active_file);
2220 if (buffer && current_view_)
2221 current_view_->setBuffer(buffer);
2223 // clear this list to save a few bytes of RAM
2224 session.lastOpened().clear();
2228 QString const GuiApplication::romanFontName()
2231 font.setKerning(false);
2232 font.setStyleHint(QFont::Serif);
2233 font.setFamily("serif");
2235 return QFontInfo(font).family();
2239 QString const GuiApplication::sansFontName()
2242 font.setKerning(false);
2243 font.setStyleHint(QFont::SansSerif);
2244 font.setFamily("sans");
2246 return QFontInfo(font).family();
2250 QString const GuiApplication::typewriterFontName()
2253 font.setKerning(false);
2254 font.setStyleHint(QFont::TypeWriter);
2255 font.setFamily("monospace");
2257 return QFontInfo(font).family();
2261 void GuiApplication::handleRegularEvents()
2263 ForkedCallsController::handleCompletedProcesses();
2267 bool GuiApplication::event(QEvent * e)
2270 case QEvent::FileOpen: {
2271 // Open a file; this happens only on Mac OS X for now.
2273 // We do this asynchronously because on startup the batch
2274 // commands are not executed here yet and the gui is not ready
2276 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2277 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2278 processFuncRequestAsync(fr);
2283 return QApplication::event(e);
2288 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2291 return QApplication::notify(receiver, event);
2293 catch (ExceptionMessage const & e) {
2295 case ErrorException:
2297 setQuitOnLastWindowClosed(false);
2299 Alert::error(e.title_, e.details_);
2301 // Properly crash in debug mode in order to get a useful backtrace.
2304 // In release mode, try to exit gracefully.
2307 case BufferException: {
2308 if (!current_view_ || !current_view_->documentBufferView())
2310 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2311 docstring details = e.details_ + '\n';
2312 details += buf->emergencyWrite();
2313 theBufferList().release(buf);
2314 details += "\n" + _("The current document was closed.");
2315 Alert::error(e.title_, details);
2318 case WarningException:
2319 Alert::warning(e.title_, e.details_);
2323 catch (exception const & e) {
2324 docstring s = _("LyX has caught an exception, it will now "
2325 "attempt to save all unsaved documents and exit."
2327 s += from_ascii(e.what());
2328 Alert::error(_("Software exception Detected"), s);
2332 docstring s = _("LyX has caught some really weird exception, it will "
2333 "now attempt to save all unsaved documents and exit.");
2334 Alert::error(_("Software exception Detected"), s);
2342 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2344 QColor const & qcol = d->color_cache_.get(col);
2345 if (!qcol.isValid()) {
2351 rgbcol.r = qcol.red();
2352 rgbcol.g = qcol.green();
2353 rgbcol.b = qcol.blue();
2358 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2360 QColor const qcol(lcolor.getX11Name(col).c_str());
2361 if (!qcol.isValid()) {
2367 rgbcol.r = qcol.red();
2368 rgbcol.g = qcol.green();
2369 rgbcol.b = qcol.blue();
2374 string const GuiApplication::hexName(ColorCode col)
2376 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2380 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2382 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2383 d->socket_notifiers_[fd] = sn;
2384 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2388 void GuiApplication::socketDataReceived(int fd)
2390 d->socket_notifiers_[fd]->func_();
2394 void GuiApplication::unregisterSocketCallback(int fd)
2396 d->socket_notifiers_.take(fd)->setEnabled(false);
2400 void GuiApplication::commitData(QSessionManager & sm)
2402 /// The implementation is required to avoid an application exit
2403 /// when session state save is triggered by session manager.
2404 /// The default implementation sends a close event to all
2405 /// visible top level widgets when session managment allows
2407 /// We are changing that to close all wiew one by one.
2408 /// FIXME: verify if the default implementation is enough now.
2409 #ifdef QT_NO_SESSIONMANAGER
2411 #warning Qt is compiled without session manager
2413 #pragma message("warning: Qt is compiled without session manager")
2417 if (sm.allowsInteraction() && !closeAllViews())
2423 void GuiApplication::unregisterView(GuiView * gv)
2425 LASSERT(d->views_[gv->id()] == gv, /**/);
2426 d->views_.remove(gv->id());
2427 if (current_view_ == gv)
2432 bool GuiApplication::closeAllViews()
2434 if (d->views_.empty())
2437 // When a view/window was closed before without quitting LyX, there
2438 // are already entries in the lastOpened list.
2439 theSession().lastOpened().clear();
2441 QList<GuiView *> const views = d->views_.values();
2442 foreach (GuiView * view, views) {
2443 if (!view->closeScheduled())
2452 GuiView & GuiApplication::view(int id) const
2454 LASSERT(d->views_.contains(id), /**/);
2455 return *d->views_.value(id);
2459 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2461 QList<GuiView *> const views = d->views_.values();
2462 foreach (GuiView * view, views)
2463 view->hideDialog(name, inset);
2467 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2469 Buffer const * buffer_ = 0;
2470 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2471 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2472 if (Buffer const * ptr = (*it)->updateInset(inset))
2479 bool GuiApplication::searchMenu(FuncRequest const & func,
2480 docstring_list & names) const
2482 return d->menus_.searchMenu(func, names);
2486 // Ensure that a file is read only once (prevents include loops)
2487 static QStringList uifiles;
2488 // store which ui files define Toolbars
2489 static QStringList toolbar_uifiles;
2492 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2503 LexerKeyword uitags[] = {
2504 { "format", ui_format },
2505 { "include", ui_include },
2506 { "menuset", ui_menuset },
2507 { "toolbars", ui_toolbars },
2508 { "toolbarset", ui_toolbarset }
2512 lex.setFile(ui_path);
2514 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2518 if (lyxerr.debugging(Debug::PARSER))
2519 lex.printTable(lyxerr);
2522 // format before introduction of format tag
2523 unsigned int format = 0;
2524 while (lex.isOK()) {
2525 int const status = lex.lex();
2527 // we have to do this check here, outside the switch,
2528 // because otherwise we would start reading include files,
2529 // e.g., if the first tag we hit was an include tag.
2530 if (status == ui_format)
2532 format = lex.getInteger();
2536 // this will trigger unless the first tag we hit is a format
2537 // tag, with the right format.
2538 if (format != LFUN_FORMAT)
2539 return FormatMismatch;
2542 case Lexer::LEX_FEOF:
2547 QString const file = toqstr(lex.getString());
2548 bool const success = readUIFile(file, true);
2550 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2557 d->menus_.read(lex);
2561 d->toolbars_.readToolbars(lex);
2565 d->toolbars_.readToolbarSettings(lex);
2566 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2570 if (!rtrim(lex.getString()).empty())
2571 lex.printError("LyX::ReadUIFile: "
2572 "Unknown menu tag: `$$Token'");
2574 LYXERR0("Error with status: " << status);
2580 return (error ? ReadError : ReadOK);
2584 bool GuiApplication::readUIFile(QString const & name, bool include)
2586 LYXERR(Debug::INIT, "About to read " << name << "...");
2590 ui_path = libFileSearch("ui", name, "inc");
2591 if (ui_path.empty())
2592 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2594 ui_path = libFileSearch("ui", name, "ui");
2597 if (ui_path.empty()) {
2598 static const QString defaultUIFile = "default";
2599 LYXERR(Debug::INIT, "Could not find " << name);
2601 Alert::warning(_("Could not find UI definition file"),
2602 bformat(_("Error while reading the included file\n%1$s\n"
2603 "Please check your installation."), qstring_to_ucs4(name)));
2606 if (name == defaultUIFile) {
2607 LYXERR(Debug::INIT, "Could not find default UI file!!");
2608 Alert::warning(_("Could not find default UI file"),
2609 _("LyX could not find the default UI file!\n"
2610 "Please check your installation."));
2613 Alert::warning(_("Could not find UI definition file"),
2614 bformat(_("Error while reading the configuration file\n%1$s\n"
2615 "Falling back to default.\n"
2616 "Please look under Tools>Preferences>User Interface and\n"
2617 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2618 return readUIFile(defaultUIFile, false);
2621 QString const uifile = toqstr(ui_path.absFileName());
2622 if (uifiles.contains(uifile)) {
2624 // We are reading again the top uifile so reset the safeguard:
2627 d->toolbars_.reset();
2629 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2630 << "Is this an include loop?");
2634 uifiles.push_back(uifile);
2636 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2638 ReturnValues retval = readUIFile(ui_path);
2640 if (retval == FormatMismatch) {
2641 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2642 FileName const tempfile = FileName::tempName("convert_ui");
2643 bool const success = prefs2prefs(ui_path, tempfile, true);
2645 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2646 " to format " << LFUN_FORMAT << ".");
2648 retval = readUIFile(tempfile);
2649 tempfile.removeFile();
2653 if (retval != ReadOK) {
2654 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2662 settings.beginGroup("ui_files");
2663 bool touched = false;
2664 for (int i = 0; i != uifiles.size(); ++i) {
2665 QFileInfo fi(uifiles[i]);
2666 QDateTime const date_value = fi.lastModified();
2667 QString const name_key = QString::number(i);
2668 // if an ui file which defines Toolbars has changed,
2669 // we have to reset the settings
2670 if (toolbar_uifiles.contains(uifiles[i])
2671 && (!settings.contains(name_key)
2672 || settings.value(name_key).toString() != uifiles[i]
2673 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2675 settings.setValue(name_key, uifiles[i]);
2676 settings.setValue(name_key + "/date", date_value);
2679 settings.endGroup();
2681 settings.remove("views");
2687 void GuiApplication::onLastWindowClosed()
2689 if (d->global_menubar_)
2690 d->global_menubar_->grabKeyboard();
2694 void GuiApplication::startLongOperation() {
2695 d->key_checker_.start();
2699 bool GuiApplication::longOperationCancelled() {
2700 return d->key_checker_.pressed();
2704 void GuiApplication::stopLongOperation() {
2705 d->key_checker_.stop();
2709 bool GuiApplication::longOperationStarted() {
2710 return d->key_checker_.started();
2714 ////////////////////////////////////////////////////////////////////////
2716 // X11 specific stuff goes here...
2719 bool GuiApplication::x11EventFilter(XEvent * xev)
2724 switch (xev->type) {
2725 case SelectionRequest: {
2726 if (xev->xselectionrequest.selection != XA_PRIMARY)
2728 LYXERR(Debug::SELECTION, "X requested selection.");
2729 BufferView * bv = current_view_->currentBufferView();
2731 docstring const sel = bv->requestSelection();
2733 d->selection_.put(sel);
2737 case SelectionClear: {
2738 if (xev->xselectionclear.selection != XA_PRIMARY)
2740 LYXERR(Debug::SELECTION, "Lost selection.");
2741 BufferView * bv = current_view_->currentBufferView();
2743 bv->clearSelection();
2751 } // namespace frontend
2754 void hideDialogs(std::string const & name, Inset * inset)
2757 frontend::guiApp->hideDialogs(name, inset);
2761 ////////////////////////////////////////////////////////////////////
2765 ////////////////////////////////////////////////////////////////////
2767 frontend::FontLoader & theFontLoader()
2769 LASSERT(frontend::guiApp, /**/);
2770 return frontend::guiApp->fontLoader();
2774 frontend::FontMetrics const & theFontMetrics(Font const & f)
2776 return theFontMetrics(f.fontInfo());
2780 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2782 LASSERT(frontend::guiApp, /**/);
2783 return frontend::guiApp->fontLoader().metrics(f);
2787 ////////////////////////////////////////////////////////////////////
2791 ////////////////////////////////////////////////////////////////////
2793 frontend::Clipboard & theClipboard()
2795 LASSERT(frontend::guiApp, /**/);
2796 return frontend::guiApp->clipboard();
2800 frontend::Selection & theSelection()
2802 LASSERT(frontend::guiApp, /**/);
2803 return frontend::guiApp->selection();
2809 #include "moc_GuiApplication.cpp"