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 "ToolTipFormatter.h"
18 #include "ColorCache.h"
20 #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 "BufferParams.h"
36 #include "BufferView.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
49 #include "LaTeXPackages.h"
52 #include "LyXAction.h"
54 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
61 #include "insets/InsetText.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/AppleSupport.h"
82 #include "support/linkback/LinkBackProxy.h"
90 #include <QDesktopWidget>
93 #include <QFileOpenEvent>
95 #include <QFontDatabase>
98 #include <QImageReader>
101 #include <QLibraryInfo>
108 #include <QSessionManager>
110 #include <QSocketNotifier>
111 #include <QSortFilterProxyModel>
112 #include <QStandardItemModel>
114 #include <QTranslator>
115 #include <QThreadPool>
119 #include <X11/Xatom.h>
120 #include <X11/Xlib.h>
124 #elif defined(QPA_XCB)
126 #ifdef HAVE_QT5_X11_EXTRAS
127 #include <QtX11Extras/QX11Info>
131 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
132 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
133 #if (QT_VERSION < 0x050000)
134 #include <QWindowsMime>
135 #define QWINDOWSMIME QWindowsMime
138 #define QWINDOWSMIME QWinMime
148 #include <QMacPasteboardMime>
151 #include <boost/crc.hpp>
158 using namespace lyx::support;
163 frontend::Application * createApplication(int & argc, char * argv[])
165 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
166 // prune -geometry argument(s) by shifting
167 // the following ones 2 places down.
168 for (int i = 0 ; i < argc ; ++i) {
169 if (strcmp(argv[i], "-geometry") == 0) {
170 int const remove = (i+1) < argc ? 2 : 1;
172 for (int j = i; j < argc; ++j)
173 argv[j] = argv[j + remove];
179 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
180 // On Windows, allow bringing the LyX window to top
181 AllowSetForegroundWindow(ASFW_ANY);
184 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
185 // I'd rather do that in the constructor, but I do not think that
186 // the palette is accessible there.
187 guiApp->colorCache().setPalette(guiApp->palette());
196 if (lyxrc.gui_language == "auto") {
197 theLocale = QLocale::system();
198 code = fromqstr(theLocale.name());
200 Language const * l = languages.getLanguage(lyxrc.gui_language);
201 code = l ? l->code() : "C";
202 theLocale = QLocale(toqstr(code));
204 // Qt tries to outsmart us and transforms en_US to C.
205 Messages::guiLanguage((code == "C") ? "en_US" : code);
206 QLocale::setDefault(theLocale);
207 setlocale(LC_NUMERIC, "C");
214 /// Return the list of loadable formats.
215 vector<string> loadableImageFormats()
219 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
221 LYXERR(Debug::GRAPHICS,
222 "\nThe image loader can load the following directly:\n");
224 if (qt_formats.empty())
225 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
227 bool jpeg_found = false;
228 bool jpg_found = false;
229 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
231 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
233 string ext = ascii_lowercase((const char *) *it);
241 else if (ext == "jpg") {
246 else if (lyxrc.use_converter_cache &&
247 (ext == "svg" || ext == "svgz") &&
248 theConverters().isReachable("svg", "png"))
249 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
250 // the SVG as in the output. However we require that the converter
251 // cache is enabled since this is expensive. We also require that
252 // an explicit svg->png converter is defined, since the default
253 // converter could produce bad quality as well. This assumes that
254 // png can always be loaded.
263 ////////////////////////////////////////////////////////////////////////
265 // Icon loading support code
267 ////////////////////////////////////////////////////////////////////////
277 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
279 return lhs.key < rhs.key;
285 CompareKey(QString const & name) : name_(name) {}
286 bool operator()(ImgMap const & other) const { return other.key == name_; }
292 // this must be sorted alphabetically
293 // Upper case comes before lower case
294 // Please don't change the formatting, this list is parsed by
295 // development/tools/generate_symbols_images.py.
296 ImgMap sorted_img_map[] = {
297 { "Arrownot", "arrownot2"},
298 { "Arrowvert", "arrowvert2"},
299 { "Bowtie", "bowtie2" },
301 { "Bumpeq", "bumpeq2" },
302 { "CIRCLE", "circle3" },
304 { "CheckedBox", "checkedbox2" },
305 { "Circle", "circle2" },
306 { "Colonapprox", "colonapprox2" },
307 { "Coloneq", "coloneq2" },
308 { "Coloneqq", "coloneqq2" },
309 { "Colonsim", "colonsim2" },
311 { "DOWNarrow", "downarrow3" },
312 { "Delta", "delta2" },
313 { "Diamond", "diamond2" },
314 { "Doteq", "doteq2" },
315 { "Downarrow", "downarrow2" },
316 { "Eqcolon", "eqcolon2" },
317 { "Eqqcolon", "eqqcolon2" },
318 { "Gamma", "gamma2" },
320 { "LEFTCIRCLE", "leftcircle3" },
321 { "LEFTarrow", "leftarrow3" },
322 { "LEFTcircle", "leftcircle4" },
324 { "Lambda", "lambda2" },
326 { "Leftarrow", "leftarrow2" },
327 { "Leftcircle", "leftcircle2" },
328 { "Leftrightarrow", "leftrightarrow2" },
329 { "Longarrownot", "longarrownot2"},
330 { "Longleftarrow", "longleftarrow2" },
331 { "Longleftrightarrow", "longleftrightarrow2" },
332 { "Longmapsfrom", "longmapsfrom2"},
333 { "Longmapsto", "longmapsto2"},
334 { "Longrightarrow", "longrightarrow2" },
335 { "Mapsfrom", "mapsfrom2"},
336 { "Mapsfromchar", "mapsfromchar2"},
337 { "Mapsto", "mapsto2"},
338 { "Mapstochar", "mapstochar2"},
339 { "Omega", "omega2" },
344 { "RIGHTCIRCLE", "rightcircle3" },
345 { "RIGHTarrow", "rightarrow3" },
346 { "RIGHTcircle", "rightcircle4" },
348 { "Rightarrow", "rightarrow2" },
349 { "Rightcircle", "rightcircle2" },
350 { "Sigma", "sigma2" },
351 { "Square", "square2" },
352 { "Subset", "subset2" },
353 { "Supset", "supset2" },
354 { "Theta", "theta2" },
355 { "Thorn", "thorn2" },
356 { "UParrow", "uparrow3" },
357 { "Uparrow", "uparrow2" },
358 { "Updownarrow", "updownarrow2" },
359 { "Upsilon", "upsilon2" },
360 { "Vdash", "vdash3" },
365 { "lVert", "vert2" },
367 { "nLeftarrow", "nleftarrow2" },
368 { "nLeftrightarrow", "nleftrightarrow2" },
369 { "nRightarrow", "nrightarrow2" },
370 { "nVDash", "nvdash3" },
371 { "nVdash", "nvdash4" },
372 { "nvDash", "nvdash2" },
373 { "rVert", "vert2" },
375 { "textrm \\AA", "textrm_AA"},
376 { "textrm \\O", "textrm_O"},
377 { "vDash", "vdash2" },
378 { "varDelta", "vardelta2" },
379 { "varGamma", "vargamma2" },
380 { "varLambda", "varlambda2" },
381 { "varOmega", "varomega2" },
382 { "varPhi", "varphi2" },
383 { "varPi", "varpi2" },
384 { "varPsi", "varpsi2" },
385 { "varSigma", "varsigma2" },
386 { "varTheta", "vartheta2" },
387 { "varUpsilon", "varupsilon2" },
388 { "varXi", "varxi2" }
392 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
394 // This list specifies which system's theme icon is related to which lyx
395 // command. It was based on:
396 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
397 // this must be sorted alphabetically
398 // Upper case comes before lower case
399 ImgMap sorted_theme_icon_map[] = {
400 { "bookmark-goto 0", "go-jump" },
401 { "buffer-new", "document-new" },
402 { "buffer-write", "document-save" },
403 { "buffer-write-as", "document-save-as" },
404 { "buffer-zoom-in", "zoom-in" },
405 { "buffer-zoom-out", "zoom-out" },
406 { "copy", "edit-copy" },
407 { "cut", "edit-cut" },
408 { "depth-decrement", "format-indent-less" },
409 { "depth-increment", "format-indent-more" },
410 { "dialog-show spellchecker", "tools-check-spelling" },
411 { "dialog-show-new-inset graphics", "insert-image" },
412 { "dialog-toggle findreplaceadv", "edit-find-replace" },
413 { "file-open", "document-open" },
414 { "font-bold", "format-text-bold" },
415 { "font-ital", "format-text-italic" },
416 { "font-strikeout", "format-text-strikethrough" },
417 { "font-underline", "format-text-underline" },
418 { "lyx-quit", "application-exit" },
419 { "paste", "edit-paste" },
420 { "redo", "edit-redo" },
421 { "undo", "edit-undo" },
422 { "window-close", "window-close" },
423 { "window-new", "window-new" }
426 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
429 QString findImg(QString const & name)
431 ImgMap const * const begin = sorted_img_map;
432 ImgMap const * const end = begin + nr_sorted_img_map;
433 LATTEST(sorted(begin, end));
435 ImgMap const * const it = find_if(begin, end, CompareKey(name));
439 img_name = it->value;
442 img_name.replace('_', "underscore");
443 img_name.replace(' ', '_');
445 // This way we can have "math-delim { }" on the toolbar.
446 img_name.replace('(', "lparen");
447 img_name.replace(')', "rparen");
448 img_name.replace('[', "lbracket");
449 img_name.replace(']', "rbracket");
450 img_name.replace('{', "lbrace");
451 img_name.replace('}', "rbrace");
452 img_name.replace('|', "bars");
453 img_name.replace(',', "thinspace");
454 img_name.replace(':', "mediumspace");
455 img_name.replace(';', "thickspace");
456 img_name.replace('!', "negthinspace");
459 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
460 << "Looking for math icon called \"" << img_name << '"');
467 QString themeIconName(QString const & action)
469 ImgMap const * const begin = sorted_theme_icon_map;
470 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
471 LASSERT(sorted(begin, end), /**/);
473 ImgMap const * const it = find_if(begin, end, CompareKey(action));
481 // the returned bool is true if the icon needs to be flipped
482 pair<QString,bool> iconName(FuncRequest const & f, bool unknown, bool rtl)
485 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
487 if (!f.argument().empty()) {
488 // if there are arguments, first search an icon which name is the full thing
489 QString name = lfunname + ' ' + toqstr(f.argument());
490 name.replace(' ', '_');
491 name.replace(';', '_');
492 name.replace('\\', "backslash");
495 // then special default icon for some lfuns
496 switch (f.action()) {
497 case LFUN_MATH_INSERT:
498 names << "math/" + findImg(toqstr(f.argument()).mid(1));
500 case LFUN_MATH_DELIM:
501 case LFUN_MATH_BIGDELIM:
502 names << "math/" + findImg(toqstr(f.argument()));
505 names << "commands/" + toqstr(f.argument());
507 case LFUN_COMMAND_ALTERNATIVES: {
508 // use the first of the alternative commands
510 docstring dummy = split(f.argument(), firstcom, ';');
511 QString name1 = toqstr(firstcom);
512 name1.replace(' ', '_');
513 name1.replace(';', '_');
514 name1.replace('\\', "backslash");
523 // next thing to try is function name alone
526 // and finally maybe the unknown icon
530 search_mode const mode = theGuiApp()->imageSearchMode();
531 // The folders where icons are searched for
532 QStringList imagedirs;
533 imagedirs << "images/" << "images/ipa/";
534 // This is used to search for rtl version of icons which have the +rrtl suffix.
535 QStringList suffixes;
538 suffixes << QString();
540 for (QString const & imagedir : imagedirs)
541 for (QString const & name : names)
542 for (QString const & suffix : suffixes) {
543 QString id = imagedir;
544 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
546 return make_pair(toqstr(fname.absFileName()),
547 rtl && suffix.isEmpty());
550 LYXERR(Debug::GUI, "Cannot find icon for command \""
551 << lyxaction.getActionName(f.action())
552 << '(' << to_utf8(f.argument()) << ")\"");
554 return make_pair(QString(), false);
558 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
560 QString imagedir = path;
561 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
562 QString fpath = toqstr(fname.absFileName());
563 QPixmap pixmap = QPixmap();
565 if (pixmap.load(fpath))
568 bool const list = ext.contains(",");
569 LYXERR(Debug::GUI, "Cannot load pixmap \""
570 << path << "/" << name << "." << (list ? "{" : "") << ext
571 << (list ? "}" : "") << "\".");
577 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
579 #if (QT_VERSION >= 0x040600)
580 if (lyxrc.use_system_theme_icons) {
581 // use the icons from system theme that are available
582 QString action = toqstr(lyxaction.getActionName(f.action()));
583 if (!f.argument().empty())
584 action += " " + toqstr(f.argument());
585 QString const theme_icon = themeIconName(action);
586 if (QIcon::hasThemeIcon(theme_icon)) {
587 QIcon const thmicn = QIcon::fromTheme(theme_icon);
588 if (!thmicn.isNull())
596 tie(icon, flip) = iconName(f, unknown, rtl);
600 //LYXERR(Debug::GUI, "Found icon: " << icon);
601 QPixmap pixmap = QPixmap();
602 if (!pixmap.load(icon)) {
603 LYXERR0("Cannot load icon " << icon << ".");
608 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
610 return QIcon(pixmap);
614 ////////////////////////////////////////////////////////////////////////
616 // LyX server support code.
618 ////////////////////////////////////////////////////////////////////////
620 class SocketNotifier : public QSocketNotifier
623 /// connect a connection notification from the LyXServerSocket
624 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
625 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
629 /// The callback function
630 Application::SocketCallback func_;
634 class GuiTranslator : public QTranslator
637 GuiTranslator(QObject * parent = nullptr)
638 : QTranslator(parent)
641 QString translate(const char * /* context */,
642 const char *sourceText,
643 #if QT_VERSION >= 0x050000
644 const char * /* disambiguation */ = 0, int /* n */ = -1) const override
646 const char * /*comment*/ = 0) const override
649 // Here we declare the strings that need to be translated from Qt own GUI
650 // This is needed to include these strings to po files
654 _("Restore Defaults");
657 // Already in po: "Cancel", "&Cancel"
658 _("Apply"); // Already in po: "&Apply"
659 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
662 docstring s = getGuiMessages().getIfFound(sourceText);
663 // This test should eventually be removed when translations are updated
665 LYXERR(Debug::LOCALE, "Missing translation for `"
666 << string(sourceText) << "'");
672 ////////////////////////////////////////////////////////////////////////
674 // Mac specific stuff goes here...
676 ////////////////////////////////////////////////////////////////////////
679 // QMacPasteboardMimeGraphics can only be compiled on Mac.
681 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
684 QMacPasteboardMimeGraphics()
685 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
688 QString convertorName() { return "Graphics"; }
690 QString flavorFor(QString const & mime)
692 LYXERR(Debug::ACTION, "flavorFor " << mime);
693 if (mime == pdfMimeType())
694 return QLatin1String("com.adobe.pdf");
698 QString mimeFor(QString flav)
700 LYXERR(Debug::ACTION, "mimeFor " << flav);
701 if (flav == QLatin1String("com.adobe.pdf"))
702 return pdfMimeType();
706 bool canConvert(QString const & mime, QString flav)
708 return mimeFor(flav) == mime;
711 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
715 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
719 QList<QByteArray> convertFromMime(QString const & /*mime*/,
720 QVariant data, QString /*flav*/)
722 QList<QByteArray> ret;
723 ret.append(data.toByteArray());
729 ///////////////////////////////////////////////////////////////
731 // You can find more platform specific stuff at the end of this file...
733 ///////////////////////////////////////////////////////////////
735 ////////////////////////////////////////////////////////////////////////
736 // Windows specific stuff goes here...
738 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
739 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
740 // QWindowsMimeMetafile can only be compiled on Windows.
742 static FORMATETC cfFromMime(QString const & mimetype)
745 if (mimetype == emfMimeType()) {
746 formatetc.cfFormat = CF_ENHMETAFILE;
747 formatetc.tymed = TYMED_ENHMF;
748 } else if (mimetype == wmfMimeType()) {
749 formatetc.cfFormat = CF_METAFILEPICT;
750 formatetc.tymed = TYMED_MFPICT;
753 formatetc.dwAspect = DVASPECT_CONTENT;
754 formatetc.lindex = -1;
759 class QWindowsMimeMetafile : public QWINDOWSMIME {
761 QWindowsMimeMetafile() {}
763 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
764 QMimeData const * /*mimedata*/) const override
769 bool canConvertToMime(QString const & mimetype,
770 IDataObject * pDataObj) const override
772 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
774 FORMATETC formatetc = cfFromMime(mimetype);
775 return pDataObj->QueryGetData(&formatetc) == S_OK;
778 bool convertFromMime(FORMATETC const & /*formatetc*/,
779 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
784 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
785 QVariant::Type /*preferredType*/) const override
788 if (!canConvertToMime(mimetype, pDataObj))
791 FORMATETC formatetc = cfFromMime(mimetype);
793 if (pDataObj->GetData(&formatetc, &s) != S_OK)
797 if (s.tymed == TYMED_ENHMF) {
798 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
799 data.resize(dataSize);
800 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
801 (LPBYTE)data.data());
802 } else if (s.tymed == TYMED_MFPICT) {
803 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
804 data.resize(dataSize);
805 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
806 (LPBYTE)data.data());
809 ReleaseStgMedium(&s);
815 QVector<FORMATETC> formatsForMime(QString const & mimetype,
816 QMimeData const * /*mimedata*/) const override
818 QVector<FORMATETC> formats;
819 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
820 formats += cfFromMime(mimetype);
824 QString mimeForFormat(FORMATETC const & formatetc) const override
826 switch (formatetc.cfFormat) {
828 return emfMimeType();
829 case CF_METAFILEPICT:
830 return wmfMimeType();
840 /// Allows to check whether ESC was pressed during a long operation
841 class KeyChecker : public QObject {
846 KeyChecker() : pressed_(false), started_(false) {}
849 QCoreApplication::instance()->installEventFilter(this);
854 QCoreApplication::instance()->removeEventFilter(this);
858 QCoreApplication::processEvents();
861 bool started() const {
864 bool eventFilter(QObject *obj, QEvent *event) override {
865 LYXERR(Debug::ACTION, "Event Type: " << event->type());
866 switch (event->type()) {
870 case QEvent::UpdateRequest:
871 case QEvent::CursorChange:
872 case QEvent::ActionChanged:
873 case QEvent::EnabledChange:
874 case QEvent::SockAct:
877 case QEvent::ToolTipChange:
878 case QEvent::LayoutRequest:
879 case QEvent::MetaCall:
880 return QObject::eventFilter(obj, event);
882 // FIXME Blocking all these events is a bad idea.
883 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
884 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
892 ////////////////////////////////////////////////////////////////////////
893 // GuiApplication::Private definition and implementation.
894 ////////////////////////////////////////////////////////////////////////
896 struct GuiApplication::Private
898 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
899 global_menubar_(nullptr)
901 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
902 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
903 /// WMF Mime handler for Windows clipboard.
904 wmf_mime_ = new QWindowsMimeMetafile;
907 initKeySequences(&theTopLevelKeymap());
910 void initKeySequences(KeyMap * kb)
912 keyseq = KeySequence(kb, kb);
913 cancel_meta_seq = KeySequence(kb, kb);
917 QSortFilterProxyModel * language_model_;
919 GuiClipboard clipboard_;
921 GuiSelection selection_;
923 FontLoader font_loader_;
925 ColorCache color_cache_;
926 /// the built-in Qt translation mechanism
927 QTranslator qt_trans_;
928 /// LyX gettext-based translation for Qt elements
929 GuiTranslator gui_trans_;
931 QHash<int, SocketNotifier *> socket_notifiers_;
935 /// The global instance
938 /// this timer is used for any regular events one wants to
939 /// perform. at present it is used to check if forked processes
941 QTimer general_timer_;
943 /// delayed FuncRequests
944 std::queue<FuncRequest> func_request_queue_;
949 KeySequence cancel_meta_seq;
951 KeyModifier meta_fake_bit;
953 /// The result of last dispatch action
954 DispatchResult dispatch_result_;
956 /// Multiple views container.
958 * Warning: This must not be a smart pointer as the destruction of the
959 * object is handled by Qt when the view is closed
960 * \sa Qt::WA_DeleteOnClose attribute.
962 QHash<int, GuiView *> views_;
964 /// Only used on mac.
965 QMenuBar * global_menubar_;
968 /// Linkback mime handler for MacOSX.
969 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
972 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
973 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
974 /// WMF Mime handler for Windows clipboard.
975 QWindowsMimeMetafile * wmf_mime_;
979 /// Allows to check whether ESC was pressed during a long operation
980 KeyChecker key_checker_;
984 GuiApplication * guiApp;
986 GuiApplication::~GuiApplication()
989 closeAllLinkBackLinks();
995 GuiApplication::GuiApplication(int & argc, char ** argv)
996 : QApplication(argc, argv), current_view_(nullptr),
997 d(new GuiApplication::Private)
999 QString app_name = "LyX";
1000 QCoreApplication::setOrganizationName(app_name);
1001 QCoreApplication::setOrganizationDomain("lyx.org");
1002 QCoreApplication::setApplicationName(lyx_package);
1003 #if QT_VERSION >= 0x050000
1004 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1007 #if QT_VERSION >= 0x050700
1008 setDesktopFileName(lyx_package);
1011 qsrand(QDateTime::currentDateTime().toTime_t());
1013 // Install LyX translator for missing Qt translations
1014 installTranslator(&d->gui_trans_);
1015 // Install Qt native translator for GUI elements.
1016 installTranslator(&d->qt_trans_);
1019 // Enable reception of XCB events.
1020 installNativeEventFilter(this);
1023 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1024 // lyxrc setting for this in order to let the application stay resident.
1025 // But then we need some kind of dock icon, at least on Windows.
1027 if (lyxrc.quit_on_last_window_closed)
1028 setQuitOnLastWindowClosed(false);
1031 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1032 // seems to be the default case for applications like LyX.
1033 setQuitOnLastWindowClosed(false);
1036 appleCleanupEditMenu();
1037 appleCleanupViewMenu();
1040 #if defined(Q_WS_X11) || defined(QPA_XCB)
1041 // doubleClickInterval() is 400 ms on X11 which is just too long.
1042 // On Windows and Mac OS X, the operating system's value is used.
1043 // On Microsoft Windows, calling this function sets the double
1044 // click interval for all applications. So we don't!
1045 QApplication::setDoubleClickInterval(300);
1048 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1050 // needs to be done before reading lyxrc
1052 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1056 // Initialize RC Fonts
1057 if (lyxrc.roman_font_name.empty())
1058 lyxrc.roman_font_name = fromqstr(romanFontName());
1060 if (lyxrc.sans_font_name.empty())
1061 lyxrc.sans_font_name = fromqstr(sansFontName());
1063 if (lyxrc.typewriter_font_name.empty())
1064 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1066 #if (QT_VERSION >= 0x050000)
1067 // Qt4 does this in event(), see below.
1068 // Track change of keyboard
1069 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1072 d->general_timer_.setInterval(500);
1073 connect(&d->general_timer_, SIGNAL(timeout()),
1074 this, SLOT(handleRegularEvents()));
1075 d->general_timer_.start();
1077 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1078 // This is clearly not enough in a time where we use threads for
1079 // document preview and/or export. 20 should be OK.
1080 QThreadPool::globalInstance()->setMaxThreadCount(20);
1082 // make sure tooltips are formatted
1083 installEventFilter(new ToolTipFormatter(this));
1087 GuiApplication * theGuiApp()
1089 return dynamic_cast<GuiApplication *>(theApp());
1093 double GuiApplication::pixelRatio() const
1095 #if QT_VERSION >= 0x050000
1096 return qt_scale_factor * devicePixelRatio();
1103 void GuiApplication::clearSession()
1110 docstring Application::iconName(FuncRequest const & f, bool unknown)
1112 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown, false).first);
1116 docstring Application::mathIcon(docstring const & c)
1118 return qstring_to_ucs4(findImg(toqstr(c)));
1122 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1126 BufferView * bv = nullptr;
1127 BufferView * doc_bv = nullptr;
1129 if (cmd.action() == LFUN_NOACTION) {
1130 status.message(from_utf8(N_("Nothing to do")));
1131 status.setEnabled(false);
1134 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1135 status.setUnknown(true);
1136 status.message(from_utf8(N_("Unknown action")));
1137 status.setEnabled(false);
1140 // Does the GuiApplication know something?
1141 else if (getStatus(cmd, status)) { }
1143 // If we do not have a GuiView, then other functions are disabled
1144 else if (!current_view_)
1145 status.setEnabled(false);
1147 // Does the GuiView know something?
1148 else if (current_view_->getStatus(cmd, status)) { }
1150 // In LyX/Mac, when a dialog is open, the menus of the
1151 // application can still be accessed without giving focus to
1152 // the main window. In this case, we want to disable the menu
1153 // entries that are buffer or view-related.
1154 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1156 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1157 status.setEnabled(false);
1160 // If we do not have a BufferView, then other functions are disabled
1161 else if (!(bv = current_view_->currentBufferView()))
1162 status.setEnabled(false);
1164 // Does the current BufferView know something?
1165 else if (bv->getStatus(cmd, status)) { }
1167 // Does the current Buffer know something?
1168 else if (bv->buffer().getStatus(cmd, status)) { }
1170 // If we do not have a document BufferView, different from the
1171 // current BufferView, then other functions are disabled
1172 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1173 status.setEnabled(false);
1175 // Does the document Buffer know something?
1176 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1179 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1180 status.message(from_utf8(N_("Command not handled")));
1181 status.setEnabled(false);
1184 // the default error message if we disable the command
1185 if (!status.enabled() && status.message().empty())
1186 status.message(from_utf8(N_("Command disabled")));
1192 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1194 // I would really like to avoid having this switch and rather try to
1195 // encode this in the function itself.
1196 // -- And I'd rather let an inset decide which LFUNs it is willing
1197 // to handle (Andre')
1199 switch (cmd.action()) {
1201 // This could be used for the no-GUI version. The GUI version is handled in
1202 // GuiView::getStatus(). See above.
1204 case LFUN_BUFFER_WRITE:
1205 case LFUN_BUFFER_WRITE_AS:
1206 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1207 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1208 enable = b && (b->isUnnamed() || !b->isClean());
1213 case LFUN_BOOKMARK_GOTO: {
1214 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1215 enable = theSession().bookmarks().isValid(num);
1219 case LFUN_BOOKMARK_CLEAR:
1220 enable = theSession().bookmarks().hasValid();
1223 // this one is difficult to get right. As a half-baked
1224 // solution, we consider only the first action of the sequence
1225 case LFUN_COMMAND_SEQUENCE: {
1226 // argument contains ';'-terminated commands
1227 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1228 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1229 func.setOrigin(cmd.origin());
1230 flag = getStatus(func);
1234 // we want to check if at least one of these is enabled
1235 case LFUN_COMMAND_ALTERNATIVES: {
1236 // argument contains ';'-terminated commands
1237 string arg = to_utf8(cmd.argument());
1238 while (!arg.empty()) {
1240 arg = split(arg, first, ';');
1241 FuncRequest func(lyxaction.lookupFunc(first));
1242 func.setOrigin(cmd.origin());
1243 flag = getStatus(func);
1244 // if this one is enabled, the whole thing is
1253 string name = to_utf8(cmd.argument());
1254 if (theTopLevelCmdDef().lock(name, func)) {
1255 func.setOrigin(cmd.origin());
1256 flag = getStatus(func);
1257 theTopLevelCmdDef().release(name);
1259 // catch recursion or unknown command
1260 // definition. all operations until the
1261 // recursion or unknown command definition
1262 // occurs are performed, so set the state to
1269 case LFUN_IF_RELATIVES: {
1270 string const lfun = to_utf8(cmd.argument());
1271 BufferView const * bv =
1272 current_view_ ? current_view_->currentBufferView() : nullptr;
1273 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1277 FuncRequest func(lyxaction.lookupFunc(lfun));
1278 func.setOrigin(cmd.origin());
1279 flag = getStatus(func);
1283 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1285 case LFUN_PREFERENCES_SAVE:
1286 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1287 case LFUN_DEBUG_LEVEL_SET:
1288 // these are handled in our dispatch()
1291 case LFUN_WINDOW_CLOSE:
1292 enable = !d->views_.empty();
1295 case LFUN_BUFFER_NEW:
1296 case LFUN_BUFFER_NEW_TEMPLATE:
1297 case LFUN_FILE_OPEN:
1298 case LFUN_HELP_OPEN:
1299 case LFUN_SCREEN_FONT_UPDATE:
1300 case LFUN_SET_COLOR:
1301 case LFUN_WINDOW_NEW:
1303 case LFUN_LYXRC_APPLY:
1304 case LFUN_COMMAND_PREFIX:
1306 case LFUN_META_PREFIX:
1307 case LFUN_RECONFIGURE:
1308 case LFUN_SERVER_GET_FILENAME:
1309 case LFUN_SERVER_NOTIFY:
1313 case LFUN_BUFFER_FORALL: {
1314 if (theBufferList().empty()) {
1315 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1316 flag.setEnabled(false);
1320 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1321 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1322 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1323 flag.setEnabled(false);
1328 case LFUN_DIALOG_SHOW: {
1329 string const name = cmd.getArg(0);
1330 return name == "aboutlyx"
1331 || name == "lyxfiles"
1333 || name == "texinfo"
1334 || name == "progress"
1335 || name == "compare";
1343 flag.setEnabled(false);
1347 /// make a post-dispatch status message
1348 static docstring makeDispatchMessage(docstring const & msg,
1349 FuncRequest const & cmd)
1351 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1352 || cmd.origin() == FuncRequest::TOOLBAR
1353 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1355 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1356 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1360 docstring dispatch_msg = msg;
1361 if (!dispatch_msg.empty())
1362 dispatch_msg += ' ';
1364 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1366 bool argsadded = false;
1368 if (!cmd.argument().empty()) {
1369 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1370 comname += ' ' + cmd.argument();
1374 docstring const shortcuts = theTopLevelKeymap().
1375 printBindings(cmd, KeySequence::ForGui);
1377 if (!shortcuts.empty())
1378 comname += ": " + shortcuts;
1379 else if (!argsadded && !cmd.argument().empty())
1380 comname += ' ' + cmd.argument();
1382 if (!comname.empty()) {
1383 comname = rtrim(comname);
1384 dispatch_msg += '(' + rtrim(comname) + ')';
1386 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1387 return dispatch_msg;
1391 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1395 Buffer * buffer = 0;
1396 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1397 //setCurrentView(cmd.view_origin); //does not work
1399 dr.setMessage(_("Wrong focus!"));
1400 d->dispatch_result_ = dr;
1401 return d->dispatch_result_;
1403 if (current_view_ && current_view_->currentBufferView()) {
1404 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1405 buffer = ¤t_view_->currentBufferView()->buffer();
1408 dr.screenUpdate(Update::FitCursor);
1410 // This handles undo groups automagically
1411 UndoGroupHelper ugh(buffer);
1413 // redraw the screen at the end (first of the two drawing steps).
1414 // This is done unless explicitly requested otherwise.
1415 // This code is kept inside the undo group because updateBuffer
1416 // can create undo actions (see #11292)
1417 updateCurrentView(cmd, dr);
1420 d->dispatch_result_ = dr;
1421 return d->dispatch_result_;
1425 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1430 BufferView * bv = current_view_->currentBufferView();
1432 if (dr.needBufferUpdate()) {
1433 bv->cursor().clearBufferUpdate();
1434 bv->buffer().updateBuffer();
1436 // BufferView::update() updates the ViewMetricsInfo and
1437 // also initializes the position cache for all insets in
1438 // (at least partially) visible top-level paragraphs.
1439 // We will redraw the screen only if needed.
1440 bv->processUpdateFlags(dr.screenUpdate());
1442 // Do we have a selection?
1443 theSelection().haveSelection(bv->cursor().selection());
1446 current_view_->restartCaret();
1448 if (dr.needMessageUpdate()) {
1449 // Some messages may already be translated, so we cannot use _()
1450 current_view_->message(makeDispatchMessage(
1451 translateIfPossible(dr.message()), cmd));
1456 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1457 bool switchToBuffer)
1459 if (!theSession().bookmarks().isValid(idx))
1461 BookmarksSection::Bookmark const & bm =
1462 theSession().bookmarks().bookmark(idx);
1463 LASSERT(!bm.filename.empty(), return);
1464 string const file = bm.filename.absFileName();
1465 // if the file is not opened, open it.
1466 if (!theBufferList().exists(bm.filename)) {
1468 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1472 // open may fail, so we need to test it again
1473 if (!theBufferList().exists(bm.filename))
1476 // bm can be changed when saving
1477 BookmarksSection::Bookmark tmp = bm;
1479 // Special case idx == 0 used for back-from-back jump navigation
1481 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1483 // if the current buffer is not that one, switch to it.
1484 BufferView * doc_bv = current_view_ ?
1485 current_view_->documentBufferView() : 0;
1486 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1487 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1488 if (switchToBuffer) {
1489 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1492 doc_bv = current_view_->documentBufferView();
1497 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1498 if (!doc_bv || !doc_bv->moveToPosition(
1499 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1502 Cursor & cur = doc_bv->cursor();
1503 if (old && cur != *old)
1504 notifyCursorLeavesOrEnters(*old, cur);
1510 // Cursor jump succeeded!
1511 pit_type new_pit = cur.pit();
1512 pos_type new_pos = cur.pos();
1513 int new_id = cur.paragraph().id();
1515 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1516 // see http://www.lyx.org/trac/ticket/3092
1517 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1518 || bm.top_id != new_id) {
1519 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1520 new_pit, new_pos, new_id);
1524 // This function runs "configure" and then rereads lyx.defaults to
1525 // reconfigure the automatic settings.
1526 void GuiApplication::reconfigure(string const & option)
1528 // emit message signal.
1530 current_view_->message(_("Running configure..."));
1532 // Run configure in user lyx directory
1533 string const lock_file = package().getConfigureLockName();
1534 int fd = fileLock(lock_file.c_str());
1535 int const ret = package().reconfigureUserLyXDir(option);
1536 // emit message signal.
1538 current_view_->message(_("Reloading configuration..."));
1539 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1540 // Re-read packages.lst
1541 LaTeXPackages::getAvailable();
1542 fileUnlock(fd, lock_file.c_str());
1545 Alert::information(_("System reconfiguration failed"),
1546 _("The system reconfiguration has failed.\n"
1547 "Default textclass is used but LyX may\n"
1548 "not be able to work properly.\n"
1549 "Please reconfigure again if needed."));
1551 Alert::information(_("System reconfigured"),
1552 _("The system has been reconfigured.\n"
1553 "You need to restart LyX to make use of any\n"
1554 "updated document class specifications."));
1557 void GuiApplication::validateCurrentView()
1559 if (!d->views_.empty() && !current_view_) {
1560 // currently at least one view exists but no view has the focus.
1561 // choose the last view to make it current.
1562 // a view without any open document is preferred.
1563 GuiView * candidate = 0;
1564 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1565 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1566 for (; it != end; ++it) {
1568 if (!candidate->documentBufferView())
1571 setCurrentView(candidate);
1575 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1577 string const argument = to_utf8(cmd.argument());
1578 FuncCode const action = cmd.action();
1580 LYXERR(Debug::ACTION, "cmd: " << cmd);
1582 // we have not done anything wrong yet.
1585 FuncStatus const flag = getStatus(cmd);
1586 if (!flag.enabled()) {
1587 // We cannot use this function here
1588 LYXERR(Debug::ACTION, "action "
1589 << lyxaction.getActionName(action)
1590 << " [" << action << "] is disabled at this location");
1591 dr.setMessage(flag.message());
1593 dr.dispatched(false);
1594 dr.screenUpdate(Update::None);
1595 dr.clearBufferUpdate();
1599 if (cmd.origin() == FuncRequest::LYXSERVER) {
1600 if (current_view_ && current_view_->currentBufferView())
1601 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1602 // we will also need to redraw the screen at the end
1603 dr.screenUpdate(Update::FitCursor);
1606 // Assumes that the action will be dispatched.
1607 dr.dispatched(true);
1609 switch (cmd.action()) {
1611 case LFUN_WINDOW_NEW:
1612 createView(toqstr(cmd.argument()));
1615 case LFUN_WINDOW_CLOSE:
1616 // update bookmark pit of the current buffer before window close
1617 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1618 gotoBookmark(i+1, false, false);
1619 // clear the last opened list, because
1620 // maybe this will end the session
1621 theSession().lastOpened().clear();
1622 // check for valid current_view_
1623 validateCurrentView();
1625 current_view_->closeScheduled();
1629 // quitting is triggered by the gui code
1630 // (leaving the event loop).
1632 current_view_->message(from_utf8(N_("Exiting.")));
1633 if (closeAllViews())
1637 case LFUN_SCREEN_FONT_UPDATE: {
1638 // handle the screen font changes.
1639 /* FIXME: this only updates the current document, whereas all
1640 * documents should see their metrics updated.
1642 d->font_loader_.update();
1643 dr.screenUpdate(Update::Force | Update::FitCursor);
1647 case LFUN_BUFFER_NEW:
1648 validateCurrentView();
1650 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1651 createView(QString(), false); // keep hidden
1652 current_view_->newDocument(to_utf8(cmd.argument()));
1653 current_view_->show();
1654 setActiveWindow(current_view_);
1656 current_view_->newDocument(to_utf8(cmd.argument()));
1660 case LFUN_BUFFER_NEW_TEMPLATE: {
1661 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1662 string const temp = cmd.getArg(1);
1663 validateCurrentView();
1665 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1667 current_view_->newDocument(file, temp, true);
1668 if (!current_view_->documentBufferView())
1669 current_view_->close();
1671 current_view_->newDocument(file, temp, true);
1676 case LFUN_FILE_OPEN: {
1677 // FIXME: normally the code below is not needed, since getStatus makes sure that
1678 // current_view_ is not null.
1679 validateCurrentView();
1680 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1681 string const fname = to_utf8(cmd.argument());
1682 bool const is_open = FileName::isAbsolute(fname)
1683 && theBufferList().getBuffer(FileName(fname));
1685 || (!lyxrc.open_buffers_in_tabs
1686 && current_view_->documentBufferView() != 0
1688 // We want the ui session to be saved per document and not per
1689 // window number. The filename crc is a good enough identifier.
1690 boost::crc_32_type crc;
1691 crc = for_each(fname.begin(), fname.end(), crc);
1692 createView(crc.checksum());
1693 current_view_->openDocument(fname);
1694 if (!current_view_->documentBufferView())
1695 current_view_->close();
1696 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1697 current_view_->raise();
1698 current_view_->activateWindow();
1699 current_view_->showNormal();
1702 current_view_->openDocument(fname);
1703 if (cmd.origin() == FuncRequest::LYXSERVER) {
1704 current_view_->raise();
1705 current_view_->activateWindow();
1706 current_view_->showNormal();
1712 case LFUN_HELP_OPEN: {
1713 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1714 if (current_view_ == 0)
1716 string const arg = to_utf8(cmd.argument());
1718 current_view_->message(_("Missing argument"));
1721 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1723 fname = i18nLibFileSearch("examples", arg, "lyx");
1725 if (fname.empty()) {
1726 lyxerr << "LyX: unable to find documentation file `"
1727 << arg << "'. Bad installation?" << endl;
1730 current_view_->message(bformat(_("Opening help file %1$s..."),
1731 makeDisplayPath(fname.absFileName())));
1732 Buffer * buf = current_view_->loadDocument(fname, false);
1734 buf->setReadonly(!current_view_->develMode());
1738 case LFUN_SET_COLOR: {
1739 string const lyx_name = cmd.getArg(0);
1740 string const x11_name = cmd.getArg(1);
1741 if (lyx_name.empty() || x11_name.empty()) {
1743 current_view_->message(
1744 _("Syntax: set-color <lyx_name> <x11_name>"));
1749 // FIXME: The graphics cache no longer has a changeDisplay method.
1750 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1751 bool const graphicsbg_changed =
1752 lyx_name == graphicsbg && x11_name != graphicsbg;
1753 if (graphicsbg_changed)
1754 graphics::GCache::get().changeDisplay(true);
1757 if (!lcolor.setColor(lyx_name, x11_name)) {
1759 current_view_->message(
1760 bformat(_("Set-color \"%1$s\" failed "
1761 "- color is undefined or "
1762 "may not be redefined"),
1763 from_utf8(lyx_name)));
1766 // Make sure we don't keep old colors in cache.
1767 d->color_cache_.clear();
1768 // Update the current view
1769 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1773 case LFUN_LYXRC_APPLY: {
1774 // reset active key sequences, since the bindings
1775 // are updated (bug 6064)
1777 LyXRC const lyxrc_orig = lyxrc;
1779 istringstream ss(to_utf8(cmd.argument()));
1780 bool const success = lyxrc.read(ss);
1783 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1784 << "Unable to read lyxrc data"
1789 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1791 // If the request comes from the minibuffer, then we can't reset
1792 // the GUI, since that would destroy the minibuffer itself and
1793 // cause a crash, since we are currently in one of the methods of
1794 // GuiCommandBuffer. See bug #8540.
1795 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1798 // FIXME Unfortunately, that leaves a bug here, since we cannot
1799 // reset the GUI in this case. If the changes to lyxrc affected the
1800 // UI, then, nothing would happen. This seems fairly unlikely, but
1801 // it definitely is a bug.
1803 dr.forceBufferUpdate();
1807 case LFUN_COMMAND_PREFIX:
1808 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1813 d->meta_fake_bit = NoModifier;
1814 GuiView * gv = currentView();
1815 if (gv && gv->currentBufferView())
1816 // cancel any selection
1817 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1818 dr.setMessage(from_ascii(N_("Cancel")));
1821 case LFUN_META_PREFIX:
1822 d->meta_fake_bit = AltModifier;
1823 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1826 // --- Menus -----------------------------------------------
1827 case LFUN_RECONFIGURE:
1828 // argument is any additional parameter to the configure.py command
1829 reconfigure(to_utf8(cmd.argument()));
1832 // --- lyxserver commands ----------------------------
1833 case LFUN_SERVER_GET_FILENAME: {
1834 if (current_view_ && current_view_->documentBufferView()) {
1835 docstring const fname = from_utf8(
1836 current_view_->documentBufferView()->buffer().absFileName());
1837 dr.setMessage(fname);
1838 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1840 dr.setMessage(docstring());
1841 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1846 case LFUN_SERVER_NOTIFY: {
1847 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1848 dr.setMessage(dispatch_buffer);
1849 theServer().notifyClient(to_utf8(dispatch_buffer));
1853 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1854 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1860 string rest = split(argument, countstr, ' ');
1861 int const count = convert<int>(countstr);
1862 // an arbitrary number to limit number of iterations
1863 int const max_iter = 10000;
1864 if (count > max_iter) {
1865 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1868 for (int i = 0; i < count; ++i) {
1869 FuncRequest lfun = lyxaction.lookupFunc(rest);
1870 lfun.allowAsync(false);
1877 case LFUN_COMMAND_SEQUENCE: {
1878 // argument contains ';'-terminated commands
1879 string arg = argument;
1880 // FIXME: this LFUN should also work without any view.
1881 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1882 ? &(current_view_->documentBufferView()->buffer()) : 0;
1883 // This handles undo groups automagically
1884 UndoGroupHelper ugh(buffer);
1885 while (!arg.empty()) {
1887 arg = split(arg, first, ';');
1888 FuncRequest func(lyxaction.lookupFunc(first));
1889 func.allowAsync(false);
1890 func.setOrigin(cmd.origin());
1896 case LFUN_BUFFER_FORALL: {
1897 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1898 funcToRun.allowAsync(false);
1900 map<Buffer *, GuiView *> views_lVisible;
1901 map<GuiView *, Buffer *> activeBuffers;
1903 QList<GuiView *> allViews = d->views_.values();
1905 // this for does not modify any buffer. It just collects info on local
1906 // visibility of buffers and on which buffer is active in each view.
1907 Buffer * const last = theBufferList().last();
1908 for(GuiView * view : allViews) {
1909 // all of the buffers might be locally hidden. That is, there is no
1911 if (!view || !view->currentBufferView())
1912 activeBuffers[view] = 0;
1914 activeBuffers[view] = &view->currentBufferView()->buffer();
1916 // find out if each is locally visible or locally hidden.
1917 // we don't use a for loop as the buffer list cycles.
1918 Buffer * b = theBufferList().first();
1920 bool const locallyVisible = view && view->workArea(*b);
1921 if (locallyVisible) {
1922 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1923 // only need to overwrite/add if we don't already know a buffer is globally
1924 // visible or we do know but we would prefer to dispatch LFUN from the
1925 // current view because of cursor position issues.
1926 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1927 views_lVisible[b] = view;
1931 b = theBufferList().next(b);
1935 GuiView * const homeView = currentView();
1936 Buffer * b = theBufferList().first();
1937 Buffer * nextBuf = 0;
1938 int numProcessed = 0;
1941 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1943 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1945 // first change to a view where b is locally visible, preferably current_view_.
1946 GuiView * const vLv = views_lVisible[b];
1948 lyx::dispatch(funcToRun);
1956 // put things back to how they were (if possible).
1957 for (GuiView * view : allViews) {
1958 Buffer * originalBuf = activeBuffers[view];
1959 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1960 if (theBufferList().isLoaded(originalBuf))
1961 view->setBuffer(originalBuf);
1963 homeView->setFocus();
1965 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
1969 case LFUN_COMMAND_ALTERNATIVES: {
1970 // argument contains ';'-terminated commands
1971 string arg = argument;
1972 while (!arg.empty()) {
1974 arg = split(arg, first, ';');
1975 FuncRequest func(lyxaction.lookupFunc(first));
1976 func.setOrigin(cmd.origin());
1977 FuncStatus const stat = getStatus(func);
1978 if (stat.enabled()) {
1988 if (theTopLevelCmdDef().lock(argument, func)) {
1989 func.setOrigin(cmd.origin());
1991 theTopLevelCmdDef().release(argument);
1993 if (func.action() == LFUN_UNKNOWN_ACTION) {
1994 // unknown command definition
1995 lyxerr << "Warning: unknown command definition `"
1999 // recursion detected
2000 lyxerr << "Warning: Recursion in the command definition `"
2001 << argument << "' detected"
2008 case LFUN_IF_RELATIVES: {
2009 string const lfun = to_utf8(cmd.argument());
2010 FuncRequest func(lyxaction.lookupFunc(lfun));
2011 func.setOrigin(cmd.origin());
2012 FuncStatus const stat = getStatus(func);
2013 if (stat.enabled()) {
2020 case LFUN_PREFERENCES_SAVE:
2021 lyxrc.write(support::makeAbsPath("preferences",
2022 package().user_support().absFileName()), false);
2025 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2026 string const fname = addName(addPath(package().user_support().absFileName(),
2027 "templates/"), "defaults.lyx");
2028 Buffer defaults(fname);
2030 istringstream ss(argument);
2035 // We need to make sure that, after we recreat the DocumentClass,
2036 // which we do in readHeader, we apply it to the document itself.
2037 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2038 int const unknown_tokens = defaults.readHeader(lex);
2039 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2041 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2042 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2044 if (unknown_tokens != 0) {
2045 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2046 << unknown_tokens << " unknown token"
2047 << (unknown_tokens == 1 ? "" : "s")
2051 if (defaults.writeFile(FileName(defaults.absFileName())))
2052 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2053 makeDisplayPath(fname)));
2056 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2061 case LFUN_BOOKMARK_GOTO:
2062 // go to bookmark, open unopened file and switch to buffer if necessary
2063 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2064 dr.screenUpdate(Update::Force | Update::FitCursor);
2067 case LFUN_BOOKMARK_CLEAR:
2068 theSession().bookmarks().clear();
2071 case LFUN_DEBUG_LEVEL_SET:
2072 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2075 case LFUN_DIALOG_SHOW: {
2076 string const name = cmd.getArg(0);
2078 if ( name == "aboutlyx"
2080 || name == "texinfo"
2081 || name == "progress"
2082 || name == "compare")
2084 // work around: on Mac OS the application
2085 // is not terminated when closing the last view.
2086 // Create a new one to be able to dispatch the
2087 // LFUN_DIALOG_SHOW to this view.
2088 if (current_view_ == 0)
2094 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2097 current_view_->dispatch(cmd, dr);
2101 if (cmd.origin() == FuncRequest::LYXSERVER)
2102 updateCurrentView(cmd, dr);
2106 docstring GuiApplication::viewStatusMessage()
2108 // When meta-fake key is pressed, show the key sequence so far + "M-".
2109 if (d->meta_fake_bit != NoModifier)
2110 return d->keyseq.print(KeySequence::ForGui) + "M-";
2112 // Else, when a non-complete key sequence is pressed,
2113 // show the available options.
2114 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2115 return d->keyseq.printOptions(true);
2121 string GuiApplication::inputLanguageCode() const
2123 #if (QT_VERSION < 0x050000)
2124 QLocale loc = keyboardInputLocale();
2126 QLocale loc = inputMethod()->locale();
2128 //LYXERR0("input lang = " << fromqstr(loc.name()));
2129 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2133 void GuiApplication::onLocaleChanged()
2135 //LYXERR0("Change language to " << inputLanguage()->lang());
2136 if (currentView() && currentView()->currentBufferView())
2137 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2141 void GuiApplication::handleKeyFunc(FuncCode action)
2145 if (d->keyseq.length())
2147 GuiView * gv = currentView();
2148 LASSERT(gv && gv->currentBufferView(), return);
2149 BufferView * bv = gv->currentBufferView();
2150 bv->getIntl().getTransManager().deadkey(
2151 c, get_accent(action).accent, bv->cursor().innerText(),
2153 // Need to clear, in case the minibuffer calls these
2156 // copied verbatim from do_accent_char
2157 bv->cursor().resetAnchor();
2161 //Keep this in sync with GuiApplication::processKeySym below
2162 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2163 KeyModifier state) const
2165 // Do nothing if we have nothing
2166 if (!keysym.isOK() || keysym.isModifier())
2168 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2170 FuncRequest func = seq.addkey(keysym, state);
2171 // When not cancel or meta-fake, do the normal lookup.
2172 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2174 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2176 // Maybe user can only reach the key via holding down shift.
2177 // Let's see. But only if shift is the only modifier
2178 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2179 // If addkey looked up a command and did not find further commands then
2180 // seq has been reset at this point
2181 func = seq.addkey(keysym, NoModifier);
2183 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2184 << seq.print(KeySequence::Portable) << ']');
2185 return func.action() != LFUN_UNKNOWN_ACTION;
2189 //Keep this in sync with GuiApplication::queryKeySym above
2190 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2192 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2194 // Do nothing if we have nothing (JMarc)
2195 if (!keysym.isOK() || keysym.isModifier()) {
2197 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2199 current_view_->restartCaret();
2203 char_type encoded_last_key = keysym.getUCSEncoded();
2205 // Do a one-deep top-level lookup for
2206 // cancel and meta-fake keys. RVDK_PATCH_5
2207 d->cancel_meta_seq.reset();
2209 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2210 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2212 // When not cancel or meta-fake, do the normal lookup.
2213 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2214 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2215 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2216 // remove Caps Lock and Mod2 as a modifiers
2217 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2218 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2221 // Don't remove this unless you know what you are doing.
2222 d->meta_fake_bit = NoModifier;
2224 // Can this happen now ?
2225 if (func.action() == LFUN_NOACTION)
2226 func = FuncRequest(LFUN_COMMAND_PREFIX);
2228 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2229 << d->keyseq.print(KeySequence::Portable) << ']');
2231 // already here we know if it any point in going further
2232 // why not return already here if action == -1 and
2233 // num_bytes == 0? (Lgb)
2235 if (d->keyseq.length() > 1 && current_view_)
2236 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2239 // Maybe user can only reach the key via holding down shift.
2240 // Let's see. But only if shift is the only modifier
2241 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2242 LYXERR(Debug::KEY, "Trying without shift");
2243 // If addkey looked up a command and did not find further commands then
2244 // seq has been reset at this point
2245 func = d->keyseq.addkey(keysym, NoModifier);
2246 LYXERR(Debug::KEY, "Action now " << func.action());
2249 if (func.action() == LFUN_UNKNOWN_ACTION) {
2250 // We didn't match any of the key sequences.
2251 // See if it's normal insertable text not already
2252 // covered by a binding
2253 if (keysym.isText() && d->keyseq.length() == 1) {
2254 // Non-printable characters (such as ASCII control characters)
2255 // must not be inserted (#5704)
2256 if (!isPrintable(encoded_last_key)) {
2257 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2259 current_view_->restartCaret();
2262 // The following modifier check is not needed on Mac.
2263 // The keysym is either not text or it is different
2264 // from the non-modifier keysym. See #9875 for the
2265 // broken alt-modifier effect of having this code active.
2266 #if !defined(Q_OS_MAC)
2267 // If a non-Shift Modifier is used we have a non-bound key sequence
2268 // (such as Alt+j = j). This should be omitted (#5575).
2269 // On Windows, AltModifier and ControlModifier are both
2270 // set when AltGr is pressed. Therefore, in order to not
2271 // break AltGr-bound symbols (see #5575 for details),
2272 // unbound Ctrl+Alt key sequences are allowed.
2273 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2274 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2275 && !(state & AltModifier && state & ControlModifier)
2279 if (current_view_) {
2280 current_view_->message(_("Unknown function."));
2281 current_view_->restartCaret();
2286 // Since all checks above were passed, we now really have text that
2287 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2288 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2290 LYXERR(Debug::KEY, "isText() is true, inserting.");
2291 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2293 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2294 if (current_view_) {
2295 current_view_->message(_("Unknown function."));
2296 current_view_->restartCaret();
2302 if (func.action() == LFUN_SELF_INSERT) {
2303 if (encoded_last_key != 0) {
2304 docstring const arg(1, encoded_last_key);
2305 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2306 FuncRequest::KEYBOARD));
2307 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2310 processFuncRequest(func);
2314 void GuiApplication::processFuncRequest(FuncRequest const & func)
2316 lyx::dispatch(func);
2320 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2322 addToFuncRequestQueue(func);
2323 processFuncRequestQueueAsync();
2327 void GuiApplication::processFuncRequestQueue()
2329 while (!d->func_request_queue_.empty()) {
2330 // take the item from the stack _before_ processing the
2331 // request in order to avoid race conditions from nested
2332 // or parallel requests (see #10406)
2333 FuncRequest const fr(d->func_request_queue_.front());
2334 d->func_request_queue_.pop();
2335 processFuncRequest(fr);
2340 void GuiApplication::processFuncRequestQueueAsync()
2342 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2346 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2348 d->func_request_queue_.push(func);
2352 void GuiApplication::resetGui()
2354 // Set the language defined by the user.
2358 if (!readUIFile(toqstr(lyxrc.ui_file)))
2359 // Gives some error box here.
2362 if (d->global_menubar_)
2363 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2365 QHash<int, GuiView *>::iterator it;
2366 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2369 gv->setLayoutDirection(layoutDirection());
2373 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2377 bool GuiApplication::rtlContext() const
2379 if (current_view_ && current_view_->currentBufferView()) {
2380 BufferView const * bv = current_view_->currentBufferView();
2381 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2383 return layoutDirection() == Qt::RightToLeft;
2387 void GuiApplication::createView(int view_id)
2389 createView(QString(), true, view_id);
2393 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2396 // release the keyboard which might have been grabbed by the global
2397 // menubar on Mac to catch shortcuts even without any GuiView.
2398 if (d->global_menubar_)
2399 d->global_menubar_->releaseKeyboard();
2403 while (d->views_.find(id) != d->views_.end())
2406 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2407 GuiView * view = new GuiView(id);
2408 // `view' is the new current_view_. Tell coverity that is is not 0.
2409 LATTEST(current_view_);
2411 d->views_[id] = view;
2415 setActiveWindow(view);
2418 if (!geometry_arg.isEmpty()) {
2419 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2423 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2424 re.indexIn(geometry_arg);
2425 w = re.cap(1).toInt();
2426 h = re.cap(2).toInt();
2427 x = re.cap(3).toInt();
2428 y = re.cap(4).toInt();
2429 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2430 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2431 // Set initial geometry such that we can get the frame size.
2432 view->setGeometry(x, y, w, h);
2433 int framewidth = view->geometry().x() - view->x();
2434 int titleheight = view->geometry().y() - view->y();
2435 // Negative displacements must be interpreted as distances
2436 // from the right or bottom screen borders.
2437 if (sx == '-' || sy == '-') {
2438 QRect rec = QApplication::desktop()->screenGeometry();
2440 x += rec.width() - w - framewidth;
2442 y += rec.height() - h - titleheight;
2443 view->setGeometry(x, y, w, h);
2445 // Make sure that the left and top frame borders are visible.
2446 if (view->x() < 0 || view->y() < 0) {
2451 view->setGeometry(x, y, w, h);
2459 bool GuiApplication::unhide(Buffer * buf)
2463 currentView()->setBuffer(buf, false);
2468 Clipboard & GuiApplication::clipboard()
2470 return d->clipboard_;
2474 Selection & GuiApplication::selection()
2476 return d->selection_;
2480 FontLoader & GuiApplication::fontLoader()
2482 return d->font_loader_;
2486 Toolbars const & GuiApplication::toolbars() const
2488 return d->toolbars_;
2492 Toolbars & GuiApplication::toolbars()
2494 return d->toolbars_;
2498 Menus const & GuiApplication::menus() const
2504 Menus & GuiApplication::menus()
2510 QList<int> GuiApplication::viewIds() const
2512 return d->views_.keys();
2516 ColorCache & GuiApplication::colorCache()
2518 return d->color_cache_;
2522 int GuiApplication::exec()
2524 // asynchronously handle batch commands. This event will be in
2525 // the event queue in front of other asynchronous events. Hence,
2526 // we can assume in the latter that the gui is setup already.
2527 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2529 return QApplication::exec();
2533 void GuiApplication::exit(int status)
2535 QApplication::exit(status);
2539 void GuiApplication::setGuiLanguage()
2543 // install translation file for Qt built-in dialogs
2544 QString const language_name = QString("qt_") + theLocale.name();
2545 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2546 // Short-named translator can be loaded from a long name, but not the
2547 // opposite. Therefore, long name should be used without truncation.
2548 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2549 if (!d->qt_trans_.load(language_name,
2550 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2551 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2554 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2558 switch (theLocale.language()) {
2559 case QLocale::Arabic :
2560 case QLocale::Hebrew :
2561 case QLocale::Persian :
2562 case QLocale::Urdu :
2563 setLayoutDirection(Qt::RightToLeft);
2566 setLayoutDirection(Qt::LeftToRight);
2571 void GuiApplication::execBatchCommands()
2576 if (!readUIFile(toqstr(lyxrc.ui_file)))
2577 // Gives some error box here.
2581 #if QT_VERSION > 0x040600
2582 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2584 #if QT_VERSION > 0x050100
2585 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2587 // Create the global default menubar which is shown for the dialogs
2588 // and if no GuiView is visible.
2589 // This must be done after the session was recovered to know the "last files".
2590 d->global_menubar_ = new QMenuBar(0);
2591 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2594 lyx::execBatchCommands();
2598 QAbstractItemModel * GuiApplication::languageModel()
2600 if (d->language_model_)
2601 return d->language_model_;
2603 QStandardItemModel * lang_model = new QStandardItemModel(this);
2604 lang_model->insertColumns(0, 3);
2605 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2606 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2607 Languages::const_iterator it = lyx::languages.begin();
2608 Languages::const_iterator end = lyx::languages.end();
2609 for (; it != end; ++it) {
2610 int current_row = lang_model->rowCount();
2611 lang_model->insertRows(current_row, 1);
2612 QModelIndex pl_item = lang_model->index(current_row, 0);
2613 QModelIndex sp_item = lang_model->index(current_row, 1);
2614 QModelIndex th_item = lang_model->index(current_row, 2);
2615 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2616 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2617 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2618 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2619 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2620 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2621 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2622 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2623 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2624 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2626 d->language_model_ = new QSortFilterProxyModel(this);
2627 d->language_model_->setSourceModel(lang_model);
2628 d->language_model_->setSortLocaleAware(true);
2629 return d->language_model_;
2633 void GuiApplication::restoreGuiSession()
2635 if (!lyxrc.load_session)
2638 Session & session = theSession();
2639 LastOpenedSection::LastOpened const & lastopened =
2640 session.lastOpened().getfiles();
2642 validateCurrentView();
2644 FileName active_file;
2645 // do not add to the lastfile list since these files are restored from
2646 // last session, and should be already there (regular files), or should
2647 // not be added at all (help files).
2648 for (auto const & last : lastopened) {
2649 FileName const & file_name = last.file_name;
2650 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2651 && current_view_->documentBufferView() != 0)) {
2652 boost::crc_32_type crc;
2653 string const & fname = file_name.absFileName();
2654 crc = for_each(fname.begin(), fname.end(), crc);
2655 createView(crc.checksum());
2657 current_view_->loadDocument(file_name, false);
2660 active_file = file_name;
2663 // Restore last active buffer
2664 Buffer * buffer = theBufferList().getBuffer(active_file);
2665 if (buffer && current_view_)
2666 current_view_->setBuffer(buffer);
2668 // clear this list to save a few bytes of RAM
2669 session.lastOpened().clear();
2673 QString const GuiApplication::romanFontName()
2676 font.setStyleHint(QFont::Serif);
2677 font.setFamily("serif");
2679 return QFontInfo(font).family();
2683 QString const GuiApplication::sansFontName()
2686 font.setStyleHint(QFont::SansSerif);
2687 font.setFamily("sans");
2689 return QFontInfo(font).family();
2693 QString const GuiApplication::typewriterFontName()
2695 return QFontInfo(typewriterSystemFont()).family();
2700 // We cannot use QFont::fixedPitch() because it doesn't
2701 // return the fact but only if it is requested.
2702 static bool isFixedPitch(const QFont & font) {
2703 const QFontInfo fi(font);
2704 return fi.fixedPitch();
2709 QFont const GuiApplication::typewriterSystemFont()
2711 #if QT_VERSION >= 0x050200
2712 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2714 QFont font("monospace");
2716 if (!isFixedPitch(font)) {
2717 // try to enforce a real monospaced font
2718 font.setStyleHint(QFont::Monospace);
2719 if (!isFixedPitch(font)) {
2720 font.setStyleHint(QFont::TypeWriter);
2721 if (!isFixedPitch(font)) font.setFamily("courier");
2725 // On a Mac the result is too small and it's not practical to
2726 // rely on Qtconfig utility to change the system settings of Qt.
2727 font.setPointSize(12);
2733 void GuiApplication::handleRegularEvents()
2735 ForkedCallsController::handleCompletedProcesses();
2739 bool GuiApplication::event(QEvent * e)
2742 case QEvent::FileOpen: {
2743 // Open a file; this happens only on Mac OS X for now.
2745 // We do this asynchronously because on startup the batch
2746 // commands are not executed here yet and the gui is not ready
2748 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2749 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2750 processFuncRequestAsync(fr);
2754 #if (QT_VERSION < 0x050000)
2755 // Qt5 uses a signal for that, see above.
2756 case QEvent::KeyboardLayoutChange:
2757 //LYXERR0("keyboard change");
2758 if (currentView() && currentView()->currentBufferView())
2759 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2764 return QApplication::event(e);
2769 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2772 return QApplication::notify(receiver, event);
2774 catch (ExceptionMessage const & e) {
2776 case ErrorException:
2778 setQuitOnLastWindowClosed(false);
2780 Alert::error(e.title_, e.details_);
2782 // Properly crash in debug mode in order to get a useful backtrace.
2785 // In release mode, try to exit gracefully.
2787 // FIXME: GCC 7 thinks we can fall through here. Can we?
2789 case BufferException: {
2790 if (!current_view_ || !current_view_->documentBufferView())
2792 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2793 docstring details = e.details_ + '\n';
2794 details += buf->emergencyWrite();
2795 theBufferList().release(buf);
2796 details += "\n" + _("The current document was closed.");
2797 Alert::error(e.title_, details);
2800 case WarningException:
2801 Alert::warning(e.title_, e.details_);
2805 catch (exception const & e) {
2806 docstring s = _("LyX has caught an exception, it will now "
2807 "attempt to save all unsaved documents and exit."
2809 s += from_ascii(e.what());
2810 Alert::error(_("Software exception Detected"), s);
2814 docstring s = _("LyX has caught some really weird exception, it will "
2815 "now attempt to save all unsaved documents and exit.");
2816 Alert::error(_("Software exception Detected"), s);
2824 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2826 QColor const & qcol = d->color_cache_.get(col);
2827 if (!qcol.isValid()) {
2833 rgbcol.r = qcol.red();
2834 rgbcol.g = qcol.green();
2835 rgbcol.b = qcol.blue();
2840 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2842 QColor const qcol(lcolor.getX11HexName(col).c_str());
2843 if (!qcol.isValid()) {
2849 rgbcol.r = qcol.red();
2850 rgbcol.g = qcol.green();
2851 rgbcol.b = qcol.blue();
2856 string const GuiApplication::hexName(ColorCode col)
2858 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2862 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2864 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2865 d->socket_notifiers_[fd] = sn;
2866 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2870 void GuiApplication::socketDataReceived(int fd)
2872 d->socket_notifiers_[fd]->func_();
2876 void GuiApplication::unregisterSocketCallback(int fd)
2878 d->socket_notifiers_.take(fd)->setEnabled(false);
2882 void GuiApplication::commitData(QSessionManager & sm)
2884 /** The implementation is required to avoid an application exit
2885 ** when session state save is triggered by session manager.
2886 ** The default implementation sends a close event to all
2887 ** visible top level widgets when session management allows
2889 ** We are changing that to check the state of each buffer in all
2890 ** views and ask the users what to do if buffers are dirty.
2891 ** Furthermore, we save the session state.
2892 ** We do NOT close the views here since the user still can cancel
2893 ** the logout process (see #9277); also, this would hide LyX from
2894 ** an OSes own session handling (application restoration).
2896 #ifdef QT_NO_SESSIONMANAGER
2898 #warning Qt is compiled without session manager
2900 #pragma message("warning: Qt is compiled without session manager")
2904 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2912 void GuiApplication::unregisterView(GuiView * gv)
2914 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2915 d->views_.remove(gv->id());
2916 if (current_view_ == gv)
2922 bool GuiApplication::closeAllViews()
2924 if (d->views_.empty())
2927 // When a view/window was closed before without quitting LyX, there
2928 // are already entries in the lastOpened list.
2929 theSession().lastOpened().clear();
2931 QList<GuiView *> const views = d->views_.values();
2932 for (GuiView * view : views) {
2933 if (!view->closeScheduled())
2942 bool GuiApplication::prepareAllViewsForLogout()
2944 if (d->views_.empty())
2947 QList<GuiView *> const views = d->views_.values();
2948 for (GuiView * view : views) {
2949 if (!view->prepareAllBuffersForLogout())
2957 GuiView & GuiApplication::view(int id) const
2959 LAPPERR(d->views_.contains(id));
2960 return *d->views_.value(id);
2964 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
2966 QList<GuiView *> const views = d->views_.values();
2967 for (GuiView * view : views)
2968 view->hideDialog(name, inset);
2972 Buffer const * GuiApplication::updateInset(Inset const * inset) const
2974 Buffer const * buf = 0;
2975 QHash<int, GuiView *>::const_iterator end = d->views_.end();
2976 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
2977 if (Buffer const * ptr = (*it)->updateInset(inset))
2984 bool GuiApplication::searchMenu(FuncRequest const & func,
2985 docstring_list & names) const
2987 BufferView * bv = 0;
2989 bv = current_view_->currentBufferView();
2990 return d->menus_.searchMenu(func, names, bv);
2994 bool GuiApplication::hasBufferView() const
2996 return (current_view_ && current_view_->currentBufferView());
3000 // Ensure that a file is read only once (prevents include loops)
3001 static QStringList uifiles;
3002 // store which ui files define Toolbars
3003 static QStringList toolbar_uifiles;
3006 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
3017 LexerKeyword uitags[] = {
3018 { "format", ui_format },
3019 { "include", ui_include },
3020 { "menuset", ui_menuset },
3021 { "toolbars", ui_toolbars },
3022 { "toolbarset", ui_toolbarset }
3026 lex.setFile(ui_path);
3028 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3032 if (lyxerr.debugging(Debug::PARSER))
3033 lex.printTable(lyxerr);
3036 // format before introduction of format tag
3037 unsigned int format = 0;
3038 while (lex.isOK()) {
3039 int const status = lex.lex();
3041 // we have to do this check here, outside the switch,
3042 // because otherwise we would start reading include files,
3043 // e.g., if the first tag we hit was an include tag.
3044 if (status == ui_format)
3046 format = lex.getInteger();
3050 // this will trigger unless the first tag we hit is a format
3051 // tag, with the right format.
3052 if (format != LFUN_FORMAT)
3053 return FormatMismatch;
3056 case Lexer::LEX_FEOF:
3061 QString const file = toqstr(lex.getString());
3062 bool const success = readUIFile(file, true);
3064 LYXERR0("Failed to read included file: " << fromqstr(file));
3071 d->menus_.read(lex);
3075 d->toolbars_.readToolbars(lex);
3079 d->toolbars_.readToolbarSettings(lex);
3080 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3084 if (!rtrim(lex.getString()).empty())
3085 lex.printError("LyX::ReadUIFile: "
3086 "Unknown menu tag: `$$Token'");
3088 LYXERR0("Error with status: " << status);
3094 return (error ? ReadError : ReadOK);
3098 bool GuiApplication::readUIFile(QString const & name, bool include)
3100 LYXERR(Debug::INIT, "About to read " << name << "...");
3104 ui_path = libFileSearch("ui", name, "inc");
3105 if (ui_path.empty())
3106 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3108 ui_path = libFileSearch("ui", name, "ui");
3111 if (ui_path.empty()) {
3112 static const QString defaultUIFile = "default";
3113 LYXERR(Debug::INIT, "Could not find " << name);
3115 Alert::warning(_("Could not find UI definition file"),
3116 bformat(_("Error while reading the included file\n%1$s\n"
3117 "Please check your installation."), qstring_to_ucs4(name)));
3120 if (name == defaultUIFile) {
3121 LYXERR(Debug::INIT, "Could not find default UI file!!");
3122 Alert::warning(_("Could not find default UI file"),
3123 _("LyX could not find the default UI file!\n"
3124 "Please check your installation."));
3127 Alert::warning(_("Could not find UI definition file"),
3128 bformat(_("Error while reading the configuration file\n%1$s\n"
3129 "Falling back to default.\n"
3130 "Please look under Tools>Preferences>User Interface and\n"
3131 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3132 return readUIFile(defaultUIFile, false);
3135 QString const uifile = toqstr(ui_path.absFileName());
3136 if (uifiles.contains(uifile)) {
3138 // We are reading again the top uifile so reset the safeguard:
3141 d->toolbars_.reset();
3143 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3144 << "Is this an include loop?");
3148 uifiles.push_back(uifile);
3150 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3152 ReturnValues retval = readUIFile(ui_path);
3154 if (retval == FormatMismatch) {
3155 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3156 TempFile tmp("convertXXXXXX.ui");
3157 FileName const tempfile = tmp.name();
3158 bool const success = prefs2prefs(ui_path, tempfile, true);
3160 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3161 " to format " << LFUN_FORMAT << ".");
3163 retval = readUIFile(tempfile);
3167 if (retval != ReadOK) {
3168 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3176 settings.beginGroup("ui_files");
3177 bool touched = false;
3178 for (int i = 0; i != uifiles.size(); ++i) {
3179 QFileInfo fi(uifiles[i]);
3180 QDateTime const date_value = fi.lastModified();
3181 QString const name_key = QString::number(i);
3182 // if an ui file which defines Toolbars has changed,
3183 // we have to reset the settings
3184 if (toolbar_uifiles.contains(uifiles[i])
3185 && (!settings.contains(name_key)
3186 || settings.value(name_key).toString() != uifiles[i]
3187 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3189 settings.setValue(name_key, uifiles[i]);
3190 settings.setValue(name_key + "/date", date_value);
3193 settings.endGroup();
3195 settings.remove("views");
3201 void GuiApplication::onLastWindowClosed()
3203 if (d->global_menubar_)
3204 d->global_menubar_->grabKeyboard();
3208 void GuiApplication::startLongOperation() {
3209 d->key_checker_.start();
3213 bool GuiApplication::longOperationCancelled() {
3214 return d->key_checker_.pressed();
3218 void GuiApplication::stopLongOperation() {
3219 d->key_checker_.stop();
3223 bool GuiApplication::longOperationStarted() {
3224 return d->key_checker_.started();
3228 ////////////////////////////////////////////////////////////////////////
3230 // X11 specific stuff goes here...
3233 bool GuiApplication::x11EventFilter(XEvent * xev)
3238 switch (xev->type) {
3239 case SelectionRequest: {
3240 if (xev->xselectionrequest.selection != XA_PRIMARY)
3242 LYXERR(Debug::SELECTION, "X requested selection.");
3243 BufferView * bv = current_view_->currentBufferView();
3245 docstring const sel = bv->requestSelection();
3247 d->selection_.put(sel);
3248 // Refresh the selection request timestamp.
3249 // We have to do this by ourselves as Qt seems
3250 // not doing that, maybe because of our
3251 // "persistent selection" implementation
3252 // (see comments in GuiSelection.cpp).
3253 XSelectionEvent nev;
3254 nev.type = SelectionNotify;
3255 nev.display = xev->xselectionrequest.display;
3256 nev.requestor = xev->xselectionrequest.requestor;
3257 nev.selection = xev->xselectionrequest.selection;
3258 nev.target = xev->xselectionrequest.target;
3259 nev.property = 0L; // None
3260 nev.time = CurrentTime;
3261 XSendEvent(QX11Info::display(),
3262 nev.requestor, False, 0,
3263 reinterpret_cast<XEvent *>(&nev));
3269 case SelectionClear: {
3270 if (xev->xselectionclear.selection != XA_PRIMARY)
3272 LYXERR(Debug::SELECTION, "Lost selection.");
3273 BufferView * bv = current_view_->currentBufferView();
3275 bv->clearSelection();
3281 #elif defined(QPA_XCB)
3282 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3283 void * message, long *)
3285 if (!current_view_ || eventType != "xcb_generic_event_t")
3288 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3290 switch (ev->response_type) {
3291 case XCB_SELECTION_REQUEST: {
3292 xcb_selection_request_event_t * srev =
3293 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3294 if (srev->selection != XCB_ATOM_PRIMARY)
3296 LYXERR(Debug::SELECTION, "X requested selection.");
3297 BufferView * bv = current_view_->currentBufferView();
3299 docstring const sel = bv->requestSelection();
3301 d->selection_.put(sel);
3302 #ifdef HAVE_QT5_X11_EXTRAS
3303 // Refresh the selection request timestamp.
3304 // We have to do this by ourselves as Qt seems
3305 // not doing that, maybe because of our
3306 // "persistent selection" implementation
3307 // (see comments in GuiSelection.cpp).
3308 // It is expected that every X11 event is
3309 // 32 bytes long, even if not all 32 bytes are
3311 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3312 struct alignas(32) padded_event
3313 : xcb_selection_notify_event_t {};
3314 padded_event nev = {};
3315 nev.response_type = XCB_SELECTION_NOTIFY;
3316 nev.requestor = srev->requestor;
3317 nev.selection = srev->selection;
3318 nev.target = srev->target;
3319 nev.property = XCB_NONE;
3320 nev.time = XCB_CURRENT_TIME;
3321 xcb_connection_t * con = QX11Info::connection();
3322 xcb_send_event(con, 0, srev->requestor,
3323 XCB_EVENT_MASK_NO_EVENT,
3324 reinterpret_cast<char const *>(&nev));
3332 case XCB_SELECTION_CLEAR: {
3333 xcb_selection_clear_event_t * scev =
3334 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3335 if (scev->selection != XCB_ATOM_PRIMARY)
3337 LYXERR(Debug::SELECTION, "Lost selection.");
3338 BufferView * bv = current_view_->currentBufferView();
3340 bv->clearSelection();
3348 } // namespace frontend
3351 void hideDialogs(std::string const & name, Inset * inset)
3354 frontend::guiApp->hideDialogs(name, inset);
3358 ////////////////////////////////////////////////////////////////////
3362 ////////////////////////////////////////////////////////////////////
3364 frontend::FontLoader & theFontLoader()
3366 LAPPERR(frontend::guiApp);
3367 return frontend::guiApp->fontLoader();
3371 frontend::FontMetrics const & theFontMetrics(Font const & f)
3373 return theFontMetrics(f.fontInfo());
3377 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3379 LAPPERR(frontend::guiApp);
3380 return frontend::guiApp->fontLoader().metrics(f);
3384 ////////////////////////////////////////////////////////////////////
3388 ////////////////////////////////////////////////////////////////////
3390 frontend::Clipboard & theClipboard()
3392 LAPPERR(frontend::guiApp);
3393 return frontend::guiApp->clipboard();
3397 frontend::Selection & theSelection()
3399 LAPPERR(frontend::guiApp);
3400 return frontend::guiApp->selection();
3406 #include "moc_GuiApplication.cpp"