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"
73 #include "support/TempFile.h"
76 #include "support/AppleScript.h"
77 #include "support/linkback/LinkBackProxy.h"
88 #include <QFileOpenEvent>
92 #include <QImageReader>
95 #include <QLibraryInfo>
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>
131 #include <QMacPasteboardMime>
134 #include "support/bind.h"
135 #include <boost/crc.hpp>
142 using namespace lyx::support;
145 static void initializeResources()
147 static bool initialized = false;
149 Q_INIT_RESOURCE(Resources);
157 frontend::Application * createApplication(int & argc, char * argv[])
160 // prune -geometry argument(s) by shifting
161 // the following ones 2 places down.
162 for (int i = 0 ; i < argc ; ++i) {
163 if (strcmp(argv[i], "-geometry") == 0) {
164 int const remove = (i+1) < argc ? 2 : 1;
166 for (int j = i; j < argc; ++j)
167 argv[j] = argv[j + remove];
172 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
173 // I'd rather do that in the constructor, but I do not think that
174 // the palette is accessible there.
175 guiApp->colorCache().setPalette(guiApp->palette());
183 if (lyxrc.gui_language == "auto") {
184 theLocale = QLocale::system();
186 Language const * l = languages.getLanguage(lyxrc.gui_language);
187 string const code = l ? l->code() : string();
188 theLocale = QLocale(toqstr(code));
190 string const code = fromqstr(theLocale.name());
191 // Qt tries to outsmart us and transforms en_US to C.
192 Messages::guiLanguage((code == "C") ? "en_US" : code);
193 QLocale::setDefault(theLocale);
194 setlocale(LC_NUMERIC, "C");
201 /// Return the list of loadable formats.
202 vector<string> loadableImageFormats()
206 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
208 LYXERR(Debug::GRAPHICS,
209 "\nThe image loader can load the following directly:\n");
211 if (qt_formats.empty())
212 LYXERR(Debug::GRAPHICS, "\nQt4 Problem: No Format available!");
214 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
216 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
218 string ext = ascii_lowercase((const char *) *it);
229 ////////////////////////////////////////////////////////////////////////
231 // Icon loading support code
233 ////////////////////////////////////////////////////////////////////////
243 bool operator<(PngMap const & lhs, PngMap const & rhs)
245 return lhs.key < rhs.key;
251 CompareKey(QString const & name) : name_(name) {}
252 bool operator()(PngMap const & other) const { return other.key == name_; }
258 // this must be sorted alphabetically
259 // Upper case comes before lower case
260 // Please don't change the formatting, this list is parsed by
261 // development/tools/generate_symbols_images.py.
262 PngMap sorted_png_map[] = {
263 { "Arrownot", "arrownot2"},
264 { "Arrowvert", "arrowvert2"},
265 { "Bowtie", "bowtie2" },
267 { "Bumpeq", "bumpeq2" },
268 { "CIRCLE", "circle3" },
270 { "CheckedBox", "checkedbox2" },
271 { "Circle", "circle2" },
272 { "Colonapprox", "colonapprox2" },
273 { "Coloneq", "coloneq2" },
274 { "Coloneqq", "coloneqq2" },
275 { "Colonsim", "colonsim2" },
277 { "DOWNarrow", "downarrow3" },
278 { "Delta", "delta2" },
279 { "Diamond", "diamond2" },
280 { "Doteq", "doteq2" },
281 { "Downarrow", "downarrow2" },
282 { "Eqcolon", "eqcolon2" },
283 { "Eqqcolon", "eqqcolon2" },
284 { "Gamma", "gamma2" },
286 { "LEFTCIRCLE", "leftcircle3" },
287 { "LEFTarrow", "leftarrow3" },
288 { "LEFTcircle", "leftcircle4" },
290 { "Lambda", "lambda2" },
292 { "Leftarrow", "leftarrow2" },
293 { "Leftcircle", "leftcircle2" },
294 { "Leftrightarrow", "leftrightarrow2" },
295 { "Longarrownot", "longarrownot2"},
296 { "Longleftarrow", "longleftarrow2" },
297 { "Longleftrightarrow", "longleftrightarrow2" },
298 { "Longmapsfrom", "longmapsfrom2"},
299 { "Longmapsto", "longmapsto2"},
300 { "Longrightarrow", "longrightarrow2" },
301 { "Mapsfrom", "mapsfrom2"},
302 { "Mapsfromchar", "mapsfromchar2"},
303 { "Mapsto", "mapsto2"},
304 { "Mapstochar", "mapstochar2"},
305 { "Omega", "omega2" },
310 { "RIGHTCIRCLE", "rightcircle3" },
311 { "RIGHTarrow", "rightarrow3" },
312 { "RIGHTcircle", "rightcircle4" },
314 { "Rightarrow", "rightarrow2" },
315 { "Rightcircle", "rightcircle2" },
316 { "Sigma", "sigma2" },
317 { "Square", "square2" },
318 { "Subset", "subset2" },
319 { "Supset", "supset2" },
320 { "Theta", "theta2" },
321 { "Thorn", "thorn2" },
322 { "UParrow", "uparrow3" },
323 { "Uparrow", "uparrow2" },
324 { "Updownarrow", "updownarrow2" },
325 { "Upsilon", "upsilon2" },
326 { "Vdash", "vdash3" },
331 { "nLeftarrow", "nleftarrow2" },
332 { "nLeftrightarrow", "nleftrightarrow2" },
333 { "nRightarrow", "nrightarrow2" },
334 { "nVDash", "nvdash3" },
335 { "nVdash", "nvdash4" },
336 { "nvDash", "nvdash2" },
337 { "textrm \\AA", "textrm_AA"},
338 { "textrm \\O", "textrm_O"},
339 { "vDash", "vdash2" },
340 { "varDelta", "vardelta2" },
341 { "varGamma", "vargamma2" },
342 { "varLambda", "varlambda2" },
343 { "varOmega", "varomega2" },
344 { "varPhi", "varphi2" },
345 { "varPi", "varpi2" },
346 { "varPsi", "varpsi2" },
347 { "varSigma", "varsigma2" },
348 { "varTheta", "vartheta2" },
349 { "varUpsilon", "varupsilon2" },
350 { "varXi", "varxi2" }
354 size_t const nr_sorted_png_map = sizeof(sorted_png_map) / sizeof(PngMap);
356 // This list specifies which system's theme icon is related to which lyx
357 // command. It was based on:
358 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
359 // this must be sorted alphabetically
360 // Upper case comes before lower case
361 PngMap sorted_theme_icon_map[] = {
362 { "bookmark-goto 0", "go-jump" },
363 { "buffer-new", "document-new" },
364 { "buffer-print", "document-print" },
365 { "buffer-write", "document-save" },
366 { "buffer-write-as", "document-save-as" },
367 { "buffer-zoom-in", "zoom-in" },
368 { "buffer-zoom-out", "zoom-out" },
369 { "copy", "edit-copy" },
370 { "cut", "edit-cut" },
371 { "depth-decrement", "format-indent-less" },
372 { "depth-increment", "format-indent-more" },
373 { "dialog-show print", "document-print" },
374 { "dialog-show spellchecker", "tools-check-spelling" },
375 { "dialog-show-new-inset graphics", "insert-image" },
376 { "dialog-toggle findreplaceadv", "edit-find-replace" },
377 { "file-open", "document-open" },
378 { "font-bold", "format-text-bold" },
379 { "font-ital", "format-text-italic" },
380 { "font-strikeout", "format-text-strikethrough" },
381 { "font-underline", "format-text-underline" },
382 { "lyx-quit", "application-exit" },
383 { "paste", "edit-paste" },
384 { "redo", "edit-redo" },
385 { "undo", "edit-undo" },
386 { "window-close", "window-close" },
387 { "window-new", "window-new" }
390 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(PngMap);
393 QString findPng(QString const & name)
395 PngMap const * const begin = sorted_png_map;
396 PngMap const * const end = begin + nr_sorted_png_map;
397 LATTEST(sorted(begin, end));
399 PngMap const * const it = find_if(begin, end, CompareKey(name));
403 png_name = it->value;
406 png_name.replace('_', "underscore");
407 png_name.replace(' ', '_');
409 // This way we can have "math-delim { }" on the toolbar.
410 png_name.replace('(', "lparen");
411 png_name.replace(')', "rparen");
412 png_name.replace('[', "lbracket");
413 png_name.replace(']', "rbracket");
414 png_name.replace('{', "lbrace");
415 png_name.replace('}', "rbrace");
416 png_name.replace('|', "bars");
417 png_name.replace(',', "thinspace");
418 png_name.replace(':', "mediumspace");
419 png_name.replace(';', "thickspace");
420 png_name.replace('!', "negthinspace");
423 LYXERR(Debug::GUI, "findPng(" << name << ")\n"
424 << "Looking for math PNG called \"" << png_name << '"');
431 QString themeIconName(QString const & action)
433 PngMap const * const begin = sorted_theme_icon_map;
434 PngMap const * const end = begin + nr_sorted_theme_icon_map;
435 LASSERT(sorted(begin, end), /**/);
437 PngMap const * const it = find_if(begin, end, CompareKey(action));
445 QString iconName(FuncRequest const & f, bool unknown)
447 initializeResources();
451 switch (f.action()) {
452 case LFUN_MATH_INSERT:
453 if (!f.argument().empty()) {
455 name1 = findPng(toqstr(f.argument()).mid(1));
458 case LFUN_MATH_DELIM:
459 case LFUN_MATH_BIGDELIM:
461 name1 = findPng(toqstr(f.argument()));
465 name1 = toqstr(f.argument());
467 case LFUN_COMMAND_ALTERNATIVES: {
468 // use the first of the alternative commands
470 docstring dummy = split(f.argument(), firstcom, ';');
471 name1 = toqstr(firstcom);
472 // FIXME: we should rename the icons to tabular-xxx instead of
473 // "tabular-feature-xxx"
474 name1.replace("inset-modify tabular", "tabular-feature");
475 name1.replace(' ', '_');
478 case LFUN_INSET_MODIFY: {
479 // FIXME: we should rename the icons to tabular-xxx instead of
480 // "tabular-feature-xxx" and generalize this naming to all
481 // insets, not to tabular using ones.
483 string const command = split(to_utf8(f.argument()), inset_name, ' ');
484 if (insetCode(inset_name) == TABULAR_CODE) {
485 name1 = "tabular-feature "+ toqstr(command);
486 name1.replace(' ', '_');
491 name2 = toqstr(lyxaction.getActionName(f.action()));
494 if (!f.argument().empty()) {
495 name1 = name2 + ' ' + toqstr(f.argument());
496 name1.replace(' ', '_');
497 name1.replace('\\', "backslash");
501 QStringList imagedirs;
502 imagedirs << "images/" << "images/ipa/";
503 for (int i = 0; i < imagedirs.size(); ++i) {
504 QString imagedir = imagedirs.at(i) + path;
505 FileName fname = imageLibFileSearch(imagedir, name1, "png");
507 return toqstr(fname.absFileName());
509 fname = imageLibFileSearch(imagedir, name2, "png");
511 return toqstr(fname.absFileName());
514 path = ":/images/" + path;
517 LYXERR0("Directory " << path << " not found in resource!");
521 if (res.exists(name1))
525 if (res.exists(name2))
528 LYXERR(Debug::GUI, "Cannot find icon with filename "
529 << "\"" << name1 << "\""
531 << "\"" << name2 << "\""
533 << lyxaction.getActionName(f.action())
534 << '(' << to_utf8(f.argument()) << ")\"");
537 QString imagedir = "images/";
538 FileName fname = imageLibFileSearch(imagedir, "unknown", "png");
540 return toqstr(fname.absFileName());
541 return QString(":/images/unknown.png");
547 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
550 QString imagedir = path;
551 FileName fname = imageLibFileSearch(imagedir, name, ext);
552 QString path1 = toqstr(fname.absFileName());
553 QString path2 = ":/" + path + name + "." + ext;
555 if (pixmap.load(path1)) {
558 else if (pixmap.load(path2)) {
562 LYXERR0("Cannot load pixmap \""
563 << path << name << '.' << ext
564 << "\", please verify resource system!");
569 QIcon getIcon(FuncRequest const & f, bool unknown)
571 #if (QT_VERSION >= 0x040600)
572 if (lyxrc.use_system_theme_icons) {
573 QString action = toqstr(lyxaction.getActionName(f.action()));
574 if (!f.argument().empty())
575 action += " " + toqstr(f.argument());
576 QString const theme_icon = themeIconName(action);
577 if (QIcon::hasThemeIcon(theme_icon))
578 return QIcon::fromTheme(theme_icon);
582 QString icon = iconName(f, unknown);
586 //LYXERR(Debug::GUI, "Found icon: " << icon);
588 if (!pm.load(icon)) {
589 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
597 ////////////////////////////////////////////////////////////////////////
599 // LyX server support code.
601 ////////////////////////////////////////////////////////////////////////
603 class SocketNotifier : public QSocketNotifier
606 /// connect a connection notification from the LyXServerSocket
607 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
608 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
612 /// The callback function
613 Application::SocketCallback func_;
617 ////////////////////////////////////////////////////////////////////////
619 // Mac specific stuff goes here...
621 ////////////////////////////////////////////////////////////////////////
623 class MenuTranslator : public QTranslator
626 MenuTranslator(QObject * parent)
627 : QTranslator(parent)
630 QString translate(const char * /*context*/,
631 const char * sourceText,
632 const char * /*comment*/ = 0) const
634 string const s = sourceText;
635 if (s == N_("About %1") || s == N_("Preferences")
636 || s == N_("Reconfigure") || s == N_("Quit %1"))
643 class GlobalMenuBar : public QMenuBar
647 GlobalMenuBar() : QMenuBar(0) {}
650 bool event(QEvent * e)
652 if (e->type() == QEvent::ShortcutOverride) {
653 // && activeWindow() == 0) {
654 QKeyEvent * ke = static_cast<QKeyEvent*>(e);
656 setKeySymbol(&sym, ke);
657 guiApp->processKeySym(sym, q_key_state(ke->modifiers()));
666 // QMacPasteboardMimeGraphics can only be compiled on Mac.
668 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
671 QMacPasteboardMimeGraphics()
672 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
675 QString convertorName() { return "Graphics"; }
677 QString flavorFor(QString const & mime)
679 LYXERR(Debug::ACTION, "flavorFor " << mime);
680 if (mime == pdfMimeType())
681 return QLatin1String("com.adobe.pdf");
685 QString mimeFor(QString flav)
687 LYXERR(Debug::ACTION, "mimeFor " << flav);
688 if (flav == QLatin1String("com.adobe.pdf"))
689 return pdfMimeType();
693 bool canConvert(QString const & mime, QString flav)
695 return mimeFor(flav) == mime;
698 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
702 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
706 QList<QByteArray> convertFromMime(QString const & /*mime*/,
707 QVariant data, QString /*flav*/)
709 QList<QByteArray> ret;
710 ret.append(data.toByteArray());
716 ///////////////////////////////////////////////////////////////
718 // You can find more platform specific stuff at the end of this file...
720 ///////////////////////////////////////////////////////////////
722 ////////////////////////////////////////////////////////////////////////
723 // Windows specific stuff goes here...
726 // QWindowsMimeMetafile can only be compiled on Windows.
728 static FORMATETC cfFromMime(QString const & mimetype)
731 if (mimetype == emfMimeType()) {
732 formatetc.cfFormat = CF_ENHMETAFILE;
733 formatetc.tymed = TYMED_ENHMF;
734 } else if (mimetype == wmfMimeType()) {
735 formatetc.cfFormat = CF_METAFILEPICT;
736 formatetc.tymed = TYMED_MFPICT;
739 formatetc.dwAspect = DVASPECT_CONTENT;
740 formatetc.lindex = -1;
745 class QWindowsMimeMetafile : public QWindowsMime {
747 QWindowsMimeMetafile() {}
749 bool canConvertFromMime(FORMATETC const & formatetc,
750 QMimeData const * mimedata) const
755 bool canConvertToMime(QString const & mimetype,
756 IDataObject * pDataObj) const
758 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
760 FORMATETC formatetc = cfFromMime(mimetype);
761 return pDataObj->QueryGetData(&formatetc) == S_OK;
764 bool convertFromMime(FORMATETC const & formatetc,
765 const QMimeData * mimedata, STGMEDIUM * pmedium) const
770 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
771 QVariant::Type preferredType) const
774 if (!canConvertToMime(mimetype, pDataObj))
777 FORMATETC formatetc = cfFromMime(mimetype);
779 if (pDataObj->GetData(&formatetc, &s) != S_OK)
783 if (s.tymed == TYMED_ENHMF) {
784 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
785 data.resize(dataSize);
786 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
787 (LPBYTE)data.data());
788 } else if (s.tymed == TYMED_MFPICT) {
789 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
790 data.resize(dataSize);
791 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
792 (LPBYTE)data.data());
795 ReleaseStgMedium(&s);
801 QVector<FORMATETC> formatsForMime(QString const & mimetype,
802 QMimeData const * mimedata) const
804 QVector<FORMATETC> formats;
805 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
806 formats += cfFromMime(mimetype);
810 QString mimeForFormat(FORMATETC const & formatetc) const
812 switch (formatetc.cfFormat) {
814 return emfMimeType();
815 case CF_METAFILEPICT:
816 return wmfMimeType();
825 /// Allows to check whether ESC was pressed during a long operation
826 class KeyChecker : public QObject {
831 KeyChecker() : pressed_(false), started_(false) {}
834 QCoreApplication::instance()->installEventFilter(this);
839 QCoreApplication::instance()->removeEventFilter(this);
843 QCoreApplication::processEvents();
846 bool started() const {
849 bool eventFilter(QObject *obj, QEvent *event) {
850 LYXERR(Debug::ACTION, "Event Type: " << event->type());
851 switch (event->type()) {
855 case QEvent::UpdateRequest:
856 case QEvent::CursorChange:
857 case QEvent::ActionChanged:
858 case QEvent::EnabledChange:
859 case QEvent::SockAct:
862 case QEvent::ToolTipChange:
863 case QEvent::LayoutRequest:
864 case QEvent::MetaCall:
865 return QObject::eventFilter(obj, event);
867 // FIXME Blocking all these events is a bad idea.
868 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
869 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
877 ////////////////////////////////////////////////////////////////////////
878 // GuiApplication::Private definition and implementation.
879 ////////////////////////////////////////////////////////////////////////
881 struct GuiApplication::Private
883 Private(): language_model_(0), meta_fake_bit(NoModifier),
887 /// WMF Mime handler for Windows clipboard.
888 wmf_mime_ = new QWindowsMimeMetafile;
890 initKeySequences(&theTopLevelKeymap());
893 void initKeySequences(KeyMap * kb)
895 keyseq = KeySequence(kb, kb);
896 cancel_meta_seq = KeySequence(kb, kb);
900 QSortFilterProxyModel * language_model_;
902 GuiClipboard clipboard_;
904 GuiSelection selection_;
906 FontLoader font_loader_;
908 ColorCache color_cache_;
910 QTranslator qt_trans_;
912 QHash<int, SocketNotifier *> socket_notifiers_;
916 /// The global instance
919 /// this timer is used for any regular events one wants to
920 /// perform. at present it is used to check if forked processes
922 QTimer general_timer_;
924 /// delayed FuncRequests
925 std::queue<FuncRequest> func_request_queue_;
930 KeySequence cancel_meta_seq;
932 KeyModifier meta_fake_bit;
934 /// Multiple views container.
936 * Warning: This must not be a smart pointer as the destruction of the
937 * object is handled by Qt when the view is closed
938 * \sa Qt::WA_DeleteOnClose attribute.
940 QHash<int, GuiView *> views_;
942 /// Only used on mac.
943 GlobalMenuBar * global_menubar_;
946 /// Linkback mime handler for MacOSX.
947 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
951 /// WMF Mime handler for Windows clipboard.
952 QWindowsMimeMetafile * wmf_mime_;
955 /// Allows to check whether ESC was pressed during a long operation
956 KeyChecker key_checker_;
960 GuiApplication * guiApp;
962 GuiApplication::~GuiApplication()
965 closeAllLinkBackLinks();
971 GuiApplication::GuiApplication(int & argc, char ** argv)
972 : QApplication(argc, argv), current_view_(0),
973 d(new GuiApplication::Private)
975 QString app_name = "LyX";
976 QCoreApplication::setOrganizationName(app_name);
977 QCoreApplication::setOrganizationDomain("lyx.org");
978 QCoreApplication::setApplicationName(lyx_package);
980 qsrand(QDateTime::currentDateTime().toTime_t());
982 // Install translator for GUI elements.
983 installTranslator(&d->qt_trans_);
985 // FIXME: quitOnLastWindowClosed is true by default. We should have a
986 // lyxrc setting for this in order to let the application stay resident.
987 // But then we need some kind of dock icon, at least on Windows.
989 if (lyxrc.quit_on_last_window_closed)
990 setQuitOnLastWindowClosed(false);
993 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
994 // seems to be the default case for applications like LyX.
995 setQuitOnLastWindowClosed(false);
996 // This allows to translate the strings that appear in the LyX menu.
997 /// A translator suitable for the entries in the LyX menu.
998 /// Only needed with Qt/Mac.
999 installTranslator(new MenuTranslator(this));
1005 // doubleClickInterval() is 400 ms on X11 which is just too long.
1006 // On Windows and Mac OS X, the operating system's value is used.
1007 // On Microsoft Windows, calling this function sets the double
1008 // click interval for all applications. So we don't!
1009 QApplication::setDoubleClickInterval(300);
1012 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1014 // needs to be done before reading lyxrc
1016 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1020 // Set the cache to 5120 kilobytes which corresponds to screen size of
1021 // 1280 by 1024 pixels with a color depth of 32 bits.
1022 QPixmapCache::setCacheLimit(5120);
1024 // Initialize RC Fonts
1025 if (lyxrc.roman_font_name.empty())
1026 lyxrc.roman_font_name = fromqstr(romanFontName());
1028 if (lyxrc.sans_font_name.empty())
1029 lyxrc.sans_font_name = fromqstr(sansFontName());
1031 if (lyxrc.typewriter_font_name.empty())
1032 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1034 d->general_timer_.setInterval(500);
1035 connect(&d->general_timer_, SIGNAL(timeout()),
1036 this, SLOT(handleRegularEvents()));
1037 d->general_timer_.start();
1039 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1040 // This is clearly not enough in a time where we use threads for
1041 // document preview and/or export. 20 should be OK.
1042 QThreadPool::globalInstance()->setMaxThreadCount(20);
1046 GuiApplication * theGuiApp()
1048 return dynamic_cast<GuiApplication *>(theApp());
1052 void GuiApplication::clearSession()
1059 docstring Application::iconName(FuncRequest const & f, bool unknown)
1061 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1065 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1069 BufferView * bv = 0;
1070 BufferView * doc_bv = 0;
1072 if (cmd.action() == LFUN_NOACTION) {
1073 status.message(from_utf8(N_("Nothing to do")));
1074 status.setEnabled(false);
1077 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1078 status.setUnknown(true);
1079 status.message(from_utf8(N_("Unknown action")));
1080 status.setEnabled(false);
1083 // Does the GuiApplication know something?
1084 else if (getStatus(cmd, status)) { }
1086 // If we do not have a GuiView, then other functions are disabled
1087 else if (!current_view_)
1088 status.setEnabled(false);
1090 // Does the GuiView know something?
1091 else if (current_view_->getStatus(cmd, status)) { }
1093 // In LyX/Mac, when a dialog is open, the menus of the
1094 // application can still be accessed without giving focus to
1095 // the main window. In this case, we want to disable the menu
1096 // entries that are buffer or view-related.
1097 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1099 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1100 status.setEnabled(false);
1103 // If we do not have a BufferView, then other functions are disabled
1104 else if (!(bv = current_view_->currentBufferView()))
1105 status.setEnabled(false);
1107 // Does the current BufferView know something?
1108 else if (bv->getStatus(cmd, status)) { }
1110 // Does the current Buffer know something?
1111 else if (bv->buffer().getStatus(cmd, status)) { }
1113 // If we do not have a document BufferView, different from the
1114 // current BufferView, then other functions are disabled
1115 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1116 status.setEnabled(false);
1118 // Does the document Buffer know something?
1119 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1122 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1123 status.message(from_utf8(N_("Command not handled")));
1124 status.setEnabled(false);
1127 // the default error message if we disable the command
1128 if (!status.enabled() && status.message().empty())
1129 status.message(from_utf8(N_("Command disabled")));
1135 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1137 // I would really like to avoid having this switch and rather try to
1138 // encode this in the function itself.
1139 // -- And I'd rather let an inset decide which LFUNs it is willing
1140 // to handle (Andre')
1142 switch (cmd.action()) {
1144 // This could be used for the no-GUI version. The GUI version is handled in
1145 // GuiView::getStatus(). See above.
1147 case LFUN_BUFFER_WRITE:
1148 case LFUN_BUFFER_WRITE_AS: {
1149 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1150 enable = b && (b->isUnnamed() || !b->isClean());
1155 case LFUN_BOOKMARK_GOTO: {
1156 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1157 enable = theSession().bookmarks().isValid(num);
1161 case LFUN_BOOKMARK_CLEAR:
1162 enable = theSession().bookmarks().hasValid();
1165 // this one is difficult to get right. As a half-baked
1166 // solution, we consider only the first action of the sequence
1167 case LFUN_COMMAND_SEQUENCE: {
1168 // argument contains ';'-terminated commands
1169 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1170 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1171 func.setOrigin(cmd.origin());
1172 flag = getStatus(func);
1176 // we want to check if at least one of these is enabled
1177 case LFUN_COMMAND_ALTERNATIVES: {
1178 // argument contains ';'-terminated commands
1179 string arg = to_utf8(cmd.argument());
1180 while (!arg.empty()) {
1182 arg = split(arg, first, ';');
1183 FuncRequest func(lyxaction.lookupFunc(first));
1184 func.setOrigin(cmd.origin());
1185 flag = getStatus(func);
1186 // if this one is enabled, the whole thing is
1195 string name = to_utf8(cmd.argument());
1196 if (theTopLevelCmdDef().lock(name, func)) {
1197 func.setOrigin(cmd.origin());
1198 flag = getStatus(func);
1199 theTopLevelCmdDef().release(name);
1201 // catch recursion or unknown command
1202 // definition. all operations until the
1203 // recursion or unknown command definition
1204 // occurs are performed, so set the state to
1211 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1213 case LFUN_PREFERENCES_SAVE:
1214 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1215 case LFUN_DEBUG_LEVEL_SET:
1216 // these are handled in our dispatch()
1219 case LFUN_WINDOW_CLOSE:
1220 enable = d->views_.size() > 0;
1223 case LFUN_BUFFER_NEW:
1224 case LFUN_BUFFER_NEW_TEMPLATE:
1225 case LFUN_FILE_OPEN:
1226 case LFUN_HELP_OPEN:
1227 case LFUN_SCREEN_FONT_UPDATE:
1228 case LFUN_SET_COLOR:
1229 case LFUN_WINDOW_NEW:
1231 case LFUN_LYXRC_APPLY:
1232 case LFUN_COMMAND_PREFIX:
1234 case LFUN_META_PREFIX:
1235 case LFUN_RECONFIGURE:
1236 case LFUN_SERVER_GET_FILENAME:
1237 case LFUN_SERVER_NOTIFY:
1241 case LFUN_BUFFER_FORALL: {
1242 if (theBufferList().empty()) {
1243 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1244 flag.setEnabled(false);
1248 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1249 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1250 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1251 flag.setEnabled(false);
1256 case LFUN_DIALOG_SHOW: {
1257 string const name = cmd.getArg(0);
1258 return name == "aboutlyx"
1260 || name == "texinfo"
1261 || name == "progress"
1262 || name == "compare";
1270 flag.setEnabled(false);
1274 /// make a post-dispatch status message
1275 static docstring makeDispatchMessage(docstring const & msg,
1276 FuncRequest const & cmd)
1278 const bool verbose = (cmd.origin() == FuncRequest::MENU
1279 || cmd.origin() == FuncRequest::TOOLBAR
1280 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1282 if (cmd.action() == LFUN_SELF_INSERT || !verbose) {
1283 LYXERR(Debug::ACTION, "dispatch msg is " << msg);
1287 docstring dispatch_msg = msg;
1288 if (!dispatch_msg.empty())
1289 dispatch_msg += ' ';
1291 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1293 bool argsadded = false;
1295 if (!cmd.argument().empty()) {
1296 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1297 comname += ' ' + cmd.argument();
1301 docstring const shortcuts = theTopLevelKeymap().
1302 printBindings(cmd, KeySequence::ForGui);
1304 if (!shortcuts.empty())
1305 comname += ": " + shortcuts;
1306 else if (!argsadded && !cmd.argument().empty())
1307 comname += ' ' + cmd.argument();
1309 if (!comname.empty()) {
1310 comname = rtrim(comname);
1311 dispatch_msg += '(' + rtrim(comname) + ')';
1313 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1314 return dispatch_msg;
1318 void GuiApplication::dispatch(FuncRequest const & cmd)
1320 Buffer * buffer = 0;
1321 if (current_view_ && current_view_->currentBufferView()) {
1322 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1323 buffer = ¤t_view_->currentBufferView()->buffer();
1325 buffer->undo().beginUndoGroup();
1329 // redraw the screen at the end (first of the two drawing steps).
1330 // This is done unless explicitly requested otherwise
1331 dr.screenUpdate(Update::FitCursor);
1333 updateCurrentView(cmd, dr);
1335 // the buffer may have been closed by one action
1336 if (theBufferList().isLoaded(buffer))
1337 buffer->undo().endUndoGroup();
1341 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1346 BufferView * bv = current_view_->currentBufferView();
1348 if (dr.needBufferUpdate()) {
1349 bv->cursor().clearBufferUpdate();
1350 bv->buffer().updateBuffer();
1352 // BufferView::update() updates the ViewMetricsInfo and
1353 // also initializes the position cache for all insets in
1354 // (at least partially) visible top-level paragraphs.
1355 // We will redraw the screen only if needed.
1356 bv->processUpdateFlags(dr.screenUpdate());
1358 // Do we have a selection?
1359 theSelection().haveSelection(bv->cursor().selection());
1362 current_view_->restartCursor();
1364 if (dr.needMessageUpdate()) {
1365 // Some messages may already be translated, so we cannot use _()
1366 current_view_->message(makeDispatchMessage(
1367 translateIfPossible(dr.message()), cmd));
1372 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1373 bool switchToBuffer)
1375 if (!theSession().bookmarks().isValid(idx))
1377 BookmarksSection::Bookmark const & bm =
1378 theSession().bookmarks().bookmark(idx);
1379 LASSERT(!bm.filename.empty(), return);
1380 string const file = bm.filename.absFileName();
1381 // if the file is not opened, open it.
1382 if (!theBufferList().exists(bm.filename)) {
1384 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1388 // open may fail, so we need to test it again
1389 if (!theBufferList().exists(bm.filename))
1392 // bm can be changed when saving
1393 BookmarksSection::Bookmark tmp = bm;
1395 // Special case idx == 0 used for back-from-back jump navigation
1397 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1399 // if the current buffer is not that one, switch to it.
1400 BufferView * doc_bv = current_view_ ?
1401 current_view_->documentBufferView() : 0;
1402 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1403 if (switchToBuffer) {
1404 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1407 doc_bv = current_view_->documentBufferView();
1412 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1413 if (!doc_bv->moveToPosition(
1414 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1421 // Cursor jump succeeded!
1422 Cursor const & cur = doc_bv->cursor();
1423 pit_type new_pit = cur.pit();
1424 pos_type new_pos = cur.pos();
1425 int new_id = cur.paragraph().id();
1427 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1428 // see http://www.lyx.org/trac/ticket/3092
1429 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1430 || bm.top_id != new_id) {
1431 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1432 new_pit, new_pos, new_id);
1436 // This function runs "configure" and then rereads lyx.defaults to
1437 // reconfigure the automatic settings.
1438 void GuiApplication::reconfigure(string const & option)
1440 // emit message signal.
1442 current_view_->message(_("Running configure..."));
1444 // Run configure in user lyx directory
1445 PathChanger p(package().user_support());
1446 string configure_command = package().configure_command();
1447 configure_command += option;
1449 int const ret = one.startscript(Systemcall::Wait, configure_command);
1451 // emit message signal.
1453 current_view_->message(_("Reloading configuration..."));
1454 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1455 // Re-read packages.lst
1456 LaTeXPackages::getAvailable();
1459 Alert::information(_("System reconfiguration failed"),
1460 _("The system reconfiguration has failed.\n"
1461 "Default textclass is used but LyX may\n"
1462 "not be able to work properly.\n"
1463 "Please reconfigure again if needed."));
1465 Alert::information(_("System reconfigured"),
1466 _("The system has been reconfigured.\n"
1467 "You need to restart LyX to make use of any\n"
1468 "updated document class specifications."));
1471 void GuiApplication::validateCurrentView()
1473 if (!d->views_.empty() && !current_view_) {
1474 // currently at least one view exists but no view has the focus.
1475 // choose the last view to make it current.
1476 // a view without any open document is preferred.
1477 GuiView * candidate = 0;
1478 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1479 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1480 for (; it != end; ++it) {
1482 if (!candidate->documentBufferView())
1485 setCurrentView(candidate);
1489 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1491 string const argument = to_utf8(cmd.argument());
1492 FuncCode const action = cmd.action();
1494 LYXERR(Debug::ACTION, "cmd: " << cmd);
1496 // we have not done anything wrong yet.
1499 FuncStatus const flag = getStatus(cmd);
1500 if (!flag.enabled()) {
1501 // We cannot use this function here
1502 LYXERR(Debug::ACTION, "action "
1503 << lyxaction.getActionName(action)
1504 << " [" << action << "] is disabled at this location");
1505 dr.setMessage(flag.message());
1507 dr.dispatched(false);
1508 dr.screenUpdate(Update::None);
1509 dr.clearBufferUpdate();
1513 if (cmd.origin() == FuncRequest::LYXSERVER) {
1514 if (current_view_ && current_view_->currentBufferView())
1515 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1516 // we will also need to redraw the screen at the end
1517 dr.screenUpdate(Update::FitCursor);
1520 // Assumes that the action will be dispatched.
1521 dr.dispatched(true);
1523 switch (cmd.action()) {
1525 case LFUN_WINDOW_NEW:
1526 createView(toqstr(cmd.argument()));
1529 case LFUN_WINDOW_CLOSE:
1530 // update bookmark pit of the current buffer before window close
1531 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1532 gotoBookmark(i+1, false, false);
1533 // clear the last opened list, because
1534 // maybe this will end the session
1535 theSession().lastOpened().clear();
1536 // check for valid current_view_
1537 validateCurrentView();
1539 current_view_->closeScheduled();
1543 // quitting is triggered by the gui code
1544 // (leaving the event loop).
1546 current_view_->message(from_utf8(N_("Exiting.")));
1547 if (closeAllViews())
1551 case LFUN_SCREEN_FONT_UPDATE: {
1552 // handle the screen font changes.
1553 d->font_loader_.update();
1554 // Backup current_view_
1555 GuiView * view = current_view_;
1556 // Set current_view_ to zero to forbid GuiWorkArea::redraw()
1557 // to skip the refresh.
1559 theBufferList().changed(false);
1560 // Restore current_view_
1561 current_view_ = view;
1565 case LFUN_BUFFER_NEW:
1566 validateCurrentView();
1567 if (d->views_.empty()
1568 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1569 createView(QString(), false); // keep hidden
1570 current_view_->newDocument(to_utf8(cmd.argument()), false);
1571 current_view_->show();
1572 setActiveWindow(current_view_);
1574 current_view_->newDocument(to_utf8(cmd.argument()), false);
1578 case LFUN_BUFFER_NEW_TEMPLATE:
1579 validateCurrentView();
1580 if (d->views_.empty()
1581 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1583 current_view_->newDocument(to_utf8(cmd.argument()), true);
1584 if (!current_view_->documentBufferView())
1585 current_view_->close();
1587 current_view_->newDocument(to_utf8(cmd.argument()), true);
1591 case LFUN_FILE_OPEN: {
1592 validateCurrentView();
1593 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1594 string const fname = to_utf8(cmd.argument());
1595 bool const is_open = FileName::isAbsolute(fname)
1596 && theBufferList().getBuffer(FileName(fname));
1597 if (d->views_.empty()
1598 || (!lyxrc.open_buffers_in_tabs
1599 && current_view_->documentBufferView() != 0
1601 // We want the ui session to be saved per document and not per
1602 // window number. The filename crc is a good enough identifier.
1603 boost::crc_32_type crc;
1604 crc = for_each(fname.begin(), fname.end(), crc);
1605 createView(crc.checksum());
1606 current_view_->openDocument(fname);
1607 if (current_view_ && !current_view_->documentBufferView())
1608 current_view_->close();
1610 current_view_->openDocument(fname);
1614 case LFUN_HELP_OPEN: {
1615 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1616 if (current_view_ == 0)
1618 string const arg = to_utf8(cmd.argument());
1620 current_view_->message(_("Missing argument"));
1623 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1625 fname = i18nLibFileSearch("examples", arg, "lyx");
1627 if (fname.empty()) {
1628 lyxerr << "LyX: unable to find documentation file `"
1629 << arg << "'. Bad installation?" << endl;
1632 current_view_->message(bformat(_("Opening help file %1$s..."),
1633 makeDisplayPath(fname.absFileName())));
1634 Buffer * buf = current_view_->loadDocument(fname, false);
1636 #ifndef DEVEL_VERSION
1638 buf->setReadonly(true);
1645 case LFUN_SET_COLOR: {
1647 string const x11_name = split(to_utf8(cmd.argument()), lyx_name, ' ');
1648 if (lyx_name.empty() || x11_name.empty()) {
1650 current_view_->message(
1651 _("Syntax: set-color <lyx_name> <x11_name>"));
1656 // FIXME: The graphics cache no longer has a changeDisplay method.
1657 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1658 bool const graphicsbg_changed =
1659 lyx_name == graphicsbg && x11_name != graphicsbg;
1660 if (graphicsbg_changed)
1661 graphics::GCache::get().changeDisplay(true);
1664 if (!lcolor.setColor(lyx_name, x11_name)) {
1666 current_view_->message(
1667 bformat(_("Set-color \"%1$s\" failed "
1668 "- color is undefined or "
1669 "may not be redefined"),
1670 from_utf8(lyx_name)));
1673 // Make sure we don't keep old colors in cache.
1674 d->color_cache_.clear();
1678 case LFUN_LYXRC_APPLY: {
1679 // reset active key sequences, since the bindings
1680 // are updated (bug 6064)
1682 LyXRC const lyxrc_orig = lyxrc;
1684 istringstream ss(to_utf8(cmd.argument()));
1685 bool const success = lyxrc.read(ss);
1688 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1689 << "Unable to read lyxrc data"
1694 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1696 // If the request comes from the minibuffer, then we can't reset
1697 // the GUI, since that would destory the minibuffer itself and
1698 // cause a crash, since we are currently in one of the methods of
1699 // GuiCommandBuffer. See bug #8540.
1700 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1703 // FIXME Unfortunately, that leaves a bug here, since we cannot
1704 // reset the GUI in this case. If the changes to lyxrc affected the
1705 // UI, then, nothing would happen. This seems fairly unlikely, but
1706 // it definitely is a bug.
1711 case LFUN_COMMAND_PREFIX:
1712 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1717 d->meta_fake_bit = NoModifier;
1718 GuiView * gv = currentView();
1719 if (gv && gv->currentBufferView())
1720 // cancel any selection
1721 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1722 dr.setMessage(from_ascii(N_("Cancel")));
1725 case LFUN_META_PREFIX:
1726 d->meta_fake_bit = AltModifier;
1727 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1730 // --- Menus -----------------------------------------------
1731 case LFUN_RECONFIGURE:
1732 // argument is any additional parameter to the configure.py command
1733 reconfigure(to_utf8(cmd.argument()));
1736 // --- lyxserver commands ----------------------------
1737 case LFUN_SERVER_GET_FILENAME: {
1738 if (current_view_ && current_view_->documentBufferView()) {
1739 docstring const fname = from_utf8(
1740 current_view_->documentBufferView()->buffer().absFileName());
1741 dr.setMessage(fname);
1742 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1744 dr.setMessage(docstring());
1745 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1750 case LFUN_SERVER_NOTIFY: {
1751 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1752 dr.setMessage(dispatch_buffer);
1753 theServer().notifyClient(to_utf8(dispatch_buffer));
1757 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1758 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1764 string rest = split(argument, countstr, ' ');
1765 istringstream is(countstr);
1768 //lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1769 for (int i = 0; i < count; ++i)
1770 dispatch(lyxaction.lookupFunc(rest));
1774 case LFUN_COMMAND_SEQUENCE: {
1775 // argument contains ';'-terminated commands
1776 string arg = argument;
1777 // FIXME: this LFUN should also work without any view.
1778 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1779 ? &(current_view_->documentBufferView()->buffer()) : 0;
1781 buffer->undo().beginUndoGroup();
1782 while (!arg.empty()) {
1784 arg = split(arg, first, ';');
1785 FuncRequest func(lyxaction.lookupFunc(first));
1786 func.setOrigin(cmd.origin());
1789 // the buffer may have been closed by one action
1790 if (theBufferList().isLoaded(buffer))
1791 buffer->undo().endUndoGroup();
1795 case LFUN_BUFFER_FORALL: {
1796 FuncRequest const funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1798 map<Buffer *, GuiView *> views_lVisible;
1799 map<GuiView *, Buffer *> activeBuffers;
1801 QList<GuiView *> allViews = d->views_.values();
1803 // this foreach does not modify any buffer. It just collects info on local visibility of buffers
1804 // and on which buffer is active in each view.
1805 Buffer * const last = theBufferList().last();
1806 foreach (GuiView * view, allViews) {
1807 // all of the buffers might be locally hidden. That is, there is no active buffer.
1808 if (!view || !view->currentBufferView() || !&view->currentBufferView()->buffer())
1809 activeBuffers[view] = 0;
1811 activeBuffers[view] = &view->currentBufferView()->buffer();
1813 // find out if each is locally visible or locally hidden.
1814 // we don't use a for loop as the buffer list cycles.
1815 Buffer * b = theBufferList().first();
1817 bool const locallyVisible = view && view->workArea(*b);
1818 if (locallyVisible) {
1819 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1820 // only need to overwrite/add if we don't already know a buffer is globally
1821 // visible or we do know but we would prefer to dispatch LFUN from the
1822 // current view because of cursor position issues.
1823 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1824 views_lVisible[b] = view;
1828 b = theBufferList().next(b);
1832 GuiView * const homeView = currentView();
1833 Buffer * b = theBufferList().first();
1834 Buffer * nextBuf = 0;
1835 int numProcessed = 0;
1838 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1840 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1842 // first change to a view where b is locally visible, preferably current_view_.
1843 GuiView * const vLv = views_lVisible[b];
1845 lyx::dispatch(funcToRun);
1853 // put things back to how they were (if possible).
1854 foreach (GuiView * view, allViews) {
1855 Buffer * originalBuf = activeBuffers[view];
1856 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1857 if (theBufferList().isLoaded(originalBuf))
1858 view->setBuffer(originalBuf);
1860 homeView->setFocus();
1862 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1866 case LFUN_COMMAND_ALTERNATIVES: {
1867 // argument contains ';'-terminated commands
1868 string arg = argument;
1869 while (!arg.empty()) {
1871 arg = split(arg, first, ';');
1872 FuncRequest func(lyxaction.lookupFunc(first));
1873 func.setOrigin(cmd.origin());
1874 FuncStatus const stat = getStatus(func);
1875 if (stat.enabled()) {
1885 if (theTopLevelCmdDef().lock(argument, func)) {
1886 func.setOrigin(cmd.origin());
1888 theTopLevelCmdDef().release(argument);
1890 if (func.action() == LFUN_UNKNOWN_ACTION) {
1891 // unknown command definition
1892 lyxerr << "Warning: unknown command definition `"
1896 // recursion detected
1897 lyxerr << "Warning: Recursion in the command definition `"
1898 << argument << "' detected"
1905 case LFUN_PREFERENCES_SAVE:
1906 lyxrc.write(support::makeAbsPath("preferences",
1907 package().user_support().absFileName()), false);
1910 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
1911 string const fname = addName(addPath(package().user_support().absFileName(),
1912 "templates/"), "defaults.lyx");
1913 Buffer defaults(fname);
1915 istringstream ss(argument);
1918 int const unknown_tokens = defaults.readHeader(lex);
1920 if (unknown_tokens != 0) {
1921 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
1922 << unknown_tokens << " unknown token"
1923 << (unknown_tokens == 1 ? "" : "s")
1927 if (defaults.writeFile(FileName(defaults.absFileName())))
1928 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
1929 makeDisplayPath(fname)));
1932 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
1937 case LFUN_BOOKMARK_GOTO:
1938 // go to bookmark, open unopened file and switch to buffer if necessary
1939 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
1940 dr.screenUpdate(Update::Force | Update::FitCursor);
1943 case LFUN_BOOKMARK_CLEAR:
1944 theSession().bookmarks().clear();
1947 case LFUN_DEBUG_LEVEL_SET:
1948 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
1951 case LFUN_DIALOG_SHOW: {
1952 string const name = cmd.getArg(0);
1954 if ( name == "aboutlyx"
1956 || name == "texinfo"
1957 || name == "progress"
1958 || name == "compare")
1960 // work around: on Mac OS the application
1961 // is not terminated when closing the last view.
1962 // Create a new one to be able to dispatch the
1963 // LFUN_DIALOG_SHOW to this view.
1964 if (current_view_ == 0)
1970 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
1973 current_view_->dispatch(cmd, dr);
1977 if (cmd.origin() == FuncRequest::LYXSERVER)
1978 updateCurrentView(cmd, dr);
1982 docstring GuiApplication::viewStatusMessage()
1984 // When meta-fake key is pressed, show the key sequence so far + "M-".
1985 if (d->meta_fake_bit != NoModifier)
1986 return d->keyseq.print(KeySequence::ForGui) + "M-";
1988 // Else, when a non-complete key sequence is pressed,
1989 // show the available options.
1990 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
1991 return d->keyseq.printOptions(true);
1997 void GuiApplication::handleKeyFunc(FuncCode action)
2001 if (d->keyseq.length())
2003 GuiView * gv = currentView();
2004 LASSERT(gv && gv->currentBufferView(), return);
2005 BufferView * bv = gv->currentBufferView();
2006 bv->getIntl().getTransManager().deadkey(
2007 c, get_accent(action).accent, bv->cursor().innerText(),
2009 // Need to clear, in case the minibuffer calls these
2012 // copied verbatim from do_accent_char
2013 bv->cursor().resetAnchor();
2017 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2019 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2021 // Do nothing if we have nothing (JMarc)
2022 if (!keysym.isOK()) {
2023 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2025 current_view_->restartCursor();
2029 if (keysym.isModifier()) {
2031 current_view_->restartCursor();
2035 char_type encoded_last_key = keysym.getUCSEncoded();
2037 // Do a one-deep top-level lookup for
2038 // cancel and meta-fake keys. RVDK_PATCH_5
2039 d->cancel_meta_seq.reset();
2041 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2042 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2044 // When not cancel or meta-fake, do the normal lookup.
2045 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2046 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2047 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2048 // remove Caps Lock and Mod2 as a modifiers
2049 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2050 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2053 // Dont remove this unless you know what you are doing.
2054 d->meta_fake_bit = NoModifier;
2056 // Can this happen now ?
2057 if (func.action() == LFUN_NOACTION)
2058 func = FuncRequest(LFUN_COMMAND_PREFIX);
2060 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2061 << d->keyseq.print(KeySequence::Portable) << ']');
2063 // already here we know if it any point in going further
2064 // why not return already here if action == -1 and
2065 // num_bytes == 0? (Lgb)
2067 if (d->keyseq.length() > 1 && current_view_)
2068 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2071 // Maybe user can only reach the key via holding down shift.
2072 // Let's see. But only if shift is the only modifier
2073 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2074 LYXERR(Debug::KEY, "Trying without shift");
2075 func = d->keyseq.addkey(keysym, NoModifier);
2076 LYXERR(Debug::KEY, "Action now " << func.action());
2079 if (func.action() == LFUN_UNKNOWN_ACTION) {
2080 // Hmm, we didn't match any of the keysequences. See
2081 // if it's normal insertable text not already covered
2083 if (keysym.isText() && d->keyseq.length() == 1) {
2084 LYXERR(Debug::KEY, "isText() is true, inserting.");
2085 func = FuncRequest(LFUN_SELF_INSERT,
2086 FuncRequest::KEYBOARD);
2088 LYXERR(Debug::KEY, "Unknown, !isText() - giving up");
2089 if (current_view_) {
2090 current_view_->message(_("Unknown function."));
2091 current_view_->restartCursor();
2097 if (func.action() == LFUN_SELF_INSERT) {
2098 if (encoded_last_key != 0) {
2099 docstring const arg(1, encoded_last_key);
2100 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2101 FuncRequest::KEYBOARD));
2102 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2105 processFuncRequest(func);
2109 void GuiApplication::processFuncRequest(FuncRequest const & func)
2111 lyx::dispatch(func);
2115 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2117 addToFuncRequestQueue(func);
2118 processFuncRequestQueueAsync();
2122 void GuiApplication::processFuncRequestQueue()
2124 while (!d->func_request_queue_.empty()) {
2125 processFuncRequest(d->func_request_queue_.front());
2126 d->func_request_queue_.pop();
2131 void GuiApplication::processFuncRequestQueueAsync()
2133 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2137 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2139 d->func_request_queue_.push(func);
2143 void GuiApplication::resetGui()
2145 // Set the language defined by the user.
2149 if (!readUIFile(toqstr(lyxrc.ui_file)))
2150 // Gives some error box here.
2153 if (d->global_menubar_)
2154 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2156 QHash<int, GuiView *>::iterator it;
2157 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2160 gv->setLayoutDirection(layoutDirection());
2164 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2168 void GuiApplication::createView(int view_id)
2170 createView(QString(), true, view_id);
2174 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2177 // release the keyboard which might have been grabed by the global
2178 // menubar on Mac to catch shortcuts even without any GuiView.
2179 if (d->global_menubar_)
2180 d->global_menubar_->releaseKeyboard();
2184 while (d->views_.find(id) != d->views_.end())
2187 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2188 GuiView * view = new GuiView(id);
2190 d->views_[id] = view;
2194 setActiveWindow(view);
2197 if (!geometry_arg.isEmpty()) {
2201 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)([+-][0-9]*)){0,1}" );
2202 re.indexIn(geometry_arg);
2203 w = re.cap(1).toInt();
2204 h = re.cap(2).toInt();
2205 x = re.cap(3).toInt();
2206 y = re.cap(4).toInt();
2207 view->setGeometry(x, y, w, h);
2214 Clipboard & GuiApplication::clipboard()
2216 return d->clipboard_;
2220 Selection & GuiApplication::selection()
2222 return d->selection_;
2226 FontLoader & GuiApplication::fontLoader()
2228 return d->font_loader_;
2232 Toolbars const & GuiApplication::toolbars() const
2234 return d->toolbars_;
2238 Toolbars & GuiApplication::toolbars()
2240 return d->toolbars_;
2244 Menus const & GuiApplication::menus() const
2250 Menus & GuiApplication::menus()
2256 QList<int> GuiApplication::viewIds() const
2258 return d->views_.keys();
2262 ColorCache & GuiApplication::colorCache()
2264 return d->color_cache_;
2268 int GuiApplication::exec()
2270 // asynchronously handle batch commands. This event will be in
2271 // the event queue in front of other asynchronous events. Hence,
2272 // we can assume in the latter that the gui is setup already.
2273 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2275 return QApplication::exec();
2279 void GuiApplication::exit(int status)
2281 QApplication::exit(status);
2285 void GuiApplication::setGuiLanguage()
2289 // install translation file for Qt built-in dialogs
2290 QString const language_name = QString("qt_") + theLocale.name();
2291 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2292 // Short-named translator can be loaded from a long name, but not the
2293 // opposite. Therefore, long name should be used without truncation.
2294 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2295 if (!d->qt_trans_.load(language_name,
2296 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2297 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2300 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2304 switch (theLocale.language()) {
2305 case QLocale::Arabic :
2306 case QLocale::Hebrew :
2307 case QLocale::Persian :
2308 case QLocale::Urdu :
2309 setLayoutDirection(Qt::RightToLeft);
2312 setLayoutDirection(Qt::LeftToRight);
2317 void GuiApplication::execBatchCommands()
2322 if (!readUIFile(toqstr(lyxrc.ui_file)))
2323 // Gives some error box here.
2327 #if QT_VERSION > 0x040600
2328 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2330 // Create the global default menubar which is shown for the dialogs
2331 // and if no GuiView is visible.
2332 // This must be done after the session was recovered to know the "last files".
2333 d->global_menubar_ = new GlobalMenuBar;
2334 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2337 lyx::execBatchCommands();
2341 QAbstractItemModel * GuiApplication::languageModel()
2343 if (d->language_model_)
2344 return d->language_model_;
2346 QStandardItemModel * lang_model = new QStandardItemModel(this);
2347 lang_model->insertColumns(0, 3);
2349 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "png"));
2350 QIcon saurus(getPixmap("images/", "thesaurus-entry", "png"));
2351 Languages::const_iterator it = lyx::languages.begin();
2352 Languages::const_iterator end = lyx::languages.end();
2353 for (; it != end; ++it) {
2354 current_row = lang_model->rowCount();
2355 lang_model->insertRows(current_row, 1);
2356 QModelIndex pl_item = lang_model->index(current_row, 0);
2357 QModelIndex sp_item = lang_model->index(current_row, 1);
2358 QModelIndex th_item = lang_model->index(current_row, 2);
2359 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2360 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2361 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2362 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2363 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2364 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2365 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2366 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2367 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2368 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2370 d->language_model_ = new QSortFilterProxyModel(this);
2371 d->language_model_->setSourceModel(lang_model);
2372 d->language_model_->setSortLocaleAware(true);
2373 return d->language_model_;
2377 void GuiApplication::restoreGuiSession()
2379 if (!lyxrc.load_session)
2382 Session & session = theSession();
2383 LastOpenedSection::LastOpened const & lastopened =
2384 session.lastOpened().getfiles();
2386 validateCurrentView();
2388 FileName active_file;
2389 // do not add to the lastfile list since these files are restored from
2390 // last session, and should be already there (regular files), or should
2391 // not be added at all (help files).
2392 for (size_t i = 0; i < lastopened.size(); ++i) {
2393 FileName const & file_name = lastopened[i].file_name;
2394 if (d->views_.empty() || (!lyxrc.open_buffers_in_tabs
2395 && current_view_->documentBufferView() != 0)) {
2396 boost::crc_32_type crc;
2397 string const & fname = file_name.absFileName();
2398 crc = for_each(fname.begin(), fname.end(), crc);
2399 createView(crc.checksum());
2401 current_view_->loadDocument(file_name, false);
2403 if (lastopened[i].active)
2404 active_file = file_name;
2407 // Restore last active buffer
2408 Buffer * buffer = theBufferList().getBuffer(active_file);
2409 if (buffer && current_view_)
2410 current_view_->setBuffer(buffer);
2412 // clear this list to save a few bytes of RAM
2413 session.lastOpened().clear();
2417 QString const GuiApplication::romanFontName()
2420 font.setStyleHint(QFont::Serif);
2421 font.setFamily("serif");
2423 return QFontInfo(font).family();
2427 QString const GuiApplication::sansFontName()
2430 font.setStyleHint(QFont::SansSerif);
2431 font.setFamily("sans");
2433 return QFontInfo(font).family();
2437 QString const GuiApplication::typewriterFontName()
2440 font.setStyleHint(QFont::TypeWriter);
2441 font.setFamily("monospace");
2443 return QFontInfo(font).family();
2447 void GuiApplication::handleRegularEvents()
2449 ForkedCallsController::handleCompletedProcesses();
2453 bool GuiApplication::event(QEvent * e)
2456 case QEvent::FileOpen: {
2457 // Open a file; this happens only on Mac OS X for now.
2459 // We do this asynchronously because on startup the batch
2460 // commands are not executed here yet and the gui is not ready
2462 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2463 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2464 processFuncRequestAsync(fr);
2469 return QApplication::event(e);
2474 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2477 return QApplication::notify(receiver, event);
2479 catch (ExceptionMessage const & e) {
2481 case ErrorException:
2483 setQuitOnLastWindowClosed(false);
2485 Alert::error(e.title_, e.details_);
2487 // Properly crash in debug mode in order to get a useful backtrace.
2490 // In release mode, try to exit gracefully.
2493 case BufferException: {
2494 if (!current_view_ || !current_view_->documentBufferView())
2496 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2497 docstring details = e.details_ + '\n';
2498 details += buf->emergencyWrite();
2499 theBufferList().release(buf);
2500 details += "\n" + _("The current document was closed.");
2501 Alert::error(e.title_, details);
2504 case WarningException:
2505 Alert::warning(e.title_, e.details_);
2509 catch (exception const & e) {
2510 docstring s = _("LyX has caught an exception, it will now "
2511 "attempt to save all unsaved documents and exit."
2513 s += from_ascii(e.what());
2514 Alert::error(_("Software exception Detected"), s);
2518 docstring s = _("LyX has caught some really weird exception, it will "
2519 "now attempt to save all unsaved documents and exit.");
2520 Alert::error(_("Software exception Detected"), s);
2528 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2530 QColor const & qcol = d->color_cache_.get(col);
2531 if (!qcol.isValid()) {
2537 rgbcol.r = qcol.red();
2538 rgbcol.g = qcol.green();
2539 rgbcol.b = qcol.blue();
2544 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2546 QColor const qcol(lcolor.getX11Name(col).c_str());
2547 if (!qcol.isValid()) {
2553 rgbcol.r = qcol.red();
2554 rgbcol.g = qcol.green();
2555 rgbcol.b = qcol.blue();
2560 string const GuiApplication::hexName(ColorCode col)
2562 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2566 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2568 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2569 d->socket_notifiers_[fd] = sn;
2570 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2574 void GuiApplication::socketDataReceived(int fd)
2576 d->socket_notifiers_[fd]->func_();
2580 void GuiApplication::unregisterSocketCallback(int fd)
2582 d->socket_notifiers_.take(fd)->setEnabled(false);
2586 void GuiApplication::commitData(QSessionManager & sm)
2588 /// The implementation is required to avoid an application exit
2589 /// when session state save is triggered by session manager.
2590 /// The default implementation sends a close event to all
2591 /// visible top level widgets when session managment allows
2593 /// We are changing that to close all wiew one by one.
2594 /// FIXME: verify if the default implementation is enough now.
2595 #ifdef QT_NO_SESSIONMANAGER
2597 #warning Qt is compiled without session manager
2599 #pragma message("warning: Qt is compiled without session manager")
2603 if (sm.allowsInteraction() && !closeAllViews())
2609 void GuiApplication::unregisterView(GuiView * gv)
2611 LAPPERR(d->views_[gv->id()] == gv);
2612 d->views_.remove(gv->id());
2613 if (current_view_ == gv)
2618 bool GuiApplication::closeAllViews()
2620 if (d->views_.empty())
2623 // When a view/window was closed before without quitting LyX, there
2624 // are already entries in the lastOpened list.
2625 theSession().lastOpened().clear();
2627 QList<GuiView *> const views = d->views_.values();
2628 foreach (GuiView * view, views) {
2629 if (!view->closeScheduled())
2638 GuiView & GuiApplication::view(int id) const
2640 LAPPERR(d->views_.contains(id));
2641 return *d->views_.value(id);
2645 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2647 QList<GuiView *> const views = d->views_.values();
2648 foreach (GuiView * view, views)
2649 view->hideDialog(name, inset);
2653 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2655 Buffer const * buffer_ = 0;
2656 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2657 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2658 if (Buffer const * ptr = (*it)->updateInset(inset))
2665 bool GuiApplication::searchMenu(FuncRequest const & func,
2666 docstring_list & names) const
2668 return d->menus_.searchMenu(func, names);
2672 // Ensure that a file is read only once (prevents include loops)
2673 static QStringList uifiles;
2674 // store which ui files define Toolbars
2675 static QStringList toolbar_uifiles;
2678 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
2689 LexerKeyword uitags[] = {
2690 { "format", ui_format },
2691 { "include", ui_include },
2692 { "menuset", ui_menuset },
2693 { "toolbars", ui_toolbars },
2694 { "toolbarset", ui_toolbarset }
2698 lex.setFile(ui_path);
2700 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
2704 if (lyxerr.debugging(Debug::PARSER))
2705 lex.printTable(lyxerr);
2708 // format before introduction of format tag
2709 unsigned int format = 0;
2710 while (lex.isOK()) {
2711 int const status = lex.lex();
2713 // we have to do this check here, outside the switch,
2714 // because otherwise we would start reading include files,
2715 // e.g., if the first tag we hit was an include tag.
2716 if (status == ui_format)
2718 format = lex.getInteger();
2722 // this will trigger unless the first tag we hit is a format
2723 // tag, with the right format.
2724 if (format != LFUN_FORMAT)
2725 return FormatMismatch;
2728 case Lexer::LEX_FEOF:
2733 QString const file = toqstr(lex.getString());
2734 bool const success = readUIFile(file, true);
2736 LYXERR0("Failed to read inlcuded file: " << fromqstr(file));
2743 d->menus_.read(lex);
2747 d->toolbars_.readToolbars(lex);
2751 d->toolbars_.readToolbarSettings(lex);
2752 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
2756 if (!rtrim(lex.getString()).empty())
2757 lex.printError("LyX::ReadUIFile: "
2758 "Unknown menu tag: `$$Token'");
2760 LYXERR0("Error with status: " << status);
2766 return (error ? ReadError : ReadOK);
2770 bool GuiApplication::readUIFile(QString const & name, bool include)
2772 LYXERR(Debug::INIT, "About to read " << name << "...");
2776 ui_path = libFileSearch("ui", name, "inc");
2777 if (ui_path.empty())
2778 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
2780 ui_path = libFileSearch("ui", name, "ui");
2783 if (ui_path.empty()) {
2784 static const QString defaultUIFile = "default";
2785 LYXERR(Debug::INIT, "Could not find " << name);
2787 Alert::warning(_("Could not find UI definition file"),
2788 bformat(_("Error while reading the included file\n%1$s\n"
2789 "Please check your installation."), qstring_to_ucs4(name)));
2792 if (name == defaultUIFile) {
2793 LYXERR(Debug::INIT, "Could not find default UI file!!");
2794 Alert::warning(_("Could not find default UI file"),
2795 _("LyX could not find the default UI file!\n"
2796 "Please check your installation."));
2799 Alert::warning(_("Could not find UI definition file"),
2800 bformat(_("Error while reading the configuration file\n%1$s\n"
2801 "Falling back to default.\n"
2802 "Please look under Tools>Preferences>User Interface and\n"
2803 "check which User Interface file you are using."), qstring_to_ucs4(name)));
2804 return readUIFile(defaultUIFile, false);
2807 QString const uifile = toqstr(ui_path.absFileName());
2808 if (uifiles.contains(uifile)) {
2810 // We are reading again the top uifile so reset the safeguard:
2813 d->toolbars_.reset();
2815 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
2816 << "Is this an include loop?");
2820 uifiles.push_back(uifile);
2822 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
2824 ReturnValues retval = readUIFile(ui_path);
2826 if (retval == FormatMismatch) {
2827 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
2828 TempFile tmp("convertXXXXXX.ui");
2829 FileName const tempfile = tmp.name();
2830 bool const success = prefs2prefs(ui_path, tempfile, true);
2832 LYXERR0("Unable to convert " << ui_path.absFileName() <<
2833 " to format " << LFUN_FORMAT << ".");
2835 retval = readUIFile(tempfile);
2839 if (retval != ReadOK) {
2840 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
2848 settings.beginGroup("ui_files");
2849 bool touched = false;
2850 for (int i = 0; i != uifiles.size(); ++i) {
2851 QFileInfo fi(uifiles[i]);
2852 QDateTime const date_value = fi.lastModified();
2853 QString const name_key = QString::number(i);
2854 // if an ui file which defines Toolbars has changed,
2855 // we have to reset the settings
2856 if (toolbar_uifiles.contains(uifiles[i])
2857 && (!settings.contains(name_key)
2858 || settings.value(name_key).toString() != uifiles[i]
2859 || settings.value(name_key + "/date").toDateTime() != date_value)) {
2861 settings.setValue(name_key, uifiles[i]);
2862 settings.setValue(name_key + "/date", date_value);
2865 settings.endGroup();
2867 settings.remove("views");
2873 void GuiApplication::onLastWindowClosed()
2875 if (d->global_menubar_)
2876 d->global_menubar_->grabKeyboard();
2880 void GuiApplication::startLongOperation() {
2881 d->key_checker_.start();
2885 bool GuiApplication::longOperationCancelled() {
2886 return d->key_checker_.pressed();
2890 void GuiApplication::stopLongOperation() {
2891 d->key_checker_.stop();
2895 bool GuiApplication::longOperationStarted() {
2896 return d->key_checker_.started();
2900 ////////////////////////////////////////////////////////////////////////
2902 // X11 specific stuff goes here...
2905 bool GuiApplication::x11EventFilter(XEvent * xev)
2910 switch (xev->type) {
2911 case SelectionRequest: {
2912 if (xev->xselectionrequest.selection != XA_PRIMARY)
2914 LYXERR(Debug::SELECTION, "X requested selection.");
2915 BufferView * bv = current_view_->currentBufferView();
2917 docstring const sel = bv->requestSelection();
2919 d->selection_.put(sel);
2923 case SelectionClear: {
2924 if (xev->xselectionclear.selection != XA_PRIMARY)
2926 LYXERR(Debug::SELECTION, "Lost selection.");
2927 BufferView * bv = current_view_->currentBufferView();
2929 bv->clearSelection();
2937 } // namespace frontend
2940 void hideDialogs(std::string const & name, Inset * inset)
2943 frontend::guiApp->hideDialogs(name, inset);
2947 ////////////////////////////////////////////////////////////////////
2951 ////////////////////////////////////////////////////////////////////
2953 frontend::FontLoader & theFontLoader()
2955 LAPPERR(frontend::guiApp);
2956 return frontend::guiApp->fontLoader();
2960 frontend::FontMetrics const & theFontMetrics(Font const & f)
2962 return theFontMetrics(f.fontInfo());
2966 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
2968 LAPPERR(frontend::guiApp);
2969 return frontend::guiApp->fontLoader().metrics(f);
2973 ////////////////////////////////////////////////////////////////////
2977 ////////////////////////////////////////////////////////////////////
2979 frontend::Clipboard & theClipboard()
2981 LAPPERR(frontend::guiApp);
2982 return frontend::guiApp->clipboard();
2986 frontend::Selection & theSelection()
2988 LAPPERR(frontend::guiApp);
2989 return frontend::guiApp->selection();
2995 #include "moc_GuiApplication.cpp"