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 { "Arrownot", "arrownot2"},
239 { "Bumpeq", "bumpeq2" },
242 { "Delta", "delta2" },
243 { "Diamond", "diamond2" },
244 { "Downarrow", "downarrow2" },
245 { "Gamma", "gamma2" },
246 { "Lambda", "lambda2" },
248 { "Leftarrow", "leftarrow2" },
249 { "Leftrightarrow", "leftrightarrow2" },
250 { "Longarrownot", "longarrownot2"},
251 { "Longleftarrow", "longleftarrow2" },
252 { "Longleftrightarrow", "longleftrightarrow2" },
253 { "Longmapsfrom", "longmapsfrom2"},
254 { "Longmapsto", "longmapsto2"},
255 { "Longrightarrow", "longrightarrow2" },
256 { "Mapsfrom", "mapsfrom2"},
257 { "Mapsfromchar", "mapsfromchar2"},
258 { "Mapsto", "mapsto2"},
259 { "Mapstochar", "mapstochar2"},
260 { "Omega", "omega2" },
265 { "Rightarrow", "rightarrow2" },
266 { "Sigma", "sigma2" },
267 { "Subset", "subset2" },
268 { "Supset", "supset2" },
269 { "Theta", "theta2" },
270 { "Uparrow", "uparrow2" },
271 { "Updownarrow", "updownarrow2" },
272 { "Upsilon", "upsilon2" },
273 { "Vdash", "vdash3" },
276 { "nLeftarrow", "nleftarrow2" },
277 { "nLeftrightarrow", "nleftrightarrow2" },
278 { "nRightarrow", "nrightarrow2" },
279 { "nVDash", "nvdash3" },
280 { "nvDash", "nvdash2" },
281 { "textrm \\AA", "textrm_AA"},
282 { "textrm \\O", "textrm_O"},
283 { "vDash", "vdash2" }
286 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
289 QString findPng(QString const & name)
291 PngMap const * const begin = sorted_png_map;
292 PngMap const * const end = begin + nr_sorted_png_map;
293 LASSERT(sorted(begin, end), /**/);
295 PngMap const * const it = find_if(begin, end, CompareKey(name));
299 png_name = it->value;
302 png_name.replace('_', "underscore");
303 png_name.replace(' ', '_');
305 // This way we can have "math-delim { }" on the toolbar.
306 png_name.replace('(', "lparen");
307 png_name.replace(')', "rparen");
308 png_name.replace('[', "lbracket");
309 png_name.replace(']', "rbracket");
310 png_name.replace('{', "lbrace");
311 png_name.replace('}', "rbrace");
312 png_name.replace('|', "bars");
313 png_name.replace(',', "thinspace");
314 png_name.replace(':', "mediumspace");
315 png_name.replace(';', "thickspace");
316 png_name.replace('!', "negthinspace");
319 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
320 << "Looking for math PNG called \"" << png_name << '"');
327 QString iconName(FuncRequest const & f, bool unknown)
329 initializeResources();
333 switch (f.action()) {
334 case LFUN_MATH_INSERT:
335 if (!f.argument().empty()) {
337 name1 = findPng(toqstr(f.argument()).mid(1));
340 case LFUN_MATH_DELIM:
341 case LFUN_MATH_BIGDELIM:
343 name1 = findPng(toqstr(f.argument()));
347 name1 = toqstr(f.argument());
349 case LFUN_COMMAND_ALTERNATIVES: {
350 // use the first of the alternative commands
352 docstring dummy = split(f.argument(), firstcom, ';');
353 name1 = toqstr(firstcom);
354 // FIXME: we should rename the icons to tabular-xxx instead of
355 // "tabular-feature-xxx"
356 name1.replace("inset-modify tabular", "tabular-feature");
357 name1.replace(' ', '_');
360 case LFUN_INSET_MODIFY: {
361 // FIXME: we should rename the icons to tabular-xxx instead of
362 // "tabular-feature-xxx" and generalize this naming to all
363 // insets, not to tabular using ones.
365 string const command = split(to_utf8(f.argument()), inset_name, ' ');
366 if (insetCode(inset_name) == TABULAR_CODE) {
367 name1 = "tabular-feature "+ toqstr(command);
368 name1.replace(' ', '_');
373 name2 = toqstr(lyxaction.getActionName(f.action()));
376 if (!f.argument().empty()) {
377 name1 = name2 + ' ' + toqstr(f.argument());
378 name1.replace(' ', '_');
379 name1.replace('\\', "backslash");
383 QStringList imagedirs;
384 imagedirs << "images/" << "images/ipa/";
385 for (int i = 0; i < imagedirs.size(); ++i) {
386 QString imagedir = imagedirs.at(i) + path;
387 FileName fname = imageLibFileSearch(imagedir, name1, "png");
389 return toqstr(fname.absFileName());
391 fname = imageLibFileSearch(imagedir, name2, "png");
393 return toqstr(fname.absFileName());
396 path = ":/images/" + path;
399 LYXERR0("Directory " << path << " not found in resource!");
403 if (res.exists(name1))
407 if (res.exists(name2))
410 LYXERR(Debug::GUI, "Cannot find icon with filename "
411 << "\"" << name1 << "\""
413 << "\"" << name2 << "\""
415 << lyxaction.getActionName(f.action())
416 << '(' << to_utf8(f.argument()) << ")\"");
419 QString imagedir = "images/";
420 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
422 return toqstr(fname.absFileName());
423 return QString(":/images/unknown.png");
429 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
432 QString imagedir = path;
433 FileName fname = imageLibFileSearch(imagedir, name, ext);
434 QString path1 = toqstr(fname.absFileName());
435 QString path2 = ":/" + path + name + "." + ext;
437 if (pixmap.load(path1)) {
440 else if (pixmap.load(path2)) {
444 LYXERR0("Cannot load pixmap \""
445 << path << name << '.' << ext
446 << "\", please verify resource system!");
451 QIcon getIcon(FuncRequest const & f, bool unknown)
453 QString icon = iconName(f, unknown);
457 //LYXERR(Debug::GUI, "Found icon: " << icon);
459 if (!pm.load(icon)) {
460 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
468 ////////////////////////////////////////////////////////////////////////
470 // LyX server support code.
472 ////////////////////////////////////////////////////////////////////////
474 class SocketNotifier : public QSocketNotifier
477 /// connect a connection notification from the LyXServerSocket
478 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
479 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
483 /// The callback function
484 Application::SocketCallback func_;
488 ////////////////////////////////////////////////////////////////////////
490 // Mac specific stuff goes here...
492 ////////////////////////////////////////////////////////////////////////
494 class MenuTranslator : public QTranslator
497 MenuTranslator(QObject * parent)
498 : QTranslator(parent)
501 QString translate(const char * /*context*/,
502 const char * sourceText,
503 const char * /*comment*/ = 0) const
505 string const s = sourceText;
506 if (s == N_("About %1") || s == N_("Preferences")
507 || s == N_("Reconfigure") || s == N_("Quit %1"))
514 class GlobalMenuBar : public QMenuBar
518 GlobalMenuBar() : QMenuBar(0) {}
521 bool event(QEvent * e)
523 if (e->type() == QEvent::ShortcutOverride) {
524 // && activeWindow() == 0) {
525 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
527 setKeySymbol(&sym, ke);
528 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
537 // QMacPasteboardMimeGraphics can only be compiled on Mac.
539 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
542 QMacPasteboardMimeGraphics()
543 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
546 QString convertorName() { return "Graphics"; }
548 QString flavorFor(QString const & mime)
550 LYXERR(Debug::ACTION, "flavorFor " << mime);
551 if (mime == pdfMimeType())
552 return QLatin1String("com.adobe.pdf");
556 QString mimeFor(QString flav)
558 LYXERR(Debug::ACTION, "mimeFor " << flav);
559 if (flav == QLatin1String("com.adobe.pdf"))
560 return pdfMimeType();
564 bool canConvert(QString const & mime, QString flav)
566 return mimeFor(flav) == mime;
569 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
573 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
577 QList<QByteArray> convertFromMime(QString const & /*mime*/,
578 QVariant data, QString /*flav*/)
580 QList<QByteArray> ret;
581 ret.append(data.toByteArray());
587 ///////////////////////////////////////////////////////////////
589 // You can find more platform specific stuff at the end of this file...
591 ///////////////////////////////////////////////////////////////
593 ////////////////////////////////////////////////////////////////////////
594 // Windows specific stuff goes here...
597 // QWindowsMimeMetafile can only be compiled on Windows.
599 static FORMATETC cfFromMime(QString const & mimetype)
602 if (mimetype == emfMimeType()) {
603 formatetc.cfFormat = CF_ENHMETAFILE;
604 formatetc.tymed = TYMED_ENHMF;
605 } else if (mimetype == wmfMimeType()) {
606 formatetc.cfFormat = CF_METAFILEPICT;
607 formatetc.tymed = TYMED_MFPICT;
610 formatetc.dwAspect = DVASPECT_CONTENT;
611 formatetc.lindex = -1;
616 class QWindowsMimeMetafile : public QWindowsMime {
618 QWindowsMimeMetafile() {}
620 bool canConvertFromMime(FORMATETC const & formatetc,
621 QMimeData const * mimedata) const
626 bool canConvertToMime(QString const & mimetype,
627 IDataObject * pDataObj) const
629 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
631 FORMATETC formatetc = cfFromMime(mimetype);
632 return pDataObj->QueryGetData(&formatetc) == S_OK;
635 bool convertFromMime(FORMATETC const & formatetc,
636 const QMimeData * mimedata, STGMEDIUM * pmedium) const
641 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
642 QVariant::Type preferredType) const
645 if (!canConvertToMime(mimetype, pDataObj))
648 FORMATETC formatetc = cfFromMime(mimetype);
650 if (pDataObj->GetData(&formatetc, &s) != S_OK)
654 if (s.tymed == TYMED_ENHMF) {
655 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
656 data.resize(dataSize);
657 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
658 (LPBYTE)data.data());
659 } else if (s.tymed == TYMED_MFPICT) {
660 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
661 data.resize(dataSize);
662 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
663 (LPBYTE)data.data());
666 ReleaseStgMedium(&s);
672 QVector<FORMATETC> formatsForMime(QString const & mimetype,
673 QMimeData const * mimedata) const
675 QVector<FORMATETC> formats;
676 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
677 formats += cfFromMime(mimetype);
681 QString mimeForFormat(FORMATETC const & formatetc) const
683 switch (formatetc.cfFormat) {
685 return emfMimeType();
686 case CF_METAFILEPICT:
687 return wmfMimeType();
696 /// Allows to check whether ESC was pressed during a long operation
697 class KeyChecker : public QObject {
702 KeyChecker() : pressed_(false), started_(false) {}
705 QCoreApplication::instance()->installEventFilter(this);
710 QCoreApplication::instance()->removeEventFilter(this);
714 QCoreApplication::processEvents();
717 bool started() const {
720 bool eventFilter(QObject *obj, QEvent *event) {
721 LYXERR(Debug::ACTION, "Event Type: " << event->type());
722 switch (event->type()) {
726 return QObject::eventFilter(obj, event);
728 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
729 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
737 ////////////////////////////////////////////////////////////////////////
738 // GuiApplication::Private definition and implementation.
739 ////////////////////////////////////////////////////////////////////////
741 struct GuiApplication::Private
743 Private(): language_model_(0), meta_fake_bit(NoModifier),
747 /// WMF Mime handler for Windows clipboard.
748 wmf_mime_ = new QWindowsMimeMetafile;
750 initKeySequences(&theTopLevelKeymap());
753 void initKeySequences(KeyMap * kb)
755 keyseq = KeySequence(kb, kb);
756 cancel_meta_seq = KeySequence(kb, kb);
760 QSortFilterProxyModel * language_model_;
762 GuiClipboard clipboard_;
764 GuiSelection selection_;
766 FontLoader font_loader_;
768 ColorCache color_cache_;
770 QTranslator qt_trans_;
772 QHash<int, SocketNotifier *> socket_notifiers_;
776 /// The global instance
779 /// this timer is used for any regular events one wants to
780 /// perform. at present it is used to check if forked processes
782 QTimer general_timer_;
784 /// delayed FuncRequests
785 std::queue<FuncRequest> func_request_queue_;
790 KeySequence cancel_meta_seq;
792 KeyModifier meta_fake_bit;
794 /// Multiple views container.
796 * Warning: This must not be a smart pointer as the destruction of the
797 * object is handled by Qt when the view is closed
798 * \sa Qt::WA_DeleteOnClose attribute.
800 QHash<int, GuiView *> views_;
802 /// Only used on mac.
803 GlobalMenuBar * global_menubar_;
806 /// Linkback mime handler for MacOSX.
807 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
811 /// WMF Mime handler for Windows clipboard.
812 QWindowsMimeMetafile * wmf_mime_;
815 /// Allows to check whether ESC was pressed during a long operation
816 KeyChecker key_checker_;
820 GuiApplication * guiApp;
822 GuiApplication::~GuiApplication()
825 closeAllLinkBackLinks();
831 GuiApplication::GuiApplication(int & argc, char ** argv)
832 : QApplication(argc, argv), current_view_(0),
833 d(new GuiApplication::Private)
835 QString app_name = "LyX";
836 QCoreApplication::setOrganizationName(app_name);
837 QCoreApplication::setOrganizationDomain("lyx.org");
838 QCoreApplication::setApplicationName(lyx_package);
840 // Install translator for GUI elements.
841 installTranslator(&d->qt_trans_);
843 // FIXME: quitOnLastWindowClosed is true by default. We should have a
844 // lyxrc setting for this in order to let the application stay resident.
845 // But then we need some kind of dock icon, at least on Windows.
847 if (lyxrc.quit_on_last_window_closed)
848 setQuitOnLastWindowClosed(false);
851 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
852 // seems to be the default case for applications like LyX.
853 setQuitOnLastWindowClosed(false);
854 // This allows to translate the strings that appear in the LyX menu.
855 /// A translator suitable for the entries in the LyX menu.
856 /// Only needed with Qt/Mac.
857 installTranslator(new MenuTranslator(this));
863 // doubleClickInterval() is 400 ms on X11 which is just too long.
864 // On Windows and Mac OS X, the operating system's value is used.
865 // On Microsoft Windows, calling this function sets the double
866 // click interval for all applications. So we don't!
867 QApplication::setDoubleClickInterval(300);
870 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
872 // needs to be done before reading lyxrc
874 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
878 // Set the cache to 5120 kilobytes which corresponds to screen size of
879 // 1280 by 1024 pixels with a color depth of 32 bits.
880 QPixmapCache::setCacheLimit(5120);
882 // Initialize RC Fonts
883 if (lyxrc.roman_font_name.empty())
884 lyxrc.roman_font_name = fromqstr(romanFontName());
886 if (lyxrc.sans_font_name.empty())
887 lyxrc.sans_font_name = fromqstr(sansFontName());
889 if (lyxrc.typewriter_font_name.empty())
890 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
892 d->general_timer_.setInterval(500);
893 connect(&d->general_timer_, SIGNAL(timeout()),
894 this, SLOT(handleRegularEvents()));
895 d->general_timer_.start();
897 // maxThreadCount() defaults in general to 2 on single or dual-processor.
898 // This is clearly not enough in a time where we use threads for
899 // document preview and/or export. 20 should be OK.
900 QThreadPool::globalInstance()->setMaxThreadCount(20);
904 GuiApplication * theGuiApp()
906 return dynamic_cast<GuiApplication *>(theApp());
910 void GuiApplication::clearSession()
917 docstring Application::iconName(FuncRequest const & f, bool unknown)
919 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
923 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
928 BufferView * doc_bv = 0;
930 if (cmd.action() == LFUN_NOACTION) {
931 status.message(from_utf8(N_("Nothing to do")));
932 status.setEnabled(false);
935 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
936 status.setUnknown(true);
937 status.message(from_utf8(N_("Unknown action")));
938 status.setEnabled(false);
941 // Does the GuiApplication know something?
942 else if (getStatus(cmd, status)) { }
944 // If we do not have a GuiView, then other functions are disabled
945 else if (!current_view_)
946 status.setEnabled(false);
948 // Does the GuiView know something?
949 else if (current_view_->getStatus(cmd, status)) { }
951 // In LyX/Mac, when a dialog is open, the menus of the
952 // application can still be accessed without giving focus to
953 // the main window. In this case, we want to disable the menu
954 // entries that are buffer or view-related.
955 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
957 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
958 status.setEnabled(false);
961 // If we do not have a BufferView, then other functions are disabled
962 else if (!(bv = current_view_->currentBufferView()))
963 status.setEnabled(false);
965 // Does the current BufferView know something?
966 else if (bv->getStatus(cmd, status)) { }
968 // Does the current Buffer know something?
969 else if (bv->buffer().getStatus(cmd, status)) { }
971 // If we do not have a document BufferView, different from the
972 // current BufferView, then other functions are disabled
973 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
974 status.setEnabled(false);
976 // Does the document Buffer know something?
977 else if (doc_bv->buffer().getStatus(cmd, status)) { }
980 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
981 status.message(from_utf8(N_("Command not handled")));
982 status.setEnabled(false);
985 // the default error message if we disable the command
986 if (!status.enabled() && status.message().empty())
987 status.message(from_utf8(N_("Command disabled")));
993 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
995 // I would really like to avoid having this switch and rather try to
996 // encode this in the function itself.
997 // -- And I'd rather let an inset decide which LFUNs it is willing
998 // to handle (Andre')
1000 switch (cmd.action()) {
1002 // This could be used for the no-GUI version. The GUI version is handled in
1003 // GuiView::getStatus(). See above.
1005 case LFUN_BUFFER_WRITE:
1006 case LFUN_BUFFER_WRITE_AS: {
1007 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1008 enable = b && (b->isUnnamed() || !b->isClean());
1013 case LFUN_BOOKMARK_GOTO: {
1014 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1015 enable = theSession().bookmarks().isValid(num);
1019 case LFUN_BOOKMARK_CLEAR:
1020 enable = theSession().bookmarks().hasValid();
1023 // this one is difficult to get right. As a half-baked
1024 // solution, we consider only the first action of the sequence
1025 case LFUN_COMMAND_SEQUENCE: {
1026 // argument contains ';'-terminated commands
1027 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1028 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1029 func.setOrigin(cmd.origin());
1030 flag = getStatus(func);
1034 // we want to check if at least one of these is enabled
1035 case LFUN_COMMAND_ALTERNATIVES: {
1036 // argument contains ';'-terminated commands
1037 string arg = to_utf8(cmd.argument());
1038 while (!arg.empty()) {
1040 arg = split(arg, first, ';');
1041 FuncRequest func(lyxaction.lookupFunc(first));
1042 func.setOrigin(cmd.origin());
1043 flag = getStatus(func);
1044 // if this one is enabled, the whole thing is
1053 string name = to_utf8(cmd.argument());
1054 if (theTopLevelCmdDef().lock(name, func)) {
1055 func.setOrigin(cmd.origin());
1056 flag = getStatus(func);
1057 theTopLevelCmdDef().release(name);
1059 // catch recursion or unknown command
1060 // definition. all operations until the
1061 // recursion or unknown command definition
1062 // occurs are performed, so set the state to
1069 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1071 case LFUN_PREFERENCES_SAVE:
1072 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1073 case LFUN_DEBUG_LEVEL_SET:
1074 // these are handled in our dispatch()
1077 case LFUN_WINDOW_CLOSE:
1078 enable = d->views_.size() > 0;
1081 case LFUN_BUFFER_NEW:
1082 case LFUN_BUFFER_NEW_TEMPLATE:
1083 case LFUN_FILE_OPEN:
1084 case LFUN_HELP_OPEN:
1085 case LFUN_SCREEN_FONT_UPDATE:
1086 case LFUN_SET_COLOR:
1087 case LFUN_WINDOW_NEW:
1089 case LFUN_LYXRC_APPLY:
1090 case LFUN_COMMAND_PREFIX:
1092 case LFUN_META_PREFIX:
1093 case LFUN_RECONFIGURE:
1094 case LFUN_SERVER_GET_FILENAME:
1095 case LFUN_SERVER_NOTIFY:
1099 case LFUN_BUFFER_FORALL: {
1100 if (theBufferList().empty()) {
1101 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1102 flag.setEnabled(false);
1106 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1107 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1108 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1109 flag.setEnabled(false);
1120 flag.setEnabled(false);
1124 /// make a post-dispatch status message
1125 static docstring makeDispatchMessage(docstring const & msg,
1126 FuncRequest const & cmd)
1128 const bool verbose = (cmd.origin() == FuncRequest::MENU
1129 || cmd.origin() == FuncRequest::TOOLBAR
1130 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1132 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1133 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1137 docstring dispatch_msg = msg;
1138 if (!dispatch_msg.empty())
1139 dispatch_msg += ' ';
1141 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1143 bool argsadded = false;
1145 if (!cmd.argument().empty()) {
1146 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1147 comname += ' ' + cmd.argument();
1151 docstring const shortcuts = theTopLevelKeymap().
1152 printBindings(cmd, KeySequence::ForGui);
1154 if (!shortcuts.empty())
1155 comname += ": " + shortcuts;
1156 else if (!argsadded && !cmd.argument().empty())
1157 comname += ' ' + cmd.argument();
1159 if (!comname.empty()) {
1160 comname = rtrim(comname);
1161 dispatch_msg += '(' + rtrim(comname) + ')';
1163 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1164 return dispatch_msg;
1168 void GuiApplication::dispatch(FuncRequest const & cmd)
1170 Buffer * buffer = 0;
1171 if (current_view_ && current_view_->currentBufferView()) {
1172 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1173 buffer = ¤t_view_->currentBufferView()->buffer();
1175 buffer->undo().beginUndoGroup();
1179 // redraw the screen at the end (first of the two drawing steps).
1180 // This is done unless explicitly requested otherwise
1181 dr.screenUpdate(Update::FitCursor);
1183 updateCurrentView(cmd, dr);
1185 // the buffer may have been closed by one action
1186 if (theBufferList().isLoaded(buffer))
1187 buffer->undo().endUndoGroup();
1191 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1196 BufferView * bv = current_view_->currentBufferView();
1198 if (dr.needBufferUpdate()) {
1199 bv->cursor().clearBufferUpdate();
1200 bv->buffer().updateBuffer();
1202 // BufferView::update() updates the ViewMetricsInfo and
1203 // also initializes the position cache for all insets in
1204 // (at least partially) visible top-level paragraphs.
1205 // We will redraw the screen only if needed.
1206 bv->processUpdateFlags(dr.screenUpdate());
1208 // Do we have a selection?
1209 theSelection().haveSelection(bv->cursor().selection());
1212 current_view_->restartCursor();
1214 if (dr.needMessageUpdate()) {
1215 // Some messages may already be translated, so we cannot use _()
1216 current_view_->message(makeDispatchMessage(
1217 translateIfPossible(dr.message()), cmd));
1222 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1223 bool switchToBuffer)
1225 if (!theSession().bookmarks().isValid(idx))
1227 BookmarksSection::Bookmark const & bm =
1228 theSession().bookmarks().bookmark(idx);
1229 LASSERT(!bm.filename.empty(), /**/);
1230 string const file = bm.filename.absFileName();
1231 // if the file is not opened, open it.
1232 if (!theBufferList().exists(bm.filename)) {
1234 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1238 // open may fail, so we need to test it again
1239 if (!theBufferList().exists(bm.filename))
1242 // bm can be changed when saving
1243 BookmarksSection::Bookmark tmp = bm;
1245 // Special case idx == 0 used for back-from-back jump navigation
1247 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1249 // if the current buffer is not that one, switch to it.
1250 BufferView * doc_bv = current_view_ ?
1251 current_view_->documentBufferView() : 0;
1252 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1253 if (switchToBuffer) {
1254 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1257 doc_bv = current_view_->documentBufferView();
1262 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1263 if (!doc_bv->moveToPosition(
1264 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1271 // Cursor jump succeeded!
1272 Cursor const & cur = doc_bv->cursor();
1273 pit_type new_pit = cur.pit();
1274 pos_type new_pos = cur.pos();
1275 int new_id = cur.paragraph().id();
1277 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1278 // see http://www.lyx.org/trac/ticket/3092
1279 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1280 || bm.top_id != new_id) {
1281 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1282 new_pit, new_pos, new_id);
1286 // This function runs "configure" and then rereads lyx.defaults to
1287 // reconfigure the automatic settings.
1288 void GuiApplication::reconfigure(string const & option)
1290 // emit message signal.
1292 current_view_->message(_("Running configure..."));
1294 // Run configure in user lyx directory
1295 PathChanger p(package().user_support());
1296 string configure_command = package().configure_command();
1297 configure_command += option;
1299 int const ret = one.startscript(Systemcall::Wait, configure_command);
1301 // emit message signal.
1303 current_view_->message(_("Reloading configuration..."));
1304 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1305 // Re-read packages.lst
1306 LaTeXPackages::getAvailable();
1309 Alert::information(_("System reconfiguration failed"),
1310 _("The system reconfiguration has failed.\n"
1311 "Default textclass is used but LyX may\n"
1312 "not be able to work properly.\n"
1313 "Please reconfigure again if needed."));
1315 Alert::information(_("System reconfigured"),
1316 _("The system has been reconfigured.\n"
1317 "You need to restart LyX to make use of any\n"
1318 "updated document class specifications."));
1321 void GuiApplication::validateCurrentView()
1323 if (!d->views_.empty() && !current_view_) {
1324 // currently at least one view exists but no view has the focus.
1325 // choose the last view to make it current.
1326 // a view without any open document is preferred.
1327 GuiView * candidate = 0;
1328 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1329 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1330 for (; it != end; ++it) {
1332 if (!candidate->documentBufferView())
1335 setCurrentView(candidate);
1339 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1341 string const argument = to_utf8(cmd.argument());
1342 FuncCode const action = cmd.action();
1344 LYXERR(Debug::ACTION, "cmd: " << cmd);
1346 // we have not done anything wrong yet.
1349 FuncStatus const flag = getStatus(cmd);
1350 if (!flag.enabled()) {
1351 // We cannot use this function here
1352 LYXERR(Debug::ACTION, "action "
1353 << lyxaction.getActionName(action)
1354 << " [" << action << "] is disabled at this location");
1355 dr.setMessage(flag.message());
1357 dr.dispatched(false);
1358 dr.screenUpdate(Update::None);
1359 dr.clearBufferUpdate();
1363 if (cmd.origin() == FuncRequest::LYXSERVER) {
1364 if (current_view_ && current_view_->currentBufferView())
1365 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1366 // we will also need to redraw the screen at the end
1367 dr.screenUpdate(Update::FitCursor);
1370 // Assumes that the action will be dispatched.
1371 dr.dispatched(true);
1373 switch (cmd.action()) {
1375 case LFUN_WINDOW_NEW:
1376 createView(toqstr(cmd.argument()));
1379 case LFUN_WINDOW_CLOSE:
1380 // update bookmark pit of the current buffer before window close
1381 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1382 gotoBookmark(i+1, false, false);
1383 // clear the last opened list, because
1384 // maybe this will end the session
1385 theSession().lastOpened().clear();
1386 // check for valid current_view_
1387 validateCurrentView();
1389 current_view_->closeScheduled();
1393 // quitting is triggered by the gui code
1394 // (leaving the event loop).
1396 current_view_->message(from_utf8(N_("Exiting.")));
1397 if (closeAllViews())
1401 case LFUN_SCREEN_FONT_UPDATE: {
1402 // handle the screen font changes.
1403 d->font_loader_.update();
1404 // Backup current_view_
1405 GuiView * view = current_view_;
1406 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1407 // to skip the refresh.
1409 theBufferList().changed(false);
1410 // Restore current_view_
1411 current_view_ = view;
1415 case LFUN_BUFFER_NEW:
1416 validateCurrentView();
1417 if (d->views_.empty()
1418 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1419 createView(QString(), false); // keep hidden
1420 current_view_->newDocument(to_utf8(cmd.argument()), false);
1421 current_view_->show();
1422 setActiveWindow(current_view_);
1424 current_view_->newDocument(to_utf8(cmd.argument()), false);
1428 case LFUN_BUFFER_NEW_TEMPLATE:
1429 validateCurrentView();
1430 if (d->views_.empty()
1431 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1433 current_view_->newDocument(to_utf8(cmd.argument()), true);
1434 if (!current_view_->documentBufferView())
1435 current_view_->close();
1437 current_view_->newDocument(to_utf8(cmd.argument()), true);
1441 case LFUN_FILE_OPEN: {
1442 validateCurrentView();
1443 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1444 string const fname = to_utf8(cmd.argument());
1445 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1446 && current_view_->documentBufferView() != 0)) {
1447 // We want the ui session to be saved per document and not per
1448 // window number. The filename crc is a good enough identifier.
1449 boost::crc_32_type crc;
1450 crc = for_each(fname.begin(), fname.end(), crc);
1451 createView(crc.checksum());
1452 current_view_->openDocument(fname);
1453 if (current_view_ && !current_view_->documentBufferView())
1454 current_view_->close();
1456 current_view_->openDocument(fname);
1460 case LFUN_HELP_OPEN: {
1461 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1462 if (current_view_ == 0)
1464 string const arg = to_utf8(cmd.argument());
1466 current_view_->message(_("Missing argument"));
1469 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1471 fname = i18nLibFileSearch("examples", arg, "lyx");
1473 if (fname.empty()) {
1474 lyxerr << "LyX: unable to find documentation file `"
1475 << arg << "'. Bad installation?" << endl;
1478 current_view_->message(bformat(_("Opening help file %1$s..."),
1479 makeDisplayPath(fname.absFileName())));
1480 Buffer * buf = current_view_->loadDocument(fname, false);
1482 #ifndef DEVEL_VERSION
1484 buf->setReadonly(true);
1491 case LFUN_SET_COLOR: {
1493 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1494 if (lyx_name.empty() || x11_name.empty()) {
1496 current_view_->message(
1497 _("Syntax: set-color <lyx_name> <x11_name>"));
1502 // FIXME: The graphics cache no longer has a changeDisplay method.
1503 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1504 bool const graphicsbg_changed =
1505 lyx_name == graphicsbg && x11_name != graphicsbg;
1506 if (graphicsbg_changed)
1507 graphics::GCache::get().changeDisplay(true);
1510 if (!lcolor.setColor(lyx_name, x11_name)) {
1512 current_view_->message(
1513 bformat(_("Set-color \"%1$s\" failed "
1514 "- color is undefined or "
1515 "may not be redefined"),
1516 from_utf8(lyx_name)));
1519 // Make sure we don't keep old colors in cache.
1520 d->color_cache_.clear();
1524 case LFUN_LYXRC_APPLY: {
1525 // reset active key sequences, since the bindings
1526 // are updated (bug 6064)
1528 LyXRC const lyxrc_orig = lyxrc;
1530 istringstream ss(to_utf8(cmd.argument()));
1531 bool const success = lyxrc.read(ss);
1534 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1535 << "Unable to read lyxrc data"
1540 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1546 case LFUN_COMMAND_PREFIX:
1547 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1552 d->meta_fake_bit = NoModifier;
1553 GuiView * gv = currentView();
1554 if (gv && gv->currentBufferView())
1555 // cancel any selection
1556 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1557 dr.setMessage(from_ascii(N_("Cancel")));
1560 case LFUN_META_PREFIX:
1561 d->meta_fake_bit = AltModifier;
1562 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1565 // --- Menus -----------------------------------------------
1566 case LFUN_RECONFIGURE:
1567 // argument is any additional parameter to the configure.py command
1568 reconfigure(to_utf8(cmd.argument()));
1571 // --- lyxserver commands ----------------------------
1572 case LFUN_SERVER_GET_FILENAME: {
1573 if (current_view_ && current_view_->documentBufferView()) {
1574 docstring const fname = from_utf8(
1575 current_view_->documentBufferView()->buffer().absFileName());
1576 dr.setMessage(fname);
1577 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1579 dr.setMessage(docstring());
1580 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1585 case LFUN_SERVER_NOTIFY: {
1586 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1587 dr.setMessage(dispatch_buffer);
1588 theServer().notifyClient(to_utf8(dispatch_buffer));
1592 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1593 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1599 string rest = split(argument, countstr, ' ');
1600 istringstream is(countstr);
1603 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1604 for (int i = 0; i < count; ++i)
1605 dispatch(lyxaction.lookupFunc(rest));
1609 case LFUN_COMMAND_SEQUENCE: {
1610 // argument contains ';'-terminated commands
1611 string arg = argument;
1612 // FIXME: this LFUN should also work without any view.
1613 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1614 ? &(current_view_->documentBufferView()->buffer()) : 0;
1616 buffer->undo().beginUndoGroup();
1617 while (!arg.empty()) {
1619 arg = split(arg, first, ';');
1620 FuncRequest func(lyxaction.lookupFunc(first));
1621 func.setOrigin(cmd.origin());
1624 // the buffer may have been closed by one action
1625 if (theBufferList().isLoaded(buffer))
1626 buffer->undo().endUndoGroup();
1630 case LFUN_BUFFER_FORALL: {
1631 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1633 map<Buffer *, GuiView *> views_lVisible;
1634 map<GuiView *, Buffer *> activeBuffers;
1636 QList<GuiView *> allViews = d->views_.values();
1638 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1639 // and on which buffer is active in each view.
1640 Buffer * const last = theBufferList().last();
1641 foreach (GuiView * view, allViews) {
1642 // all of the buffers might be locally hidden. That is, there is no active buffer.
1643 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1644 activeBuffers[view] = 0;
1646 activeBuffers[view] = &view->currentBufferView()->buffer();
1648 // find out if each is locally visible or locally hidden.
1649 // we don't use a for loop as the buffer list cycles.
1650 Buffer * b = theBufferList().first();
1652 bool const locallyVisible = view && view->workArea(*b);
1653 if (locallyVisible) {
1654 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1655 // only need to overwrite/add if we don't already know a buffer is globally
1656 // visible or we do know but we would prefer to dispatch LFUN from the
1657 // current view because of cursor position issues.
1658 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1659 views_lVisible[b] = view;
1663 b = theBufferList().next(b);
1667 GuiView * const homeView = currentView();
1668 Buffer * b = theBufferList().first();
1669 Buffer * nextBuf = 0;
1670 int numProcessed = 0;
1673 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1675 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1677 // first change to a view where b is locally visible, preferably current_view_.
1678 GuiView * const vLv = views_lVisible[b];
1680 lyx::dispatch(funcToRun);
1688 // put things back to how they were (if possible).
1689 foreach (GuiView * view, allViews) {
1690 Buffer * originalBuf = activeBuffers[view];
1691 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1692 if (theBufferList().isLoaded(originalBuf))
1693 view->setBuffer(originalBuf);
1695 homeView->setFocus();
1697 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1701 case LFUN_COMMAND_ALTERNATIVES: {
1702 // argument contains ';'-terminated commands
1703 string arg = argument;
1704 while (!arg.empty()) {
1706 arg = split(arg, first, ';');
1707 FuncRequest func(lyxaction.lookupFunc(first));
1708 func.setOrigin(cmd.origin());
1709 FuncStatus const stat = getStatus(func);
1710 if (stat.enabled()) {
1720 if (theTopLevelCmdDef().lock(argument, func)) {
1721 func.setOrigin(cmd.origin());
1723 theTopLevelCmdDef().release(argument);
1725 if (func.action() == LFUN_UNKNOWN_ACTION) {
1726 // unknown command definition
1727 lyxerr << "Warning: unknown command definition `"
1731 // recursion detected
1732 lyxerr << "Warning: Recursion in the command definition `"
1733 << argument << "' detected"
1740 case LFUN_PREFERENCES_SAVE:
1741 lyxrc.write(support::makeAbsPath("preferences",
1742 package().user_support().absFileName()), false);
1745 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1746 string const fname = addName(addPath(package().user_support().absFileName(),
1747 "templates/"), "defaults.lyx");
1748 Buffer defaults(fname);
1750 istringstream ss(argument);
1753 int const unknown_tokens = defaults.readHeader(lex);
1755 if (unknown_tokens != 0) {
1756 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1757 << unknown_tokens << " unknown token"
1758 << (unknown_tokens == 1 ? "" : "s")
1762 if (defaults.writeFile(FileName(defaults.absFileName())))
1763 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1764 makeDisplayPath(fname)));
1767 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1772 case LFUN_BOOKMARK_GOTO:
1773 // go to bookmark, open unopened file and switch to buffer if necessary
1774 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1775 dr.screenUpdate(Update::Force | Update::FitCursor);
1778 case LFUN_BOOKMARK_CLEAR:
1779 theSession().bookmarks().clear();
1782 case LFUN_DEBUG_LEVEL_SET:
1783 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1787 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1790 current_view_->dispatch(cmd, dr);
1794 if (cmd.origin() == FuncRequest::LYXSERVER)
1795 updateCurrentView(cmd, dr);
1799 docstring GuiApplication::viewStatusMessage()
1801 // When meta-fake key is pressed, show the key sequence so far + "M-".
1802 if (d->meta_fake_bit != NoModifier)
1803 return d->keyseq.print(KeySequence::ForGui) + "M-";
1805 // Else, when a non-complete key sequence is pressed,
1806 // show the available options.
1807 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1808 return d->keyseq.printOptions(true);
1814 void GuiApplication::handleKeyFunc(FuncCode action)
1818 if (d->keyseq.length())
1820 GuiView * gv = currentView();
1821 LASSERT(gv && gv->currentBufferView(), return);
1822 BufferView * bv = gv->currentBufferView();
1823 bv->getIntl().getTransManager().deadkey(
1824 c, get_accent(action).accent, bv->cursor().innerText(),
1826 // Need to clear, in case the minibuffer calls these
1829 // copied verbatim from do_accent_char
1830 bv->cursor().resetAnchor();
1834 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1836 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1838 // Do nothing if we have nothing (JMarc)
1839 if (!keysym.isOK()) {
1840 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1842 current_view_->restartCursor();
1846 if (keysym.isModifier()) {
1848 current_view_->restartCursor();
1852 char_type encoded_last_key = keysym.getUCSEncoded();
1854 // Do a one-deep top-level lookup for
1855 // cancel and meta-fake keys. RVDK_PATCH_5
1856 d->cancel_meta_seq.reset();
1858 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1859 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1861 // When not cancel or meta-fake, do the normal lookup.
1862 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1863 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1864 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1865 // remove Caps Lock and Mod2 as a modifiers
1866 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1867 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1870 // Dont remove this unless you know what you are doing.
1871 d->meta_fake_bit = NoModifier;
1873 // Can this happen now ?
1874 if (func.action() == LFUN_NOACTION)
1875 func = FuncRequest(LFUN_COMMAND_PREFIX);
1877 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1878 << d->keyseq.print(KeySequence::Portable) << ']');
1880 // already here we know if it any point in going further
1881 // why not return already here if action == -1 and
1882 // num_bytes == 0? (Lgb)
1884 if (d->keyseq.length() > 1 && current_view_)
1885 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1888 // Maybe user can only reach the key via holding down shift.
1889 // Let's see. But only if shift is the only modifier
1890 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1891 LYXERR(Debug::KEY, "Trying without shift");
1892 func = d->keyseq.addkey(keysym, NoModifier);
1893 LYXERR(Debug::KEY, "Action now " << func.action());
1896 if (func.action() == LFUN_UNKNOWN_ACTION) {
1897 // Hmm, we didn't match any of the keysequences. See
1898 // if it's normal insertable text not already covered
1900 if (keysym.isText() && d->keyseq.length() == 1) {
1901 LYXERR(Debug::KEY, "isText() is true, inserting.");
1902 func = FuncRequest(LFUN_SELF_INSERT,
1903 FuncRequest::KEYBOARD);
1905 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1906 if (current_view_) {
1907 current_view_->message(_("Unknown function."));
1908 current_view_->restartCursor();
1914 if (func.action() == LFUN_SELF_INSERT) {
1915 if (encoded_last_key != 0) {
1916 docstring const arg(1, encoded_last_key);
1917 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1918 FuncRequest::KEYBOARD));
1919 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1922 processFuncRequest(func);
1926 void GuiApplication::processFuncRequest(FuncRequest const & func)
1928 lyx::dispatch(func);
1932 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1934 addToFuncRequestQueue(func);
1935 processFuncRequestQueueAsync();
1939 void GuiApplication::processFuncRequestQueue()
1941 while (!d->func_request_queue_.empty()) {
1942 processFuncRequest(d->func_request_queue_.front());
1943 d->func_request_queue_.pop();
1948 void GuiApplication::processFuncRequestQueueAsync()
1950 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1954 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1956 d->func_request_queue_.push(func);
1960 void GuiApplication::resetGui()
1962 // Set the language defined by the user.
1966 if (!readUIFile(toqstr(lyxrc.ui_file)))
1967 // Gives some error box here.
1970 if (d->global_menubar_)
1971 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
1973 QHash<int, GuiView *>::iterator it;
1974 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
1977 gv->setLayoutDirection(layoutDirection());
1981 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1985 void GuiApplication::createView(int view_id)
1987 createView(QString(), true, view_id);
1991 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
1994 // release the keyboard which might have been grabed by the global
1995 // menubar on Mac to catch shortcuts even without any GuiView.
1996 if (d->global_menubar_)
1997 d->global_menubar_->releaseKeyboard();
2001 while (d->views_.find(id) != d->views_.end())
2004 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2005 GuiView * view = new GuiView(id);
2007 d->views_[id] = view;
2011 setActiveWindow(view);
2014 if (!geometry_arg.isEmpty()) {
2018 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2019 re.indexIn(geometry_arg);
2020 w = re.cap(1).toInt();
2021 h = re.cap(2).toInt();
2022 x = re.cap(3).toInt();
2023 y = re.cap(4).toInt();
2024 view->setGeometry(x, y, w, h);
2031 Clipboard & GuiApplication::clipboard()
2033 return d->clipboard_;
2037 Selection & GuiApplication::selection()
2039 return d->selection_;
2043 FontLoader & GuiApplication::fontLoader()
2045 return d->font_loader_;
2049 Toolbars const & GuiApplication::toolbars() const
2051 return d->toolbars_;
2055 Toolbars & GuiApplication::toolbars()
2057 return d->toolbars_;
2061 Menus const & GuiApplication::menus() const
2067 Menus & GuiApplication::menus()
2073 QList<int> GuiApplication::viewIds() const
2075 return d->views_.keys();
2079 ColorCache & GuiApplication::colorCache()
2081 return d->color_cache_;
2085 int GuiApplication::exec()
2087 // asynchronously handle batch commands. This event will be in
2088 // the event queue in front of other asynchronous events. Hence,
2089 // we can assume in the latter that the gui is setup already.
2090 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2092 return QApplication::exec();
2096 void GuiApplication::exit(int status)
2098 QApplication::exit(status);
2102 void GuiApplication::setGuiLanguage()
2104 QString const default_language = toqstr(getGuiMessages().language());
2105 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2106 QLocale const default_locale(default_language);
2107 QLocale::setDefault(default_locale);
2109 // install translation file for Qt built-in dialogs
2110 QString const language_name = QString("qt_") + default_locale.name();
2112 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2113 // Short-named translator can be loaded from a long name, but not the
2114 // opposite. Therefore, long name should be used without truncation.
2115 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2116 if (!d->qt_trans_.load(language_name,
2117 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2118 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2121 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2125 switch (default_locale.language()) {
2126 case QLocale::Arabic :
2127 case QLocale::Hebrew :
2128 case QLocale::Persian :
2129 case QLocale::Urdu :
2130 setLayoutDirection(Qt::RightToLeft);
2133 setLayoutDirection(Qt::LeftToRight);
2138 void GuiApplication::execBatchCommands()
2143 if (!readUIFile(toqstr(lyxrc.ui_file)))
2144 // Gives some error box here.
2148 #if QT_VERSION > 0x040600
2149 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2151 // Create the global default menubar which is shown for the dialogs
2152 // and if no GuiView is visible.
2153 // This must be done after the session was recovered to know the "last files".
2154 d->global_menubar_ = new GlobalMenuBar;
2155 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2158 lyx::execBatchCommands();
2162 QAbstractItemModel * GuiApplication::languageModel()
2164 if (d->language_model_)
2165 return d->language_model_;
2167 QStandardItemModel * lang_model = new QStandardItemModel(this);
2168 lang_model->insertColumns(0, 3);
2170 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2171 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2172 Languages::const_iterator it = lyx::languages.begin();
2173 Languages::const_iterator end = lyx::languages.end();
2174 for (; it != end; ++it) {
2175 current_row = lang_model->rowCount();
2176 lang_model->insertRows(current_row, 1);
2177 QModelIndex pl_item = lang_model->index(current_row, 0);
2178 QModelIndex sp_item = lang_model->index(current_row, 1);
2179 QModelIndex th_item = lang_model->index(current_row, 2);
2180 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2181 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2182 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2183 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2184 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2185 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2186 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2187 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2188 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2189 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2191 d->language_model_ = new QSortFilterProxyModel(this);
2192 d->language_model_->setSourceModel(lang_model);
2193 d->language_model_->setSortLocaleAware(true);
2194 return d->language_model_;
2198 void GuiApplication::restoreGuiSession()
2200 if (!lyxrc.load_session)
2203 Session & session = theSession();
2204 LastOpenedSection::LastOpened const & lastopened =
2205 session.lastOpened().getfiles();
2207 validateCurrentView();
2209 FileName active_file;
2210 // do not add to the lastfile list since these files are restored from
2211 // last session, and should be already there (regular files), or should
2212 // not be added at all (help files).
2213 for (size_t i = 0; i < lastopened.size(); ++i) {
2214 FileName const & file_name = lastopened[i].file_name;
2215 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2216 && current_view_->documentBufferView() != 0)) {
2217 boost::crc_32_type crc;
2218 string const & fname = file_name.absFileName();
2219 crc = for_each(fname.begin(), fname.end(), crc);
2220 createView(crc.checksum());
2222 current_view_->loadDocument(file_name, false);
2224 if (lastopened[i].active)
2225 active_file = file_name;
2228 // Restore last active buffer
2229 Buffer * buffer = theBufferList().getBuffer(active_file);
2230 if (buffer && current_view_)
2231 current_view_->setBuffer(buffer);
2233 // clear this list to save a few bytes of RAM
2234 session.lastOpened().clear();
2238 QString const GuiApplication::romanFontName()
2241 font.setKerning(false);
2242 font.setStyleHint(QFont::Serif);
2243 font.setFamily("serif");
2245 return QFontInfo(font).family();
2249 QString const GuiApplication::sansFontName()
2252 font.setKerning(false);
2253 font.setStyleHint(QFont::SansSerif);
2254 font.setFamily("sans");
2256 return QFontInfo(font).family();
2260 QString const GuiApplication::typewriterFontName()
2263 font.setKerning(false);
2264 font.setStyleHint(QFont::TypeWriter);
2265 font.setFamily("monospace");
2267 return QFontInfo(font).family();
2271 void GuiApplication::handleRegularEvents()
2273 ForkedCallsController::handleCompletedProcesses();
2277 bool GuiApplication::event(QEvent * e)
2280 case QEvent::FileOpen: {
2281 // Open a file; this happens only on Mac OS X for now.
2283 // We do this asynchronously because on startup the batch
2284 // commands are not executed here yet and the gui is not ready
2286 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2287 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2288 processFuncRequestAsync(fr);
2293 return QApplication::event(e);
2298 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2301 return QApplication::notify(receiver, event);
2303 catch (ExceptionMessage const & e) {
2305 case ErrorException:
2307 setQuitOnLastWindowClosed(false);
2309 Alert::error(e.title_, e.details_);
2311 // Properly crash in debug mode in order to get a useful backtrace.
2314 // In release mode, try to exit gracefully.
2317 case BufferException: {
2318 if (!current_view_ || !current_view_->documentBufferView())
2320 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2321 docstring details = e.details_ + '\n';
2322 details += buf->emergencyWrite();
2323 theBufferList().release(buf);
2324 details += "\n" + _("The current document was closed.");
2325 Alert::error(e.title_, details);
2328 case WarningException:
2329 Alert::warning(e.title_, e.details_);
2333 catch (exception const & e) {
2334 docstring s = _("LyX has caught an exception, it will now "
2335 "attempt to save all unsaved documents and exit."
2337 s += from_ascii(e.what());
2338 Alert::error(_("Software exception Detected"), s);
2342 docstring s = _("LyX has caught some really weird exception, it will "
2343 "now attempt to save all unsaved documents and exit.");
2344 Alert::error(_("Software exception Detected"), s);
2352 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2354 QColor const & qcol = d->color_cache_.get(col);
2355 if (!qcol.isValid()) {
2361 rgbcol.r = qcol.red();
2362 rgbcol.g = qcol.green();
2363 rgbcol.b = qcol.blue();
2368 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2370 QColor const qcol(lcolor.getX11Name(col).c_str());
2371 if (!qcol.isValid()) {
2377 rgbcol.r = qcol.red();
2378 rgbcol.g = qcol.green();
2379 rgbcol.b = qcol.blue();
2384 string const GuiApplication::hexName(ColorCode col)
2386 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2390 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2392 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2393 d->socket_notifiers_[fd] = sn;
2394 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2398 void GuiApplication::socketDataReceived(int fd)
2400 d->socket_notifiers_[fd]->func_();
2404 void GuiApplication::unregisterSocketCallback(int fd)
2406 d->socket_notifiers_.take(fd)->setEnabled(false);
2410 void GuiApplication::commitData(QSessionManager & sm)
2412 /// The implementation is required to avoid an application exit
2413 /// when session state save is triggered by session manager.
2414 /// The default implementation sends a close event to all
2415 /// visible top level widgets when session managment allows
2417 /// We are changing that to close all wiew one by one.
2418 /// FIXME: verify if the default implementation is enough now.
2419 #ifdef QT_NO_SESSIONMANAGER
2421 #warning Qt is compiled without session manager
2423 #pragma message("warning: Qt is compiled without session manager")
2427 if (sm.allowsInteraction() && !closeAllViews())
2433 void GuiApplication::unregisterView(GuiView * gv)
2435 LASSERT(d->views_[gv->id()] == gv, /**/);
2436 d->views_.remove(gv->id());
2437 if (current_view_ == gv)
2442 bool GuiApplication::closeAllViews()
2444 if (d->views_.empty())
2447 // When a view/window was closed before without quitting LyX, there
2448 // are already entries in the lastOpened list.
2449 theSession().lastOpened().clear();
2451 QList<GuiView *> const views = d->views_.values();
2452 foreach (GuiView * view, views) {
2453 if (!view->closeScheduled())
2462 GuiView & GuiApplication::view(int id) const
2464 LASSERT(d->views_.contains(id), /**/);
2465 return *d->views_.value(id);
2469 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2471 QList<GuiView *> const views = d->views_.values();
2472 foreach (GuiView * view, views)
2473 view->hideDialog(name, inset);
2477 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2479 Buffer const * buffer_ = 0;
2480 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2481 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2482 if (Buffer const * ptr = (*it)->updateInset(inset))
2489 bool GuiApplication::searchMenu(FuncRequest const & func,
2490 docstring_list & names) const
2492 return d->menus_.searchMenu(func, names);
2496 // Ensure that a file is read only once (prevents include loops)
2497 static QStringList uifiles;
2498 // store which ui files define Toolbars
2499 static QStringList toolbar_uifiles;
2502 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2513 LexerKeyword uitags[] = {
2514 { "format", ui_format },
2515 { "include", ui_include },
2516 { "menuset", ui_menuset },
2517 { "toolbars", ui_toolbars },
2518 { "toolbarset", ui_toolbarset }
2522 lex.setFile(ui_path);
2524 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2528 if (lyxerr.debugging(Debug::PARSER))
2529 lex.printTable(lyxerr);
2532 // format before introduction of format tag
2533 unsigned int format = 0;
2534 while (lex.isOK()) {
2535 int const status = lex.lex();
2537 // we have to do this check here, outside the switch,
2538 // because otherwise we would start reading include files,
2539 // e.g., if the first tag we hit was an include tag.
2540 if (status == ui_format)
2542 format = lex.getInteger();
2546 // this will trigger unless the first tag we hit is a format
2547 // tag, with the right format.
2548 if (format != LFUN_FORMAT)
2549 return FormatMismatch;
2552 case Lexer::LEX_FEOF:
2557 QString const file = toqstr(lex.getString());
2558 bool const success = readUIFile(file, true);
2560 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2567 d->menus_.read(lex);
2571 d->toolbars_.readToolbars(lex);
2575 d->toolbars_.readToolbarSettings(lex);
2576 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2580 if (!rtrim(lex.getString()).empty())
2581 lex.printError("LyX::ReadUIFile: "
2582 "Unknown menu tag: `$$Token'");
2584 LYXERR0("Error with status: " << status);
2590 return (error ? ReadError : ReadOK);
2594 bool GuiApplication::readUIFile(QString const & name, bool include)
2596 LYXERR(Debug::INIT, "About to read " << name << "...");
2600 ui_path = libFileSearch("ui", name, "inc");
2601 if (ui_path.empty())
2602 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2604 ui_path = libFileSearch("ui", name, "ui");
2607 if (ui_path.empty()) {
2608 static const QString defaultUIFile = "default";
2609 LYXERR(Debug::INIT, "Could not find " << name);
2611 Alert::warning(_("Could not find UI definition file"),
2612 bformat(_("Error while reading the included file\n%1$s\n"
2613 "Please check your installation."), qstring_to_ucs4(name)));
2616 if (name == defaultUIFile) {
2617 LYXERR(Debug::INIT, "Could not find default UI file!!");
2618 Alert::warning(_("Could not find default UI file"),
2619 _("LyX could not find the default UI file!\n"
2620 "Please check your installation."));
2623 Alert::warning(_("Could not find UI definition file"),
2624 bformat(_("Error while reading the configuration file\n%1$s\n"
2625 "Falling back to default.\n"
2626 "Please look under Tools>Preferences>User Interface and\n"
2627 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2628 return readUIFile(defaultUIFile, false);
2631 QString const uifile = toqstr(ui_path.absFileName());
2632 if (uifiles.contains(uifile)) {
2634 // We are reading again the top uifile so reset the safeguard:
2637 d->toolbars_.reset();
2639 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2640 << "Is this an include loop?");
2644 uifiles.push_back(uifile);
2646 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2648 ReturnValues retval = readUIFile(ui_path);
2650 if (retval == FormatMismatch) {
2651 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2652 FileName const tempfile = FileName::tempName("convert_ui");
2653 bool const success = prefs2prefs(ui_path, tempfile, true);
2655 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2656 " to format " << LFUN_FORMAT << ".");
2658 retval = readUIFile(tempfile);
2659 tempfile.removeFile();
2663 if (retval != ReadOK) {
2664 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2672 settings.beginGroup("ui_files");
2673 bool touched = false;
2674 for (int i = 0; i != uifiles.size(); ++i) {
2675 QFileInfo fi(uifiles[i]);
2676 QDateTime const date_value = fi.lastModified();
2677 QString const name_key = QString::number(i);
2678 // if an ui file which defines Toolbars has changed,
2679 // we have to reset the settings
2680 if (toolbar_uifiles.contains(uifiles[i])
2681 && (!settings.contains(name_key)
2682 || settings.value(name_key).toString() != uifiles[i]
2683 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2685 settings.setValue(name_key, uifiles[i]);
2686 settings.setValue(name_key + "/date", date_value);
2689 settings.endGroup();
2691 settings.remove("views");
2697 void GuiApplication::onLastWindowClosed()
2699 if (d->global_menubar_)
2700 d->global_menubar_->grabKeyboard();
2704 void GuiApplication::startLongOperation() {
2705 d->key_checker_.start();
2709 bool GuiApplication::longOperationCancelled() {
2710 return d->key_checker_.pressed();
2714 void GuiApplication::stopLongOperation() {
2715 d->key_checker_.stop();
2719 bool GuiApplication::longOperationStarted() {
2720 return d->key_checker_.started();
2724 ////////////////////////////////////////////////////////////////////////
2726 // X11 specific stuff goes here...
2729 bool GuiApplication::x11EventFilter(XEvent * xev)
2734 switch (xev->type) {
2735 case SelectionRequest: {
2736 if (xev->xselectionrequest.selection != XA_PRIMARY)
2738 LYXERR(Debug::SELECTION, "X requested selection.");
2739 BufferView * bv = current_view_->currentBufferView();
2741 docstring const sel = bv->requestSelection();
2743 d->selection_.put(sel);
2747 case SelectionClear: {
2748 if (xev->xselectionclear.selection != XA_PRIMARY)
2750 LYXERR(Debug::SELECTION, "Lost selection.");
2751 BufferView * bv = current_view_->currentBufferView();
2753 bv->clearSelection();
2761 } // namespace frontend
2764 void hideDialogs(std::string const & name, Inset * inset)
2767 frontend::guiApp->hideDialogs(name, inset);
2771 ////////////////////////////////////////////////////////////////////
2775 ////////////////////////////////////////////////////////////////////
2777 frontend::FontLoader & theFontLoader()
2779 LASSERT(frontend::guiApp, /**/);
2780 return frontend::guiApp->fontLoader();
2784 frontend::FontMetrics const & theFontMetrics(Font const & f)
2786 return theFontMetrics(f.fontInfo());
2790 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2792 LASSERT(frontend::guiApp, /**/);
2793 return frontend::guiApp->fontLoader().metrics(f);
2797 ////////////////////////////////////////////////////////////////////
2801 ////////////////////////////////////////////////////////////////////
2803 frontend::Clipboard & theClipboard()
2805 LASSERT(frontend::guiApp, /**/);
2806 return frontend::guiApp->clipboard();
2810 frontend::Selection & theSelection()
2812 LASSERT(frontend::guiApp, /**/);
2813 return frontend::guiApp->selection();
2819 #include "moc_GuiApplication.cpp"