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/PathChanger.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>
100 #include <QPixmapCache>
102 #include <QSessionManager>
104 #include <QShowEvent>
105 #include <QSocketNotifier>
106 #include <QSortFilterProxyModel>
107 #include <QStandardItemModel>
108 #include <QTextCodec>
110 #include <QTranslator>
111 #include <QThreadPool>
115 #include <X11/Xatom.h>
116 #include <X11/Xlib.h>
122 #include <QWindowsMime>
130 #include <QMacPasteboardMime>
133 #include "support/bind.h"
134 #include <boost/crc.hpp>
141 using namespace lyx::support;
144 static void initializeResources()
146 static bool initialized = false;
148 Q_INIT_RESOURCE(Resources);
156 frontend::Application * createApplication(int & argc, char * argv[])
159 // prune -geometry argument(s) by shifting
160 // the following ones 2 places down.
161 for (int i = 0 ; i < argc ; ++i) {
162 if (strcmp(argv[i], "-geometry") == 0) {
163 int const remove = (i+1) < argc ? 2 : 1;
165 for (int j = i; j < argc; ++j)
166 argv[j] = argv[j + remove];
171 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
172 // I'd rather do that in the constructor, but I do not think that
173 // the palette is accessible there.
174 guiApp->colorCache().setPalette(guiApp->palette());
181 /// Return the list of loadable formats.
182 vector<string> loadableImageFormats()
186 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
188 LYXERR(Debug::GRAPHICS,
189 "\nThe image loader can load the following directly:\n");
191 if (qt_formats.empty())
192 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
194 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
196 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
198 string ext = ascii_lowercase((const char *) *it);
209 ////////////////////////////////////////////////////////////////////////
211 // Icon loading support code
213 ////////////////////////////////////////////////////////////////////////
223 bool operator<(PngMap const & lhs, PngMap const & rhs)
225 return lhs.key < rhs.key;
231 CompareKey(QString const & name) : name_(name) {}
232 bool operator()(PngMap const & other) const { return other.key == name_; }
238 // this must be sorted alphabetically
239 // Upper case comes before lower case
240 // Please don't change the formatting, this list is parsed by
241 // development/tools/generate_symbols_images.py.
242 PngMap sorted_png_map[] = {
243 { "Arrownot", "arrownot2"},
244 { "Arrowvert", "arrowvert2"},
245 { "Bowtie", "bowtie2" },
247 { "Bumpeq", "bumpeq2" },
248 { "CIRCLE", "circle3" },
250 { "CheckedBox", "checkedbox2" },
251 { "Circle", "circle2" },
252 { "Colonapprox", "colonapprox2" },
253 { "Coloneq", "coloneq2" },
254 { "Coloneqq", "coloneqq2" },
255 { "Colonsim", "colonsim2" },
257 { "DOWNarrow", "downarrow3" },
258 { "Delta", "delta2" },
259 { "Diamond", "diamond2" },
260 { "Doteq", "doteq2" },
261 { "Downarrow", "downarrow2" },
262 { "Eqcolon", "eqcolon2" },
263 { "Eqqcolon", "eqqcolon2" },
264 { "Gamma", "gamma2" },
266 { "LEFTCIRCLE", "leftcircle3" },
267 { "LEFTarrow", "leftarrow3" },
268 { "LEFTcircle", "leftcircle4" },
270 { "Lambda", "lambda2" },
272 { "Leftarrow", "leftarrow2" },
273 { "Leftcircle", "leftcircle2" },
274 { "Leftrightarrow", "leftrightarrow2" },
275 { "Longarrownot", "longarrownot2"},
276 { "Longleftarrow", "longleftarrow2" },
277 { "Longleftrightarrow", "longleftrightarrow2" },
278 { "Longmapsfrom", "longmapsfrom2"},
279 { "Longmapsto", "longmapsto2"},
280 { "Longrightarrow", "longrightarrow2" },
281 { "Mapsfrom", "mapsfrom2"},
282 { "Mapsfromchar", "mapsfromchar2"},
283 { "Mapsto", "mapsto2"},
284 { "Mapstochar", "mapstochar2"},
285 { "Omega", "omega2" },
290 { "RIGHTCIRCLE", "rightcircle3" },
291 { "RIGHTarrow", "rightarrow3" },
292 { "RIGHTcircle", "rightcircle4" },
294 { "Rightarrow", "rightarrow2" },
295 { "Rightcircle", "rightcircle2" },
296 { "Sigma", "sigma2" },
297 { "Square", "square2" },
298 { "Subset", "subset2" },
299 { "Supset", "supset2" },
300 { "Theta", "theta2" },
301 { "Thorn", "thorn2" },
302 { "UParrow", "uparrow3" },
303 { "Uparrow", "uparrow2" },
304 { "Updownarrow", "updownarrow2" },
305 { "Upsilon", "upsilon2" },
306 { "Vdash", "vdash3" },
311 { "nLeftarrow", "nleftarrow2" },
312 { "nLeftrightarrow", "nleftrightarrow2" },
313 { "nRightarrow", "nrightarrow2" },
314 { "nVDash", "nvdash3" },
315 { "nVdash", "nvdash4" },
316 { "nvDash", "nvdash2" },
317 { "textrm \\AA", "textrm_AA"},
318 { "textrm \\O", "textrm_O"},
319 { "vDash", "vdash2" },
320 { "varDelta", "vardelta2" },
321 { "varGamma", "vargamma2" },
322 { "varLambda", "varlambda2" },
323 { "varOmega", "varomega2" },
324 { "varPhi", "varphi2" },
325 { "varPi", "varpi2" },
326 { "varPsi", "varpsi2" },
327 { "varSigma", "varsigma2" },
328 { "varTheta", "vartheta2" },
329 { "varUpsilon", "varupsilon2" },
330 { "varXi", "varxi2" }
334 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
337 QString findPng(QString const & name)
339 PngMap const * const begin = sorted_png_map;
340 PngMap const * const end = begin + nr_sorted_png_map;
341 LASSERT(sorted(begin, end), /**/);
343 PngMap const * const it = find_if(begin, end, CompareKey(name));
347 png_name = it->value;
350 png_name.replace('_', "underscore");
351 png_name.replace(' ', '_');
353 // This way we can have "math-delim { }" on the toolbar.
354 png_name.replace('(', "lparen");
355 png_name.replace(')', "rparen");
356 png_name.replace('[', "lbracket");
357 png_name.replace(']', "rbracket");
358 png_name.replace('{', "lbrace");
359 png_name.replace('}', "rbrace");
360 png_name.replace('|', "bars");
361 png_name.replace(',', "thinspace");
362 png_name.replace(':', "mediumspace");
363 png_name.replace(';', "thickspace");
364 png_name.replace('!', "negthinspace");
367 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
368 << "Looking for math PNG called \"" << png_name << '"');
375 QString iconName(FuncRequest const & f, bool unknown)
377 initializeResources();
381 switch (f.action()) {
382 case LFUN_MATH_INSERT:
383 if (!f.argument().empty()) {
385 name1 = findPng(toqstr(f.argument()).mid(1));
388 case LFUN_MATH_DELIM:
389 case LFUN_MATH_BIGDELIM:
391 name1 = findPng(toqstr(f.argument()));
395 name1 = toqstr(f.argument());
397 case LFUN_COMMAND_ALTERNATIVES: {
398 // use the first of the alternative commands
400 docstring dummy = split(f.argument(), firstcom, ';');
401 name1 = toqstr(firstcom);
402 // FIXME: we should rename the icons to tabular-xxx instead of
403 // "tabular-feature-xxx"
404 name1.replace("inset-modify tabular", "tabular-feature");
405 name1.replace(' ', '_');
408 case LFUN_INSET_MODIFY: {
409 // FIXME: we should rename the icons to tabular-xxx instead of
410 // "tabular-feature-xxx" and generalize this naming to all
411 // insets, not to tabular using ones.
413 string const command = split(to_utf8(f.argument()), inset_name, ' ');
414 if (insetCode(inset_name) == TABULAR_CODE) {
415 name1 = "tabular-feature "+ toqstr(command);
416 name1.replace(' ', '_');
421 name2 = toqstr(lyxaction.getActionName(f.action()));
424 if (!f.argument().empty()) {
425 name1 = name2 + ' ' + toqstr(f.argument());
426 name1.replace(' ', '_');
427 name1.replace('\\', "backslash");
431 QStringList imagedirs;
432 imagedirs << "images/" << "images/ipa/";
433 for (int i = 0; i < imagedirs.size(); ++i) {
434 QString imagedir = imagedirs.at(i) + path;
435 FileName fname = imageLibFileSearch(imagedir, name1, "png");
437 return toqstr(fname.absFileName());
439 fname = imageLibFileSearch(imagedir, name2, "png");
441 return toqstr(fname.absFileName());
444 path = ":/images/" + path;
447 LYXERR0("Directory " << path << " not found in resource!");
451 if (res.exists(name1))
455 if (res.exists(name2))
458 LYXERR(Debug::GUI, "Cannot find icon with filename "
459 << "\"" << name1 << "\""
461 << "\"" << name2 << "\""
463 << lyxaction.getActionName(f.action())
464 << '(' << to_utf8(f.argument()) << ")\"");
467 QString imagedir = "images/";
468 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
470 return toqstr(fname.absFileName());
471 return QString(":/images/unknown.png");
477 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
480 QString imagedir = path;
481 FileName fname = imageLibFileSearch(imagedir, name, ext);
482 QString path1 = toqstr(fname.absFileName());
483 QString path2 = ":/" + path + name + "." + ext;
485 if (pixmap.load(path1)) {
488 else if (pixmap.load(path2)) {
492 LYXERR0("Cannot load pixmap \""
493 << path << name << '.' << ext
494 << "\", please verify resource system!");
499 QIcon getIcon(FuncRequest const & f, bool unknown)
501 QString icon = iconName(f, unknown);
505 //LYXERR(Debug::GUI, "Found icon: " << icon);
507 if (!pm.load(icon)) {
508 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
516 ////////////////////////////////////////////////////////////////////////
518 // LyX server support code.
520 ////////////////////////////////////////////////////////////////////////
522 class SocketNotifier : public QSocketNotifier
525 /// connect a connection notification from the LyXServerSocket
526 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
527 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
531 /// The callback function
532 Application::SocketCallback func_;
536 ////////////////////////////////////////////////////////////////////////
538 // Mac specific stuff goes here...
540 ////////////////////////////////////////////////////////////////////////
542 class MenuTranslator : public QTranslator
545 MenuTranslator(QObject * parent)
546 : QTranslator(parent)
549 QString translate(const char * /*context*/,
550 const char * sourceText,
551 const char * /*comment*/ = 0) const
553 string const s = sourceText;
554 if (s == N_("About %1") || s == N_("Preferences")
555 || s == N_("Reconfigure") || s == N_("Quit %1"))
562 class GlobalMenuBar : public QMenuBar
566 GlobalMenuBar() : QMenuBar(0) {}
569 bool event(QEvent * e)
571 if (e->type() == QEvent::ShortcutOverride) {
572 // && activeWindow() == 0) {
573 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
575 setKeySymbol(&sym, ke);
576 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
585 // QMacPasteboardMimeGraphics can only be compiled on Mac.
587 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
590 QMacPasteboardMimeGraphics()
591 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
594 QString convertorName() { return "Graphics"; }
596 QString flavorFor(QString const & mime)
598 LYXERR(Debug::ACTION, "flavorFor " << mime);
599 if (mime == pdfMimeType())
600 return QLatin1String("com.adobe.pdf");
604 QString mimeFor(QString flav)
606 LYXERR(Debug::ACTION, "mimeFor " << flav);
607 if (flav == QLatin1String("com.adobe.pdf"))
608 return pdfMimeType();
612 bool canConvert(QString const & mime, QString flav)
614 return mimeFor(flav) == mime;
617 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
621 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
625 QList<QByteArray> convertFromMime(QString const & /*mime*/,
626 QVariant data, QString /*flav*/)
628 QList<QByteArray> ret;
629 ret.append(data.toByteArray());
635 ///////////////////////////////////////////////////////////////
637 // You can find more platform specific stuff at the end of this file...
639 ///////////////////////////////////////////////////////////////
641 ////////////////////////////////////////////////////////////////////////
642 // Windows specific stuff goes here...
645 // QWindowsMimeMetafile can only be compiled on Windows.
647 static FORMATETC cfFromMime(QString const & mimetype)
650 if (mimetype == emfMimeType()) {
651 formatetc.cfFormat = CF_ENHMETAFILE;
652 formatetc.tymed = TYMED_ENHMF;
653 } else if (mimetype == wmfMimeType()) {
654 formatetc.cfFormat = CF_METAFILEPICT;
655 formatetc.tymed = TYMED_MFPICT;
658 formatetc.dwAspect = DVASPECT_CONTENT;
659 formatetc.lindex = -1;
664 class QWindowsMimeMetafile : public QWindowsMime {
666 QWindowsMimeMetafile() {}
668 bool canConvertFromMime(FORMATETC const & formatetc,
669 QMimeData const * mimedata) const
674 bool canConvertToMime(QString const & mimetype,
675 IDataObject * pDataObj) const
677 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
679 FORMATETC formatetc = cfFromMime(mimetype);
680 return pDataObj->QueryGetData(&formatetc) == S_OK;
683 bool convertFromMime(FORMATETC const & formatetc,
684 const QMimeData * mimedata, STGMEDIUM * pmedium) const
689 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
690 QVariant::Type preferredType) const
693 if (!canConvertToMime(mimetype, pDataObj))
696 FORMATETC formatetc = cfFromMime(mimetype);
698 if (pDataObj->GetData(&formatetc, &s) != S_OK)
702 if (s.tymed == TYMED_ENHMF) {
703 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
704 data.resize(dataSize);
705 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
706 (LPBYTE)data.data());
707 } else if (s.tymed == TYMED_MFPICT) {
708 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
709 data.resize(dataSize);
710 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
711 (LPBYTE)data.data());
714 ReleaseStgMedium(&s);
720 QVector<FORMATETC> formatsForMime(QString const & mimetype,
721 QMimeData const * mimedata) const
723 QVector<FORMATETC> formats;
724 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
725 formats += cfFromMime(mimetype);
729 QString mimeForFormat(FORMATETC const & formatetc) const
731 switch (formatetc.cfFormat) {
733 return emfMimeType();
734 case CF_METAFILEPICT:
735 return wmfMimeType();
744 /// Allows to check whether ESC was pressed during a long operation
745 class KeyChecker : public QObject {
750 KeyChecker() : pressed_(false), started_(false) {}
753 QCoreApplication::instance()->installEventFilter(this);
758 QCoreApplication::instance()->removeEventFilter(this);
762 QCoreApplication::processEvents();
765 bool started() const {
768 bool eventFilter(QObject *obj, QEvent *event) {
769 LYXERR(Debug::ACTION, "Event Type: " << event->type());
770 switch (event->type()) {
774 return QObject::eventFilter(obj, event);
776 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
777 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
785 ////////////////////////////////////////////////////////////////////////
786 // GuiApplication::Private definition and implementation.
787 ////////////////////////////////////////////////////////////////////////
789 struct GuiApplication::Private
791 Private(): language_model_(0), meta_fake_bit(NoModifier),
795 /// WMF Mime handler for Windows clipboard.
796 wmf_mime_ = new QWindowsMimeMetafile;
798 initKeySequences(&theTopLevelKeymap());
801 void initKeySequences(KeyMap * kb)
803 keyseq = KeySequence(kb, kb);
804 cancel_meta_seq = KeySequence(kb, kb);
808 QSortFilterProxyModel * language_model_;
810 GuiClipboard clipboard_;
812 GuiSelection selection_;
814 FontLoader font_loader_;
816 ColorCache color_cache_;
818 QTranslator qt_trans_;
820 QHash<int, SocketNotifier *> socket_notifiers_;
824 /// The global instance
827 /// this timer is used for any regular events one wants to
828 /// perform. at present it is used to check if forked processes
830 QTimer general_timer_;
832 /// delayed FuncRequests
833 std::queue<FuncRequest> func_request_queue_;
838 KeySequence cancel_meta_seq;
840 KeyModifier meta_fake_bit;
842 /// Multiple views container.
844 * Warning: This must not be a smart pointer as the destruction of the
845 * object is handled by Qt when the view is closed
846 * \sa Qt::WA_DeleteOnClose attribute.
848 QHash<int, GuiView *> views_;
850 /// Only used on mac.
851 GlobalMenuBar * global_menubar_;
854 /// Linkback mime handler for MacOSX.
855 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
859 /// WMF Mime handler for Windows clipboard.
860 QWindowsMimeMetafile * wmf_mime_;
863 /// Allows to check whether ESC was pressed during a long operation
864 KeyChecker key_checker_;
868 GuiApplication * guiApp;
870 GuiApplication::~GuiApplication()
873 closeAllLinkBackLinks();
879 GuiApplication::GuiApplication(int & argc, char ** argv)
880 : QApplication(argc, argv), current_view_(0),
881 d(new GuiApplication::Private)
883 QString app_name = "LyX";
884 QCoreApplication::setOrganizationName(app_name);
885 QCoreApplication::setOrganizationDomain("lyx.org");
886 QCoreApplication::setApplicationName(lyx_package);
888 // Install translator for GUI elements.
889 installTranslator(&d->qt_trans_);
891 // FIXME: quitOnLastWindowClosed is true by default. We should have a
892 // lyxrc setting for this in order to let the application stay resident.
893 // But then we need some kind of dock icon, at least on Windows.
895 if (lyxrc.quit_on_last_window_closed)
896 setQuitOnLastWindowClosed(false);
899 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
900 // seems to be the default case for applications like LyX.
901 setQuitOnLastWindowClosed(false);
902 // This allows to translate the strings that appear in the LyX menu.
903 /// A translator suitable for the entries in the LyX menu.
904 /// Only needed with Qt/Mac.
905 installTranslator(new MenuTranslator(this));
911 // doubleClickInterval() is 400 ms on X11 which is just too long.
912 // On Windows and Mac OS X, the operating system's value is used.
913 // On Microsoft Windows, calling this function sets the double
914 // click interval for all applications. So we don't!
915 QApplication::setDoubleClickInterval(300);
918 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
920 // needs to be done before reading lyxrc
922 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
926 // Set the cache to 5120 kilobytes which corresponds to screen size of
927 // 1280 by 1024 pixels with a color depth of 32 bits.
928 QPixmapCache::setCacheLimit(5120);
930 // Initialize RC Fonts
931 if (lyxrc.roman_font_name.empty())
932 lyxrc.roman_font_name = fromqstr(romanFontName());
934 if (lyxrc.sans_font_name.empty())
935 lyxrc.sans_font_name = fromqstr(sansFontName());
937 if (lyxrc.typewriter_font_name.empty())
938 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
940 d->general_timer_.setInterval(500);
941 connect(&d->general_timer_, SIGNAL(timeout()),
942 this, SLOT(handleRegularEvents()));
943 d->general_timer_.start();
945 // maxThreadCount() defaults in general to 2 on single or dual-processor.
946 // This is clearly not enough in a time where we use threads for
947 // document preview and/or export. 20 should be OK.
948 QThreadPool::globalInstance()->setMaxThreadCount(20);
952 GuiApplication * theGuiApp()
954 return dynamic_cast<GuiApplication *>(theApp());
958 void GuiApplication::clearSession()
965 docstring Application::iconName(FuncRequest const & f, bool unknown)
967 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
971 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
976 BufferView * doc_bv = 0;
978 if (cmd.action() == LFUN_NOACTION) {
979 status.message(from_utf8(N_("Nothing to do")));
980 status.setEnabled(false);
983 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
984 status.setUnknown(true);
985 status.message(from_utf8(N_("Unknown action")));
986 status.setEnabled(false);
989 // Does the GuiApplication know something?
990 else if (getStatus(cmd, status)) { }
992 // If we do not have a GuiView, then other functions are disabled
993 else if (!current_view_)
994 status.setEnabled(false);
996 // Does the GuiView know something?
997 else if (current_view_->getStatus(cmd, status)) { }
999 // In LyX/Mac, when a dialog is open, the menus of the
1000 // application can still be accessed without giving focus to
1001 // the main window. In this case, we want to disable the menu
1002 // entries that are buffer or view-related.
1003 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1005 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1006 status.setEnabled(false);
1009 // If we do not have a BufferView, then other functions are disabled
1010 else if (!(bv = current_view_->currentBufferView()))
1011 status.setEnabled(false);
1013 // Does the current BufferView know something?
1014 else if (bv->getStatus(cmd, status)) { }
1016 // Does the current Buffer know something?
1017 else if (bv->buffer().getStatus(cmd, status)) { }
1019 // If we do not have a document BufferView, different from the
1020 // current BufferView, then other functions are disabled
1021 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1022 status.setEnabled(false);
1024 // Does the document Buffer know something?
1025 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1028 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1029 status.message(from_utf8(N_("Command not handled")));
1030 status.setEnabled(false);
1033 // the default error message if we disable the command
1034 if (!status.enabled() && status.message().empty())
1035 status.message(from_utf8(N_("Command disabled")));
1041 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1043 // I would really like to avoid having this switch and rather try to
1044 // encode this in the function itself.
1045 // -- And I'd rather let an inset decide which LFUNs it is willing
1046 // to handle (Andre')
1048 switch (cmd.action()) {
1050 // This could be used for the no-GUI version. The GUI version is handled in
1051 // GuiView::getStatus(). See above.
1053 case LFUN_BUFFER_WRITE:
1054 case LFUN_BUFFER_WRITE_AS: {
1055 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1056 enable = b && (b->isUnnamed() || !b->isClean());
1061 case LFUN_BOOKMARK_GOTO: {
1062 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1063 enable = theSession().bookmarks().isValid(num);
1067 case LFUN_BOOKMARK_CLEAR:
1068 enable = theSession().bookmarks().hasValid();
1071 // this one is difficult to get right. As a half-baked
1072 // solution, we consider only the first action of the sequence
1073 case LFUN_COMMAND_SEQUENCE: {
1074 // argument contains ';'-terminated commands
1075 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1076 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1077 func.setOrigin(cmd.origin());
1078 flag = getStatus(func);
1082 // we want to check if at least one of these is enabled
1083 case LFUN_COMMAND_ALTERNATIVES: {
1084 // argument contains ';'-terminated commands
1085 string arg = to_utf8(cmd.argument());
1086 while (!arg.empty()) {
1088 arg = split(arg, first, ';');
1089 FuncRequest func(lyxaction.lookupFunc(first));
1090 func.setOrigin(cmd.origin());
1091 flag = getStatus(func);
1092 // if this one is enabled, the whole thing is
1101 string name = to_utf8(cmd.argument());
1102 if (theTopLevelCmdDef().lock(name, func)) {
1103 func.setOrigin(cmd.origin());
1104 flag = getStatus(func);
1105 theTopLevelCmdDef().release(name);
1107 // catch recursion or unknown command
1108 // definition. all operations until the
1109 // recursion or unknown command definition
1110 // occurs are performed, so set the state to
1117 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1119 case LFUN_PREFERENCES_SAVE:
1120 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1121 case LFUN_DEBUG_LEVEL_SET:
1122 // these are handled in our dispatch()
1125 case LFUN_WINDOW_CLOSE:
1126 enable = d->views_.size() > 0;
1129 case LFUN_BUFFER_NEW:
1130 case LFUN_BUFFER_NEW_TEMPLATE:
1131 case LFUN_FILE_OPEN:
1132 case LFUN_HELP_OPEN:
1133 case LFUN_SCREEN_FONT_UPDATE:
1134 case LFUN_SET_COLOR:
1135 case LFUN_WINDOW_NEW:
1137 case LFUN_LYXRC_APPLY:
1138 case LFUN_COMMAND_PREFIX:
1140 case LFUN_META_PREFIX:
1141 case LFUN_RECONFIGURE:
1142 case LFUN_SERVER_GET_FILENAME:
1143 case LFUN_SERVER_NOTIFY:
1147 case LFUN_BUFFER_FORALL: {
1148 if (theBufferList().empty()) {
1149 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1150 flag.setEnabled(false);
1154 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1155 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1156 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1157 flag.setEnabled(false);
1168 flag.setEnabled(false);
1172 /// make a post-dispatch status message
1173 static docstring makeDispatchMessage(docstring const & msg,
1174 FuncRequest const & cmd)
1176 const bool verbose = (cmd.origin() == FuncRequest::MENU
1177 || cmd.origin() == FuncRequest::TOOLBAR
1178 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1180 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1181 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1185 docstring dispatch_msg = msg;
1186 if (!dispatch_msg.empty())
1187 dispatch_msg += ' ';
1189 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1191 bool argsadded = false;
1193 if (!cmd.argument().empty()) {
1194 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1195 comname += ' ' + cmd.argument();
1199 docstring const shortcuts = theTopLevelKeymap().
1200 printBindings(cmd, KeySequence::ForGui);
1202 if (!shortcuts.empty())
1203 comname += ": " + shortcuts;
1204 else if (!argsadded && !cmd.argument().empty())
1205 comname += ' ' + cmd.argument();
1207 if (!comname.empty()) {
1208 comname = rtrim(comname);
1209 dispatch_msg += '(' + rtrim(comname) + ')';
1211 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1212 return dispatch_msg;
1216 void GuiApplication::dispatch(FuncRequest const & cmd)
1218 Buffer * buffer = 0;
1219 if (current_view_ && current_view_->currentBufferView()) {
1220 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1221 buffer = ¤t_view_->currentBufferView()->buffer();
1223 buffer->undo().beginUndoGroup();
1227 // redraw the screen at the end (first of the two drawing steps).
1228 // This is done unless explicitly requested otherwise
1229 dr.screenUpdate(Update::FitCursor);
1231 updateCurrentView(cmd, dr);
1233 // the buffer may have been closed by one action
1234 if (theBufferList().isLoaded(buffer))
1235 buffer->undo().endUndoGroup();
1239 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1244 BufferView * bv = current_view_->currentBufferView();
1246 if (dr.needBufferUpdate()) {
1247 bv->cursor().clearBufferUpdate();
1248 bv->buffer().updateBuffer();
1250 // BufferView::update() updates the ViewMetricsInfo and
1251 // also initializes the position cache for all insets in
1252 // (at least partially) visible top-level paragraphs.
1253 // We will redraw the screen only if needed.
1254 bv->processUpdateFlags(dr.screenUpdate());
1256 // Do we have a selection?
1257 theSelection().haveSelection(bv->cursor().selection());
1260 current_view_->restartCursor();
1262 if (dr.needMessageUpdate()) {
1263 // Some messages may already be translated, so we cannot use _()
1264 current_view_->message(makeDispatchMessage(
1265 translateIfPossible(dr.message()), cmd));
1270 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1271 bool switchToBuffer)
1273 if (!theSession().bookmarks().isValid(idx))
1275 BookmarksSection::Bookmark const & bm =
1276 theSession().bookmarks().bookmark(idx);
1277 LASSERT(!bm.filename.empty(), /**/);
1278 string const file = bm.filename.absFileName();
1279 // if the file is not opened, open it.
1280 if (!theBufferList().exists(bm.filename)) {
1282 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1286 // open may fail, so we need to test it again
1287 if (!theBufferList().exists(bm.filename))
1290 // bm can be changed when saving
1291 BookmarksSection::Bookmark tmp = bm;
1293 // Special case idx == 0 used for back-from-back jump navigation
1295 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1297 // if the current buffer is not that one, switch to it.
1298 BufferView * doc_bv = current_view_ ?
1299 current_view_->documentBufferView() : 0;
1300 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1301 if (switchToBuffer) {
1302 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1305 doc_bv = current_view_->documentBufferView();
1310 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1311 if (!doc_bv->moveToPosition(
1312 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1319 // Cursor jump succeeded!
1320 Cursor const & cur = doc_bv->cursor();
1321 pit_type new_pit = cur.pit();
1322 pos_type new_pos = cur.pos();
1323 int new_id = cur.paragraph().id();
1325 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1326 // see http://www.lyx.org/trac/ticket/3092
1327 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1328 || bm.top_id != new_id) {
1329 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1330 new_pit, new_pos, new_id);
1334 // This function runs "configure" and then rereads lyx.defaults to
1335 // reconfigure the automatic settings.
1336 void GuiApplication::reconfigure(string const & option)
1338 // emit message signal.
1340 current_view_->message(_("Running configure..."));
1342 // Run configure in user lyx directory
1343 PathChanger p(package().user_support());
1344 string configure_command = package().configure_command();
1345 configure_command += option;
1347 int const ret = one.startscript(Systemcall::Wait, configure_command);
1349 // emit message signal.
1351 current_view_->message(_("Reloading configuration..."));
1352 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1353 // Re-read packages.lst
1354 LaTeXPackages::getAvailable();
1357 Alert::information(_("System reconfiguration failed"),
1358 _("The system reconfiguration has failed.\n"
1359 "Default textclass is used but LyX may\n"
1360 "not be able to work properly.\n"
1361 "Please reconfigure again if needed."));
1363 Alert::information(_("System reconfigured"),
1364 _("The system has been reconfigured.\n"
1365 "You need to restart LyX to make use of any\n"
1366 "updated document class specifications."));
1369 void GuiApplication::validateCurrentView()
1371 if (!d->views_.empty() && !current_view_) {
1372 // currently at least one view exists but no view has the focus.
1373 // choose the last view to make it current.
1374 // a view without any open document is preferred.
1375 GuiView * candidate = 0;
1376 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1377 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1378 for (; it != end; ++it) {
1380 if (!candidate->documentBufferView())
1383 setCurrentView(candidate);
1387 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1389 string const argument = to_utf8(cmd.argument());
1390 FuncCode const action = cmd.action();
1392 LYXERR(Debug::ACTION, "cmd: " << cmd);
1394 // we have not done anything wrong yet.
1397 FuncStatus const flag = getStatus(cmd);
1398 if (!flag.enabled()) {
1399 // We cannot use this function here
1400 LYXERR(Debug::ACTION, "action "
1401 << lyxaction.getActionName(action)
1402 << " [" << action << "] is disabled at this location");
1403 dr.setMessage(flag.message());
1405 dr.dispatched(false);
1406 dr.screenUpdate(Update::None);
1407 dr.clearBufferUpdate();
1411 if (cmd.origin() == FuncRequest::LYXSERVER) {
1412 if (current_view_ && current_view_->currentBufferView())
1413 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1414 // we will also need to redraw the screen at the end
1415 dr.screenUpdate(Update::FitCursor);
1418 // Assumes that the action will be dispatched.
1419 dr.dispatched(true);
1421 switch (cmd.action()) {
1423 case LFUN_WINDOW_NEW:
1424 createView(toqstr(cmd.argument()));
1427 case LFUN_WINDOW_CLOSE:
1428 // update bookmark pit of the current buffer before window close
1429 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1430 gotoBookmark(i+1, false, false);
1431 // clear the last opened list, because
1432 // maybe this will end the session
1433 theSession().lastOpened().clear();
1434 // check for valid current_view_
1435 validateCurrentView();
1437 current_view_->closeScheduled();
1441 // quitting is triggered by the gui code
1442 // (leaving the event loop).
1444 current_view_->message(from_utf8(N_("Exiting.")));
1445 if (closeAllViews())
1449 case LFUN_SCREEN_FONT_UPDATE: {
1450 // handle the screen font changes.
1451 d->font_loader_.update();
1452 // Backup current_view_
1453 GuiView * view = current_view_;
1454 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1455 // to skip the refresh.
1457 theBufferList().changed(false);
1458 // Restore current_view_
1459 current_view_ = view;
1463 case LFUN_BUFFER_NEW:
1464 validateCurrentView();
1465 if (d->views_.empty()
1466 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1467 createView(QString(), false); // keep hidden
1468 current_view_->newDocument(to_utf8(cmd.argument()), false);
1469 current_view_->show();
1470 setActiveWindow(current_view_);
1472 current_view_->newDocument(to_utf8(cmd.argument()), false);
1476 case LFUN_BUFFER_NEW_TEMPLATE:
1477 validateCurrentView();
1478 if (d->views_.empty()
1479 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1481 current_view_->newDocument(to_utf8(cmd.argument()), true);
1482 if (!current_view_->documentBufferView())
1483 current_view_->close();
1485 current_view_->newDocument(to_utf8(cmd.argument()), true);
1489 case LFUN_FILE_OPEN: {
1490 validateCurrentView();
1491 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1492 string const fname = to_utf8(cmd.argument());
1493 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
1494 && current_view_->documentBufferView() != 0)) {
1495 // We want the ui session to be saved per document and not per
1496 // window number. The filename crc is a good enough identifier.
1497 boost::crc_32_type crc;
1498 crc = for_each(fname.begin(), fname.end(), crc);
1499 createView(crc.checksum());
1500 current_view_->openDocument(fname);
1501 if (current_view_ && !current_view_->documentBufferView())
1502 current_view_->close();
1504 current_view_->openDocument(fname);
1508 case LFUN_HELP_OPEN: {
1509 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1510 if (current_view_ == 0)
1512 string const arg = to_utf8(cmd.argument());
1514 current_view_->message(_("Missing argument"));
1517 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1519 fname = i18nLibFileSearch("examples", arg, "lyx");
1521 if (fname.empty()) {
1522 lyxerr << "LyX: unable to find documentation file `"
1523 << arg << "'. Bad installation?" << endl;
1526 current_view_->message(bformat(_("Opening help file %1$s..."),
1527 makeDisplayPath(fname.absFileName())));
1528 Buffer * buf = current_view_->loadDocument(fname, false);
1530 #ifndef DEVEL_VERSION
1532 buf->setReadonly(true);
1539 case LFUN_SET_COLOR: {
1541 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1542 if (lyx_name.empty() || x11_name.empty()) {
1544 current_view_->message(
1545 _("Syntax: set-color <lyx_name> <x11_name>"));
1550 // FIXME: The graphics cache no longer has a changeDisplay method.
1551 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1552 bool const graphicsbg_changed =
1553 lyx_name == graphicsbg && x11_name != graphicsbg;
1554 if (graphicsbg_changed)
1555 graphics::GCache::get().changeDisplay(true);
1558 if (!lcolor.setColor(lyx_name, x11_name)) {
1560 current_view_->message(
1561 bformat(_("Set-color \"%1$s\" failed "
1562 "- color is undefined or "
1563 "may not be redefined"),
1564 from_utf8(lyx_name)));
1567 // Make sure we don't keep old colors in cache.
1568 d->color_cache_.clear();
1572 case LFUN_LYXRC_APPLY: {
1573 // reset active key sequences, since the bindings
1574 // are updated (bug 6064)
1576 LyXRC const lyxrc_orig = lyxrc;
1578 istringstream ss(to_utf8(cmd.argument()));
1579 bool const success = lyxrc.read(ss);
1582 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1583 << "Unable to read lyxrc data"
1588 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1594 case LFUN_COMMAND_PREFIX:
1595 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1600 d->meta_fake_bit = NoModifier;
1601 GuiView * gv = currentView();
1602 if (gv && gv->currentBufferView())
1603 // cancel any selection
1604 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1605 dr.setMessage(from_ascii(N_("Cancel")));
1608 case LFUN_META_PREFIX:
1609 d->meta_fake_bit = AltModifier;
1610 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1613 // --- Menus -----------------------------------------------
1614 case LFUN_RECONFIGURE:
1615 // argument is any additional parameter to the configure.py command
1616 reconfigure(to_utf8(cmd.argument()));
1619 // --- lyxserver commands ----------------------------
1620 case LFUN_SERVER_GET_FILENAME: {
1621 if (current_view_ && current_view_->documentBufferView()) {
1622 docstring const fname = from_utf8(
1623 current_view_->documentBufferView()->buffer().absFileName());
1624 dr.setMessage(fname);
1625 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1627 dr.setMessage(docstring());
1628 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1633 case LFUN_SERVER_NOTIFY: {
1634 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1635 dr.setMessage(dispatch_buffer);
1636 theServer().notifyClient(to_utf8(dispatch_buffer));
1640 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1641 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1647 string rest = split(argument, countstr, ' ');
1648 istringstream is(countstr);
1651 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1652 for (int i = 0; i < count; ++i)
1653 dispatch(lyxaction.lookupFunc(rest));
1657 case LFUN_COMMAND_SEQUENCE: {
1658 // argument contains ';'-terminated commands
1659 string arg = argument;
1660 // FIXME: this LFUN should also work without any view.
1661 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1662 ? &(current_view_->documentBufferView()->buffer()) : 0;
1664 buffer->undo().beginUndoGroup();
1665 while (!arg.empty()) {
1667 arg = split(arg, first, ';');
1668 FuncRequest func(lyxaction.lookupFunc(first));
1669 func.setOrigin(cmd.origin());
1672 // the buffer may have been closed by one action
1673 if (theBufferList().isLoaded(buffer))
1674 buffer->undo().endUndoGroup();
1678 case LFUN_BUFFER_FORALL: {
1679 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1681 map<Buffer *, GuiView *> views_lVisible;
1682 map<GuiView *, Buffer *> activeBuffers;
1684 QList<GuiView *> allViews = d->views_.values();
1686 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1687 // and on which buffer is active in each view.
1688 Buffer * const last = theBufferList().last();
1689 foreach (GuiView * view, allViews) {
1690 // all of the buffers might be locally hidden. That is, there is no active buffer.
1691 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1692 activeBuffers[view] = 0;
1694 activeBuffers[view] = &view->currentBufferView()->buffer();
1696 // find out if each is locally visible or locally hidden.
1697 // we don't use a for loop as the buffer list cycles.
1698 Buffer * b = theBufferList().first();
1700 bool const locallyVisible = view && view->workArea(*b);
1701 if (locallyVisible) {
1702 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1703 // only need to overwrite/add if we don't already know a buffer is globally
1704 // visible or we do know but we would prefer to dispatch LFUN from the
1705 // current view because of cursor position issues.
1706 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1707 views_lVisible[b] = view;
1711 b = theBufferList().next(b);
1715 GuiView * const homeView = currentView();
1716 Buffer * b = theBufferList().first();
1717 Buffer * nextBuf = 0;
1718 int numProcessed = 0;
1721 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1723 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1725 // first change to a view where b is locally visible, preferably current_view_.
1726 GuiView * const vLv = views_lVisible[b];
1728 lyx::dispatch(funcToRun);
1736 // put things back to how they were (if possible).
1737 foreach (GuiView * view, allViews) {
1738 Buffer * originalBuf = activeBuffers[view];
1739 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1740 if (theBufferList().isLoaded(originalBuf))
1741 view->setBuffer(originalBuf);
1743 homeView->setFocus();
1745 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1749 case LFUN_COMMAND_ALTERNATIVES: {
1750 // argument contains ';'-terminated commands
1751 string arg = argument;
1752 while (!arg.empty()) {
1754 arg = split(arg, first, ';');
1755 FuncRequest func(lyxaction.lookupFunc(first));
1756 func.setOrigin(cmd.origin());
1757 FuncStatus const stat = getStatus(func);
1758 if (stat.enabled()) {
1768 if (theTopLevelCmdDef().lock(argument, func)) {
1769 func.setOrigin(cmd.origin());
1771 theTopLevelCmdDef().release(argument);
1773 if (func.action() == LFUN_UNKNOWN_ACTION) {
1774 // unknown command definition
1775 lyxerr << "Warning: unknown command definition `"
1779 // recursion detected
1780 lyxerr << "Warning: Recursion in the command definition `"
1781 << argument << "' detected"
1788 case LFUN_PREFERENCES_SAVE:
1789 lyxrc.write(support::makeAbsPath("preferences",
1790 package().user_support().absFileName()), false);
1793 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1794 string const fname = addName(addPath(package().user_support().absFileName(),
1795 "templates/"), "defaults.lyx");
1796 Buffer defaults(fname);
1798 istringstream ss(argument);
1801 int const unknown_tokens = defaults.readHeader(lex);
1803 if (unknown_tokens != 0) {
1804 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1805 << unknown_tokens << " unknown token"
1806 << (unknown_tokens == 1 ? "" : "s")
1810 if (defaults.writeFile(FileName(defaults.absFileName())))
1811 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1812 makeDisplayPath(fname)));
1815 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1820 case LFUN_BOOKMARK_GOTO:
1821 // go to bookmark, open unopened file and switch to buffer if necessary
1822 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1823 dr.screenUpdate(Update::Force | Update::FitCursor);
1826 case LFUN_BOOKMARK_CLEAR:
1827 theSession().bookmarks().clear();
1830 case LFUN_DEBUG_LEVEL_SET:
1831 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1835 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1838 current_view_->dispatch(cmd, dr);
1842 if (cmd.origin() == FuncRequest::LYXSERVER)
1843 updateCurrentView(cmd, dr);
1847 docstring GuiApplication::viewStatusMessage()
1849 // When meta-fake key is pressed, show the key sequence so far + "M-".
1850 if (d->meta_fake_bit != NoModifier)
1851 return d->keyseq.print(KeySequence::ForGui) + "M-";
1853 // Else, when a non-complete key sequence is pressed,
1854 // show the available options.
1855 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1856 return d->keyseq.printOptions(true);
1862 void GuiApplication::handleKeyFunc(FuncCode action)
1866 if (d->keyseq.length())
1868 GuiView * gv = currentView();
1869 LASSERT(gv && gv->currentBufferView(), return);
1870 BufferView * bv = gv->currentBufferView();
1871 bv->getIntl().getTransManager().deadkey(
1872 c, get_accent(action).accent, bv->cursor().innerText(),
1874 // Need to clear, in case the minibuffer calls these
1877 // copied verbatim from do_accent_char
1878 bv->cursor().resetAnchor();
1882 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
1884 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
1886 // Do nothing if we have nothing (JMarc)
1887 if (!keysym.isOK()) {
1888 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
1890 current_view_->restartCursor();
1894 if (keysym.isModifier()) {
1896 current_view_->restartCursor();
1900 char_type encoded_last_key = keysym.getUCSEncoded();
1902 // Do a one-deep top-level lookup for
1903 // cancel and meta-fake keys. RVDK_PATCH_5
1904 d->cancel_meta_seq.reset();
1906 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
1907 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
1909 // When not cancel or meta-fake, do the normal lookup.
1910 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
1911 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
1912 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
1913 // remove Caps Lock and Mod2 as a modifiers
1914 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
1915 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
1918 // Dont remove this unless you know what you are doing.
1919 d->meta_fake_bit = NoModifier;
1921 // Can this happen now ?
1922 if (func.action() == LFUN_NOACTION)
1923 func = FuncRequest(LFUN_COMMAND_PREFIX);
1925 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
1926 << d->keyseq.print(KeySequence::Portable) << ']');
1928 // already here we know if it any point in going further
1929 // why not return already here if action == -1 and
1930 // num_bytes == 0? (Lgb)
1932 if (d->keyseq.length() > 1 && current_view_)
1933 current_view_->message(d->keyseq.print(KeySequence::ForGui));
1936 // Maybe user can only reach the key via holding down shift.
1937 // Let's see. But only if shift is the only modifier
1938 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
1939 LYXERR(Debug::KEY, "Trying without shift");
1940 func = d->keyseq.addkey(keysym, NoModifier);
1941 LYXERR(Debug::KEY, "Action now " << func.action());
1944 if (func.action() == LFUN_UNKNOWN_ACTION) {
1945 // Hmm, we didn't match any of the keysequences. See
1946 // if it's normal insertable text not already covered
1948 if (keysym.isText() && d->keyseq.length() == 1) {
1949 LYXERR(Debug::KEY, "isText() is true, inserting.");
1950 func = FuncRequest(LFUN_SELF_INSERT,
1951 FuncRequest::KEYBOARD);
1953 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
1954 if (current_view_) {
1955 current_view_->message(_("Unknown function."));
1956 current_view_->restartCursor();
1962 if (func.action() == LFUN_SELF_INSERT) {
1963 if (encoded_last_key != 0) {
1964 docstring const arg(1, encoded_last_key);
1965 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
1966 FuncRequest::KEYBOARD));
1967 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
1970 processFuncRequest(func);
1974 void GuiApplication::processFuncRequest(FuncRequest const & func)
1976 lyx::dispatch(func);
1980 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
1982 addToFuncRequestQueue(func);
1983 processFuncRequestQueueAsync();
1987 void GuiApplication::processFuncRequestQueue()
1989 while (!d->func_request_queue_.empty()) {
1990 processFuncRequest(d->func_request_queue_.front());
1991 d->func_request_queue_.pop();
1996 void GuiApplication::processFuncRequestQueueAsync()
1998 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2002 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2004 d->func_request_queue_.push(func);
2008 void GuiApplication::resetGui()
2010 // Set the language defined by the user.
2014 if (!readUIFile(toqstr(lyxrc.ui_file)))
2015 // Gives some error box here.
2018 if (d->global_menubar_)
2019 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2021 QHash<int, GuiView *>::iterator it;
2022 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2025 gv->setLayoutDirection(layoutDirection());
2029 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2033 void GuiApplication::createView(int view_id)
2035 createView(QString(), true, view_id);
2039 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2042 // release the keyboard which might have been grabed by the global
2043 // menubar on Mac to catch shortcuts even without any GuiView.
2044 if (d->global_menubar_)
2045 d->global_menubar_->releaseKeyboard();
2049 while (d->views_.find(id) != d->views_.end())
2052 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2053 GuiView * view = new GuiView(id);
2055 d->views_[id] = view;
2059 setActiveWindow(view);
2062 if (!geometry_arg.isEmpty()) {
2066 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2067 re.indexIn(geometry_arg);
2068 w = re.cap(1).toInt();
2069 h = re.cap(2).toInt();
2070 x = re.cap(3).toInt();
2071 y = re.cap(4).toInt();
2072 view->setGeometry(x, y, w, h);
2079 Clipboard & GuiApplication::clipboard()
2081 return d->clipboard_;
2085 Selection & GuiApplication::selection()
2087 return d->selection_;
2091 FontLoader & GuiApplication::fontLoader()
2093 return d->font_loader_;
2097 Toolbars const & GuiApplication::toolbars() const
2099 return d->toolbars_;
2103 Toolbars & GuiApplication::toolbars()
2105 return d->toolbars_;
2109 Menus const & GuiApplication::menus() const
2115 Menus & GuiApplication::menus()
2121 QList<int> GuiApplication::viewIds() const
2123 return d->views_.keys();
2127 ColorCache & GuiApplication::colorCache()
2129 return d->color_cache_;
2133 int GuiApplication::exec()
2135 // asynchronously handle batch commands. This event will be in
2136 // the event queue in front of other asynchronous events. Hence,
2137 // we can assume in the latter that the gui is setup already.
2138 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2140 return QApplication::exec();
2144 void GuiApplication::exit(int status)
2146 QApplication::exit(status);
2150 void GuiApplication::setGuiLanguage()
2152 QString const default_language = toqstr(getGuiMessages().language());
2153 LYXERR(Debug::LOCALE, "Trying to set default locale to: " << default_language);
2154 QLocale const default_locale(default_language);
2155 QLocale::setDefault(default_locale);
2157 // install translation file for Qt built-in dialogs
2158 QString const language_name = QString("qt_") + default_locale.name();
2160 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2161 // Short-named translator can be loaded from a long name, but not the
2162 // opposite. Therefore, long name should be used without truncation.
2163 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2164 if (!d->qt_trans_.load(language_name,
2165 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2166 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2169 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2173 switch (default_locale.language()) {
2174 case QLocale::Arabic :
2175 case QLocale::Hebrew :
2176 case QLocale::Persian :
2177 case QLocale::Urdu :
2178 setLayoutDirection(Qt::RightToLeft);
2181 setLayoutDirection(Qt::LeftToRight);
2186 void GuiApplication::execBatchCommands()
2191 if (!readUIFile(toqstr(lyxrc.ui_file)))
2192 // Gives some error box here.
2196 #if QT_VERSION > 0x040600
2197 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2199 // Create the global default menubar which is shown for the dialogs
2200 // and if no GuiView is visible.
2201 // This must be done after the session was recovered to know the "last files".
2202 d->global_menubar_ = new GlobalMenuBar;
2203 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2206 lyx::execBatchCommands();
2210 QAbstractItemModel * GuiApplication::languageModel()
2212 if (d->language_model_)
2213 return d->language_model_;
2215 QStandardItemModel * lang_model = new QStandardItemModel(this);
2216 lang_model->insertColumns(0, 3);
2218 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2219 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2220 Languages::const_iterator it = lyx::languages.begin();
2221 Languages::const_iterator end = lyx::languages.end();
2222 for (; it != end; ++it) {
2223 current_row = lang_model->rowCount();
2224 lang_model->insertRows(current_row, 1);
2225 QModelIndex pl_item = lang_model->index(current_row, 0);
2226 QModelIndex sp_item = lang_model->index(current_row, 1);
2227 QModelIndex th_item = lang_model->index(current_row, 2);
2228 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2229 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2230 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2231 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2232 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2233 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2234 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2235 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2236 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2237 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2239 d->language_model_ = new QSortFilterProxyModel(this);
2240 d->language_model_->setSourceModel(lang_model);
2241 d->language_model_->setSortLocaleAware(true);
2242 return d->language_model_;
2246 void GuiApplication::restoreGuiSession()
2248 if (!lyxrc.load_session)
2251 Session & session = theSession();
2252 LastOpenedSection::LastOpened const & lastopened =
2253 session.lastOpened().getfiles();
2255 validateCurrentView();
2257 FileName active_file;
2258 // do not add to the lastfile list since these files are restored from
2259 // last session, and should be already there (regular files), or should
2260 // not be added at all (help files).
2261 for (size_t i = 0; i < lastopened.size(); ++i) {
2262 FileName const & file_name = lastopened[i].file_name;
2263 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2264 && current_view_->documentBufferView() != 0)) {
2265 boost::crc_32_type crc;
2266 string const & fname = file_name.absFileName();
2267 crc = for_each(fname.begin(), fname.end(), crc);
2268 createView(crc.checksum());
2270 current_view_->loadDocument(file_name, false);
2272 if (lastopened[i].active)
2273 active_file = file_name;
2276 // Restore last active buffer
2277 Buffer * buffer = theBufferList().getBuffer(active_file);
2278 if (buffer && current_view_)
2279 current_view_->setBuffer(buffer);
2281 // clear this list to save a few bytes of RAM
2282 session.lastOpened().clear();
2286 QString const GuiApplication::romanFontName()
2289 font.setKerning(false);
2290 font.setStyleHint(QFont::Serif);
2291 font.setFamily("serif");
2293 return QFontInfo(font).family();
2297 QString const GuiApplication::sansFontName()
2300 font.setKerning(false);
2301 font.setStyleHint(QFont::SansSerif);
2302 font.setFamily("sans");
2304 return QFontInfo(font).family();
2308 QString const GuiApplication::typewriterFontName()
2311 font.setKerning(false);
2312 font.setStyleHint(QFont::TypeWriter);
2313 font.setFamily("monospace");
2315 return QFontInfo(font).family();
2319 void GuiApplication::handleRegularEvents()
2321 ForkedCallsController::handleCompletedProcesses();
2325 bool GuiApplication::event(QEvent * e)
2328 case QEvent::FileOpen: {
2329 // Open a file; this happens only on Mac OS X for now.
2331 // We do this asynchronously because on startup the batch
2332 // commands are not executed here yet and the gui is not ready
2334 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2335 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2336 processFuncRequestAsync(fr);
2341 return QApplication::event(e);
2346 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2349 return QApplication::notify(receiver, event);
2351 catch (ExceptionMessage const & e) {
2353 case ErrorException:
2355 setQuitOnLastWindowClosed(false);
2357 Alert::error(e.title_, e.details_);
2359 // Properly crash in debug mode in order to get a useful backtrace.
2362 // In release mode, try to exit gracefully.
2365 case BufferException: {
2366 if (!current_view_ || !current_view_->documentBufferView())
2368 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2369 docstring details = e.details_ + '\n';
2370 details += buf->emergencyWrite();
2371 theBufferList().release(buf);
2372 details += "\n" + _("The current document was closed.");
2373 Alert::error(e.title_, details);
2376 case WarningException:
2377 Alert::warning(e.title_, e.details_);
2381 catch (exception const & e) {
2382 docstring s = _("LyX has caught an exception, it will now "
2383 "attempt to save all unsaved documents and exit."
2385 s += from_ascii(e.what());
2386 Alert::error(_("Software exception Detected"), s);
2390 docstring s = _("LyX has caught some really weird exception, it will "
2391 "now attempt to save all unsaved documents and exit.");
2392 Alert::error(_("Software exception Detected"), s);
2400 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2402 QColor const & qcol = d->color_cache_.get(col);
2403 if (!qcol.isValid()) {
2409 rgbcol.r = qcol.red();
2410 rgbcol.g = qcol.green();
2411 rgbcol.b = qcol.blue();
2416 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2418 QColor const qcol(lcolor.getX11Name(col).c_str());
2419 if (!qcol.isValid()) {
2425 rgbcol.r = qcol.red();
2426 rgbcol.g = qcol.green();
2427 rgbcol.b = qcol.blue();
2432 string const GuiApplication::hexName(ColorCode col)
2434 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2438 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2440 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2441 d->socket_notifiers_[fd] = sn;
2442 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2446 void GuiApplication::socketDataReceived(int fd)
2448 d->socket_notifiers_[fd]->func_();
2452 void GuiApplication::unregisterSocketCallback(int fd)
2454 d->socket_notifiers_.take(fd)->setEnabled(false);
2458 void GuiApplication::commitData(QSessionManager & sm)
2460 /// The implementation is required to avoid an application exit
2461 /// when session state save is triggered by session manager.
2462 /// The default implementation sends a close event to all
2463 /// visible top level widgets when session managment allows
2465 /// We are changing that to close all wiew one by one.
2466 /// FIXME: verify if the default implementation is enough now.
2467 #ifdef QT_NO_SESSIONMANAGER
2469 #warning Qt is compiled without session manager
2471 #pragma message("warning: Qt is compiled without session manager")
2475 if (sm.allowsInteraction() && !closeAllViews())
2481 void GuiApplication::unregisterView(GuiView * gv)
2483 LASSERT(d->views_[gv->id()] == gv, /**/);
2484 d->views_.remove(gv->id());
2485 if (current_view_ == gv)
2490 bool GuiApplication::closeAllViews()
2492 if (d->views_.empty())
2495 // When a view/window was closed before without quitting LyX, there
2496 // are already entries in the lastOpened list.
2497 theSession().lastOpened().clear();
2499 QList<GuiView *> const views = d->views_.values();
2500 foreach (GuiView * view, views) {
2501 if (!view->closeScheduled())
2510 GuiView & GuiApplication::view(int id) const
2512 LASSERT(d->views_.contains(id), /**/);
2513 return *d->views_.value(id);
2517 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2519 QList<GuiView *> const views = d->views_.values();
2520 foreach (GuiView * view, views)
2521 view->hideDialog(name, inset);
2525 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2527 Buffer const * buffer_ = 0;
2528 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2529 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2530 if (Buffer const * ptr = (*it)->updateInset(inset))
2537 bool GuiApplication::searchMenu(FuncRequest const & func,
2538 docstring_list & names) const
2540 return d->menus_.searchMenu(func, names);
2544 // Ensure that a file is read only once (prevents include loops)
2545 static QStringList uifiles;
2546 // store which ui files define Toolbars
2547 static QStringList toolbar_uifiles;
2550 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2561 LexerKeyword uitags[] = {
2562 { "format", ui_format },
2563 { "include", ui_include },
2564 { "menuset", ui_menuset },
2565 { "toolbars", ui_toolbars },
2566 { "toolbarset", ui_toolbarset }
2570 lex.setFile(ui_path);
2572 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2576 if (lyxerr.debugging(Debug::PARSER))
2577 lex.printTable(lyxerr);
2580 // format before introduction of format tag
2581 unsigned int format = 0;
2582 while (lex.isOK()) {
2583 int const status = lex.lex();
2585 // we have to do this check here, outside the switch,
2586 // because otherwise we would start reading include files,
2587 // e.g., if the first tag we hit was an include tag.
2588 if (status == ui_format)
2590 format = lex.getInteger();
2594 // this will trigger unless the first tag we hit is a format
2595 // tag, with the right format.
2596 if (format != LFUN_FORMAT)
2597 return FormatMismatch;
2600 case Lexer::LEX_FEOF:
2605 QString const file = toqstr(lex.getString());
2606 bool const success = readUIFile(file, true);
2608 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2615 d->menus_.read(lex);
2619 d->toolbars_.readToolbars(lex);
2623 d->toolbars_.readToolbarSettings(lex);
2624 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2628 if (!rtrim(lex.getString()).empty())
2629 lex.printError("LyX::ReadUIFile: "
2630 "Unknown menu tag: `$$Token'");
2632 LYXERR0("Error with status: " << status);
2638 return (error ? ReadError : ReadOK);
2642 bool GuiApplication::readUIFile(QString const & name, bool include)
2644 LYXERR(Debug::INIT, "About to read " << name << "...");
2648 ui_path = libFileSearch("ui", name, "inc");
2649 if (ui_path.empty())
2650 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2652 ui_path = libFileSearch("ui", name, "ui");
2655 if (ui_path.empty()) {
2656 static const QString defaultUIFile = "default";
2657 LYXERR(Debug::INIT, "Could not find " << name);
2659 Alert::warning(_("Could not find UI definition file"),
2660 bformat(_("Error while reading the included file\n%1$s\n"
2661 "Please check your installation."), qstring_to_ucs4(name)));
2664 if (name == defaultUIFile) {
2665 LYXERR(Debug::INIT, "Could not find default UI file!!");
2666 Alert::warning(_("Could not find default UI file"),
2667 _("LyX could not find the default UI file!\n"
2668 "Please check your installation."));
2671 Alert::warning(_("Could not find UI definition file"),
2672 bformat(_("Error while reading the configuration file\n%1$s\n"
2673 "Falling back to default.\n"
2674 "Please look under Tools>Preferences>User Interface and\n"
2675 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2676 return readUIFile(defaultUIFile, false);
2679 QString const uifile = toqstr(ui_path.absFileName());
2680 if (uifiles.contains(uifile)) {
2682 // We are reading again the top uifile so reset the safeguard:
2685 d->toolbars_.reset();
2687 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2688 << "Is this an include loop?");
2692 uifiles.push_back(uifile);
2694 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2696 ReturnValues retval = readUIFile(ui_path);
2698 if (retval == FormatMismatch) {
2699 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2700 FileName const tempfile = FileName::tempName("convert_ui");
2701 bool const success = prefs2prefs(ui_path, tempfile, true);
2703 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2704 " to format " << LFUN_FORMAT << ".");
2706 retval = readUIFile(tempfile);
2707 tempfile.removeFile();
2711 if (retval != ReadOK) {
2712 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2720 settings.beginGroup("ui_files");
2721 bool touched = false;
2722 for (int i = 0; i != uifiles.size(); ++i) {
2723 QFileInfo fi(uifiles[i]);
2724 QDateTime const date_value = fi.lastModified();
2725 QString const name_key = QString::number(i);
2726 // if an ui file which defines Toolbars has changed,
2727 // we have to reset the settings
2728 if (toolbar_uifiles.contains(uifiles[i])
2729 && (!settings.contains(name_key)
2730 || settings.value(name_key).toString() != uifiles[i]
2731 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2733 settings.setValue(name_key, uifiles[i]);
2734 settings.setValue(name_key + "/date", date_value);
2737 settings.endGroup();
2739 settings.remove("views");
2745 void GuiApplication::onLastWindowClosed()
2747 if (d->global_menubar_)
2748 d->global_menubar_->grabKeyboard();
2752 void GuiApplication::startLongOperation() {
2753 d->key_checker_.start();
2757 bool GuiApplication::longOperationCancelled() {
2758 return d->key_checker_.pressed();
2762 void GuiApplication::stopLongOperation() {
2763 d->key_checker_.stop();
2767 bool GuiApplication::longOperationStarted() {
2768 return d->key_checker_.started();
2772 ////////////////////////////////////////////////////////////////////////
2774 // X11 specific stuff goes here...
2777 bool GuiApplication::x11EventFilter(XEvent * xev)
2782 switch (xev->type) {
2783 case SelectionRequest: {
2784 if (xev->xselectionrequest.selection != XA_PRIMARY)
2786 LYXERR(Debug::SELECTION, "X requested selection.");
2787 BufferView * bv = current_view_->currentBufferView();
2789 docstring const sel = bv->requestSelection();
2791 d->selection_.put(sel);
2795 case SelectionClear: {
2796 if (xev->xselectionclear.selection != XA_PRIMARY)
2798 LYXERR(Debug::SELECTION, "Lost selection.");
2799 BufferView * bv = current_view_->currentBufferView();
2801 bv->clearSelection();
2809 } // namespace frontend
2812 void hideDialogs(std::string const & name, Inset * inset)
2815 frontend::guiApp->hideDialogs(name, inset);
2819 ////////////////////////////////////////////////////////////////////
2823 ////////////////////////////////////////////////////////////////////
2825 frontend::FontLoader & theFontLoader()
2827 LASSERT(frontend::guiApp, /**/);
2828 return frontend::guiApp->fontLoader();
2832 frontend::FontMetrics const & theFontMetrics(Font const & f)
2834 return theFontMetrics(f.fontInfo());
2838 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2840 LASSERT(frontend::guiApp, /**/);
2841 return frontend::guiApp->fontLoader().metrics(f);
2845 ////////////////////////////////////////////////////////////////////
2849 ////////////////////////////////////////////////////////////////////
2851 frontend::Clipboard & theClipboard()
2853 LASSERT(frontend::guiApp, /**/);
2854 return frontend::guiApp->clipboard();
2858 frontend::Selection & theSelection()
2860 LASSERT(frontend::guiApp, /**/);
2861 return frontend::guiApp->selection();
2867 #include "moc_GuiApplication.cpp"