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 // Please don't change the formatting, this list is parsed by
238 // development/tools/generate_symbols_images.py.
239 PngMap sorted_png_map[] = {
240 { "Arrownot", "arrownot2"},
241 { "Arrowvert", "arrowvert2"},
242 { "Bowtie", "bowtie2" },
244 { "Bumpeq", "bumpeq2" },
245 { "CIRCLE", "circle3" },
247 { "CheckedBox", "checkedbox2" },
248 { "Circle", "circle2" },
249 { "Colonapprox", "colonapprox2" },
250 { "Coloneq", "coloneq2" },
251 { "Coloneqq", "coloneqq2" },
252 { "Colonsim", "colonsim2" },
254 { "DOWNarrow", "downarrow3" },
255 { "Delta", "delta2" },
256 { "Diamond", "diamond2" },
257 { "Doteq", "doteq2" },
258 { "Downarrow", "downarrow2" },
259 { "Eqcolon", "eqcolon2" },
260 { "Eqqcolon", "eqqcolon2" },
261 { "Gamma", "gamma2" },
263 { "LEFTCIRCLE", "leftcircle3" },
264 { "LEFTarrow", "leftarrow3" },
265 { "LEFTcircle", "leftcircle4" },
267 { "Lambda", "lambda2" },
269 { "Leftarrow", "leftarrow2" },
270 { "Leftcircle", "leftcircle2" },
271 { "Leftrightarrow", "leftrightarrow2" },
272 { "Longarrownot", "longarrownot2"},
273 { "Longleftarrow", "longleftarrow2" },
274 { "Longleftrightarrow", "longleftrightarrow2" },
275 { "Longmapsfrom", "longmapsfrom2"},
276 { "Longmapsto", "longmapsto2"},
277 { "Longrightarrow", "longrightarrow2" },
278 { "Mapsfrom", "mapsfrom2"},
279 { "Mapsfromchar", "mapsfromchar2"},
280 { "Mapsto", "mapsto2"},
281 { "Mapstochar", "mapstochar2"},
282 { "Omega", "omega2" },
287 { "RIGHTCIRCLE", "rightcircle3" },
288 { "RIGHTarrow", "rightarrow3" },
289 { "RIGHTcircle", "rightcircle4" },
291 { "Rightarrow", "rightarrow2" },
292 { "Rightcircle", "rightcircle2" },
293 { "Sigma", "sigma2" },
294 { "Square", "square2" },
295 { "Subset", "subset2" },
296 { "Supset", "supset2" },
297 { "Theta", "theta2" },
298 { "Thorn", "thorn2" },
299 { "UParrow", "uparrow3" },
300 { "Uparrow", "uparrow2" },
301 { "Updownarrow", "updownarrow2" },
302 { "Upsilon", "upsilon2" },
303 { "Vdash", "vdash3" },
308 { "nLeftarrow", "nleftarrow2" },
309 { "nLeftrightarrow", "nleftrightarrow2" },
310 { "nRightarrow", "nrightarrow2" },
311 { "nVDash", "nvdash3" },
312 { "nVdash", "nvdash4" },
313 { "nvDash", "nvdash2" },
314 { "textrm \\AA", "textrm_AA"},
315 { "textrm \\O", "textrm_O"},
316 { "vDash", "vdash2" },
317 { "varDelta", "vardelta2" },
318 { "varGamma", "vargamma2" },
319 { "varLambda", "varlambda2" },
320 { "varOmega", "varomega2" },
321 { "varPhi", "varphi2" },
322 { "varPi", "varpi2" },
323 { "varPsi", "varpsi2" },
324 { "varSigma", "varsigma2" },
325 { "varTheta", "vartheta2" },
326 { "varUpsilon", "varupsilon2" },
327 { "varXi", "varxi2" }
331 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
334 QString findPng(QString const & name)
336 PngMap const * const begin = sorted_png_map;
337 PngMap const * const end = begin + nr_sorted_png_map;
338 LASSERT(sorted(begin, end), /**/);
340 PngMap const * const it = find_if(begin, end, CompareKey(name));
344 png_name = it->value;
347 png_name.replace('_', "underscore");
348 png_name.replace(' ', '_');
350 // This way we can have "math-delim { }" on the toolbar.
351 png_name.replace('(', "lparen");
352 png_name.replace(')', "rparen");
353 png_name.replace('[', "lbracket");
354 png_name.replace(']', "rbracket");
355 png_name.replace('{', "lbrace");
356 png_name.replace('}', "rbrace");
357 png_name.replace('|', "bars");
358 png_name.replace(',', "thinspace");
359 png_name.replace(':', "mediumspace");
360 png_name.replace(';', "thickspace");
361 png_name.replace('!', "negthinspace");
364 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
365 << "Looking for math PNG called \"" << png_name << '"');
372 QString iconName(FuncRequest const & f, bool unknown)
374 initializeResources();
378 switch (f.action()) {
379 case LFUN_MATH_INSERT:
380 if (!f.argument().empty()) {
382 name1 = findPng(toqstr(f.argument()).mid(1));
385 case LFUN_MATH_DELIM:
386 case LFUN_MATH_BIGDELIM:
388 name1 = findPng(toqstr(f.argument()));
392 name1 = toqstr(f.argument());
394 case LFUN_COMMAND_ALTERNATIVES: {
395 // use the first of the alternative commands
397 docstring dummy = split(f.argument(), firstcom, ';');
398 name1 = toqstr(firstcom);
399 // FIXME: we should rename the icons to tabular-xxx instead of
400 // "tabular-feature-xxx"
401 name1.replace("inset-modify tabular", "tabular-feature");
402 name1.replace(' ', '_');
405 case LFUN_INSET_MODIFY: {
406 // FIXME: we should rename the icons to tabular-xxx instead of
407 // "tabular-feature-xxx" and generalize this naming to all
408 // insets, not to tabular using ones.
410 string const command = split(to_utf8(f.argument()), inset_name, ' ');
411 if (insetCode(inset_name) == TABULAR_CODE) {
412 name1 = "tabular-feature "+ toqstr(command);
413 name1.replace(' ', '_');
418 name2 = toqstr(lyxaction.getActionName(f.action()));
421 if (!f.argument().empty()) {
422 name1 = name2 + ' ' + toqstr(f.argument());
423 name1.replace(' ', '_');
424 name1.replace('\\', "backslash");
428 QStringList imagedirs;
429 imagedirs << "images/" << "images/ipa/";
430 for (int i = 0; i < imagedirs.size(); ++i) {
431 QString imagedir = imagedirs.at(i) + path;
432 FileName fname = imageLibFileSearch(imagedir, name1, "png");
434 return toqstr(fname.absFileName());
436 fname = imageLibFileSearch(imagedir, name2, "png");
438 return toqstr(fname.absFileName());
441 path = ":/images/" + path;
444 LYXERR0("Directory " << path << " not found in resource!");
448 if (res.exists(name1))
452 if (res.exists(name2))
455 LYXERR(Debug::GUI, "Cannot find icon with filename "
456 << "\"" << name1 << "\""
458 << "\"" << name2 << "\""
460 << lyxaction.getActionName(f.action())
461 << '(' << to_utf8(f.argument()) << ")\"");
464 QString imagedir = "images/";
465 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
467 return toqstr(fname.absFileName());
468 return QString(":/images/unknown.png");
474 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
477 QString imagedir = path;
478 FileName fname = imageLibFileSearch(imagedir, name, ext);
479 QString path1 = toqstr(fname.absFileName());
480 QString path2 = ":/" + path + name + "." + ext;
482 if (pixmap.load(path1)) {
485 else if (pixmap.load(path2)) {
489 LYXERR0("Cannot load pixmap \""
490 << path << name << '.' << ext
491 << "\", please verify resource system!");
496 QIcon getIcon(FuncRequest const & f, bool unknown)
498 QString icon = iconName(f, unknown);
502 //LYXERR(Debug::GUI, "Found icon: " << icon);
504 if (!pm.load(icon)) {
505 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
513 ////////////////////////////////////////////////////////////////////////
515 // LyX server support code.
517 ////////////////////////////////////////////////////////////////////////
519 class SocketNotifier : public QSocketNotifier
522 /// connect a connection notification from the LyXServerSocket
523 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
524 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
528 /// The callback function
529 Application::SocketCallback func_;
533 ////////////////////////////////////////////////////////////////////////
535 // Mac specific stuff goes here...
537 ////////////////////////////////////////////////////////////////////////
539 class MenuTranslator : public QTranslator
542 MenuTranslator(QObject * parent)
543 : QTranslator(parent)
546 QString translate(const char * /*context*/,
547 const char * sourceText,
548 const char * /*comment*/ = 0) const
550 string const s = sourceText;
551 if (s == N_("About %1") || s == N_("Preferences")
552 || s == N_("Reconfigure") || s == N_("Quit %1"))
559 class GlobalMenuBar : public QMenuBar
563 GlobalMenuBar() : QMenuBar(0) {}
566 bool event(QEvent * e)
568 if (e->type() == QEvent::ShortcutOverride) {
569 // && activeWindow() == 0) {
570 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
572 setKeySymbol(&sym, ke);
573 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
582 // QMacPasteboardMimeGraphics can only be compiled on Mac.
584 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
587 QMacPasteboardMimeGraphics()
588 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
591 QString convertorName() { return "Graphics"; }
593 QString flavorFor(QString const & mime)
595 LYXERR(Debug::ACTION, "flavorFor " << mime);
596 if (mime == pdfMimeType())
597 return QLatin1String("com.adobe.pdf");
601 QString mimeFor(QString flav)
603 LYXERR(Debug::ACTION, "mimeFor " << flav);
604 if (flav == QLatin1String("com.adobe.pdf"))
605 return pdfMimeType();
609 bool canConvert(QString const & mime, QString flav)
611 return mimeFor(flav) == mime;
614 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
618 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
622 QList<QByteArray> convertFromMime(QString const & /*mime*/,
623 QVariant data, QString /*flav*/)
625 QList<QByteArray> ret;
626 ret.append(data.toByteArray());
632 ///////////////////////////////////////////////////////////////
634 // You can find more platform specific stuff at the end of this file...
636 ///////////////////////////////////////////////////////////////
638 ////////////////////////////////////////////////////////////////////////
639 // Windows specific stuff goes here...
642 // QWindowsMimeMetafile can only be compiled on Windows.
644 static FORMATETC cfFromMime(QString const & mimetype)
647 if (mimetype == emfMimeType()) {
648 formatetc.cfFormat = CF_ENHMETAFILE;
649 formatetc.tymed = TYMED_ENHMF;
650 } else if (mimetype == wmfMimeType()) {
651 formatetc.cfFormat = CF_METAFILEPICT;
652 formatetc.tymed = TYMED_MFPICT;
655 formatetc.dwAspect = DVASPECT_CONTENT;
656 formatetc.lindex = -1;
661 class QWindowsMimeMetafile : public QWindowsMime {
663 QWindowsMimeMetafile() {}
665 bool canConvertFromMime(FORMATETC const & formatetc,
666 QMimeData const * mimedata) const
671 bool canConvertToMime(QString const & mimetype,
672 IDataObject * pDataObj) const
674 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
676 FORMATETC formatetc = cfFromMime(mimetype);
677 return pDataObj->QueryGetData(&formatetc) == S_OK;
680 bool convertFromMime(FORMATETC const & formatetc,
681 const QMimeData * mimedata, STGMEDIUM * pmedium) const
686 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
687 QVariant::Type preferredType) const
690 if (!canConvertToMime(mimetype, pDataObj))
693 FORMATETC formatetc = cfFromMime(mimetype);
695 if (pDataObj->GetData(&formatetc, &s) != S_OK)
699 if (s.tymed == TYMED_ENHMF) {
700 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
701 data.resize(dataSize);
702 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
703 (LPBYTE)data.data());
704 } else if (s.tymed == TYMED_MFPICT) {
705 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
706 data.resize(dataSize);
707 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
708 (LPBYTE)data.data());
711 ReleaseStgMedium(&s);
717 QVector<FORMATETC> formatsForMime(QString const & mimetype,
718 QMimeData const * mimedata) const
720 QVector<FORMATETC> formats;
721 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
722 formats += cfFromMime(mimetype);
726 QString mimeForFormat(FORMATETC const & formatetc) const
728 switch (formatetc.cfFormat) {
730 return emfMimeType();
731 case CF_METAFILEPICT:
732 return wmfMimeType();
741 /// Allows to check whether ESC was pressed during a long operation
742 class KeyChecker : public QObject {
747 KeyChecker() : pressed_(false), started_(false) {}
750 QCoreApplication::instance()->installEventFilter(this);
755 QCoreApplication::instance()->removeEventFilter(this);
759 QCoreApplication::processEvents();
762 bool started() const {
765 bool eventFilter(QObject *obj, QEvent *event) {
766 LYXERR(Debug::ACTION, "Event Type: " << event->type());
767 switch (event->type()) {
771 return QObject::eventFilter(obj, event);
773 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
774 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
782 ////////////////////////////////////////////////////////////////////////
783 // GuiApplication::Private definition and implementation.
784 ////////////////////////////////////////////////////////////////////////
786 struct GuiApplication::Private
788 Private(): language_model_(0), meta_fake_bit(NoModifier),
792 /// WMF Mime handler for Windows clipboard.
793 wmf_mime_ = new QWindowsMimeMetafile;
795 initKeySequences(&theTopLevelKeymap());
798 void initKeySequences(KeyMap * kb)
800 keyseq = KeySequence(kb, kb);
801 cancel_meta_seq = KeySequence(kb, kb);
805 QSortFilterProxyModel * language_model_;
807 GuiClipboard clipboard_;
809 GuiSelection selection_;
811 FontLoader font_loader_;
813 ColorCache color_cache_;
815 QTranslator qt_trans_;
817 QHash<int, SocketNotifier *> socket_notifiers_;
821 /// The global instance
824 /// this timer is used for any regular events one wants to
825 /// perform. at present it is used to check if forked processes
827 QTimer general_timer_;
829 /// delayed FuncRequests
830 std::queue<FuncRequest> func_request_queue_;
835 KeySequence cancel_meta_seq;
837 KeyModifier meta_fake_bit;
839 /// Multiple views container.
841 * Warning: This must not be a smart pointer as the destruction of the
842 * object is handled by Qt when the view is closed
843 * \sa Qt::WA_DeleteOnClose attribute.
845 QHash<int, GuiView *> views_;
847 /// Only used on mac.
848 GlobalMenuBar * global_menubar_;
851 /// Linkback mime handler for MacOSX.
852 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
856 /// WMF Mime handler for Windows clipboard.
857 QWindowsMimeMetafile * wmf_mime_;
860 /// Allows to check whether ESC was pressed during a long operation
861 KeyChecker key_checker_;
865 GuiApplication * guiApp;
867 GuiApplication::~GuiApplication()
870 closeAllLinkBackLinks();
876 GuiApplication::GuiApplication(int & argc, char ** argv)
877 : QApplication(argc, argv), current_view_(0),
878 d(new GuiApplication::Private)
880 QString app_name = "LyX";
881 QCoreApplication::setOrganizationName(app_name);
882 QCoreApplication::setOrganizationDomain("lyx.org");
883 QCoreApplication::setApplicationName(lyx_package);
885 // Install translator for GUI elements.
886 installTranslator(&d->qt_trans_);
888 // FIXME: quitOnLastWindowClosed is true by default. We should have a
889 // lyxrc setting for this in order to let the application stay resident.
890 // But then we need some kind of dock icon, at least on Windows.
892 if (lyxrc.quit_on_last_window_closed)
893 setQuitOnLastWindowClosed(false);
896 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
897 // seems to be the default case for applications like LyX.
898 setQuitOnLastWindowClosed(false);
899 // This allows to translate the strings that appear in the LyX menu.
900 /// A translator suitable for the entries in the LyX menu.
901 /// Only needed with Qt/Mac.
902 installTranslator(new MenuTranslator(this));
908 // doubleClickInterval() is 400 ms on X11 which is just too long.
909 // On Windows and Mac OS X, the operating system's value is used.
910 // On Microsoft Windows, calling this function sets the double
911 // click interval for all applications. So we don't!
912 QApplication::setDoubleClickInterval(300);
915 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
917 // needs to be done before reading lyxrc
919 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
923 // Set the cache to 5120 kilobytes which corresponds to screen size of
924 // 1280 by 1024 pixels with a color depth of 32 bits.
925 QPixmapCache::setCacheLimit(5120);
927 // Initialize RC Fonts
928 if (lyxrc.roman_font_name.empty())
929 lyxrc.roman_font_name = fromqstr(romanFontName());
931 if (lyxrc.sans_font_name.empty())
932 lyxrc.sans_font_name = fromqstr(sansFontName());
934 if (lyxrc.typewriter_font_name.empty())
935 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
937 d->general_timer_.setInterval(500);
938 connect(&d->general_timer_, SIGNAL(timeout()),
939 this, SLOT(handleRegularEvents()));
940 d->general_timer_.start();
942 // maxThreadCount() defaults in general to 2 on single or dual-processor.
943 // This is clearly not enough in a time where we use threads for
944 // document preview and/or export. 20 should be OK.
945 QThreadPool::globalInstance()->setMaxThreadCount(20);
949 GuiApplication * theGuiApp()
951 return dynamic_cast<GuiApplication *>(theApp());
955 void GuiApplication::clearSession()
962 docstring Application::iconName(FuncRequest const & f, bool unknown)
964 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
968 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
973 BufferView * doc_bv = 0;
975 if (cmd.action() == LFUN_NOACTION) {
976 status.message(from_utf8(N_("Nothing to do")));
977 status.setEnabled(false);
980 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
981 status.setUnknown(true);
982 status.message(from_utf8(N_("Unknown action")));
983 status.setEnabled(false);
986 // Does the GuiApplication know something?
987 else if (getStatus(cmd, status)) { }
989 // If we do not have a GuiView, then other functions are disabled
990 else if (!current_view_)
991 status.setEnabled(false);
993 // Does the GuiView know something?
994 else if (current_view_->getStatus(cmd, status)) { }
996 // In LyX/Mac, when a dialog is open, the menus of the
997 // application can still be accessed without giving focus to
998 // the main window. In this case, we want to disable the menu
999 // entries that are buffer or view-related.
1000 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1002 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1003 status.setEnabled(false);
1006 // If we do not have a BufferView, then other functions are disabled
1007 else if (!(bv = current_view_->currentBufferView()))
1008 status.setEnabled(false);
1010 // Does the current BufferView know something?
1011 else if (bv->getStatus(cmd, status)) { }
1013 // Does the current Buffer know something?
1014 else if (bv->buffer().getStatus(cmd, status)) { }
1016 // If we do not have a document BufferView, different from the
1017 // current BufferView, then other functions are disabled
1018 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1019 status.setEnabled(false);
1021 // Does the document Buffer know something?
1022 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1025 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1026 status.message(from_utf8(N_("Command not handled")));
1027 status.setEnabled(false);
1030 // the default error message if we disable the command
1031 if (!status.enabled() && status.message().empty())
1032 status.message(from_utf8(N_("Command disabled")));
1038 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1040 // I would really like to avoid having this switch and rather try to
1041 // encode this in the function itself.
1042 // -- And I'd rather let an inset decide which LFUNs it is willing
1043 // to handle (Andre')
1045 switch (cmd.action()) {
1047 // This could be used for the no-GUI version. The GUI version is handled in
1048 // GuiView::getStatus(). See above.
1050 case LFUN_BUFFER_WRITE:
1051 case LFUN_BUFFER_WRITE_AS: {
1052 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1053 enable = b && (b->isUnnamed() || !b->isClean());
1058 case LFUN_BOOKMARK_GOTO: {
1059 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1060 enable = theSession().bookmarks().isValid(num);
1064 case LFUN_BOOKMARK_CLEAR:
1065 enable = theSession().bookmarks().hasValid();
1068 // this one is difficult to get right. As a half-baked
1069 // solution, we consider only the first action of the sequence
1070 case LFUN_COMMAND_SEQUENCE: {
1071 // argument contains ';'-terminated commands
1072 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1073 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1074 func.setOrigin(cmd.origin());
1075 flag = getStatus(func);
1079 // we want to check if at least one of these is enabled
1080 case LFUN_COMMAND_ALTERNATIVES: {
1081 // argument contains ';'-terminated commands
1082 string arg = to_utf8(cmd.argument());
1083 while (!arg.empty()) {
1085 arg = split(arg, first, ';');
1086 FuncRequest func(lyxaction.lookupFunc(first));
1087 func.setOrigin(cmd.origin());
1088 flag = getStatus(func);
1089 // if this one is enabled, the whole thing is
1098 string name = to_utf8(cmd.argument());
1099 if (theTopLevelCmdDef().lock(name, func)) {
1100 func.setOrigin(cmd.origin());
1101 flag = getStatus(func);
1102 theTopLevelCmdDef().release(name);
1104 // catch recursion or unknown command
1105 // definition. all operations until the
1106 // recursion or unknown command definition
1107 // occurs are performed, so set the state to
1114 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1116 case LFUN_PREFERENCES_SAVE:
1117 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1118 case LFUN_DEBUG_LEVEL_SET:
1119 // these are handled in our dispatch()
1122 case LFUN_WINDOW_CLOSE:
1123 enable = d->views_.size() > 0;
1126 case LFUN_BUFFER_NEW:
1127 case LFUN_BUFFER_NEW_TEMPLATE:
1128 case LFUN_FILE_OPEN:
1129 case LFUN_HELP_OPEN:
1130 case LFUN_SCREEN_FONT_UPDATE:
1131 case LFUN_SET_COLOR:
1132 case LFUN_WINDOW_NEW:
1134 case LFUN_LYXRC_APPLY:
1135 case LFUN_COMMAND_PREFIX:
1137 case LFUN_META_PREFIX:
1138 case LFUN_RECONFIGURE:
1139 case LFUN_SERVER_GET_FILENAME:
1140 case LFUN_SERVER_NOTIFY:
1144 case LFUN_BUFFER_FORALL: {
1145 if (theBufferList().empty()) {
1146 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1147 flag.setEnabled(false);
1151 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1152 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1153 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1154 flag.setEnabled(false);
1165 flag.setEnabled(false);
1169 /// make a post-dispatch status message
1170 static docstring makeDispatchMessage(docstring const & msg,
1171 FuncRequest const & cmd)
1173 const bool verbose = (cmd.origin() == FuncRequest::MENU
1174 || cmd.origin() == FuncRequest::TOOLBAR
1175 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1177 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1178 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1182 docstring dispatch_msg = msg;
1183 if (!dispatch_msg.empty())
1184 dispatch_msg += ' ';
1186 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1188 bool argsadded = false;
1190 if (!cmd.argument().empty()) {
1191 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1192 comname += ' ' + cmd.argument();
1196 docstring const shortcuts = theTopLevelKeymap().
1197 printBindings(cmd, KeySequence::ForGui);
1199 if (!shortcuts.empty())
1200 comname += ": " + shortcuts;
1201 else if (!argsadded && !cmd.argument().empty())
1202 comname += ' ' + cmd.argument();
1204 if (!comname.empty()) {
1205 comname = rtrim(comname);
1206 dispatch_msg += '(' + rtrim(comname) + ')';
1208 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1209 return dispatch_msg;
1213 void GuiApplication::dispatch(FuncRequest const & cmd)
1215 Buffer * buffer = 0;
1216 if (current_view_ && current_view_->currentBufferView()) {
1217 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1218 buffer = ¤t_view_->currentBufferView()->buffer();
1220 buffer->undo().beginUndoGroup();
1224 // redraw the screen at the end (first of the two drawing steps).
1225 // This is done unless explicitly requested otherwise
1226 dr.screenUpdate(Update::FitCursor);
1228 updateCurrentView(cmd, dr);
1230 // the buffer may have been closed by one action
1231 if (theBufferList().isLoaded(buffer))
1232 buffer->undo().endUndoGroup();
1236 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1241 BufferView * bv = current_view_->currentBufferView();
1243 if (dr.needBufferUpdate()) {
1244 bv->cursor().clearBufferUpdate();
1245 bv->buffer().updateBuffer();
1247 // BufferView::update() updates the ViewMetricsInfo and
1248 // also initializes the position cache for all insets in
1249 // (at least partially) visible top-level paragraphs.
1250 // We will redraw the screen only if needed.
1251 bv->processUpdateFlags(dr.screenUpdate());
1253 // Do we have a selection?
1254 theSelection().haveSelection(bv->cursor().selection());
1257 current_view_->restartCursor();
1259 if (dr.needMessageUpdate()) {
1260 // Some messages may already be translated, so we cannot use _()
1261 current_view_->message(makeDispatchMessage(
1262 translateIfPossible(dr.message()), cmd));
1267 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1268 bool switchToBuffer)
1270 if (!theSession().bookmarks().isValid(idx))
1272 BookmarksSection::Bookmark const & bm =
1273 theSession().bookmarks().bookmark(idx);
1274 LASSERT(!bm.filename.empty(), /**/);
1275 string const file = bm.filename.absFileName();
1276 // if the file is not opened, open it.
1277 if (!theBufferList().exists(bm.filename)) {
1279 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1283 // open may fail, so we need to test it again
1284 if (!theBufferList().exists(bm.filename))
1287 // bm can be changed when saving
1288 BookmarksSection::Bookmark tmp = bm;
1290 // Special case idx == 0 used for back-from-back jump navigation
1292 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1294 // if the current buffer is not that one, switch to it.
1295 BufferView * doc_bv = current_view_ ?
1296 current_view_->documentBufferView() : 0;
1297 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1298 if (switchToBuffer) {
1299 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1302 doc_bv = current_view_->documentBufferView();
1307 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1308 if (!doc_bv->moveToPosition(
1309 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1316 // Cursor jump succeeded!
1317 Cursor const & cur = doc_bv->cursor();
1318 pit_type new_pit = cur.pit();
1319 pos_type new_pos = cur.pos();
1320 int new_id = cur.paragraph().id();
1322 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1323 // see http://www.lyx.org/trac/ticket/3092
1324 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1325 || bm.top_id != new_id) {
1326 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1327 new_pit, new_pos, new_id);
1331 // This function runs "configure" and then rereads lyx.defaults to
1332 // reconfigure the automatic settings.
1333 void GuiApplication::reconfigure(string const & option)
1335 // emit message signal.
1337 current_view_->message(_("Running configure..."));
1339 // Run configure in user lyx directory
1340 PathChanger p(package().user_support());
1341 string configure_command = package().configure_command();
1342 configure_command += option;
1344 int const ret = one.startscript(Systemcall::Wait, configure_command);
1346 // emit message signal.
1348 current_view_->message(_("Reloading configuration..."));
1349 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1350 // Re-read packages.lst
1351 LaTeXPackages::getAvailable();
1354 Alert::information(_("System reconfiguration failed"),
1355 _("The system reconfiguration has failed.\n"
1356 "Default textclass is used but LyX may\n"
1357 "not be able to work properly.\n"
1358 "Please reconfigure again if needed."));
1360 Alert::information(_("System reconfigured"),
1361 _("The system has been reconfigured.\n"
1362 "You need to restart LyX to make use of any\n"
1363 "updated document class specifications."));
1366 void GuiApplication::validateCurrentView()
1368 if (!d->views_.empty() && !current_view_) {
1369 // currently at least one view exists but no view has the focus.
1370 // choose the last view to make it current.
1371 // a view without any open document is preferred.
1372 GuiView * candidate = 0;
1373 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1374 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1375 for (; it != end; ++it) {
1377 if (!candidate->documentBufferView())
1380 setCurrentView(candidate);
1384 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1386 string const argument = to_utf8(cmd.argument());
1387 FuncCode const action = cmd.action();
1389 LYXERR(Debug::ACTION, "cmd: " << cmd);
1391 // we have not done anything wrong yet.
1394 FuncStatus const flag = getStatus(cmd);
1395 if (!flag.enabled()) {
1396 // We cannot use this function here
1397 LYXERR(Debug::ACTION, "action "
1398 << lyxaction.getActionName(action)
1399 << " [" << action << "] is disabled at this location");
1400 dr.setMessage(flag.message());
1402 dr.dispatched(false);
1403 dr.screenUpdate(Update::None);
1404 dr.clearBufferUpdate();
1408 if (cmd.origin() == FuncRequest::LYXSERVER) {
1409 if (current_view_ && current_view_->currentBufferView())
1410 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1411 // we will also need to redraw the screen at the end
1412 dr.screenUpdate(Update::FitCursor);
1415 // Assumes that the action will be dispatched.
1416 dr.dispatched(true);
1418 switch (cmd.action()) {
1420 case LFUN_WINDOW_NEW:
1421 createView(toqstr(cmd.argument()));
1424 case LFUN_WINDOW_CLOSE:
1425 // update bookmark pit of the current buffer before window close
1426 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1427 gotoBookmark(i+1, false, false);
1428 // clear the last opened list, because
1429 // maybe this will end the session
1430 theSession().lastOpened().clear();
1431 // check for valid current_view_
1432 validateCurrentView();
1434 current_view_->closeScheduled();
1438 // quitting is triggered by the gui code
1439 // (leaving the event loop).
1441 current_view_->message(from_utf8(N_("Exiting.")));
1442 if (closeAllViews())
1446 case LFUN_SCREEN_FONT_UPDATE: {
1447 // handle the screen font changes.
1448 d->font_loader_.update();
1449 // Backup current_view_
1450 GuiView * view = current_view_;
1451 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1452 // to skip the refresh.
1454 theBufferList().changed(false);
1455 // Restore current_view_
1456 current_view_ = view;
1460 case LFUN_BUFFER_NEW:
1461 validateCurrentView();
1462 if (d->views_.empty()
1463 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1464 createView(QString(), false); // keep hidden
1465 current_view_->newDocument(to_utf8(cmd.argument()), false);
1466 current_view_->show();
1467 setActiveWindow(current_view_);
1469 current_view_->newDocument(to_utf8(cmd.argument()), false);
1473 case LFUN_BUFFER_NEW_TEMPLATE:
1474 validateCurrentView();
1475 if (d->views_.empty()
1476 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1478 current_view_->newDocument(to_utf8(cmd.argument()), true);
1479 if (!current_view_->documentBufferView())
1480 current_view_->close();
1482 current_view_->newDocument(to_utf8(cmd.argument()), true);
1486 case LFUN_FILE_OPEN: {
1487 validateCurrentView();
1488 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1489 string const fname = to_utf8(cmd.argument());
1490 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1491 && current_view_->documentBufferView() != 0)) {
1492 // We want the ui session to be saved per document and not per
1493 // window number. The filename crc is a good enough identifier.
1494 boost::crc_32_type crc;
1495 crc = for_each(fname.begin(), fname.end(), crc);
1496 createView(crc.checksum());
1497 current_view_->openDocument(fname);
1498 if (current_view_ && !current_view_->documentBufferView())
1499 current_view_->close();
1501 current_view_->openDocument(fname);
1505 case LFUN_HELP_OPEN: {
1506 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1507 if (current_view_ == 0)
1509 string const arg = to_utf8(cmd.argument());
1511 current_view_->message(_("Missing argument"));
1514 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1516 fname = i18nLibFileSearch("examples", arg, "lyx");
1518 if (fname.empty()) {
1519 lyxerr << "LyX: unable to find documentation file `"
1520 << arg << "'. Bad installation?" << endl;
1523 current_view_->message(bformat(_("Opening help file %1$s..."),
1524 makeDisplayPath(fname.absFileName())));
1525 Buffer * buf = current_view_->loadDocument(fname, false);
1527 #ifndef DEVEL_VERSION
1529 buf->setReadonly(true);
1536 case LFUN_SET_COLOR: {
1538 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1539 if (lyx_name.empty() || x11_name.empty()) {
1541 current_view_->message(
1542 _("Syntax: set-color <lyx_name> <x11_name>"));
1547 // FIXME: The graphics cache no longer has a changeDisplay method.
1548 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1549 bool const graphicsbg_changed =
1550 lyx_name == graphicsbg && x11_name != graphicsbg;
1551 if (graphicsbg_changed)
1552 graphics::GCache::get().changeDisplay(true);
1555 if (!lcolor.setColor(lyx_name, x11_name)) {
1557 current_view_->message(
1558 bformat(_("Set-color \"%1$s\" failed "
1559 "- color is undefined or "
1560 "may not be redefined"),
1561 from_utf8(lyx_name)));
1564 // Make sure we don't keep old colors in cache.
1565 d->color_cache_.clear();
1569 case LFUN_LYXRC_APPLY: {
1570 // reset active key sequences, since the bindings
1571 // are updated (bug 6064)
1573 LyXRC const lyxrc_orig = lyxrc;
1575 istringstream ss(to_utf8(cmd.argument()));
1576 bool const success = lyxrc.read(ss);
1579 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1580 << "Unable to read lyxrc data"
1585 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1591 case LFUN_COMMAND_PREFIX:
1592 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1597 d->meta_fake_bit = NoModifier;
1598 GuiView * gv = currentView();
1599 if (gv && gv->currentBufferView())
1600 // cancel any selection
1601 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1602 dr.setMessage(from_ascii(N_("Cancel")));
1605 case LFUN_META_PREFIX:
1606 d->meta_fake_bit = AltModifier;
1607 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1610 // --- Menus -----------------------------------------------
1611 case LFUN_RECONFIGURE:
1612 // argument is any additional parameter to the configure.py command
1613 reconfigure(to_utf8(cmd.argument()));
1616 // --- lyxserver commands ----------------------------
1617 case LFUN_SERVER_GET_FILENAME: {
1618 if (current_view_ && current_view_->documentBufferView()) {
1619 docstring const fname = from_utf8(
1620 current_view_->documentBufferView()->buffer().absFileName());
1621 dr.setMessage(fname);
1622 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1624 dr.setMessage(docstring());
1625 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1630 case LFUN_SERVER_NOTIFY: {
1631 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1632 dr.setMessage(dispatch_buffer);
1633 theServer().notifyClient(to_utf8(dispatch_buffer));
1637 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1638 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1644 string rest = split(argument, countstr, ' ');
1645 istringstream is(countstr);
1648 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1649 for (int i = 0; i < count; ++i)
1650 dispatch(lyxaction.lookupFunc(rest));
1654 case LFUN_COMMAND_SEQUENCE: {
1655 // argument contains ';'-terminated commands
1656 string arg = argument;
1657 // FIXME: this LFUN should also work without any view.
1658 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1659 ? &(current_view_->documentBufferView()->buffer()) : 0;
1661 buffer->undo().beginUndoGroup();
1662 while (!arg.empty()) {
1664 arg = split(arg, first, ';');
1665 FuncRequest func(lyxaction.lookupFunc(first));
1666 func.setOrigin(cmd.origin());
1669 // the buffer may have been closed by one action
1670 if (theBufferList().isLoaded(buffer))
1671 buffer->undo().endUndoGroup();
1675 case LFUN_BUFFER_FORALL: {
1676 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1678 map<Buffer *, GuiView *> views_lVisible;
1679 map<GuiView *, Buffer *> activeBuffers;
1681 QList<GuiView *> allViews = d->views_.values();
1683 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1684 // and on which buffer is active in each view.
1685 Buffer * const last = theBufferList().last();
1686 foreach (GuiView * view, allViews) {
1687 // all of the buffers might be locally hidden. That is, there is no active buffer.
1688 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1689 activeBuffers[view] = 0;
1691 activeBuffers[view] = &view->currentBufferView()->buffer();
1693 // find out if each is locally visible or locally hidden.
1694 // we don't use a for loop as the buffer list cycles.
1695 Buffer * b = theBufferList().first();
1697 bool const locallyVisible = view && view->workArea(*b);
1698 if (locallyVisible) {
1699 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1700 // only need to overwrite/add if we don't already know a buffer is globally
1701 // visible or we do know but we would prefer to dispatch LFUN from the
1702 // current view because of cursor position issues.
1703 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1704 views_lVisible[b] = view;
1708 b = theBufferList().next(b);
1712 GuiView * const homeView = currentView();
1713 Buffer * b = theBufferList().first();
1714 Buffer * nextBuf = 0;
1715 int numProcessed = 0;
1718 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1720 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1722 // first change to a view where b is locally visible, preferably current_view_.
1723 GuiView * const vLv = views_lVisible[b];
1725 lyx::dispatch(funcToRun);
1733 // put things back to how they were (if possible).
1734 foreach (GuiView * view, allViews) {
1735 Buffer * originalBuf = activeBuffers[view];
1736 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1737 if (theBufferList().isLoaded(originalBuf))
1738 view->setBuffer(originalBuf);
1740 homeView->setFocus();
1742 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1746 case LFUN_COMMAND_ALTERNATIVES: {
1747 // argument contains ';'-terminated commands
1748 string arg = argument;
1749 while (!arg.empty()) {
1751 arg = split(arg, first, ';');
1752 FuncRequest func(lyxaction.lookupFunc(first));
1753 func.setOrigin(cmd.origin());
1754 FuncStatus const stat = getStatus(func);
1755 if (stat.enabled()) {
1765 if (theTopLevelCmdDef().lock(argument, func)) {
1766 func.setOrigin(cmd.origin());
1768 theTopLevelCmdDef().release(argument);
1770 if (func.action() == LFUN_UNKNOWN_ACTION) {
1771 // unknown command definition
1772 lyxerr << "Warning: unknown command definition `"
1776 // recursion detected
1777 lyxerr << "Warning: Recursion in the command definition `"
1778 << argument << "' detected"
1785 case LFUN_PREFERENCES_SAVE:
1786 lyxrc.write(support::makeAbsPath("preferences",
1787 package().user_support().absFileName()), false);
1790 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1791 string const fname = addName(addPath(package().user_support().absFileName(),
1792 "templates/"), "defaults.lyx");
1793 Buffer defaults(fname);
1795 istringstream ss(argument);
1798 int const unknown_tokens = defaults.readHeader(lex);
1800 if (unknown_tokens != 0) {
1801 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1802 << unknown_tokens << " unknown token"
1803 << (unknown_tokens == 1 ? "" : "s")
1807 if (defaults.writeFile(FileName(defaults.absFileName())))
1808 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1809 makeDisplayPath(fname)));
1812 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1817 case LFUN_BOOKMARK_GOTO:
1818 // go to bookmark, open unopened file and switch to buffer if necessary
1819 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1820 dr.screenUpdate(Update::Force | Update::FitCursor);
1823 case LFUN_BOOKMARK_CLEAR:
1824 theSession().bookmarks().clear();
1827 case LFUN_DEBUG_LEVEL_SET:
1828 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1832 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1835 current_view_->dispatch(cmd, dr);
1839 if (cmd.origin() == FuncRequest::LYXSERVER)
1840 updateCurrentView(cmd, dr);
1844 docstring GuiApplication::viewStatusMessage()
1846 // When meta-fake key is pressed, show the key sequence so far + "M-".
1847 if (d->meta_fake_bit != NoModifier)
1848 return d->keyseq.print(KeySequence::ForGui) + "M-";
1850 // Else, when a non-complete key sequence is pressed,
1851 // show the available options.
1852 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1853 return d->keyseq.printOptions(true);
1859 void GuiApplication::handleKeyFunc(FuncCode action)
1863 if (d->keyseq.length())
1865 GuiView * gv = currentView();
1866 LASSERT(gv && gv->currentBufferView(), return);
1867 BufferView * bv = gv->currentBufferView();
1868 bv->getIntl().getTransManager().deadkey(
1869 c, get_accent(action).accent, bv->cursor().innerText(),
1871 // Need to clear, in case the minibuffer calls these
1874 // copied verbatim from do_accent_char
1875 bv->cursor().resetAnchor();
1879 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1881 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1883 // Do nothing if we have nothing (JMarc)
1884 if (!keysym.isOK()) {
1885 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1887 current_view_->restartCursor();
1891 if (keysym.isModifier()) {
1893 current_view_->restartCursor();
1897 char_type encoded_last_key = keysym.getUCSEncoded();
1899 // Do a one-deep top-level lookup for
1900 // cancel and meta-fake keys. RVDK_PATCH_5
1901 d->cancel_meta_seq.reset();
1903 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1904 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1906 // When not cancel or meta-fake, do the normal lookup.
1907 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1908 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1909 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1910 // remove Caps Lock and Mod2 as a modifiers
1911 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1912 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1915 // Dont remove this unless you know what you are doing.
1916 d->meta_fake_bit = NoModifier;
1918 // Can this happen now ?
1919 if (func.action() == LFUN_NOACTION)
1920 func = FuncRequest(LFUN_COMMAND_PREFIX);
1922 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1923 << d->keyseq.print(KeySequence::Portable) << ']');
1925 // already here we know if it any point in going further
1926 // why not return already here if action == -1 and
1927 // num_bytes == 0? (Lgb)
1929 if (d->keyseq.length() > 1 && current_view_)
1930 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1933 // Maybe user can only reach the key via holding down shift.
1934 // Let's see. But only if shift is the only modifier
1935 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1936 LYXERR(Debug::KEY, "Trying without shift");
1937 func = d->keyseq.addkey(keysym, NoModifier);
1938 LYXERR(Debug::KEY, "Action now " << func.action());
1941 if (func.action() == LFUN_UNKNOWN_ACTION) {
1942 // Hmm, we didn't match any of the keysequences. See
1943 // if it's normal insertable text not already covered
1945 if (keysym.isText() && d->keyseq.length() == 1) {
1946 LYXERR(Debug::KEY, "isText() is true, inserting.");
1947 func = FuncRequest(LFUN_SELF_INSERT,
1948 FuncRequest::KEYBOARD);
1950 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1951 if (current_view_) {
1952 current_view_->message(_("Unknown function."));
1953 current_view_->restartCursor();
1959 if (func.action() == LFUN_SELF_INSERT) {
1960 if (encoded_last_key != 0) {
1961 docstring const arg(1, encoded_last_key);
1962 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1963 FuncRequest::KEYBOARD));
1964 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1967 processFuncRequest(func);
1971 void GuiApplication::processFuncRequest(FuncRequest const & func)
1973 lyx::dispatch(func);
1977 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1979 addToFuncRequestQueue(func);
1980 processFuncRequestQueueAsync();
1984 void GuiApplication::processFuncRequestQueue()
1986 while (!d->func_request_queue_.empty()) {
1987 processFuncRequest(d->func_request_queue_.front());
1988 d->func_request_queue_.pop();
1993 void GuiApplication::processFuncRequestQueueAsync()
1995 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1999 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2001 d->func_request_queue_.push(func);
2005 void GuiApplication::resetGui()
2007 // Set the language defined by the user.
2011 if (!readUIFile(toqstr(lyxrc.ui_file)))
2012 // Gives some error box here.
2015 if (d->global_menubar_)
2016 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2018 QHash<int, GuiView *>::iterator it;
2019 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2022 gv->setLayoutDirection(layoutDirection());
2026 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2030 void GuiApplication::createView(int view_id)
2032 createView(QString(), true, view_id);
2036 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2039 // release the keyboard which might have been grabed by the global
2040 // menubar on Mac to catch shortcuts even without any GuiView.
2041 if (d->global_menubar_)
2042 d->global_menubar_->releaseKeyboard();
2046 while (d->views_.find(id) != d->views_.end())
2049 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2050 GuiView * view = new GuiView(id);
2052 d->views_[id] = view;
2056 setActiveWindow(view);
2059 if (!geometry_arg.isEmpty()) {
2063 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2064 re.indexIn(geometry_arg);
2065 w = re.cap(1).toInt();
2066 h = re.cap(2).toInt();
2067 x = re.cap(3).toInt();
2068 y = re.cap(4).toInt();
2069 view->setGeometry(x, y, w, h);
2076 Clipboard & GuiApplication::clipboard()
2078 return d->clipboard_;
2082 Selection & GuiApplication::selection()
2084 return d->selection_;
2088 FontLoader & GuiApplication::fontLoader()
2090 return d->font_loader_;
2094 Toolbars const & GuiApplication::toolbars() const
2096 return d->toolbars_;
2100 Toolbars & GuiApplication::toolbars()
2102 return d->toolbars_;
2106 Menus const & GuiApplication::menus() const
2112 Menus & GuiApplication::menus()
2118 QList<int> GuiApplication::viewIds() const
2120 return d->views_.keys();
2124 ColorCache & GuiApplication::colorCache()
2126 return d->color_cache_;
2130 int GuiApplication::exec()
2132 // asynchronously handle batch commands. This event will be in
2133 // the event queue in front of other asynchronous events. Hence,
2134 // we can assume in the latter that the gui is setup already.
2135 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2137 return QApplication::exec();
2141 void GuiApplication::exit(int status)
2143 QApplication::exit(status);
2147 void GuiApplication::setGuiLanguage()
2149 QString const default_language = toqstr(getGuiMessages().language());
2150 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2151 QLocale const default_locale(default_language);
2152 QLocale::setDefault(default_locale);
2154 // install translation file for Qt built-in dialogs
2155 QString const language_name = QString("qt_") + default_locale.name();
2157 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2158 // Short-named translator can be loaded from a long name, but not the
2159 // opposite. Therefore, long name should be used without truncation.
2160 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2161 if (!d->qt_trans_.load(language_name,
2162 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2163 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2166 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2170 switch (default_locale.language()) {
2171 case QLocale::Arabic :
2172 case QLocale::Hebrew :
2173 case QLocale::Persian :
2174 case QLocale::Urdu :
2175 setLayoutDirection(Qt::RightToLeft);
2178 setLayoutDirection(Qt::LeftToRight);
2183 void GuiApplication::execBatchCommands()
2188 if (!readUIFile(toqstr(lyxrc.ui_file)))
2189 // Gives some error box here.
2193 #if QT_VERSION > 0x040600
2194 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2196 // Create the global default menubar which is shown for the dialogs
2197 // and if no GuiView is visible.
2198 // This must be done after the session was recovered to know the "last files".
2199 d->global_menubar_ = new GlobalMenuBar;
2200 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2203 lyx::execBatchCommands();
2207 QAbstractItemModel * GuiApplication::languageModel()
2209 if (d->language_model_)
2210 return d->language_model_;
2212 QStandardItemModel * lang_model = new QStandardItemModel(this);
2213 lang_model->insertColumns(0, 3);
2215 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2216 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2217 Languages::const_iterator it = lyx::languages.begin();
2218 Languages::const_iterator end = lyx::languages.end();
2219 for (; it != end; ++it) {
2220 current_row = lang_model->rowCount();
2221 lang_model->insertRows(current_row, 1);
2222 QModelIndex pl_item = lang_model->index(current_row, 0);
2223 QModelIndex sp_item = lang_model->index(current_row, 1);
2224 QModelIndex th_item = lang_model->index(current_row, 2);
2225 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2226 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2227 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2228 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2229 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2230 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2231 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2232 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2233 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2234 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2236 d->language_model_ = new QSortFilterProxyModel(this);
2237 d->language_model_->setSourceModel(lang_model);
2238 d->language_model_->setSortLocaleAware(true);
2239 return d->language_model_;
2243 void GuiApplication::restoreGuiSession()
2245 if (!lyxrc.load_session)
2248 Session & session = theSession();
2249 LastOpenedSection::LastOpened const & lastopened =
2250 session.lastOpened().getfiles();
2252 validateCurrentView();
2254 FileName active_file;
2255 // do not add to the lastfile list since these files are restored from
2256 // last session, and should be already there (regular files), or should
2257 // not be added at all (help files).
2258 for (size_t i = 0; i < lastopened.size(); ++i) {
2259 FileName const & file_name = lastopened[i].file_name;
2260 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2261 && current_view_->documentBufferView() != 0)) {
2262 boost::crc_32_type crc;
2263 string const & fname = file_name.absFileName();
2264 crc = for_each(fname.begin(), fname.end(), crc);
2265 createView(crc.checksum());
2267 current_view_->loadDocument(file_name, false);
2269 if (lastopened[i].active)
2270 active_file = file_name;
2273 // Restore last active buffer
2274 Buffer * buffer = theBufferList().getBuffer(active_file);
2275 if (buffer && current_view_)
2276 current_view_->setBuffer(buffer);
2278 // clear this list to save a few bytes of RAM
2279 session.lastOpened().clear();
2283 QString const GuiApplication::romanFontName()
2286 font.setKerning(false);
2287 font.setStyleHint(QFont::Serif);
2288 font.setFamily("serif");
2290 return QFontInfo(font).family();
2294 QString const GuiApplication::sansFontName()
2297 font.setKerning(false);
2298 font.setStyleHint(QFont::SansSerif);
2299 font.setFamily("sans");
2301 return QFontInfo(font).family();
2305 QString const GuiApplication::typewriterFontName()
2308 font.setKerning(false);
2309 font.setStyleHint(QFont::TypeWriter);
2310 font.setFamily("monospace");
2312 return QFontInfo(font).family();
2316 void GuiApplication::handleRegularEvents()
2318 ForkedCallsController::handleCompletedProcesses();
2322 bool GuiApplication::event(QEvent * e)
2325 case QEvent::FileOpen: {
2326 // Open a file; this happens only on Mac OS X for now.
2328 // We do this asynchronously because on startup the batch
2329 // commands are not executed here yet and the gui is not ready
2331 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2332 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2333 processFuncRequestAsync(fr);
2338 return QApplication::event(e);
2343 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2346 return QApplication::notify(receiver, event);
2348 catch (ExceptionMessage const & e) {
2350 case ErrorException:
2352 setQuitOnLastWindowClosed(false);
2354 Alert::error(e.title_, e.details_);
2356 // Properly crash in debug mode in order to get a useful backtrace.
2359 // In release mode, try to exit gracefully.
2362 case BufferException: {
2363 if (!current_view_ || !current_view_->documentBufferView())
2365 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2366 docstring details = e.details_ + '\n';
2367 details += buf->emergencyWrite();
2368 theBufferList().release(buf);
2369 details += "\n" + _("The current document was closed.");
2370 Alert::error(e.title_, details);
2373 case WarningException:
2374 Alert::warning(e.title_, e.details_);
2378 catch (exception const & e) {
2379 docstring s = _("LyX has caught an exception, it will now "
2380 "attempt to save all unsaved documents and exit."
2382 s += from_ascii(e.what());
2383 Alert::error(_("Software exception Detected"), s);
2387 docstring s = _("LyX has caught some really weird exception, it will "
2388 "now attempt to save all unsaved documents and exit.");
2389 Alert::error(_("Software exception Detected"), s);
2397 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2399 QColor const & qcol = d->color_cache_.get(col);
2400 if (!qcol.isValid()) {
2406 rgbcol.r = qcol.red();
2407 rgbcol.g = qcol.green();
2408 rgbcol.b = qcol.blue();
2413 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2415 QColor const qcol(lcolor.getX11Name(col).c_str());
2416 if (!qcol.isValid()) {
2422 rgbcol.r = qcol.red();
2423 rgbcol.g = qcol.green();
2424 rgbcol.b = qcol.blue();
2429 string const GuiApplication::hexName(ColorCode col)
2431 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2435 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2437 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2438 d->socket_notifiers_[fd] = sn;
2439 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2443 void GuiApplication::socketDataReceived(int fd)
2445 d->socket_notifiers_[fd]->func_();
2449 void GuiApplication::unregisterSocketCallback(int fd)
2451 d->socket_notifiers_.take(fd)->setEnabled(false);
2455 void GuiApplication::commitData(QSessionManager & sm)
2457 /// The implementation is required to avoid an application exit
2458 /// when session state save is triggered by session manager.
2459 /// The default implementation sends a close event to all
2460 /// visible top level widgets when session managment allows
2462 /// We are changing that to close all wiew one by one.
2463 /// FIXME: verify if the default implementation is enough now.
2464 #ifdef QT_NO_SESSIONMANAGER
2466 #warning Qt is compiled without session manager
2468 #pragma message("warning: Qt is compiled without session manager")
2472 if (sm.allowsInteraction() && !closeAllViews())
2478 void GuiApplication::unregisterView(GuiView * gv)
2480 LASSERT(d->views_[gv->id()] == gv, /**/);
2481 d->views_.remove(gv->id());
2482 if (current_view_ == gv)
2487 bool GuiApplication::closeAllViews()
2489 if (d->views_.empty())
2492 // When a view/window was closed before without quitting LyX, there
2493 // are already entries in the lastOpened list.
2494 theSession().lastOpened().clear();
2496 QList<GuiView *> const views = d->views_.values();
2497 foreach (GuiView * view, views) {
2498 if (!view->closeScheduled())
2507 GuiView & GuiApplication::view(int id) const
2509 LASSERT(d->views_.contains(id), /**/);
2510 return *d->views_.value(id);
2514 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2516 QList<GuiView *> const views = d->views_.values();
2517 foreach (GuiView * view, views)
2518 view->hideDialog(name, inset);
2522 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2524 Buffer const * buffer_ = 0;
2525 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2526 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2527 if (Buffer const * ptr = (*it)->updateInset(inset))
2534 bool GuiApplication::searchMenu(FuncRequest const & func,
2535 docstring_list & names) const
2537 return d->menus_.searchMenu(func, names);
2541 // Ensure that a file is read only once (prevents include loops)
2542 static QStringList uifiles;
2543 // store which ui files define Toolbars
2544 static QStringList toolbar_uifiles;
2547 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2558 LexerKeyword uitags[] = {
2559 { "format", ui_format },
2560 { "include", ui_include },
2561 { "menuset", ui_menuset },
2562 { "toolbars", ui_toolbars },
2563 { "toolbarset", ui_toolbarset }
2567 lex.setFile(ui_path);
2569 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2573 if (lyxerr.debugging(Debug::PARSER))
2574 lex.printTable(lyxerr);
2577 // format before introduction of format tag
2578 unsigned int format = 0;
2579 while (lex.isOK()) {
2580 int const status = lex.lex();
2582 // we have to do this check here, outside the switch,
2583 // because otherwise we would start reading include files,
2584 // e.g., if the first tag we hit was an include tag.
2585 if (status == ui_format)
2587 format = lex.getInteger();
2591 // this will trigger unless the first tag we hit is a format
2592 // tag, with the right format.
2593 if (format != LFUN_FORMAT)
2594 return FormatMismatch;
2597 case Lexer::LEX_FEOF:
2602 QString const file = toqstr(lex.getString());
2603 bool const success = readUIFile(file, true);
2605 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2612 d->menus_.read(lex);
2616 d->toolbars_.readToolbars(lex);
2620 d->toolbars_.readToolbarSettings(lex);
2621 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2625 if (!rtrim(lex.getString()).empty())
2626 lex.printError("LyX::ReadUIFile: "
2627 "Unknown menu tag: `$$Token'");
2629 LYXERR0("Error with status: " << status);
2635 return (error ? ReadError : ReadOK);
2639 bool GuiApplication::readUIFile(QString const & name, bool include)
2641 LYXERR(Debug::INIT, "About to read " << name << "...");
2645 ui_path = libFileSearch("ui", name, "inc");
2646 if (ui_path.empty())
2647 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2649 ui_path = libFileSearch("ui", name, "ui");
2652 if (ui_path.empty()) {
2653 static const QString defaultUIFile = "default";
2654 LYXERR(Debug::INIT, "Could not find " << name);
2656 Alert::warning(_("Could not find UI definition file"),
2657 bformat(_("Error while reading the included file\n%1$s\n"
2658 "Please check your installation."), qstring_to_ucs4(name)));
2661 if (name == defaultUIFile) {
2662 LYXERR(Debug::INIT, "Could not find default UI file!!");
2663 Alert::warning(_("Could not find default UI file"),
2664 _("LyX could not find the default UI file!\n"
2665 "Please check your installation."));
2668 Alert::warning(_("Could not find UI definition file"),
2669 bformat(_("Error while reading the configuration file\n%1$s\n"
2670 "Falling back to default.\n"
2671 "Please look under Tools>Preferences>User Interface and\n"
2672 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2673 return readUIFile(defaultUIFile, false);
2676 QString const uifile = toqstr(ui_path.absFileName());
2677 if (uifiles.contains(uifile)) {
2679 // We are reading again the top uifile so reset the safeguard:
2682 d->toolbars_.reset();
2684 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2685 << "Is this an include loop?");
2689 uifiles.push_back(uifile);
2691 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2693 ReturnValues retval = readUIFile(ui_path);
2695 if (retval == FormatMismatch) {
2696 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2697 FileName const tempfile = FileName::tempName("convert_ui");
2698 bool const success = prefs2prefs(ui_path, tempfile, true);
2700 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2701 " to format " << LFUN_FORMAT << ".");
2703 retval = readUIFile(tempfile);
2704 tempfile.removeFile();
2708 if (retval != ReadOK) {
2709 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2717 settings.beginGroup("ui_files");
2718 bool touched = false;
2719 for (int i = 0; i != uifiles.size(); ++i) {
2720 QFileInfo fi(uifiles[i]);
2721 QDateTime const date_value = fi.lastModified();
2722 QString const name_key = QString::number(i);
2723 // if an ui file which defines Toolbars has changed,
2724 // we have to reset the settings
2725 if (toolbar_uifiles.contains(uifiles[i])
2726 && (!settings.contains(name_key)
2727 || settings.value(name_key).toString() != uifiles[i]
2728 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2730 settings.setValue(name_key, uifiles[i]);
2731 settings.setValue(name_key + "/date", date_value);
2734 settings.endGroup();
2736 settings.remove("views");
2742 void GuiApplication::onLastWindowClosed()
2744 if (d->global_menubar_)
2745 d->global_menubar_->grabKeyboard();
2749 void GuiApplication::startLongOperation() {
2750 d->key_checker_.start();
2754 bool GuiApplication::longOperationCancelled() {
2755 return d->key_checker_.pressed();
2759 void GuiApplication::stopLongOperation() {
2760 d->key_checker_.stop();
2764 bool GuiApplication::longOperationStarted() {
2765 return d->key_checker_.started();
2769 ////////////////////////////////////////////////////////////////////////
2771 // X11 specific stuff goes here...
2774 bool GuiApplication::x11EventFilter(XEvent * xev)
2779 switch (xev->type) {
2780 case SelectionRequest: {
2781 if (xev->xselectionrequest.selection != XA_PRIMARY)
2783 LYXERR(Debug::SELECTION, "X requested selection.");
2784 BufferView * bv = current_view_->currentBufferView();
2786 docstring const sel = bv->requestSelection();
2788 d->selection_.put(sel);
2792 case SelectionClear: {
2793 if (xev->xselectionclear.selection != XA_PRIMARY)
2795 LYXERR(Debug::SELECTION, "Lost selection.");
2796 BufferView * bv = current_view_->currentBufferView();
2798 bv->clearSelection();
2806 } // namespace frontend
2809 void hideDialogs(std::string const & name, Inset * inset)
2812 frontend::guiApp->hideDialogs(name, inset);
2816 ////////////////////////////////////////////////////////////////////
2820 ////////////////////////////////////////////////////////////////////
2822 frontend::FontLoader & theFontLoader()
2824 LASSERT(frontend::guiApp, /**/);
2825 return frontend::guiApp->fontLoader();
2829 frontend::FontMetrics const & theFontMetrics(Font const & f)
2831 return theFontMetrics(f.fontInfo());
2835 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2837 LASSERT(frontend::guiApp, /**/);
2838 return frontend::guiApp->fontLoader().metrics(f);
2842 ////////////////////////////////////////////////////////////////////
2846 ////////////////////////////////////////////////////////////////////
2848 frontend::Clipboard & theClipboard()
2850 LASSERT(frontend::guiApp, /**/);
2851 return frontend::guiApp->clipboard();
2855 frontend::Selection & theSelection()
2857 LASSERT(frontend::guiApp, /**/);
2858 return frontend::guiApp->selection();
2864 #include "moc_GuiApplication.cpp"