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" },
246 { "Circle", "circle2" },
247 { "Colonapprox", "colonapprox2" },
248 { "Coloneq", "coloneq2" },
249 { "Coloneqq", "coloneqq2" },
250 { "Colonsim", "colonsim2" },
252 { "Delta", "delta2" },
253 { "Diamond", "diamond2" },
254 { "Doteq", "doteq2" },
255 { "Downarrow", "downarrow2" },
256 { "Eqcolon", "eqcolon2" },
257 { "Eqqcolon", "eqqcolon2" },
258 { "Gamma", "gamma2" },
260 { "Lambda", "lambda2" },
262 { "Leftarrow", "leftarrow2" },
263 { "Leftcircle", "leftcircle2" },
264 { "Leftrightarrow", "leftrightarrow2" },
265 { "Longarrownot", "longarrownot2"},
266 { "Longleftarrow", "longleftarrow2" },
267 { "Longleftrightarrow", "longleftrightarrow2" },
268 { "Longmapsfrom", "longmapsfrom2"},
269 { "Longmapsto", "longmapsto2"},
270 { "Longrightarrow", "longrightarrow2" },
271 { "Mapsfrom", "mapsfrom2"},
272 { "Mapsfromchar", "mapsfromchar2"},
273 { "Mapsto", "mapsto2"},
274 { "Mapstochar", "mapstochar2"},
275 { "Omega", "omega2" },
281 { "Rightarrow", "rightarrow2" },
282 { "Rightcircle", "rightcircle2" },
283 { "Sigma", "sigma2" },
284 { "Square", "square2" },
285 { "Subset", "subset2" },
286 { "Supset", "supset2" },
287 { "Theta", "theta2" },
288 { "Thorn", "thorn2" },
289 { "Uparrow", "uparrow2" },
290 { "Updownarrow", "updownarrow2" },
291 { "Upsilon", "upsilon2" },
292 { "Vdash", "vdash3" },
295 { "nLeftarrow", "nleftarrow2" },
296 { "nLeftrightarrow", "nleftrightarrow2" },
297 { "nRightarrow", "nrightarrow2" },
298 { "nVDash", "nvdash3" },
299 { "nVdash", "nvdash4" },
300 { "nvDash", "nvdash2" },
301 { "textrm \\AA", "textrm_AA"},
302 { "textrm \\O", "textrm_O"},
303 { "vDash", "vdash2" },
304 { "varDelta", "vardelta2" },
305 { "varGamma", "vargamma2" },
306 { "varLambda", "varlambda2" },
307 { "varOmega", "varomega2" },
308 { "varPhi", "varphi2" },
309 { "varPi", "varpi2" },
310 { "varPsi", "varpsi2" },
311 { "varSigma", "varsigma2" },
312 { "varTheta", "vartheta2" },
313 { "varUpsilon", "varupsilon2" },
314 { "varXi", "varxi2" }
318 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
321 QString findPng(QString const & name)
323 PngMap const * const begin = sorted_png_map;
324 PngMap const * const end = begin + nr_sorted_png_map;
325 LASSERT(sorted(begin, end), /**/);
327 PngMap const * const it = find_if(begin, end, CompareKey(name));
331 png_name = it->value;
334 png_name.replace('_', "underscore");
335 png_name.replace(' ', '_');
337 // This way we can have "math-delim { }" on the toolbar.
338 png_name.replace('(', "lparen");
339 png_name.replace(')', "rparen");
340 png_name.replace('[', "lbracket");
341 png_name.replace(']', "rbracket");
342 png_name.replace('{', "lbrace");
343 png_name.replace('}', "rbrace");
344 png_name.replace('|', "bars");
345 png_name.replace(',', "thinspace");
346 png_name.replace(':', "mediumspace");
347 png_name.replace(';', "thickspace");
348 png_name.replace('!', "negthinspace");
351 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
352 << "Looking for math PNG called \"" << png_name << '"');
359 QString iconName(FuncRequest const & f, bool unknown)
361 initializeResources();
365 switch (f.action()) {
366 case LFUN_MATH_INSERT:
367 if (!f.argument().empty()) {
369 name1 = findPng(toqstr(f.argument()).mid(1));
372 case LFUN_MATH_DELIM:
373 case LFUN_MATH_BIGDELIM:
375 name1 = findPng(toqstr(f.argument()));
379 name1 = toqstr(f.argument());
381 case LFUN_COMMAND_ALTERNATIVES: {
382 // use the first of the alternative commands
384 docstring dummy = split(f.argument(), firstcom, ';');
385 name1 = toqstr(firstcom);
386 // FIXME: we should rename the icons to tabular-xxx instead of
387 // "tabular-feature-xxx"
388 name1.replace("inset-modify tabular", "tabular-feature");
389 name1.replace(' ', '_');
392 case LFUN_INSET_MODIFY: {
393 // FIXME: we should rename the icons to tabular-xxx instead of
394 // "tabular-feature-xxx" and generalize this naming to all
395 // insets, not to tabular using ones.
397 string const command = split(to_utf8(f.argument()), inset_name, ' ');
398 if (insetCode(inset_name) == TABULAR_CODE) {
399 name1 = "tabular-feature "+ toqstr(command);
400 name1.replace(' ', '_');
405 name2 = toqstr(lyxaction.getActionName(f.action()));
408 if (!f.argument().empty()) {
409 name1 = name2 + ' ' + toqstr(f.argument());
410 name1.replace(' ', '_');
411 name1.replace('\\', "backslash");
415 QStringList imagedirs;
416 imagedirs << "images/" << "images/ipa/";
417 for (int i = 0; i < imagedirs.size(); ++i) {
418 QString imagedir = imagedirs.at(i) + path;
419 FileName fname = imageLibFileSearch(imagedir, name1, "png");
421 return toqstr(fname.absFileName());
423 fname = imageLibFileSearch(imagedir, name2, "png");
425 return toqstr(fname.absFileName());
428 path = ":/images/" + path;
431 LYXERR0("Directory " << path << " not found in resource!");
435 if (res.exists(name1))
439 if (res.exists(name2))
442 LYXERR(Debug::GUI, "Cannot find icon with filename "
443 << "\"" << name1 << "\""
445 << "\"" << name2 << "\""
447 << lyxaction.getActionName(f.action())
448 << '(' << to_utf8(f.argument()) << ")\"");
451 QString imagedir = "images/";
452 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
454 return toqstr(fname.absFileName());
455 return QString(":/images/unknown.png");
461 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
464 QString imagedir = path;
465 FileName fname = imageLibFileSearch(imagedir, name, ext);
466 QString path1 = toqstr(fname.absFileName());
467 QString path2 = ":/" + path + name + "." + ext;
469 if (pixmap.load(path1)) {
472 else if (pixmap.load(path2)) {
476 LYXERR0("Cannot load pixmap \""
477 << path << name << '.' << ext
478 << "\", please verify resource system!");
483 QIcon getIcon(FuncRequest const & f, bool unknown)
485 QString icon = iconName(f, unknown);
489 //LYXERR(Debug::GUI, "Found icon: " << icon);
491 if (!pm.load(icon)) {
492 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
500 ////////////////////////////////////////////////////////////////////////
502 // LyX server support code.
504 ////////////////////////////////////////////////////////////////////////
506 class SocketNotifier : public QSocketNotifier
509 /// connect a connection notification from the LyXServerSocket
510 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
511 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
515 /// The callback function
516 Application::SocketCallback func_;
520 ////////////////////////////////////////////////////////////////////////
522 // Mac specific stuff goes here...
524 ////////////////////////////////////////////////////////////////////////
526 class MenuTranslator : public QTranslator
529 MenuTranslator(QObject * parent)
530 : QTranslator(parent)
533 QString translate(const char * /*context*/,
534 const char * sourceText,
535 const char * /*comment*/ = 0) const
537 string const s = sourceText;
538 if (s == N_("About %1") || s == N_("Preferences")
539 || s == N_("Reconfigure") || s == N_("Quit %1"))
546 class GlobalMenuBar : public QMenuBar
550 GlobalMenuBar() : QMenuBar(0) {}
553 bool event(QEvent * e)
555 if (e->type() == QEvent::ShortcutOverride) {
556 // && activeWindow() == 0) {
557 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
559 setKeySymbol(&sym, ke);
560 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
569 // QMacPasteboardMimeGraphics can only be compiled on Mac.
571 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
574 QMacPasteboardMimeGraphics()
575 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
578 QString convertorName() { return "Graphics"; }
580 QString flavorFor(QString const & mime)
582 LYXERR(Debug::ACTION, "flavorFor " << mime);
583 if (mime == pdfMimeType())
584 return QLatin1String("com.adobe.pdf");
588 QString mimeFor(QString flav)
590 LYXERR(Debug::ACTION, "mimeFor " << flav);
591 if (flav == QLatin1String("com.adobe.pdf"))
592 return pdfMimeType();
596 bool canConvert(QString const & mime, QString flav)
598 return mimeFor(flav) == mime;
601 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
605 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
609 QList<QByteArray> convertFromMime(QString const & /*mime*/,
610 QVariant data, QString /*flav*/)
612 QList<QByteArray> ret;
613 ret.append(data.toByteArray());
619 ///////////////////////////////////////////////////////////////
621 // You can find more platform specific stuff at the end of this file...
623 ///////////////////////////////////////////////////////////////
625 ////////////////////////////////////////////////////////////////////////
626 // Windows specific stuff goes here...
629 // QWindowsMimeMetafile can only be compiled on Windows.
631 static FORMATETC cfFromMime(QString const & mimetype)
634 if (mimetype == emfMimeType()) {
635 formatetc.cfFormat = CF_ENHMETAFILE;
636 formatetc.tymed = TYMED_ENHMF;
637 } else if (mimetype == wmfMimeType()) {
638 formatetc.cfFormat = CF_METAFILEPICT;
639 formatetc.tymed = TYMED_MFPICT;
642 formatetc.dwAspect = DVASPECT_CONTENT;
643 formatetc.lindex = -1;
648 class QWindowsMimeMetafile : public QWindowsMime {
650 QWindowsMimeMetafile() {}
652 bool canConvertFromMime(FORMATETC const & formatetc,
653 QMimeData const * mimedata) const
658 bool canConvertToMime(QString const & mimetype,
659 IDataObject * pDataObj) const
661 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
663 FORMATETC formatetc = cfFromMime(mimetype);
664 return pDataObj->QueryGetData(&formatetc) == S_OK;
667 bool convertFromMime(FORMATETC const & formatetc,
668 const QMimeData * mimedata, STGMEDIUM * pmedium) const
673 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
674 QVariant::Type preferredType) const
677 if (!canConvertToMime(mimetype, pDataObj))
680 FORMATETC formatetc = cfFromMime(mimetype);
682 if (pDataObj->GetData(&formatetc, &s) != S_OK)
686 if (s.tymed == TYMED_ENHMF) {
687 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
688 data.resize(dataSize);
689 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
690 (LPBYTE)data.data());
691 } else if (s.tymed == TYMED_MFPICT) {
692 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
693 data.resize(dataSize);
694 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
695 (LPBYTE)data.data());
698 ReleaseStgMedium(&s);
704 QVector<FORMATETC> formatsForMime(QString const & mimetype,
705 QMimeData const * mimedata) const
707 QVector<FORMATETC> formats;
708 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
709 formats += cfFromMime(mimetype);
713 QString mimeForFormat(FORMATETC const & formatetc) const
715 switch (formatetc.cfFormat) {
717 return emfMimeType();
718 case CF_METAFILEPICT:
719 return wmfMimeType();
728 /// Allows to check whether ESC was pressed during a long operation
729 class KeyChecker : public QObject {
734 KeyChecker() : pressed_(false), started_(false) {}
737 QCoreApplication::instance()->installEventFilter(this);
742 QCoreApplication::instance()->removeEventFilter(this);
746 QCoreApplication::processEvents();
749 bool started() const {
752 bool eventFilter(QObject *obj, QEvent *event) {
753 LYXERR(Debug::ACTION, "Event Type: " << event->type());
754 switch (event->type()) {
758 return QObject::eventFilter(obj, event);
760 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
761 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
769 ////////////////////////////////////////////////////////////////////////
770 // GuiApplication::Private definition and implementation.
771 ////////////////////////////////////////////////////////////////////////
773 struct GuiApplication::Private
775 Private(): language_model_(0), meta_fake_bit(NoModifier),
779 /// WMF Mime handler for Windows clipboard.
780 wmf_mime_ = new QWindowsMimeMetafile;
782 initKeySequences(&theTopLevelKeymap());
785 void initKeySequences(KeyMap * kb)
787 keyseq = KeySequence(kb, kb);
788 cancel_meta_seq = KeySequence(kb, kb);
792 QSortFilterProxyModel * language_model_;
794 GuiClipboard clipboard_;
796 GuiSelection selection_;
798 FontLoader font_loader_;
800 ColorCache color_cache_;
802 QTranslator qt_trans_;
804 QHash<int, SocketNotifier *> socket_notifiers_;
808 /// The global instance
811 /// this timer is used for any regular events one wants to
812 /// perform. at present it is used to check if forked processes
814 QTimer general_timer_;
816 /// delayed FuncRequests
817 std::queue<FuncRequest> func_request_queue_;
822 KeySequence cancel_meta_seq;
824 KeyModifier meta_fake_bit;
826 /// Multiple views container.
828 * Warning: This must not be a smart pointer as the destruction of the
829 * object is handled by Qt when the view is closed
830 * \sa Qt::WA_DeleteOnClose attribute.
832 QHash<int, GuiView *> views_;
834 /// Only used on mac.
835 GlobalMenuBar * global_menubar_;
838 /// Linkback mime handler for MacOSX.
839 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
843 /// WMF Mime handler for Windows clipboard.
844 QWindowsMimeMetafile * wmf_mime_;
847 /// Allows to check whether ESC was pressed during a long operation
848 KeyChecker key_checker_;
852 GuiApplication * guiApp;
854 GuiApplication::~GuiApplication()
857 closeAllLinkBackLinks();
863 GuiApplication::GuiApplication(int & argc, char ** argv)
864 : QApplication(argc, argv), current_view_(0),
865 d(new GuiApplication::Private)
867 QString app_name = "LyX";
868 QCoreApplication::setOrganizationName(app_name);
869 QCoreApplication::setOrganizationDomain("lyx.org");
870 QCoreApplication::setApplicationName(lyx_package);
872 // Install translator for GUI elements.
873 installTranslator(&d->qt_trans_);
875 // FIXME: quitOnLastWindowClosed is true by default. We should have a
876 // lyxrc setting for this in order to let the application stay resident.
877 // But then we need some kind of dock icon, at least on Windows.
879 if (lyxrc.quit_on_last_window_closed)
880 setQuitOnLastWindowClosed(false);
883 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
884 // seems to be the default case for applications like LyX.
885 setQuitOnLastWindowClosed(false);
886 // This allows to translate the strings that appear in the LyX menu.
887 /// A translator suitable for the entries in the LyX menu.
888 /// Only needed with Qt/Mac.
889 installTranslator(new MenuTranslator(this));
895 // doubleClickInterval() is 400 ms on X11 which is just too long.
896 // On Windows and Mac OS X, the operating system's value is used.
897 // On Microsoft Windows, calling this function sets the double
898 // click interval for all applications. So we don't!
899 QApplication::setDoubleClickInterval(300);
902 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
904 // needs to be done before reading lyxrc
906 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
910 // Set the cache to 5120 kilobytes which corresponds to screen size of
911 // 1280 by 1024 pixels with a color depth of 32 bits.
912 QPixmapCache::setCacheLimit(5120);
914 // Initialize RC Fonts
915 if (lyxrc.roman_font_name.empty())
916 lyxrc.roman_font_name = fromqstr(romanFontName());
918 if (lyxrc.sans_font_name.empty())
919 lyxrc.sans_font_name = fromqstr(sansFontName());
921 if (lyxrc.typewriter_font_name.empty())
922 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
924 d->general_timer_.setInterval(500);
925 connect(&d->general_timer_, SIGNAL(timeout()),
926 this, SLOT(handleRegularEvents()));
927 d->general_timer_.start();
929 // maxThreadCount() defaults in general to 2 on single or dual-processor.
930 // This is clearly not enough in a time where we use threads for
931 // document preview and/or export. 20 should be OK.
932 QThreadPool::globalInstance()->setMaxThreadCount(20);
936 GuiApplication * theGuiApp()
938 return dynamic_cast<GuiApplication *>(theApp());
942 void GuiApplication::clearSession()
949 docstring Application::iconName(FuncRequest const & f, bool unknown)
951 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
955 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
960 BufferView * doc_bv = 0;
962 if (cmd.action() == LFUN_NOACTION) {
963 status.message(from_utf8(N_("Nothing to do")));
964 status.setEnabled(false);
967 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
968 status.setUnknown(true);
969 status.message(from_utf8(N_("Unknown action")));
970 status.setEnabled(false);
973 // Does the GuiApplication know something?
974 else if (getStatus(cmd, status)) { }
976 // If we do not have a GuiView, then other functions are disabled
977 else if (!current_view_)
978 status.setEnabled(false);
980 // Does the GuiView know something?
981 else if (current_view_->getStatus(cmd, status)) { }
983 // In LyX/Mac, when a dialog is open, the menus of the
984 // application can still be accessed without giving focus to
985 // the main window. In this case, we want to disable the menu
986 // entries that are buffer or view-related.
987 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
989 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
990 status.setEnabled(false);
993 // If we do not have a BufferView, then other functions are disabled
994 else if (!(bv = current_view_->currentBufferView()))
995 status.setEnabled(false);
997 // Does the current BufferView know something?
998 else if (bv->getStatus(cmd, status)) { }
1000 // Does the current Buffer know something?
1001 else if (bv->buffer().getStatus(cmd, status)) { }
1003 // If we do not have a document BufferView, different from the
1004 // current BufferView, then other functions are disabled
1005 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1006 status.setEnabled(false);
1008 // Does the document Buffer know something?
1009 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1012 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1013 status.message(from_utf8(N_("Command not handled")));
1014 status.setEnabled(false);
1017 // the default error message if we disable the command
1018 if (!status.enabled() && status.message().empty())
1019 status.message(from_utf8(N_("Command disabled")));
1025 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1027 // I would really like to avoid having this switch and rather try to
1028 // encode this in the function itself.
1029 // -- And I'd rather let an inset decide which LFUNs it is willing
1030 // to handle (Andre')
1032 switch (cmd.action()) {
1034 // This could be used for the no-GUI version. The GUI version is handled in
1035 // GuiView::getStatus(). See above.
1037 case LFUN_BUFFER_WRITE:
1038 case LFUN_BUFFER_WRITE_AS: {
1039 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1040 enable = b && (b->isUnnamed() || !b->isClean());
1045 case LFUN_BOOKMARK_GOTO: {
1046 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1047 enable = theSession().bookmarks().isValid(num);
1051 case LFUN_BOOKMARK_CLEAR:
1052 enable = theSession().bookmarks().hasValid();
1055 // this one is difficult to get right. As a half-baked
1056 // solution, we consider only the first action of the sequence
1057 case LFUN_COMMAND_SEQUENCE: {
1058 // argument contains ';'-terminated commands
1059 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1060 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1061 func.setOrigin(cmd.origin());
1062 flag = getStatus(func);
1066 // we want to check if at least one of these is enabled
1067 case LFUN_COMMAND_ALTERNATIVES: {
1068 // argument contains ';'-terminated commands
1069 string arg = to_utf8(cmd.argument());
1070 while (!arg.empty()) {
1072 arg = split(arg, first, ';');
1073 FuncRequest func(lyxaction.lookupFunc(first));
1074 func.setOrigin(cmd.origin());
1075 flag = getStatus(func);
1076 // if this one is enabled, the whole thing is
1085 string name = to_utf8(cmd.argument());
1086 if (theTopLevelCmdDef().lock(name, func)) {
1087 func.setOrigin(cmd.origin());
1088 flag = getStatus(func);
1089 theTopLevelCmdDef().release(name);
1091 // catch recursion or unknown command
1092 // definition. all operations until the
1093 // recursion or unknown command definition
1094 // occurs are performed, so set the state to
1101 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1103 case LFUN_PREFERENCES_SAVE:
1104 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1105 case LFUN_DEBUG_LEVEL_SET:
1106 // these are handled in our dispatch()
1109 case LFUN_WINDOW_CLOSE:
1110 enable = d->views_.size() > 0;
1113 case LFUN_BUFFER_NEW:
1114 case LFUN_BUFFER_NEW_TEMPLATE:
1115 case LFUN_FILE_OPEN:
1116 case LFUN_HELP_OPEN:
1117 case LFUN_SCREEN_FONT_UPDATE:
1118 case LFUN_SET_COLOR:
1119 case LFUN_WINDOW_NEW:
1121 case LFUN_LYXRC_APPLY:
1122 case LFUN_COMMAND_PREFIX:
1124 case LFUN_META_PREFIX:
1125 case LFUN_RECONFIGURE:
1126 case LFUN_SERVER_GET_FILENAME:
1127 case LFUN_SERVER_NOTIFY:
1131 case LFUN_BUFFER_FORALL: {
1132 if (theBufferList().empty()) {
1133 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1134 flag.setEnabled(false);
1138 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1139 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1140 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1141 flag.setEnabled(false);
1152 flag.setEnabled(false);
1156 /// make a post-dispatch status message
1157 static docstring makeDispatchMessage(docstring const & msg,
1158 FuncRequest const & cmd)
1160 const bool verbose = (cmd.origin() == FuncRequest::MENU
1161 || cmd.origin() == FuncRequest::TOOLBAR
1162 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1164 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1165 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1169 docstring dispatch_msg = msg;
1170 if (!dispatch_msg.empty())
1171 dispatch_msg += ' ';
1173 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1175 bool argsadded = false;
1177 if (!cmd.argument().empty()) {
1178 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1179 comname += ' ' + cmd.argument();
1183 docstring const shortcuts = theTopLevelKeymap().
1184 printBindings(cmd, KeySequence::ForGui);
1186 if (!shortcuts.empty())
1187 comname += ": " + shortcuts;
1188 else if (!argsadded && !cmd.argument().empty())
1189 comname += ' ' + cmd.argument();
1191 if (!comname.empty()) {
1192 comname = rtrim(comname);
1193 dispatch_msg += '(' + rtrim(comname) + ')';
1195 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1196 return dispatch_msg;
1200 void GuiApplication::dispatch(FuncRequest const & cmd)
1202 Buffer * buffer = 0;
1203 if (current_view_ && current_view_->currentBufferView()) {
1204 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1205 buffer = ¤t_view_->currentBufferView()->buffer();
1207 buffer->undo().beginUndoGroup();
1211 // redraw the screen at the end (first of the two drawing steps).
1212 // This is done unless explicitly requested otherwise
1213 dr.screenUpdate(Update::FitCursor);
1215 updateCurrentView(cmd, dr);
1217 // the buffer may have been closed by one action
1218 if (theBufferList().isLoaded(buffer))
1219 buffer->undo().endUndoGroup();
1223 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1228 BufferView * bv = current_view_->currentBufferView();
1230 if (dr.needBufferUpdate()) {
1231 bv->cursor().clearBufferUpdate();
1232 bv->buffer().updateBuffer();
1234 // BufferView::update() updates the ViewMetricsInfo and
1235 // also initializes the position cache for all insets in
1236 // (at least partially) visible top-level paragraphs.
1237 // We will redraw the screen only if needed.
1238 bv->processUpdateFlags(dr.screenUpdate());
1240 // Do we have a selection?
1241 theSelection().haveSelection(bv->cursor().selection());
1244 current_view_->restartCursor();
1246 if (dr.needMessageUpdate()) {
1247 // Some messages may already be translated, so we cannot use _()
1248 current_view_->message(makeDispatchMessage(
1249 translateIfPossible(dr.message()), cmd));
1254 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1255 bool switchToBuffer)
1257 if (!theSession().bookmarks().isValid(idx))
1259 BookmarksSection::Bookmark const & bm =
1260 theSession().bookmarks().bookmark(idx);
1261 LASSERT(!bm.filename.empty(), /**/);
1262 string const file = bm.filename.absFileName();
1263 // if the file is not opened, open it.
1264 if (!theBufferList().exists(bm.filename)) {
1266 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1270 // open may fail, so we need to test it again
1271 if (!theBufferList().exists(bm.filename))
1274 // bm can be changed when saving
1275 BookmarksSection::Bookmark tmp = bm;
1277 // Special case idx == 0 used for back-from-back jump navigation
1279 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1281 // if the current buffer is not that one, switch to it.
1282 BufferView * doc_bv = current_view_ ?
1283 current_view_->documentBufferView() : 0;
1284 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1285 if (switchToBuffer) {
1286 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1289 doc_bv = current_view_->documentBufferView();
1294 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1295 if (!doc_bv->moveToPosition(
1296 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1303 // Cursor jump succeeded!
1304 Cursor const & cur = doc_bv->cursor();
1305 pit_type new_pit = cur.pit();
1306 pos_type new_pos = cur.pos();
1307 int new_id = cur.paragraph().id();
1309 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1310 // see http://www.lyx.org/trac/ticket/3092
1311 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1312 || bm.top_id != new_id) {
1313 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1314 new_pit, new_pos, new_id);
1318 // This function runs "configure" and then rereads lyx.defaults to
1319 // reconfigure the automatic settings.
1320 void GuiApplication::reconfigure(string const & option)
1322 // emit message signal.
1324 current_view_->message(_("Running configure..."));
1326 // Run configure in user lyx directory
1327 PathChanger p(package().user_support());
1328 string configure_command = package().configure_command();
1329 configure_command += option;
1331 int const ret = one.startscript(Systemcall::Wait, configure_command);
1333 // emit message signal.
1335 current_view_->message(_("Reloading configuration..."));
1336 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1337 // Re-read packages.lst
1338 LaTeXPackages::getAvailable();
1341 Alert::information(_("System reconfiguration failed"),
1342 _("The system reconfiguration has failed.\n"
1343 "Default textclass is used but LyX may\n"
1344 "not be able to work properly.\n"
1345 "Please reconfigure again if needed."));
1347 Alert::information(_("System reconfigured"),
1348 _("The system has been reconfigured.\n"
1349 "You need to restart LyX to make use of any\n"
1350 "updated document class specifications."));
1353 void GuiApplication::validateCurrentView()
1355 if (!d->views_.empty() && !current_view_) {
1356 // currently at least one view exists but no view has the focus.
1357 // choose the last view to make it current.
1358 // a view without any open document is preferred.
1359 GuiView * candidate = 0;
1360 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1361 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1362 for (; it != end; ++it) {
1364 if (!candidate->documentBufferView())
1367 setCurrentView(candidate);
1371 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1373 string const argument = to_utf8(cmd.argument());
1374 FuncCode const action = cmd.action();
1376 LYXERR(Debug::ACTION, "cmd: " << cmd);
1378 // we have not done anything wrong yet.
1381 FuncStatus const flag = getStatus(cmd);
1382 if (!flag.enabled()) {
1383 // We cannot use this function here
1384 LYXERR(Debug::ACTION, "action "
1385 << lyxaction.getActionName(action)
1386 << " [" << action << "] is disabled at this location");
1387 dr.setMessage(flag.message());
1389 dr.dispatched(false);
1390 dr.screenUpdate(Update::None);
1391 dr.clearBufferUpdate();
1395 if (cmd.origin() == FuncRequest::LYXSERVER) {
1396 if (current_view_ && current_view_->currentBufferView())
1397 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1398 // we will also need to redraw the screen at the end
1399 dr.screenUpdate(Update::FitCursor);
1402 // Assumes that the action will be dispatched.
1403 dr.dispatched(true);
1405 switch (cmd.action()) {
1407 case LFUN_WINDOW_NEW:
1408 createView(toqstr(cmd.argument()));
1411 case LFUN_WINDOW_CLOSE:
1412 // update bookmark pit of the current buffer before window close
1413 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1414 gotoBookmark(i+1, false, false);
1415 // clear the last opened list, because
1416 // maybe this will end the session
1417 theSession().lastOpened().clear();
1418 // check for valid current_view_
1419 validateCurrentView();
1421 current_view_->closeScheduled();
1425 // quitting is triggered by the gui code
1426 // (leaving the event loop).
1428 current_view_->message(from_utf8(N_("Exiting.")));
1429 if (closeAllViews())
1433 case LFUN_SCREEN_FONT_UPDATE: {
1434 // handle the screen font changes.
1435 d->font_loader_.update();
1436 // Backup current_view_
1437 GuiView * view = current_view_;
1438 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1439 // to skip the refresh.
1441 theBufferList().changed(false);
1442 // Restore current_view_
1443 current_view_ = view;
1447 case LFUN_BUFFER_NEW:
1448 validateCurrentView();
1449 if (d->views_.empty()
1450 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1451 createView(QString(), false); // keep hidden
1452 current_view_->newDocument(to_utf8(cmd.argument()), false);
1453 current_view_->show();
1454 setActiveWindow(current_view_);
1456 current_view_->newDocument(to_utf8(cmd.argument()), false);
1460 case LFUN_BUFFER_NEW_TEMPLATE:
1461 validateCurrentView();
1462 if (d->views_.empty()
1463 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1465 current_view_->newDocument(to_utf8(cmd.argument()), true);
1466 if (!current_view_->documentBufferView())
1467 current_view_->close();
1469 current_view_->newDocument(to_utf8(cmd.argument()), true);
1473 case LFUN_FILE_OPEN: {
1474 validateCurrentView();
1475 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1476 string const fname = to_utf8(cmd.argument());
1477 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1478 && current_view_->documentBufferView() != 0)) {
1479 // We want the ui session to be saved per document and not per
1480 // window number. The filename crc is a good enough identifier.
1481 boost::crc_32_type crc;
1482 crc = for_each(fname.begin(), fname.end(), crc);
1483 createView(crc.checksum());
1484 current_view_->openDocument(fname);
1485 if (current_view_ && !current_view_->documentBufferView())
1486 current_view_->close();
1488 current_view_->openDocument(fname);
1492 case LFUN_HELP_OPEN: {
1493 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1494 if (current_view_ == 0)
1496 string const arg = to_utf8(cmd.argument());
1498 current_view_->message(_("Missing argument"));
1501 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1503 fname = i18nLibFileSearch("examples", arg, "lyx");
1505 if (fname.empty()) {
1506 lyxerr << "LyX: unable to find documentation file `"
1507 << arg << "'. Bad installation?" << endl;
1510 current_view_->message(bformat(_("Opening help file %1$s..."),
1511 makeDisplayPath(fname.absFileName())));
1512 Buffer * buf = current_view_->loadDocument(fname, false);
1514 #ifndef DEVEL_VERSION
1516 buf->setReadonly(true);
1523 case LFUN_SET_COLOR: {
1525 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1526 if (lyx_name.empty() || x11_name.empty()) {
1528 current_view_->message(
1529 _("Syntax: set-color <lyx_name> <x11_name>"));
1534 // FIXME: The graphics cache no longer has a changeDisplay method.
1535 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1536 bool const graphicsbg_changed =
1537 lyx_name == graphicsbg && x11_name != graphicsbg;
1538 if (graphicsbg_changed)
1539 graphics::GCache::get().changeDisplay(true);
1542 if (!lcolor.setColor(lyx_name, x11_name)) {
1544 current_view_->message(
1545 bformat(_("Set-color \"%1$s\" failed "
1546 "- color is undefined or "
1547 "may not be redefined"),
1548 from_utf8(lyx_name)));
1551 // Make sure we don't keep old colors in cache.
1552 d->color_cache_.clear();
1556 case LFUN_LYXRC_APPLY: {
1557 // reset active key sequences, since the bindings
1558 // are updated (bug 6064)
1560 LyXRC const lyxrc_orig = lyxrc;
1562 istringstream ss(to_utf8(cmd.argument()));
1563 bool const success = lyxrc.read(ss);
1566 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1567 << "Unable to read lyxrc data"
1572 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1578 case LFUN_COMMAND_PREFIX:
1579 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1584 d->meta_fake_bit = NoModifier;
1585 GuiView * gv = currentView();
1586 if (gv && gv->currentBufferView())
1587 // cancel any selection
1588 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1589 dr.setMessage(from_ascii(N_("Cancel")));
1592 case LFUN_META_PREFIX:
1593 d->meta_fake_bit = AltModifier;
1594 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1597 // --- Menus -----------------------------------------------
1598 case LFUN_RECONFIGURE:
1599 // argument is any additional parameter to the configure.py command
1600 reconfigure(to_utf8(cmd.argument()));
1603 // --- lyxserver commands ----------------------------
1604 case LFUN_SERVER_GET_FILENAME: {
1605 if (current_view_ && current_view_->documentBufferView()) {
1606 docstring const fname = from_utf8(
1607 current_view_->documentBufferView()->buffer().absFileName());
1608 dr.setMessage(fname);
1609 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1611 dr.setMessage(docstring());
1612 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1617 case LFUN_SERVER_NOTIFY: {
1618 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1619 dr.setMessage(dispatch_buffer);
1620 theServer().notifyClient(to_utf8(dispatch_buffer));
1624 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1625 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1631 string rest = split(argument, countstr, ' ');
1632 istringstream is(countstr);
1635 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1636 for (int i = 0; i < count; ++i)
1637 dispatch(lyxaction.lookupFunc(rest));
1641 case LFUN_COMMAND_SEQUENCE: {
1642 // argument contains ';'-terminated commands
1643 string arg = argument;
1644 // FIXME: this LFUN should also work without any view.
1645 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1646 ? &(current_view_->documentBufferView()->buffer()) : 0;
1648 buffer->undo().beginUndoGroup();
1649 while (!arg.empty()) {
1651 arg = split(arg, first, ';');
1652 FuncRequest func(lyxaction.lookupFunc(first));
1653 func.setOrigin(cmd.origin());
1656 // the buffer may have been closed by one action
1657 if (theBufferList().isLoaded(buffer))
1658 buffer->undo().endUndoGroup();
1662 case LFUN_BUFFER_FORALL: {
1663 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1665 map<Buffer *, GuiView *> views_lVisible;
1666 map<GuiView *, Buffer *> activeBuffers;
1668 QList<GuiView *> allViews = d->views_.values();
1670 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1671 // and on which buffer is active in each view.
1672 Buffer * const last = theBufferList().last();
1673 foreach (GuiView * view, allViews) {
1674 // all of the buffers might be locally hidden. That is, there is no active buffer.
1675 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1676 activeBuffers[view] = 0;
1678 activeBuffers[view] = &view->currentBufferView()->buffer();
1680 // find out if each is locally visible or locally hidden.
1681 // we don't use a for loop as the buffer list cycles.
1682 Buffer * b = theBufferList().first();
1684 bool const locallyVisible = view && view->workArea(*b);
1685 if (locallyVisible) {
1686 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1687 // only need to overwrite/add if we don't already know a buffer is globally
1688 // visible or we do know but we would prefer to dispatch LFUN from the
1689 // current view because of cursor position issues.
1690 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1691 views_lVisible[b] = view;
1695 b = theBufferList().next(b);
1699 GuiView * const homeView = currentView();
1700 Buffer * b = theBufferList().first();
1701 Buffer * nextBuf = 0;
1702 int numProcessed = 0;
1705 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1707 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1709 // first change to a view where b is locally visible, preferably current_view_.
1710 GuiView * const vLv = views_lVisible[b];
1712 lyx::dispatch(funcToRun);
1720 // put things back to how they were (if possible).
1721 foreach (GuiView * view, allViews) {
1722 Buffer * originalBuf = activeBuffers[view];
1723 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1724 if (theBufferList().isLoaded(originalBuf))
1725 view->setBuffer(originalBuf);
1727 homeView->setFocus();
1729 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1733 case LFUN_COMMAND_ALTERNATIVES: {
1734 // argument contains ';'-terminated commands
1735 string arg = argument;
1736 while (!arg.empty()) {
1738 arg = split(arg, first, ';');
1739 FuncRequest func(lyxaction.lookupFunc(first));
1740 func.setOrigin(cmd.origin());
1741 FuncStatus const stat = getStatus(func);
1742 if (stat.enabled()) {
1752 if (theTopLevelCmdDef().lock(argument, func)) {
1753 func.setOrigin(cmd.origin());
1755 theTopLevelCmdDef().release(argument);
1757 if (func.action() == LFUN_UNKNOWN_ACTION) {
1758 // unknown command definition
1759 lyxerr << "Warning: unknown command definition `"
1763 // recursion detected
1764 lyxerr << "Warning: Recursion in the command definition `"
1765 << argument << "' detected"
1772 case LFUN_PREFERENCES_SAVE:
1773 lyxrc.write(support::makeAbsPath("preferences",
1774 package().user_support().absFileName()), false);
1777 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1778 string const fname = addName(addPath(package().user_support().absFileName(),
1779 "templates/"), "defaults.lyx");
1780 Buffer defaults(fname);
1782 istringstream ss(argument);
1785 int const unknown_tokens = defaults.readHeader(lex);
1787 if (unknown_tokens != 0) {
1788 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1789 << unknown_tokens << " unknown token"
1790 << (unknown_tokens == 1 ? "" : "s")
1794 if (defaults.writeFile(FileName(defaults.absFileName())))
1795 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1796 makeDisplayPath(fname)));
1799 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1804 case LFUN_BOOKMARK_GOTO:
1805 // go to bookmark, open unopened file and switch to buffer if necessary
1806 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1807 dr.screenUpdate(Update::Force | Update::FitCursor);
1810 case LFUN_BOOKMARK_CLEAR:
1811 theSession().bookmarks().clear();
1814 case LFUN_DEBUG_LEVEL_SET:
1815 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1819 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1822 current_view_->dispatch(cmd, dr);
1826 if (cmd.origin() == FuncRequest::LYXSERVER)
1827 updateCurrentView(cmd, dr);
1831 docstring GuiApplication::viewStatusMessage()
1833 // When meta-fake key is pressed, show the key sequence so far + "M-".
1834 if (d->meta_fake_bit != NoModifier)
1835 return d->keyseq.print(KeySequence::ForGui) + "M-";
1837 // Else, when a non-complete key sequence is pressed,
1838 // show the available options.
1839 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1840 return d->keyseq.printOptions(true);
1846 void GuiApplication::handleKeyFunc(FuncCode action)
1850 if (d->keyseq.length())
1852 GuiView * gv = currentView();
1853 LASSERT(gv && gv->currentBufferView(), return);
1854 BufferView * bv = gv->currentBufferView();
1855 bv->getIntl().getTransManager().deadkey(
1856 c, get_accent(action).accent, bv->cursor().innerText(),
1858 // Need to clear, in case the minibuffer calls these
1861 // copied verbatim from do_accent_char
1862 bv->cursor().resetAnchor();
1866 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1868 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1870 // Do nothing if we have nothing (JMarc)
1871 if (!keysym.isOK()) {
1872 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1874 current_view_->restartCursor();
1878 if (keysym.isModifier()) {
1880 current_view_->restartCursor();
1884 char_type encoded_last_key = keysym.getUCSEncoded();
1886 // Do a one-deep top-level lookup for
1887 // cancel and meta-fake keys. RVDK_PATCH_5
1888 d->cancel_meta_seq.reset();
1890 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1891 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1893 // When not cancel or meta-fake, do the normal lookup.
1894 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1895 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1896 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1897 // remove Caps Lock and Mod2 as a modifiers
1898 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1899 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1902 // Dont remove this unless you know what you are doing.
1903 d->meta_fake_bit = NoModifier;
1905 // Can this happen now ?
1906 if (func.action() == LFUN_NOACTION)
1907 func = FuncRequest(LFUN_COMMAND_PREFIX);
1909 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1910 << d->keyseq.print(KeySequence::Portable) << ']');
1912 // already here we know if it any point in going further
1913 // why not return already here if action == -1 and
1914 // num_bytes == 0? (Lgb)
1916 if (d->keyseq.length() > 1 && current_view_)
1917 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1920 // Maybe user can only reach the key via holding down shift.
1921 // Let's see. But only if shift is the only modifier
1922 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1923 LYXERR(Debug::KEY, "Trying without shift");
1924 func = d->keyseq.addkey(keysym, NoModifier);
1925 LYXERR(Debug::KEY, "Action now " << func.action());
1928 if (func.action() == LFUN_UNKNOWN_ACTION) {
1929 // Hmm, we didn't match any of the keysequences. See
1930 // if it's normal insertable text not already covered
1932 if (keysym.isText() && d->keyseq.length() == 1) {
1933 LYXERR(Debug::KEY, "isText() is true, inserting.");
1934 func = FuncRequest(LFUN_SELF_INSERT,
1935 FuncRequest::KEYBOARD);
1937 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1938 if (current_view_) {
1939 current_view_->message(_("Unknown function."));
1940 current_view_->restartCursor();
1946 if (func.action() == LFUN_SELF_INSERT) {
1947 if (encoded_last_key != 0) {
1948 docstring const arg(1, encoded_last_key);
1949 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1950 FuncRequest::KEYBOARD));
1951 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1954 processFuncRequest(func);
1958 void GuiApplication::processFuncRequest(FuncRequest const & func)
1960 lyx::dispatch(func);
1964 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1966 addToFuncRequestQueue(func);
1967 processFuncRequestQueueAsync();
1971 void GuiApplication::processFuncRequestQueue()
1973 while (!d->func_request_queue_.empty()) {
1974 processFuncRequest(d->func_request_queue_.front());
1975 d->func_request_queue_.pop();
1980 void GuiApplication::processFuncRequestQueueAsync()
1982 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
1986 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
1988 d->func_request_queue_.push(func);
1992 void GuiApplication::resetGui()
1994 // Set the language defined by the user.
1998 if (!readUIFile(toqstr(lyxrc.ui_file)))
1999 // Gives some error box here.
2002 if (d->global_menubar_)
2003 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2005 QHash<int, GuiView *>::iterator it;
2006 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2009 gv->setLayoutDirection(layoutDirection());
2013 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2017 void GuiApplication::createView(int view_id)
2019 createView(QString(), true, view_id);
2023 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2026 // release the keyboard which might have been grabed by the global
2027 // menubar on Mac to catch shortcuts even without any GuiView.
2028 if (d->global_menubar_)
2029 d->global_menubar_->releaseKeyboard();
2033 while (d->views_.find(id) != d->views_.end())
2036 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2037 GuiView * view = new GuiView(id);
2039 d->views_[id] = view;
2043 setActiveWindow(view);
2046 if (!geometry_arg.isEmpty()) {
2050 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2051 re.indexIn(geometry_arg);
2052 w = re.cap(1).toInt();
2053 h = re.cap(2).toInt();
2054 x = re.cap(3).toInt();
2055 y = re.cap(4).toInt();
2056 view->setGeometry(x, y, w, h);
2063 Clipboard & GuiApplication::clipboard()
2065 return d->clipboard_;
2069 Selection & GuiApplication::selection()
2071 return d->selection_;
2075 FontLoader & GuiApplication::fontLoader()
2077 return d->font_loader_;
2081 Toolbars const & GuiApplication::toolbars() const
2083 return d->toolbars_;
2087 Toolbars & GuiApplication::toolbars()
2089 return d->toolbars_;
2093 Menus const & GuiApplication::menus() const
2099 Menus & GuiApplication::menus()
2105 QList<int> GuiApplication::viewIds() const
2107 return d->views_.keys();
2111 ColorCache & GuiApplication::colorCache()
2113 return d->color_cache_;
2117 int GuiApplication::exec()
2119 // asynchronously handle batch commands. This event will be in
2120 // the event queue in front of other asynchronous events. Hence,
2121 // we can assume in the latter that the gui is setup already.
2122 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2124 return QApplication::exec();
2128 void GuiApplication::exit(int status)
2130 QApplication::exit(status);
2134 void GuiApplication::setGuiLanguage()
2136 QString const default_language = toqstr(getGuiMessages().language());
2137 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2138 QLocale const default_locale(default_language);
2139 QLocale::setDefault(default_locale);
2141 // install translation file for Qt built-in dialogs
2142 QString const language_name = QString("qt_") + default_locale.name();
2144 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2145 // Short-named translator can be loaded from a long name, but not the
2146 // opposite. Therefore, long name should be used without truncation.
2147 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2148 if (!d->qt_trans_.load(language_name,
2149 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2150 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2153 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2157 switch (default_locale.language()) {
2158 case QLocale::Arabic :
2159 case QLocale::Hebrew :
2160 case QLocale::Persian :
2161 case QLocale::Urdu :
2162 setLayoutDirection(Qt::RightToLeft);
2165 setLayoutDirection(Qt::LeftToRight);
2170 void GuiApplication::execBatchCommands()
2175 if (!readUIFile(toqstr(lyxrc.ui_file)))
2176 // Gives some error box here.
2180 #if QT_VERSION > 0x040600
2181 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2183 // Create the global default menubar which is shown for the dialogs
2184 // and if no GuiView is visible.
2185 // This must be done after the session was recovered to know the "last files".
2186 d->global_menubar_ = new GlobalMenuBar;
2187 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2190 lyx::execBatchCommands();
2194 QAbstractItemModel * GuiApplication::languageModel()
2196 if (d->language_model_)
2197 return d->language_model_;
2199 QStandardItemModel * lang_model = new QStandardItemModel(this);
2200 lang_model->insertColumns(0, 3);
2202 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2203 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2204 Languages::const_iterator it = lyx::languages.begin();
2205 Languages::const_iterator end = lyx::languages.end();
2206 for (; it != end; ++it) {
2207 current_row = lang_model->rowCount();
2208 lang_model->insertRows(current_row, 1);
2209 QModelIndex pl_item = lang_model->index(current_row, 0);
2210 QModelIndex sp_item = lang_model->index(current_row, 1);
2211 QModelIndex th_item = lang_model->index(current_row, 2);
2212 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2213 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2214 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2215 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2216 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2217 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2218 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2219 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2220 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2221 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2223 d->language_model_ = new QSortFilterProxyModel(this);
2224 d->language_model_->setSourceModel(lang_model);
2225 d->language_model_->setSortLocaleAware(true);
2226 return d->language_model_;
2230 void GuiApplication::restoreGuiSession()
2232 if (!lyxrc.load_session)
2235 Session & session = theSession();
2236 LastOpenedSection::LastOpened const & lastopened =
2237 session.lastOpened().getfiles();
2239 validateCurrentView();
2241 FileName active_file;
2242 // do not add to the lastfile list since these files are restored from
2243 // last session, and should be already there (regular files), or should
2244 // not be added at all (help files).
2245 for (size_t i = 0; i < lastopened.size(); ++i) {
2246 FileName const & file_name = lastopened[i].file_name;
2247 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2248 && current_view_->documentBufferView() != 0)) {
2249 boost::crc_32_type crc;
2250 string const & fname = file_name.absFileName();
2251 crc = for_each(fname.begin(), fname.end(), crc);
2252 createView(crc.checksum());
2254 current_view_->loadDocument(file_name, false);
2256 if (lastopened[i].active)
2257 active_file = file_name;
2260 // Restore last active buffer
2261 Buffer * buffer = theBufferList().getBuffer(active_file);
2262 if (buffer && current_view_)
2263 current_view_->setBuffer(buffer);
2265 // clear this list to save a few bytes of RAM
2266 session.lastOpened().clear();
2270 QString const GuiApplication::romanFontName()
2273 font.setKerning(false);
2274 font.setStyleHint(QFont::Serif);
2275 font.setFamily("serif");
2277 return QFontInfo(font).family();
2281 QString const GuiApplication::sansFontName()
2284 font.setKerning(false);
2285 font.setStyleHint(QFont::SansSerif);
2286 font.setFamily("sans");
2288 return QFontInfo(font).family();
2292 QString const GuiApplication::typewriterFontName()
2295 font.setKerning(false);
2296 font.setStyleHint(QFont::TypeWriter);
2297 font.setFamily("monospace");
2299 return QFontInfo(font).family();
2303 void GuiApplication::handleRegularEvents()
2305 ForkedCallsController::handleCompletedProcesses();
2309 bool GuiApplication::event(QEvent * e)
2312 case QEvent::FileOpen: {
2313 // Open a file; this happens only on Mac OS X for now.
2315 // We do this asynchronously because on startup the batch
2316 // commands are not executed here yet and the gui is not ready
2318 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2319 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2320 processFuncRequestAsync(fr);
2325 return QApplication::event(e);
2330 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2333 return QApplication::notify(receiver, event);
2335 catch (ExceptionMessage const & e) {
2337 case ErrorException:
2339 setQuitOnLastWindowClosed(false);
2341 Alert::error(e.title_, e.details_);
2343 // Properly crash in debug mode in order to get a useful backtrace.
2346 // In release mode, try to exit gracefully.
2349 case BufferException: {
2350 if (!current_view_ || !current_view_->documentBufferView())
2352 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2353 docstring details = e.details_ + '\n';
2354 details += buf->emergencyWrite();
2355 theBufferList().release(buf);
2356 details += "\n" + _("The current document was closed.");
2357 Alert::error(e.title_, details);
2360 case WarningException:
2361 Alert::warning(e.title_, e.details_);
2365 catch (exception const & e) {
2366 docstring s = _("LyX has caught an exception, it will now "
2367 "attempt to save all unsaved documents and exit."
2369 s += from_ascii(e.what());
2370 Alert::error(_("Software exception Detected"), s);
2374 docstring s = _("LyX has caught some really weird exception, it will "
2375 "now attempt to save all unsaved documents and exit.");
2376 Alert::error(_("Software exception Detected"), s);
2384 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2386 QColor const & qcol = d->color_cache_.get(col);
2387 if (!qcol.isValid()) {
2393 rgbcol.r = qcol.red();
2394 rgbcol.g = qcol.green();
2395 rgbcol.b = qcol.blue();
2400 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2402 QColor const qcol(lcolor.getX11Name(col).c_str());
2403 if (!qcol.isValid()) {
2409 rgbcol.r = qcol.red();
2410 rgbcol.g = qcol.green();
2411 rgbcol.b = qcol.blue();
2416 string const GuiApplication::hexName(ColorCode col)
2418 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2422 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2424 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2425 d->socket_notifiers_[fd] = sn;
2426 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2430 void GuiApplication::socketDataReceived(int fd)
2432 d->socket_notifiers_[fd]->func_();
2436 void GuiApplication::unregisterSocketCallback(int fd)
2438 d->socket_notifiers_.take(fd)->setEnabled(false);
2442 void GuiApplication::commitData(QSessionManager & sm)
2444 /// The implementation is required to avoid an application exit
2445 /// when session state save is triggered by session manager.
2446 /// The default implementation sends a close event to all
2447 /// visible top level widgets when session managment allows
2449 /// We are changing that to close all wiew one by one.
2450 /// FIXME: verify if the default implementation is enough now.
2451 #ifdef QT_NO_SESSIONMANAGER
2453 #warning Qt is compiled without session manager
2455 #pragma message("warning: Qt is compiled without session manager")
2459 if (sm.allowsInteraction() && !closeAllViews())
2465 void GuiApplication::unregisterView(GuiView * gv)
2467 LASSERT(d->views_[gv->id()] == gv, /**/);
2468 d->views_.remove(gv->id());
2469 if (current_view_ == gv)
2474 bool GuiApplication::closeAllViews()
2476 if (d->views_.empty())
2479 // When a view/window was closed before without quitting LyX, there
2480 // are already entries in the lastOpened list.
2481 theSession().lastOpened().clear();
2483 QList<GuiView *> const views = d->views_.values();
2484 foreach (GuiView * view, views) {
2485 if (!view->closeScheduled())
2494 GuiView & GuiApplication::view(int id) const
2496 LASSERT(d->views_.contains(id), /**/);
2497 return *d->views_.value(id);
2501 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2503 QList<GuiView *> const views = d->views_.values();
2504 foreach (GuiView * view, views)
2505 view->hideDialog(name, inset);
2509 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2511 Buffer const * buffer_ = 0;
2512 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2513 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2514 if (Buffer const * ptr = (*it)->updateInset(inset))
2521 bool GuiApplication::searchMenu(FuncRequest const & func,
2522 docstring_list & names) const
2524 return d->menus_.searchMenu(func, names);
2528 // Ensure that a file is read only once (prevents include loops)
2529 static QStringList uifiles;
2530 // store which ui files define Toolbars
2531 static QStringList toolbar_uifiles;
2534 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2545 LexerKeyword uitags[] = {
2546 { "format", ui_format },
2547 { "include", ui_include },
2548 { "menuset", ui_menuset },
2549 { "toolbars", ui_toolbars },
2550 { "toolbarset", ui_toolbarset }
2554 lex.setFile(ui_path);
2556 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2560 if (lyxerr.debugging(Debug::PARSER))
2561 lex.printTable(lyxerr);
2564 // format before introduction of format tag
2565 unsigned int format = 0;
2566 while (lex.isOK()) {
2567 int const status = lex.lex();
2569 // we have to do this check here, outside the switch,
2570 // because otherwise we would start reading include files,
2571 // e.g., if the first tag we hit was an include tag.
2572 if (status == ui_format)
2574 format = lex.getInteger();
2578 // this will trigger unless the first tag we hit is a format
2579 // tag, with the right format.
2580 if (format != LFUN_FORMAT)
2581 return FormatMismatch;
2584 case Lexer::LEX_FEOF:
2589 QString const file = toqstr(lex.getString());
2590 bool const success = readUIFile(file, true);
2592 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2599 d->menus_.read(lex);
2603 d->toolbars_.readToolbars(lex);
2607 d->toolbars_.readToolbarSettings(lex);
2608 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2612 if (!rtrim(lex.getString()).empty())
2613 lex.printError("LyX::ReadUIFile: "
2614 "Unknown menu tag: `$$Token'");
2616 LYXERR0("Error with status: " << status);
2622 return (error ? ReadError : ReadOK);
2626 bool GuiApplication::readUIFile(QString const & name, bool include)
2628 LYXERR(Debug::INIT, "About to read " << name << "...");
2632 ui_path = libFileSearch("ui", name, "inc");
2633 if (ui_path.empty())
2634 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2636 ui_path = libFileSearch("ui", name, "ui");
2639 if (ui_path.empty()) {
2640 static const QString defaultUIFile = "default";
2641 LYXERR(Debug::INIT, "Could not find " << name);
2643 Alert::warning(_("Could not find UI definition file"),
2644 bformat(_("Error while reading the included file\n%1$s\n"
2645 "Please check your installation."), qstring_to_ucs4(name)));
2648 if (name == defaultUIFile) {
2649 LYXERR(Debug::INIT, "Could not find default UI file!!");
2650 Alert::warning(_("Could not find default UI file"),
2651 _("LyX could not find the default UI file!\n"
2652 "Please check your installation."));
2655 Alert::warning(_("Could not find UI definition file"),
2656 bformat(_("Error while reading the configuration file\n%1$s\n"
2657 "Falling back to default.\n"
2658 "Please look under Tools>Preferences>User Interface and\n"
2659 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2660 return readUIFile(defaultUIFile, false);
2663 QString const uifile = toqstr(ui_path.absFileName());
2664 if (uifiles.contains(uifile)) {
2666 // We are reading again the top uifile so reset the safeguard:
2669 d->toolbars_.reset();
2671 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2672 << "Is this an include loop?");
2676 uifiles.push_back(uifile);
2678 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2680 ReturnValues retval = readUIFile(ui_path);
2682 if (retval == FormatMismatch) {
2683 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2684 FileName const tempfile = FileName::tempName("convert_ui");
2685 bool const success = prefs2prefs(ui_path, tempfile, true);
2687 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2688 " to format " << LFUN_FORMAT << ".");
2690 retval = readUIFile(tempfile);
2691 tempfile.removeFile();
2695 if (retval != ReadOK) {
2696 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2704 settings.beginGroup("ui_files");
2705 bool touched = false;
2706 for (int i = 0; i != uifiles.size(); ++i) {
2707 QFileInfo fi(uifiles[i]);
2708 QDateTime const date_value = fi.lastModified();
2709 QString const name_key = QString::number(i);
2710 // if an ui file which defines Toolbars has changed,
2711 // we have to reset the settings
2712 if (toolbar_uifiles.contains(uifiles[i])
2713 && (!settings.contains(name_key)
2714 || settings.value(name_key).toString() != uifiles[i]
2715 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2717 settings.setValue(name_key, uifiles[i]);
2718 settings.setValue(name_key + "/date", date_value);
2721 settings.endGroup();
2723 settings.remove("views");
2729 void GuiApplication::onLastWindowClosed()
2731 if (d->global_menubar_)
2732 d->global_menubar_->grabKeyboard();
2736 void GuiApplication::startLongOperation() {
2737 d->key_checker_.start();
2741 bool GuiApplication::longOperationCancelled() {
2742 return d->key_checker_.pressed();
2746 void GuiApplication::stopLongOperation() {
2747 d->key_checker_.stop();
2751 bool GuiApplication::longOperationStarted() {
2752 return d->key_checker_.started();
2756 ////////////////////////////////////////////////////////////////////////
2758 // X11 specific stuff goes here...
2761 bool GuiApplication::x11EventFilter(XEvent * xev)
2766 switch (xev->type) {
2767 case SelectionRequest: {
2768 if (xev->xselectionrequest.selection != XA_PRIMARY)
2770 LYXERR(Debug::SELECTION, "X requested selection.");
2771 BufferView * bv = current_view_->currentBufferView();
2773 docstring const sel = bv->requestSelection();
2775 d->selection_.put(sel);
2779 case SelectionClear: {
2780 if (xev->xselectionclear.selection != XA_PRIMARY)
2782 LYXERR(Debug::SELECTION, "Lost selection.");
2783 BufferView * bv = current_view_->currentBufferView();
2785 bv->clearSelection();
2793 } // namespace frontend
2796 void hideDialogs(std::string const & name, Inset * inset)
2799 frontend::guiApp->hideDialogs(name, inset);
2803 ////////////////////////////////////////////////////////////////////
2807 ////////////////////////////////////////////////////////////////////
2809 frontend::FontLoader & theFontLoader()
2811 LASSERT(frontend::guiApp, /**/);
2812 return frontend::guiApp->fontLoader();
2816 frontend::FontMetrics const & theFontMetrics(Font const & f)
2818 return theFontMetrics(f.fontInfo());
2822 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2824 LASSERT(frontend::guiApp, /**/);
2825 return frontend::guiApp->fontLoader().metrics(f);
2829 ////////////////////////////////////////////////////////////////////
2833 ////////////////////////////////////////////////////////////////////
2835 frontend::Clipboard & theClipboard()
2837 LASSERT(frontend::guiApp, /**/);
2838 return frontend::guiApp->clipboard();
2842 frontend::Selection & theSelection()
2844 LASSERT(frontend::guiApp, /**/);
2845 return frontend::guiApp->selection();
2851 #include "moc_GuiApplication.cpp"