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"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
23 #include "qt_helpers.h"
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
37 #include "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/environment.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/ForkedCalls.h"
70 #include "support/gettext.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/lyxalgo.h" // sorted
74 #include "support/textutils.h"
75 #include "support/Messages.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/TempFile.h"
81 #include "support/AppleScript.h"
82 #include "support/AppleSupport.h"
83 #include "support/linkback/LinkBackProxy.h"
92 #include <QDesktopWidget>
94 #include <QFileOpenEvent>
96 #include <QFontDatabase>
99 #include <QImageReader>
102 #include <QLibraryInfo>
110 #include <QSessionManager>
112 #include <QSocketNotifier>
113 #include <QSortFilterProxyModel>
114 #include <QStandardItemModel>
116 #include <QTranslator>
117 #include <QThreadPool>
121 #include <X11/Xatom.h>
122 #include <X11/Xlib.h>
126 #elif defined(QPA_XCB)
128 #ifdef HAVE_QT5_X11_EXTRAS
129 #include <QtX11Extras/QX11Info>
133 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
134 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
135 #if (QT_VERSION < 0x050000)
136 #include <QWindowsMime>
137 #define QWINDOWSMIME QWindowsMime
140 #define QWINDOWSMIME QWinMime
150 #include <QMacPasteboardMime>
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);
185 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
186 // macOS does it by itself.
187 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
188 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
189 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
190 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
191 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
192 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
195 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
196 // HighDPI scale factor policy must be set before QGuiApplication is created
197 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
198 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
202 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
203 // I'd rather do that in the constructor, but I do not think that
204 // the palette is accessible there.
205 guiApp->colorCache().setPalette(guiApp->palette());
214 if (lyxrc.gui_language == "auto") {
215 theLocale = QLocale::system();
216 code = fromqstr(theLocale.name());
218 Language const * l = languages.getLanguage(lyxrc.gui_language);
219 code = l ? l->code() : "C";
220 theLocale = QLocale(toqstr(code));
222 // Qt tries to outsmart us and transforms en_US to C.
223 Messages::guiLanguage((code == "C") ? "en_US" : code);
224 QLocale::setDefault(theLocale);
225 setlocale(LC_NUMERIC, "C");
232 /// Return the list of loadable formats.
233 vector<string> loadableImageFormats()
237 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
239 LYXERR(Debug::GRAPHICS,
240 "\nThe image loader can load the following directly:\n");
242 if (qt_formats.empty())
243 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
245 bool jpeg_found = false;
246 bool jpg_found = false;
247 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
249 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
251 string ext = ascii_lowercase((const char *) *it);
259 else if (ext == "jpg") {
264 else if (lyxrc.use_converter_cache &&
265 (ext == "svg" || ext == "svgz") &&
266 theConverters().isReachable("svg", "png"))
267 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
268 // the SVG as in the output. However we require that the converter
269 // cache is enabled since this is expensive. We also require that
270 // an explicit svg->png converter is defined, since the default
271 // converter could produce bad quality as well. This assumes that
272 // png can always be loaded.
281 ////////////////////////////////////////////////////////////////////////
283 // Icon loading support code
285 ////////////////////////////////////////////////////////////////////////
295 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
297 return lhs.key < rhs.key;
303 CompareKey(QString const & name) : name_(name) {}
304 bool operator()(ImgMap const & other) const { return other.key == name_; }
310 // this must be sorted alphabetically
311 // Upper case comes before lower case
312 // Please don't change the formatting, this list is parsed by
313 // development/tools/generate_symbols_images.py.
314 ImgMap sorted_img_map[] = {
315 { "Arrownot", "arrownot2"},
316 { "Arrowvert", "arrowvert2"},
317 { "Bowtie", "bowtie2" },
319 { "Bumpeq", "bumpeq2" },
320 { "CIRCLE", "circle3" },
322 { "CheckedBox", "checkedbox2" },
323 { "Circle", "circle2" },
324 { "Colonapprox", "colonapprox2" },
325 { "Coloneq", "coloneq2" },
326 { "Coloneqq", "coloneqq2" },
327 { "Colonsim", "colonsim2" },
329 { "DOWNarrow", "downarrow3" },
330 { "Delta", "delta2" },
331 { "Diamond", "diamond2" },
332 { "Doteq", "doteq2" },
333 { "Downarrow", "downarrow2" },
334 { "Eqcolon", "eqcolon2" },
335 { "Eqqcolon", "eqqcolon2" },
336 { "Gamma", "gamma2" },
338 { "LEFTCIRCLE", "leftcircle3" },
339 { "LEFTarrow", "leftarrow3" },
340 { "LEFTcircle", "leftcircle4" },
342 { "Lambda", "lambda2" },
344 { "Leftarrow", "leftarrow2" },
345 { "Leftcircle", "leftcircle2" },
346 { "Leftrightarrow", "leftrightarrow2" },
347 { "Longarrownot", "longarrownot2"},
348 { "Longleftarrow", "longleftarrow2" },
349 { "Longleftrightarrow", "longleftrightarrow2" },
350 { "Longmapsfrom", "longmapsfrom2"},
351 { "Longmapsto", "longmapsto2"},
352 { "Longrightarrow", "longrightarrow2" },
353 { "Mapsfrom", "mapsfrom2"},
354 { "Mapsfromchar", "mapsfromchar2"},
355 { "Mapsto", "mapsto2"},
356 { "Mapstochar", "mapstochar2"},
357 { "Omega", "omega2" },
362 { "RIGHTCIRCLE", "rightcircle3" },
363 { "RIGHTarrow", "rightarrow3" },
364 { "RIGHTcircle", "rightcircle4" },
366 { "Rightarrow", "rightarrow2" },
367 { "Rightcircle", "rightcircle2" },
368 { "Sigma", "sigma2" },
369 { "Square", "square2" },
370 { "Subset", "subset2" },
371 { "Supset", "supset2" },
372 { "Theta", "theta2" },
373 { "Thorn", "thorn2" },
374 { "UParrow", "uparrow3" },
375 { "Uparrow", "uparrow2" },
376 { "Updownarrow", "updownarrow2" },
377 { "Upsilon", "upsilon2" },
378 { "Vdash", "vdash3" },
383 { "lVert", "vert2" },
385 { "nLeftarrow", "nleftarrow2" },
386 { "nLeftrightarrow", "nleftrightarrow2" },
387 { "nRightarrow", "nrightarrow2" },
388 { "nVDash", "nvdash3" },
389 { "nVdash", "nvdash4" },
390 { "nvDash", "nvdash2" },
391 { "rVert", "vert2" },
393 { "textrm \\AA", "textrm_AA"},
394 { "textrm \\O", "textrm_O"},
395 { "vDash", "vdash2" },
396 { "varDelta", "vardelta2" },
397 { "varGamma", "vargamma2" },
398 { "varLambda", "varlambda2" },
399 { "varOmega", "varomega2" },
400 { "varPhi", "varphi2" },
401 { "varPi", "varpi2" },
402 { "varPsi", "varpsi2" },
403 { "varSigma", "varsigma2" },
404 { "varTheta", "vartheta2" },
405 { "varUpsilon", "varupsilon2" },
406 { "varXi", "varxi2" }
410 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
412 // This list specifies which system's theme icon is related to which lyx
413 // command. It was based on:
414 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
415 // this must be sorted alphabetically
416 // Upper case comes before lower case
417 ImgMap sorted_theme_icon_map[] = {
418 { "bookmark-goto 0", "go-jump" },
419 { "buffer-new", "document-new" },
420 { "buffer-write", "document-save" },
421 { "buffer-write-as", "document-save-as" },
422 { "buffer-zoom-in", "zoom-in" },
423 { "buffer-zoom-out", "zoom-out" },
424 { "copy", "edit-copy" },
425 { "cut", "edit-cut" },
426 { "depth-decrement", "format-indent-less" },
427 { "depth-increment", "format-indent-more" },
428 { "dialog-show spellchecker", "tools-check-spelling" },
429 { "dialog-show-new-inset graphics", "insert-image" },
430 { "dialog-toggle findreplaceadv", "edit-find-replace" },
431 { "file-open", "document-open" },
432 { "font-bold", "format-text-bold" },
433 { "font-ital", "format-text-italic" },
434 { "font-strikeout", "format-text-strikethrough" },
435 { "font-underline", "format-text-underline" },
436 { "lyx-quit", "application-exit" },
437 { "paste", "edit-paste" },
438 { "redo", "edit-redo" },
439 { "undo", "edit-undo" },
440 { "window-close", "window-close" },
441 { "window-new", "window-new" }
444 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
447 QString findImg(QString const & name)
449 ImgMap const * const begin = sorted_img_map;
450 ImgMap const * const end = begin + nr_sorted_img_map;
451 LATTEST(sorted(begin, end));
453 ImgMap const * const it = find_if(begin, end, CompareKey(name));
457 img_name = it->value;
460 img_name.replace('_', "underscore");
461 img_name.replace(' ', '_');
463 // This way we can have "math-delim { }" on the toolbar.
464 img_name.replace('(', "lparen");
465 img_name.replace(')', "rparen");
466 img_name.replace('[', "lbracket");
467 img_name.replace(']', "rbracket");
468 img_name.replace('{', "lbrace");
469 img_name.replace('}', "rbrace");
470 img_name.replace('|', "bars");
471 img_name.replace(',', "thinspace");
472 img_name.replace(':', "mediumspace");
473 img_name.replace(';', "thickspace");
474 img_name.replace('!', "negthinspace");
477 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
478 << "Looking for math icon called \"" << img_name << '"');
485 QString themeIconName(QString const & action)
487 ImgMap const * const begin = sorted_theme_icon_map;
488 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
489 LASSERT(sorted(begin, end), /**/);
491 ImgMap const * const it = find_if(begin, end, CompareKey(action));
499 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
504 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
506 if (!f.argument().empty()) {
507 // if there are arguments, first search an icon which name is the full thing
508 QString name = lfunname + ' ' + toqstr(f.argument());
509 name.replace(' ', '_');
510 name.replace(';', '_');
511 name.replace('\\', "backslash");
512 // avoid duplication for these
513 name.replace("dialog-toggle", "dialog-show");
516 // then special default icon for some lfuns
517 switch (f.action()) {
518 case LFUN_MATH_INSERT:
519 names << "math/" + findImg(toqstr(f.argument()).mid(1));
521 case LFUN_MATH_DELIM:
522 case LFUN_MATH_BIGDELIM:
523 names << "math/" + findImg(toqstr(f.argument()));
526 names << "commands/" + toqstr(f.argument());
528 case LFUN_COMMAND_ALTERNATIVES: {
529 // use the first of the alternative commands
531 docstring dummy = split(f.argument(), firstcom, ';');
532 QString name1 = toqstr(firstcom);
533 name1.replace(' ', '_');
534 name1.replace(';', '_');
535 name1.replace('\\', "backslash");
544 // next thing to try is function name alone
547 // and finally maybe the unknown icon
551 search_mode const mode = theGuiApp()->imageSearchMode();
552 // The folders where icons are searched for
553 QStringList imagedirs;
554 imagedirs << "images/ipa/" << "images/";
555 // This is used to search for rtl version of icons which have the +rrtl suffix.
556 QStringList suffixes;
559 suffixes << QString();
561 for (QString const & imagedir : imagedirs)
562 for (QString const & name : names)
563 for (QString const & suffix : suffixes) {
564 QString id = imagedir;
565 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
566 if (fname.exists()) {
567 docstring const fpath = fname.absoluteFilePath();
568 res.filepath = toqstr(fname.absFileName());
569 // these icons are subject to inversion in dark mode
570 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
571 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
572 res.swap = rtl && suffix.isEmpty();
577 LYXERR(Debug::GUI, "Cannot find icon for command \""
578 << lyxaction.getActionName(f.action())
579 << '(' << to_utf8(f.argument()) << ")\"");
585 QPixmap prepareForDarkMode(QPixmap pixmap)
587 QPalette palette = QPalette();
588 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
589 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
591 // guess whether we are in dark mode
592 if (text_color.black() > bg_color.black())
593 // not in dark mode, do nothing
596 // create a layer with black text turned to QPalette::WindowText
597 QPixmap black_overlay(pixmap.size());
598 black_overlay.fill(text_color);
599 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
601 // create a layer with blue text turned to lighter blue
602 QPixmap blue_overlay(pixmap.size());
603 QColor math_blue(0, 0, 255);
604 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
605 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
607 // create a layer with ("latex") red text turned to lighter red
608 QPixmap red_overlay(pixmap.size());
609 QColor math_red(128, 0, 0);
610 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
611 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
613 // put layers on top of existing pixmap
614 QPainter painter(&pixmap);
615 painter.drawPixmap(pixmap.rect(), black_overlay);
616 painter.drawPixmap(pixmap.rect(), blue_overlay);
617 painter.drawPixmap(pixmap.rect(), red_overlay);
623 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
625 QString imagedir = path;
626 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
627 QString fpath = toqstr(fname.absFileName());
628 QPixmap pixmap = QPixmap();
630 if (pixmap.load(fpath)) {
631 if (fpath.contains("math") || fpath.contains("ipa")
632 || fpath.contains("bullets"))
633 return prepareForDarkMode(pixmap);
637 bool const list = ext.contains(",");
638 LYXERR(Debug::GUI, "Cannot load pixmap \""
639 << path << "/" << name << "." << (list ? "{" : "") << ext
640 << (list ? "}" : "") << "\".");
646 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
648 #if (QT_VERSION >= 0x040600)
649 if (lyxrc.use_system_theme_icons) {
650 // use the icons from system theme that are available
651 QString action = toqstr(lyxaction.getActionName(f.action()));
652 if (!f.argument().empty())
653 action += " " + toqstr(f.argument());
654 QString const theme_icon = themeIconName(action);
655 if (QIcon::hasThemeIcon(theme_icon)) {
656 QIcon const thmicn = QIcon::fromTheme(theme_icon);
657 if (!thmicn.isNull())
663 IconInfo icondata = iconInfo(f, unknown, rtl);
664 if (icondata.filepath.isEmpty())
667 //LYXERR(Debug::GUI, "Found icon: " << icon);
668 QPixmap pixmap = QPixmap();
669 if (!pixmap.load(icondata.filepath)) {
670 LYXERR0("Cannot load icon " << icondata.filepath << ".");
675 pixmap = prepareForDarkMode(pixmap);
678 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
680 return QIcon(pixmap);
684 ////////////////////////////////////////////////////////////////////////
686 // LyX server support code.
688 ////////////////////////////////////////////////////////////////////////
690 class SocketNotifier : public QSocketNotifier
693 /// connect a connection notification from the LyXServerSocket
694 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
695 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
699 /// The callback function
700 Application::SocketCallback func_;
704 class GuiTranslator : public QTranslator
707 GuiTranslator(QObject * parent = nullptr)
708 : QTranslator(parent)
711 QString translate(const char * /* context */,
712 const char *sourceText,
713 #if QT_VERSION >= 0x050000
714 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
716 const char * /*comment*/ = 0) const override
719 // Here we declare the strings that need to be translated from Qt own GUI
720 // This is needed to include these strings to po files
724 _("Restore Defaults");
727 // Already in po: "Cancel", "&Cancel"
728 _("Apply"); // Already in po: "&Apply"
729 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
732 docstring s = getGuiMessages().getIfFound(sourceText);
733 // This test should eventually be removed when translations are updated
735 LYXERR(Debug::LOCALE, "Missing translation for `"
736 << string(sourceText) << "'");
742 ////////////////////////////////////////////////////////////////////////
744 // Mac specific stuff goes here...
746 ////////////////////////////////////////////////////////////////////////
749 // QMacPasteboardMimeGraphics can only be compiled on Mac.
751 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
754 QMacPasteboardMimeGraphics()
755 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
758 QString convertorName() { return "Graphics"; }
760 QString flavorFor(QString const & mime)
762 LYXERR(Debug::ACTION, "flavorFor " << mime);
763 if (mime == pdfMimeType())
764 return QLatin1String("com.adobe.pdf");
768 QString mimeFor(QString flav)
770 LYXERR(Debug::ACTION, "mimeFor " << flav);
771 if (flav == QLatin1String("com.adobe.pdf"))
772 return pdfMimeType();
776 bool canConvert(QString const & mime, QString flav)
778 return mimeFor(flav) == mime;
781 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
785 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
789 QList<QByteArray> convertFromMime(QString const & /*mime*/,
790 QVariant data, QString /*flav*/)
792 QList<QByteArray> ret;
793 ret.append(data.toByteArray());
799 ///////////////////////////////////////////////////////////////
801 // You can find more platform specific stuff at the end of this file...
803 ///////////////////////////////////////////////////////////////
805 ////////////////////////////////////////////////////////////////////////
806 // Windows specific stuff goes here...
808 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
809 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
810 // QWindowsMimeMetafile can only be compiled on Windows.
812 static FORMATETC cfFromMime(QString const & mimetype)
815 if (mimetype == emfMimeType()) {
816 formatetc.cfFormat = CF_ENHMETAFILE;
817 formatetc.tymed = TYMED_ENHMF;
818 } else if (mimetype == wmfMimeType()) {
819 formatetc.cfFormat = CF_METAFILEPICT;
820 formatetc.tymed = TYMED_MFPICT;
823 formatetc.dwAspect = DVASPECT_CONTENT;
824 formatetc.lindex = -1;
829 class QWindowsMimeMetafile : public QWINDOWSMIME {
831 QWindowsMimeMetafile() {}
833 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
834 QMimeData const * /*mimedata*/) const override
839 bool canConvertToMime(QString const & mimetype,
840 IDataObject * pDataObj) const override
842 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
844 FORMATETC formatetc = cfFromMime(mimetype);
845 return pDataObj->QueryGetData(&formatetc) == S_OK;
848 bool convertFromMime(FORMATETC const & /*formatetc*/,
849 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
854 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
855 QVariant::Type /*preferredType*/) const override
858 if (!canConvertToMime(mimetype, pDataObj))
861 FORMATETC formatetc = cfFromMime(mimetype);
863 if (pDataObj->GetData(&formatetc, &s) != S_OK)
867 if (s.tymed == TYMED_ENHMF) {
868 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
869 data.resize(dataSize);
870 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
871 (LPBYTE)data.data());
872 } else if (s.tymed == TYMED_MFPICT) {
873 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
874 data.resize(dataSize);
875 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
876 (LPBYTE)data.data());
879 ReleaseStgMedium(&s);
885 QVector<FORMATETC> formatsForMime(QString const & mimetype,
886 QMimeData const * /*mimedata*/) const override
888 QVector<FORMATETC> formats;
889 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
890 formats += cfFromMime(mimetype);
894 QString mimeForFormat(FORMATETC const & formatetc) const override
896 switch (formatetc.cfFormat) {
898 return emfMimeType();
899 case CF_METAFILEPICT:
900 return wmfMimeType();
910 /// Allows to check whether ESC was pressed during a long operation
911 class KeyChecker : public QObject {
916 KeyChecker() : pressed_(false), started_(false) {}
919 QCoreApplication::instance()->installEventFilter(this);
924 QCoreApplication::instance()->removeEventFilter(this);
928 QCoreApplication::processEvents();
931 bool started() const {
934 bool eventFilter(QObject *obj, QEvent *event) override {
935 LYXERR(Debug::ACTION, "Event Type: " << event->type());
936 switch (event->type()) {
940 case QEvent::UpdateRequest:
941 case QEvent::CursorChange:
942 case QEvent::ActionChanged:
943 case QEvent::EnabledChange:
944 case QEvent::SockAct:
947 case QEvent::ToolTipChange:
948 case QEvent::LayoutRequest:
949 case QEvent::MetaCall:
950 return QObject::eventFilter(obj, event);
952 // FIXME Blocking all these events is a bad idea.
953 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
954 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
962 ////////////////////////////////////////////////////////////////////////
963 // GuiApplication::Private definition and implementation.
964 ////////////////////////////////////////////////////////////////////////
966 struct GuiApplication::Private
968 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
969 global_menubar_(nullptr)
970 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
971 , last_state_(Qt::ApplicationInactive)
974 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
975 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
976 /// WMF Mime handler for Windows clipboard.
977 wmf_mime_ = new QWindowsMimeMetafile;
980 initKeySequences(&theTopLevelKeymap());
983 void initKeySequences(KeyMap * kb)
985 keyseq = KeySequence(kb, kb);
986 cancel_meta_seq = KeySequence(kb, kb);
990 QSortFilterProxyModel * language_model_;
992 GuiClipboard clipboard_;
994 GuiSelection selection_;
996 FontLoader font_loader_;
998 ColorCache color_cache_;
999 /// the built-in Qt translation mechanism
1000 QTranslator qt_trans_;
1001 /// LyX gettext-based translation for Qt elements
1002 GuiTranslator gui_trans_;
1004 QHash<int, SocketNotifier *> socket_notifiers_;
1008 /// The global instance
1011 /// this timer is used for any regular events one wants to
1012 /// perform. at present it is used to check if forked processes
1014 QTimer general_timer_;
1016 /// delayed FuncRequests
1017 std::queue<FuncRequest> func_request_queue_;
1022 KeySequence cancel_meta_seq;
1024 KeyModifier meta_fake_bit;
1026 /// The result of last dispatch action
1027 DispatchResult dispatch_result_;
1029 /// Multiple views container.
1031 * Warning: This must not be a smart pointer as the destruction of the
1032 * object is handled by Qt when the view is closed
1033 * \sa Qt::WA_DeleteOnClose attribute.
1035 QHash<int, GuiView *> views_;
1037 /// Only used on mac.
1038 QMenuBar * global_menubar_;
1039 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1040 /// Holds previous application state on Mac
1041 Qt::ApplicationState last_state_;
1045 /// Linkback mime handler for MacOSX.
1046 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1049 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1050 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1051 /// WMF Mime handler for Windows clipboard.
1052 QWindowsMimeMetafile * wmf_mime_;
1056 /// Allows to check whether ESC was pressed during a long operation
1057 KeyChecker key_checker_;
1061 GuiApplication * guiApp;
1063 GuiApplication::~GuiApplication()
1066 closeAllLinkBackLinks();
1072 GuiApplication::GuiApplication(int & argc, char ** argv)
1073 : QApplication(argc, argv), current_view_(nullptr),
1074 d(new GuiApplication::Private)
1076 QString app_name = "LyX";
1077 QCoreApplication::setOrganizationName(app_name);
1078 QCoreApplication::setOrganizationDomain("lyx.org");
1079 QCoreApplication::setApplicationName(lyx_package);
1080 #if QT_VERSION >= 0x050000
1081 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1084 #if QT_VERSION >= 0x050700
1085 setDesktopFileName(lyx_package);
1088 // FIXME Deprecated. Should use QRandomGenerator since 5.10
1089 qsrand(QDateTime::currentDateTime().toTime_t());
1091 // Install LyX translator for missing Qt translations
1092 installTranslator(&d->gui_trans_);
1093 // Install Qt native translator for GUI elements.
1094 installTranslator(&d->qt_trans_);
1097 // Enable reception of XCB events.
1098 installNativeEventFilter(this);
1101 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1102 // lyxrc setting for this in order to let the application stay resident.
1103 // But then we need some kind of dock icon, at least on Windows.
1105 if (lyxrc.quit_on_last_window_closed)
1106 setQuitOnLastWindowClosed(false);
1109 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1110 // seems to be the default case for applications like LyX.
1111 setQuitOnLastWindowClosed(false);
1114 appleCleanupEditMenu();
1115 appleCleanupViewMenu();
1116 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1117 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1118 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1122 #if defined(Q_WS_X11) || defined(QPA_XCB)
1123 // doubleClickInterval() is 400 ms on X11 which is just too long.
1124 // On Windows and Mac OS X, the operating system's value is used.
1125 // On Microsoft Windows, calling this function sets the double
1126 // click interval for all applications. So we don't!
1127 QApplication::setDoubleClickInterval(300);
1130 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1132 // needs to be done before reading lyxrc
1134 lyxrc.dpi = (w.physicalDpiX() + w.physicalDpiY()) / 2;
1138 // Initialize RC Fonts
1139 if (lyxrc.roman_font_name.empty())
1140 lyxrc.roman_font_name = fromqstr(romanFontName());
1142 if (lyxrc.sans_font_name.empty())
1143 lyxrc.sans_font_name = fromqstr(sansFontName());
1145 if (lyxrc.typewriter_font_name.empty())
1146 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1148 #if (QT_VERSION >= 0x050000)
1149 // Qt4 does this in event(), see below.
1150 // Track change of keyboard
1151 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1154 d->general_timer_.setInterval(500);
1155 connect(&d->general_timer_, SIGNAL(timeout()),
1156 this, SLOT(handleRegularEvents()));
1157 d->general_timer_.start();
1159 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1160 // This is clearly not enough in a time where we use threads for
1161 // document preview and/or export. 20 should be OK.
1162 QThreadPool::globalInstance()->setMaxThreadCount(20);
1164 // make sure tooltips are formatted
1165 installEventFilter(new ToolTipFormatter(this));
1169 GuiApplication * theGuiApp()
1171 return dynamic_cast<GuiApplication *>(theApp());
1175 #if QT_VERSION < 0x050000
1176 // Emulate platformName() for Qt4
1178 // FIXME: when ditching this method, remove all tests
1179 // platformName() == "qt4x11"
1181 QString GuiApplication::platformName() const
1183 # if defined(Q_WS_X11)
1184 // Note that this one does not really exist
1186 # elif defined(Q_OS_MAC)
1188 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1191 LYXERR0("Unknown platform!");
1198 double GuiApplication::pixelRatio() const
1200 #if QT_VERSION >= 0x050000
1201 return qt_scale_factor * devicePixelRatio();
1208 void GuiApplication::clearSession()
1215 docstring Application::iconName(FuncRequest const & f, bool unknown)
1217 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1221 docstring Application::mathIcon(docstring const & c)
1223 return qstring_to_ucs4(findImg(toqstr(c)));
1227 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1231 BufferView * bv = nullptr;
1232 BufferView * doc_bv = nullptr;
1234 if (cmd.action() == LFUN_NOACTION) {
1235 status.message(from_utf8(N_("Nothing to do")));
1236 status.setEnabled(false);
1239 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1240 status.setUnknown(true);
1241 status.message(from_utf8(N_("Unknown action")));
1242 status.setEnabled(false);
1245 // Does the GuiApplication know something?
1246 else if (getStatus(cmd, status)) { }
1248 // If we do not have a GuiView, then other functions are disabled
1249 else if (!current_view_)
1250 status.setEnabled(false);
1252 // Does the GuiView know something?
1253 else if (current_view_->getStatus(cmd, status)) { }
1255 // In LyX/Mac, when a dialog is open, the menus of the
1256 // application can still be accessed without giving focus to
1257 // the main window. In this case, we want to disable the menu
1258 // entries that are buffer or view-related.
1259 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1261 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1262 status.setEnabled(false);
1265 // If we do not have a BufferView, then other functions are disabled
1266 else if (!(bv = current_view_->currentBufferView()))
1267 status.setEnabled(false);
1269 // Does the current BufferView know something?
1270 else if (bv->getStatus(cmd, status)) { }
1272 // Does the current Buffer know something?
1273 else if (bv->buffer().getStatus(cmd, status)) { }
1275 // If we do not have a document BufferView, different from the
1276 // current BufferView, then other functions are disabled
1277 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1278 status.setEnabled(false);
1280 // Does the document Buffer know something?
1281 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1284 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1285 status.message(from_utf8(N_("Command not handled")));
1286 status.setEnabled(false);
1289 // the default error message if we disable the command
1290 if (!status.enabled() && status.message().empty())
1291 status.message(from_utf8(N_("Command disabled")));
1297 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1299 // I would really like to avoid having this switch and rather try to
1300 // encode this in the function itself.
1301 // -- And I'd rather let an inset decide which LFUNs it is willing
1302 // to handle (Andre')
1304 switch (cmd.action()) {
1306 // This could be used for the no-GUI version. The GUI version is handled in
1307 // GuiView::getStatus(). See above.
1309 case LFUN_BUFFER_WRITE:
1310 case LFUN_BUFFER_WRITE_AS:
1311 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1312 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1313 enable = b && (b->isUnnamed() || !b->isClean());
1318 case LFUN_BOOKMARK_GOTO: {
1319 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1320 enable = theSession().bookmarks().isValid(num);
1324 case LFUN_BOOKMARK_CLEAR:
1325 enable = theSession().bookmarks().hasValid();
1328 // this one is difficult to get right. As a half-baked
1329 // solution, we consider only the first action of the sequence
1330 case LFUN_COMMAND_SEQUENCE: {
1331 // argument contains ';'-terminated commands
1332 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1333 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1334 func.setOrigin(cmd.origin());
1335 flag = getStatus(func);
1339 // we want to check if at least one of these is enabled
1340 case LFUN_COMMAND_ALTERNATIVES: {
1341 // argument contains ';'-terminated commands
1342 string arg = to_utf8(cmd.argument());
1343 while (!arg.empty()) {
1345 arg = split(arg, first, ';');
1346 FuncRequest func(lyxaction.lookupFunc(first));
1347 func.setOrigin(cmd.origin());
1348 flag = getStatus(func);
1349 // if this one is enabled, the whole thing is
1358 string name = to_utf8(cmd.argument());
1359 if (theTopLevelCmdDef().lock(name, func)) {
1360 func.setOrigin(cmd.origin());
1361 flag = getStatus(func);
1362 theTopLevelCmdDef().release(name);
1364 // catch recursion or unknown command
1365 // definition. all operations until the
1366 // recursion or unknown command definition
1367 // occurs are performed, so set the state to
1374 case LFUN_IF_RELATIVES: {
1375 string const lfun = to_utf8(cmd.argument());
1376 BufferView const * bv =
1377 current_view_ ? current_view_->currentBufferView() : nullptr;
1378 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1382 FuncRequest func(lyxaction.lookupFunc(lfun));
1383 func.setOrigin(cmd.origin());
1384 flag = getStatus(func);
1388 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1390 case LFUN_PREFERENCES_SAVE:
1391 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1392 case LFUN_DEBUG_LEVEL_SET:
1393 // these are handled in our dispatch()
1396 case LFUN_WINDOW_CLOSE:
1397 enable = !d->views_.empty();
1400 case LFUN_BUFFER_NEW:
1401 case LFUN_BUFFER_NEW_TEMPLATE:
1402 case LFUN_FILE_OPEN:
1403 case LFUN_LYXFILES_OPEN:
1404 case LFUN_HELP_OPEN:
1405 case LFUN_SCREEN_FONT_UPDATE:
1406 case LFUN_SET_COLOR:
1407 case LFUN_WINDOW_NEW:
1409 case LFUN_LYXRC_APPLY:
1410 case LFUN_COMMAND_PREFIX:
1412 case LFUN_META_PREFIX:
1413 case LFUN_RECONFIGURE:
1414 case LFUN_SERVER_GET_FILENAME:
1415 case LFUN_SERVER_NOTIFY:
1419 case LFUN_BUFFER_FORALL: {
1420 if (theBufferList().empty()) {
1421 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1422 flag.setEnabled(false);
1426 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1427 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1428 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1429 flag.setEnabled(false);
1434 case LFUN_DIALOG_SHOW: {
1435 string const name = cmd.getArg(0);
1436 return name == "aboutlyx"
1437 || name == "lyxfiles"
1439 || name == "texinfo"
1440 || name == "progress"
1441 || name == "compare";
1449 flag.setEnabled(false);
1453 /// make a post-dispatch status message
1454 static docstring makeDispatchMessage(docstring const & msg,
1455 FuncRequest const & cmd)
1457 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1458 || cmd.origin() == FuncRequest::TOOLBAR
1459 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1461 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1462 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1466 docstring dispatch_msg = msg;
1467 if (!dispatch_msg.empty())
1468 dispatch_msg += ' ';
1470 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1472 bool argsadded = false;
1474 if (!cmd.argument().empty()) {
1475 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1476 comname += ' ' + cmd.argument();
1480 docstring const shortcuts = theTopLevelKeymap().
1481 printBindings(cmd, KeySequence::ForGui);
1483 if (!shortcuts.empty())
1484 comname += ": " + shortcuts;
1485 else if (!argsadded && !cmd.argument().empty())
1486 comname += ' ' + cmd.argument();
1488 if (!comname.empty()) {
1489 comname = rtrim(comname);
1490 dispatch_msg += '(' + rtrim(comname) + ')';
1492 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1493 return dispatch_msg;
1497 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1501 Buffer * buffer = nullptr;
1502 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1503 //setCurrentView(cmd.view_origin); //does not work
1505 dr.setMessage(_("Wrong focus!"));
1506 d->dispatch_result_ = dr;
1507 return d->dispatch_result_;
1509 if (current_view_ && current_view_->currentBufferView()) {
1510 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1511 buffer = ¤t_view_->currentBufferView()->buffer();
1514 dr.screenUpdate(Update::FitCursor);
1516 // All the code is kept inside the undo group because
1517 // updateBuffer can create undo actions (see #11292)
1518 UndoGroupHelper ugh(buffer);
1520 if (dr.screenUpdate() & Update::ForceAll) {
1521 for (Buffer const * b : theBufferList())
1523 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1526 updateCurrentView(cmd, dr);
1529 d->dispatch_result_ = dr;
1530 return d->dispatch_result_;
1534 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1539 BufferView * bv = current_view_->currentBufferView();
1541 if (dr.needBufferUpdate()) {
1542 bv->cursor().clearBufferUpdate();
1543 bv->buffer().updateBuffer();
1545 // BufferView::update() updates the ViewMetricsInfo and
1546 // also initializes the position cache for all insets in
1547 // (at least partially) visible top-level paragraphs.
1548 // We will redraw the screen only if needed.
1549 bv->processUpdateFlags(dr.screenUpdate());
1551 // Do we have a selection?
1552 theSelection().haveSelection(bv->cursor().selection());
1555 current_view_->restartCaret();
1557 if (dr.needMessageUpdate()) {
1558 // Some messages may already be translated, so we cannot use _()
1559 current_view_->message(makeDispatchMessage(
1560 translateIfPossible(dr.message()), cmd));
1565 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1566 bool switchToBuffer)
1568 if (!theSession().bookmarks().isValid(idx))
1570 BookmarksSection::Bookmark const & bm =
1571 theSession().bookmarks().bookmark(idx);
1572 LASSERT(!bm.filename.empty(), return);
1573 string const file = bm.filename.absFileName();
1574 // if the file is not opened, open it.
1575 if (!theBufferList().exists(bm.filename)) {
1577 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1581 // open may fail, so we need to test it again
1582 if (!theBufferList().exists(bm.filename))
1585 // bm can be changed when saving
1586 BookmarksSection::Bookmark tmp = bm;
1588 // Special case idx == 0 used for back-from-back jump navigation
1590 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1592 // if the current buffer is not that one, switch to it.
1593 BufferView * doc_bv = current_view_ ?
1594 current_view_->documentBufferView() : nullptr;
1595 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1596 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1597 if (switchToBuffer) {
1598 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1601 doc_bv = current_view_->documentBufferView();
1606 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1607 if (!doc_bv || !doc_bv->moveToPosition(
1608 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1611 Cursor & cur = doc_bv->cursor();
1612 if (old && cur != *old)
1613 notifyCursorLeavesOrEnters(*old, cur);
1619 // Cursor jump succeeded!
1620 pit_type new_pit = cur.pit();
1621 pos_type new_pos = cur.pos();
1622 int new_id = cur.paragraph().id();
1624 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1625 // see http://www.lyx.org/trac/ticket/3092
1626 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1627 || bm.top_id != new_id) {
1628 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1629 new_pit, new_pos, new_id);
1633 // This function runs "configure" and then rereads lyx.defaults to
1634 // reconfigure the automatic settings.
1635 void GuiApplication::reconfigure(string const & option)
1637 // emit message signal.
1639 current_view_->message(_("Running configure..."));
1641 // Run configure in user lyx directory
1642 string const lock_file = package().getConfigureLockName();
1643 int fd = fileLock(lock_file.c_str());
1644 int const ret = package().reconfigureUserLyXDir(option);
1645 // emit message signal.
1647 current_view_->message(_("Reloading configuration..."));
1648 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1649 // Re-read packages.lst
1650 LaTeXPackages::getAvailable();
1651 fileUnlock(fd, lock_file.c_str());
1654 Alert::information(_("System reconfiguration failed"),
1655 _("The system reconfiguration has failed.\n"
1656 "Default textclass is used but LyX may\n"
1657 "not be able to work properly.\n"
1658 "Please reconfigure again if needed."));
1660 Alert::information(_("System reconfigured"),
1661 _("The system has been reconfigured.\n"
1662 "You need to restart LyX to make use of any\n"
1663 "updated document class specifications."));
1666 void GuiApplication::validateCurrentView()
1668 if (!d->views_.empty() && !current_view_) {
1669 // currently at least one view exists but no view has the focus.
1670 // choose the last view to make it current.
1671 // a view without any open document is preferred.
1672 GuiView * candidate = nullptr;
1673 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1674 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1675 for (; it != end; ++it) {
1677 if (!candidate->documentBufferView())
1680 setCurrentView(candidate);
1684 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1686 string const argument = to_utf8(cmd.argument());
1687 FuncCode const action = cmd.action();
1689 LYXERR(Debug::ACTION, "cmd: " << cmd);
1691 // we have not done anything wrong yet.
1694 FuncStatus const flag = getStatus(cmd);
1695 if (!flag.enabled()) {
1696 // We cannot use this function here
1697 LYXERR(Debug::ACTION, "action "
1698 << lyxaction.getActionName(action)
1699 << " [" << action << "] is disabled at this location");
1700 dr.setMessage(flag.message());
1702 dr.dispatched(false);
1703 dr.screenUpdate(Update::None);
1704 dr.clearBufferUpdate();
1708 if (cmd.origin() == FuncRequest::LYXSERVER) {
1709 if (current_view_ && current_view_->currentBufferView())
1710 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1711 // we will also need to redraw the screen at the end
1712 dr.screenUpdate(Update::FitCursor);
1715 // Assumes that the action will be dispatched.
1716 dr.dispatched(true);
1718 switch (cmd.action()) {
1720 case LFUN_WINDOW_NEW:
1721 createView(toqstr(cmd.argument()));
1724 case LFUN_WINDOW_CLOSE:
1725 // FIXME: this is done also in GuiView::closeBuffer()!
1726 // update bookmark pit of the current buffer before window close
1727 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1728 gotoBookmark(i, false, false);
1729 // clear the last opened list, because
1730 // maybe this will end the session
1731 theSession().lastOpened().clear();
1732 // check for valid current_view_
1733 validateCurrentView();
1735 current_view_->closeScheduled();
1739 // quitting is triggered by the gui code
1740 // (leaving the event loop).
1742 current_view_->message(from_utf8(N_("Exiting.")));
1743 if (closeAllViews())
1747 case LFUN_SCREEN_FONT_UPDATE: {
1748 // handle the screen font changes.
1749 /* FIXME: this only updates the current document, whereas all
1750 * documents should see their metrics updated.
1752 d->font_loader_.update();
1753 dr.screenUpdate(Update::Force | Update::FitCursor);
1757 case LFUN_BUFFER_NEW:
1758 validateCurrentView();
1760 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1761 createView(QString(), false); // keep hidden
1762 current_view_->newDocument(to_utf8(cmd.argument()));
1763 current_view_->show();
1764 setActiveWindow(current_view_);
1766 current_view_->newDocument(to_utf8(cmd.argument()));
1770 case LFUN_BUFFER_NEW_TEMPLATE: {
1771 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1772 string const temp = cmd.getArg(1);
1773 validateCurrentView();
1775 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1777 current_view_->newDocument(file, temp, true);
1778 if (!current_view_->documentBufferView())
1779 current_view_->close();
1781 current_view_->newDocument(file, temp, true);
1786 case LFUN_FILE_OPEN: {
1787 // FIXME: normally the code below is not needed, since getStatus makes sure that
1788 // current_view_ is not null.
1789 validateCurrentView();
1790 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1791 string const fname = trim(to_utf8(cmd.argument()), "\"");
1792 bool const is_open = FileName::isAbsolute(fname)
1793 && theBufferList().getBuffer(FileName(fname));
1795 || (!lyxrc.open_buffers_in_tabs
1796 && current_view_->documentBufferView() != nullptr
1798 // We want the ui session to be saved per document and not per
1799 // window number. The filename crc is a good enough identifier.
1800 createView(support::checksum(fname));
1801 current_view_->openDocument(fname);
1802 if (!current_view_->documentBufferView())
1803 current_view_->close();
1804 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1805 current_view_->raise();
1806 current_view_->activateWindow();
1807 current_view_->showNormal();
1810 current_view_->openDocument(fname);
1811 if (cmd.origin() == FuncRequest::LYXSERVER) {
1812 current_view_->raise();
1813 current_view_->activateWindow();
1814 current_view_->showNormal();
1820 case LFUN_HELP_OPEN: {
1821 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1822 if (current_view_ == nullptr)
1824 string const arg = to_utf8(cmd.argument());
1826 current_view_->message(_("Missing argument"));
1829 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1831 fname = i18nLibFileSearch("examples", arg, "lyx");
1833 if (fname.empty()) {
1834 lyxerr << "LyX: unable to find documentation file `"
1835 << arg << "'. Bad installation?" << endl;
1838 current_view_->message(bformat(_("Opening help file %1$s..."),
1839 makeDisplayPath(fname.absFileName())));
1840 Buffer * buf = current_view_->loadDocument(fname, false);
1842 buf->setReadonly(!current_view_->develMode());
1846 case LFUN_LYXFILES_OPEN: {
1847 // This is the actual reason for this method (#12106).
1848 validateCurrentView();
1850 || (!lyxrc.open_buffers_in_tabs
1851 && current_view_->documentBufferView() != nullptr))
1853 string arg = to_utf8(cmd.argument());
1857 if (arg != "templates" && arg != "examples") {
1858 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1861 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1865 case LFUN_SET_COLOR: {
1866 string const lyx_name = cmd.getArg(0);
1867 string x11_name = cmd.getArg(1);
1868 string x11_darkname = cmd.getArg(2);
1869 if (lyx_name.empty() || x11_name.empty()) {
1871 current_view_->message(
1872 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1877 // FIXME: The graphics cache no longer has a changeDisplay method.
1878 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1879 bool const graphicsbg_changed =
1880 lyx_name == graphicsbg && x11_name != graphicsbg;
1881 if (graphicsbg_changed)
1882 graphics::GCache::get().changeDisplay(true);
1885 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1886 x11_darkname = x11_name;
1889 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1891 current_view_->message(
1892 bformat(_("Set-color \"%1$s\" failed "
1893 "- color is undefined or "
1894 "may not be redefined"),
1895 from_utf8(lyx_name)));
1898 // Make sure we don't keep old colors in cache.
1899 d->color_cache_.clear();
1900 // Update the current view
1901 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1905 case LFUN_LYXRC_APPLY: {
1906 // reset active key sequences, since the bindings
1907 // are updated (bug 6064)
1909 LyXRC const lyxrc_orig = lyxrc;
1911 istringstream ss(to_utf8(cmd.argument()));
1912 bool const success = lyxrc.read(ss);
1915 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1916 << "Unable to read lyxrc data"
1921 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1923 // If the request comes from the minibuffer, then we can't reset
1924 // the GUI, since that would destroy the minibuffer itself and
1925 // cause a crash, since we are currently in one of the methods of
1926 // GuiCommandBuffer. See bug #8540.
1927 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1930 // FIXME Unfortunately, that leaves a bug here, since we cannot
1931 // reset the GUI in this case. If the changes to lyxrc affected the
1932 // UI, then, nothing would happen. This seems fairly unlikely, but
1933 // it definitely is a bug.
1935 dr.forceBufferUpdate();
1939 case LFUN_COMMAND_PREFIX:
1940 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1945 d->meta_fake_bit = NoModifier;
1946 GuiView * gv = currentView();
1947 if (gv && gv->currentBufferView())
1948 // cancel any selection
1949 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1950 dr.setMessage(from_ascii(N_("Cancel")));
1953 case LFUN_META_PREFIX:
1954 d->meta_fake_bit = AltModifier;
1955 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1958 // --- Menus -----------------------------------------------
1959 case LFUN_RECONFIGURE:
1960 // argument is any additional parameter to the configure.py command
1961 reconfigure(to_utf8(cmd.argument()));
1964 // --- lyxserver commands ----------------------------
1965 case LFUN_SERVER_GET_FILENAME: {
1966 if (current_view_ && current_view_->documentBufferView()) {
1967 docstring const fname = from_utf8(
1968 current_view_->documentBufferView()->buffer().absFileName());
1969 dr.setMessage(fname);
1970 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1972 dr.setMessage(docstring());
1973 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1978 case LFUN_SERVER_NOTIFY: {
1979 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1980 dr.setMessage(dispatch_buffer);
1981 theServer().notifyClient(to_utf8(dispatch_buffer));
1985 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1986 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1992 string rest = split(argument, countstr, ' ');
1993 int const count = convert<int>(countstr);
1994 // an arbitrary number to limit number of iterations
1995 int const max_iter = 10000;
1996 if (count > max_iter) {
1997 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2000 for (int i = 0; i < count; ++i) {
2001 FuncRequest lfun = lyxaction.lookupFunc(rest);
2002 lfun.allowAsync(false);
2009 case LFUN_COMMAND_SEQUENCE: {
2010 // argument contains ';'-terminated commands
2011 string arg = argument;
2012 // FIXME: this LFUN should also work without any view.
2013 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2014 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2015 // This handles undo groups automagically
2016 UndoGroupHelper ugh(buffer);
2017 while (!arg.empty()) {
2019 arg = split(arg, first, ';');
2020 FuncRequest func(lyxaction.lookupFunc(first));
2021 func.allowAsync(false);
2022 func.setOrigin(cmd.origin());
2028 case LFUN_BUFFER_FORALL: {
2029 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2030 funcToRun.allowAsync(false);
2032 map<Buffer *, GuiView *> views_lVisible;
2033 map<GuiView *, Buffer *> activeBuffers;
2035 QList<GuiView *> allViews = d->views_.values();
2037 // this for does not modify any buffer. It just collects info on local
2038 // visibility of buffers and on which buffer is active in each view.
2039 Buffer * const last = theBufferList().last();
2040 for(GuiView * view : allViews) {
2041 // all of the buffers might be locally hidden. That is, there is no
2043 if (!view || !view->currentBufferView())
2044 activeBuffers[view] = nullptr;
2046 activeBuffers[view] = &view->currentBufferView()->buffer();
2048 // find out if each is locally visible or locally hidden.
2049 // we don't use a for loop as the buffer list cycles.
2050 Buffer * b = theBufferList().first();
2052 bool const locallyVisible = view && view->workArea(*b);
2053 if (locallyVisible) {
2054 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2055 // only need to overwrite/add if we don't already know a buffer is globally
2056 // visible or we do know but we would prefer to dispatch LFUN from the
2057 // current view because of cursor position issues.
2058 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2059 views_lVisible[b] = view;
2063 b = theBufferList().next(b);
2067 GuiView * const homeView = currentView();
2068 Buffer * b = theBufferList().first();
2069 Buffer * nextBuf = nullptr;
2070 int numProcessed = 0;
2073 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2075 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2077 // first change to a view where b is locally visible, preferably current_view_.
2078 GuiView * const vLv = views_lVisible[b];
2080 lyx::dispatch(funcToRun);
2088 // put things back to how they were (if possible).
2089 for (GuiView * view : allViews) {
2090 Buffer * originalBuf = activeBuffers[view];
2091 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2092 if (theBufferList().isLoaded(originalBuf))
2093 view->setBuffer(originalBuf);
2095 homeView->setFocus();
2097 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2101 case LFUN_COMMAND_ALTERNATIVES: {
2102 // argument contains ';'-terminated commands
2103 string arg = argument;
2104 while (!arg.empty()) {
2106 arg = split(arg, first, ';');
2107 FuncRequest func(lyxaction.lookupFunc(first));
2108 func.setOrigin(cmd.origin());
2109 FuncStatus const stat = getStatus(func);
2110 if (stat.enabled()) {
2120 if (theTopLevelCmdDef().lock(argument, func)) {
2121 func.setOrigin(cmd.origin());
2123 theTopLevelCmdDef().release(argument);
2125 if (func.action() == LFUN_UNKNOWN_ACTION) {
2126 // unknown command definition
2127 lyxerr << "Warning: unknown command definition `"
2131 // recursion detected
2132 lyxerr << "Warning: Recursion in the command definition `"
2133 << argument << "' detected"
2140 case LFUN_IF_RELATIVES: {
2141 string const lfun = to_utf8(cmd.argument());
2142 FuncRequest func(lyxaction.lookupFunc(lfun));
2143 func.setOrigin(cmd.origin());
2144 FuncStatus const stat = getStatus(func);
2145 if (stat.enabled()) {
2152 case LFUN_PREFERENCES_SAVE:
2153 lyxrc.write(support::makeAbsPath("preferences",
2154 package().user_support().absFileName()), false);
2157 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2158 string const fname = addName(addPath(package().user_support().absFileName(),
2159 "templates/"), "defaults.lyx");
2160 Buffer defaults(fname);
2162 istringstream ss(argument);
2167 // We need to make sure that, after we recreat the DocumentClass,
2168 // which we do in readHeader, we apply it to the document itself.
2169 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2170 int const unknown_tokens = defaults.readHeader(lex);
2171 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2172 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2173 cap::switchBetweenClasses(olddc, newdc, theinset);
2175 if (unknown_tokens != 0) {
2176 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2177 << unknown_tokens << " unknown token"
2178 << (unknown_tokens == 1 ? "" : "s")
2182 if (defaults.writeFile(FileName(defaults.absFileName())))
2183 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2184 makeDisplayPath(fname)));
2187 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2192 case LFUN_BOOKMARK_GOTO:
2193 // go to bookmark, open unopened file and switch to buffer if necessary
2194 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2195 dr.screenUpdate(Update::Force | Update::FitCursor);
2198 case LFUN_BOOKMARK_CLEAR:
2199 theSession().bookmarks().clear();
2200 dr.screenUpdate(Update::Force);
2203 case LFUN_DEBUG_LEVEL_SET:
2204 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2207 case LFUN_DIALOG_SHOW: {
2208 string const name = cmd.getArg(0);
2210 if ( name == "aboutlyx"
2212 || name == "texinfo"
2213 || name == "progress"
2214 || name == "compare")
2216 // work around: on Mac OS the application
2217 // is not terminated when closing the last view.
2218 // Create a new one to be able to dispatch the
2219 // LFUN_DIALOG_SHOW to this view.
2220 if (current_view_ == nullptr)
2226 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2229 current_view_->dispatch(cmd, dr);
2233 if (current_view_ && current_view_->isFullScreen()) {
2234 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2235 current_view_->menuBar()->hide();
2238 if (cmd.origin() == FuncRequest::LYXSERVER)
2239 updateCurrentView(cmd, dr);
2243 docstring GuiApplication::viewStatusMessage()
2245 // When meta-fake key is pressed, show the key sequence so far + "M-".
2246 if (d->meta_fake_bit != NoModifier)
2247 return d->keyseq.print(KeySequence::ForGui) + "M-";
2249 // Else, when a non-complete key sequence is pressed,
2250 // show the available options.
2251 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2252 return d->keyseq.printOptions(true);
2258 string GuiApplication::inputLanguageCode() const
2260 #if (QT_VERSION < 0x050000)
2261 QLocale loc = keyboardInputLocale();
2263 QLocale loc = inputMethod()->locale();
2265 //LYXERR0("input lang = " << fromqstr(loc.name()));
2266 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2270 void GuiApplication::onLocaleChanged()
2272 //LYXERR0("Change language to " << inputLanguage()->lang());
2273 if (currentView() && currentView()->currentBufferView())
2274 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2278 void GuiApplication::handleKeyFunc(FuncCode action)
2282 if (d->keyseq.length())
2284 GuiView * gv = currentView();
2285 LASSERT(gv && gv->currentBufferView(), return);
2286 BufferView * bv = gv->currentBufferView();
2287 bv->getIntl().getTransManager().deadkey(
2288 c, get_accent(action).accent, bv->cursor().innerText(),
2290 // Need to clear, in case the minibuffer calls these
2293 // copied verbatim from do_accent_char
2294 bv->cursor().resetAnchor();
2298 //Keep this in sync with GuiApplication::processKeySym below
2299 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2300 KeyModifier state) const
2302 // Do nothing if we have nothing
2303 if (!keysym.isOK() || keysym.isModifier())
2305 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2307 FuncRequest func = seq.addkey(keysym, state);
2308 // When not cancel or meta-fake, do the normal lookup.
2309 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2311 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2313 // Maybe user can only reach the key via holding down shift.
2314 // Let's see. But only if shift is the only modifier
2315 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2316 // If addkey looked up a command and did not find further commands then
2317 // seq has been reset at this point
2318 func = seq.addkey(keysym, NoModifier);
2320 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2321 << seq.print(KeySequence::Portable) << ']');
2322 return func.action() != LFUN_UNKNOWN_ACTION;
2326 //Keep this in sync with GuiApplication::queryKeySym above
2327 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2329 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2331 // Do nothing if we have nothing (JMarc)
2332 if (!keysym.isOK() || keysym.isModifier()) {
2334 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2336 current_view_->restartCaret();
2340 char_type encoded_last_key = keysym.getUCSEncoded();
2342 // Do a one-deep top-level lookup for
2343 // cancel and meta-fake keys. RVDK_PATCH_5
2344 d->cancel_meta_seq.reset();
2346 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2347 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2349 // When not cancel or meta-fake, do the normal lookup.
2350 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2351 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2352 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2353 // remove Caps Lock and Mod2 as a modifiers
2354 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2355 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2358 // Don't remove this unless you know what you are doing.
2359 d->meta_fake_bit = NoModifier;
2361 // Can this happen now ?
2362 if (func.action() == LFUN_NOACTION)
2363 func = FuncRequest(LFUN_COMMAND_PREFIX);
2365 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2366 << d->keyseq.print(KeySequence::Portable) << ']');
2368 // already here we know if it any point in going further
2369 // why not return already here if action == -1 and
2370 // num_bytes == 0? (Lgb)
2372 if (d->keyseq.length() > 1 && current_view_)
2373 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2376 // Maybe user can only reach the key via holding down shift.
2377 // Let's see. But only if shift is the only modifier
2378 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2379 LYXERR(Debug::KEY, "Trying without shift");
2380 // If addkey looked up a command and did not find further commands then
2381 // seq has been reset at this point
2382 func = d->keyseq.addkey(keysym, NoModifier);
2383 LYXERR(Debug::KEY, "Action now " << func.action());
2386 if (func.action() == LFUN_UNKNOWN_ACTION) {
2387 // We didn't match any of the key sequences.
2388 // See if it's normal insertable text not already
2389 // covered by a binding
2390 if (keysym.isText() && d->keyseq.length() == 1) {
2391 // Non-printable characters (such as ASCII control characters)
2392 // must not be inserted (#5704)
2393 if (!isPrintable(encoded_last_key)) {
2394 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2396 current_view_->restartCaret();
2399 // The following modifier check is not needed on Mac.
2400 // The keysym is either not text or it is different
2401 // from the non-modifier keysym. See #9875 for the
2402 // broken alt-modifier effect of having this code active.
2403 #if !defined(Q_OS_MAC)
2404 // If a non-Shift Modifier is used we have a non-bound key sequence
2405 // (such as Alt+j = j). This should be omitted (#5575).
2406 // On Windows, AltModifier and ControlModifier are both
2407 // set when AltGr is pressed. Therefore, in order to not
2408 // break AltGr-bound symbols (see #5575 for details),
2409 // unbound Ctrl+Alt key sequences are allowed.
2410 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2411 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2412 && !(state & AltModifier && state & ControlModifier)
2416 if (current_view_) {
2417 current_view_->message(_("Unknown function."));
2418 current_view_->restartCaret();
2423 // Since all checks above were passed, we now really have text that
2424 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2425 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2427 LYXERR(Debug::KEY, "isText() is true, inserting.");
2428 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2430 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2431 if (current_view_) {
2432 current_view_->message(_("Unknown function."));
2433 current_view_->restartCaret();
2439 if (func.action() == LFUN_SELF_INSERT) {
2440 if (encoded_last_key != 0) {
2441 docstring const arg(1, encoded_last_key);
2442 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2443 FuncRequest::KEYBOARD));
2444 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2447 processFuncRequest(func);
2451 void GuiApplication::processFuncRequest(FuncRequest const & func)
2453 lyx::dispatch(func);
2457 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2459 addToFuncRequestQueue(func);
2460 processFuncRequestQueueAsync();
2464 void GuiApplication::processFuncRequestQueue()
2466 while (!d->func_request_queue_.empty()) {
2467 // take the item from the stack _before_ processing the
2468 // request in order to avoid race conditions from nested
2469 // or parallel requests (see #10406)
2470 FuncRequest const fr(d->func_request_queue_.front());
2471 d->func_request_queue_.pop();
2472 processFuncRequest(fr);
2477 void GuiApplication::processFuncRequestQueueAsync()
2479 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2483 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2485 d->func_request_queue_.push(func);
2489 void GuiApplication::resetGui()
2491 // Set the language defined by the user.
2495 if (!readUIFile(toqstr(lyxrc.ui_file)))
2496 // Gives some error box here.
2499 if (d->global_menubar_)
2500 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2502 QHash<int, GuiView *>::iterator it;
2503 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2506 gv->setLayoutDirection(layoutDirection());
2510 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2514 bool GuiApplication::rtlContext() const
2516 if (current_view_ && current_view_->currentBufferView()) {
2517 BufferView const * bv = current_view_->currentBufferView();
2518 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2520 return layoutDirection() == Qt::RightToLeft;
2524 void GuiApplication::createView(int view_id)
2526 createView(QString(), true, view_id);
2530 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2533 // release the keyboard which might have been grabbed by the global
2534 // menubar on Mac to catch shortcuts even without any GuiView.
2535 if (d->global_menubar_)
2536 d->global_menubar_->releaseKeyboard();
2540 while (d->views_.find(id) != d->views_.end())
2543 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2544 GuiView * view = new GuiView(id);
2545 // `view' is the new current_view_. Tell coverity that is is not 0.
2546 LATTEST(current_view_);
2548 d->views_[id] = view;
2552 setActiveWindow(view);
2555 if (!geometry_arg.isEmpty()) {
2556 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2560 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2561 re.indexIn(geometry_arg);
2562 w = re.cap(1).toInt();
2563 h = re.cap(2).toInt();
2564 x = re.cap(3).toInt();
2565 y = re.cap(4).toInt();
2566 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2567 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2568 // Set initial geometry such that we can get the frame size.
2569 view->setGeometry(x, y, w, h);
2570 int framewidth = view->geometry().x() - view->x();
2571 int titleheight = view->geometry().y() - view->y();
2572 // Negative displacements must be interpreted as distances
2573 // from the right or bottom screen borders.
2574 if (sx == '-' || sy == '-') {
2575 QRect rec = QApplication::desktop()->screenGeometry();
2577 x += rec.width() - w - framewidth;
2579 y += rec.height() - h - titleheight;
2580 view->setGeometry(x, y, w, h);
2582 // Make sure that the left and top frame borders are visible.
2583 if (view->x() < 0 || view->y() < 0) {
2588 view->setGeometry(x, y, w, h);
2596 bool GuiApplication::unhide(Buffer * buf)
2600 currentView()->setBuffer(buf, false);
2605 Clipboard & GuiApplication::clipboard()
2607 return d->clipboard_;
2611 Selection & GuiApplication::selection()
2613 return d->selection_;
2617 FontLoader & GuiApplication::fontLoader()
2619 return d->font_loader_;
2623 Toolbars const & GuiApplication::toolbars() const
2625 return d->toolbars_;
2629 Toolbars & GuiApplication::toolbars()
2631 return d->toolbars_;
2635 Menus const & GuiApplication::menus() const
2641 Menus & GuiApplication::menus()
2647 QList<int> GuiApplication::viewIds() const
2649 return d->views_.keys();
2653 ColorCache & GuiApplication::colorCache()
2655 return d->color_cache_;
2659 int GuiApplication::exec()
2661 // asynchronously handle batch commands. This event will be in
2662 // the event queue in front of other asynchronous events. Hence,
2663 // we can assume in the latter that the gui is setup already.
2664 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2666 return QApplication::exec();
2670 void GuiApplication::exit(int status)
2672 QApplication::exit(status);
2676 void GuiApplication::setGuiLanguage()
2680 // install translation file for Qt built-in dialogs
2681 QString const language_name = QString("qt_") + theLocale.name();
2682 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2683 // Short-named translator can be loaded from a long name, but not the
2684 // opposite. Therefore, long name should be used without truncation.
2685 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2686 if (!d->qt_trans_.load(language_name,
2687 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2688 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2691 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2695 switch (theLocale.language()) {
2696 case QLocale::Arabic :
2697 case QLocale::Hebrew :
2698 case QLocale::Persian :
2699 case QLocale::Urdu :
2700 setLayoutDirection(Qt::RightToLeft);
2703 setLayoutDirection(Qt::LeftToRight);
2708 void GuiApplication::execBatchCommands()
2713 if (!readUIFile(toqstr(lyxrc.ui_file)))
2714 // Gives some error box here.
2718 #if QT_VERSION > 0x040600
2719 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2721 #if QT_VERSION > 0x050100
2722 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2724 // Create the global default menubar which is shown for the dialogs
2725 // and if no GuiView is visible.
2726 // This must be done after the session was recovered to know the "last files".
2727 d->global_menubar_ = new QMenuBar(0);
2728 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2731 lyx::execBatchCommands();
2735 QAbstractItemModel * GuiApplication::languageModel()
2737 if (d->language_model_)
2738 return d->language_model_;
2740 QStandardItemModel * lang_model = new QStandardItemModel(this);
2741 lang_model->insertColumns(0, 3);
2742 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2743 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2744 Languages::const_iterator it = lyx::languages.begin();
2745 Languages::const_iterator end = lyx::languages.end();
2746 for (; it != end; ++it) {
2747 int current_row = lang_model->rowCount();
2748 lang_model->insertRows(current_row, 1);
2749 QModelIndex pl_item = lang_model->index(current_row, 0);
2750 QModelIndex sp_item = lang_model->index(current_row, 1);
2751 QModelIndex th_item = lang_model->index(current_row, 2);
2752 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2753 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2754 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2755 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2756 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2757 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2758 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2759 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2760 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2761 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2763 d->language_model_ = new QSortFilterProxyModel(this);
2764 d->language_model_->setSourceModel(lang_model);
2765 d->language_model_->setSortLocaleAware(true);
2766 return d->language_model_;
2770 void GuiApplication::restoreGuiSession()
2772 if (!lyxrc.load_session)
2775 Session & session = theSession();
2776 LastOpenedSection::LastOpened const & lastopened =
2777 session.lastOpened().getfiles();
2779 validateCurrentView();
2781 FileName active_file;
2782 // do not add to the lastfile list since these files are restored from
2783 // last session, and should be already there (regular files), or should
2784 // not be added at all (help files).
2785 for (auto const & last : lastopened) {
2786 FileName const & file_name = last.file_name;
2787 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2788 && current_view_->documentBufferView() != nullptr)) {
2789 string const & fname = file_name.absFileName();
2790 createView(support::checksum(fname));
2792 current_view_->loadDocument(file_name, false);
2795 active_file = file_name;
2798 // Restore last active buffer
2799 Buffer * buffer = theBufferList().getBuffer(active_file);
2800 if (buffer && current_view_)
2801 current_view_->setBuffer(buffer);
2803 // clear this list to save a few bytes of RAM
2804 session.lastOpened().clear();
2808 QString const GuiApplication::romanFontName()
2811 font.setStyleHint(QFont::Serif);
2812 font.setFamily("serif");
2814 return QFontInfo(font).family();
2818 QString const GuiApplication::sansFontName()
2821 font.setStyleHint(QFont::SansSerif);
2822 font.setFamily("sans");
2824 return QFontInfo(font).family();
2828 QString const GuiApplication::typewriterFontName()
2830 return QFontInfo(typewriterSystemFont()).family();
2835 // We cannot use QFont::fixedPitch() because it doesn't
2836 // return the fact but only if it is requested.
2837 static bool isFixedPitch(const QFont & font) {
2838 const QFontInfo fi(font);
2839 return fi.fixedPitch();
2844 QFont const GuiApplication::typewriterSystemFont()
2846 #if QT_VERSION >= 0x050200
2847 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2849 QFont font("monospace");
2851 if (!isFixedPitch(font)) {
2852 // try to enforce a real monospaced font
2853 font.setStyleHint(QFont::Monospace);
2854 if (!isFixedPitch(font)) {
2855 font.setStyleHint(QFont::TypeWriter);
2856 if (!isFixedPitch(font)) font.setFamily("courier");
2860 // On a Mac the result is too small and it's not practical to
2861 // rely on Qtconfig utility to change the system settings of Qt.
2862 font.setPointSize(12);
2868 void GuiApplication::handleRegularEvents()
2870 ForkedCallsController::handleCompletedProcesses();
2874 bool GuiApplication::event(QEvent * e)
2877 case QEvent::FileOpen: {
2878 // Open a file; this happens only on Mac OS X for now.
2880 // We do this asynchronously because on startup the batch
2881 // commands are not executed here yet and the gui is not ready
2883 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2884 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2885 processFuncRequestAsync(fr);
2889 #if (QT_VERSION < 0x050000)
2890 // Qt5 uses a signal for that, see above.
2891 case QEvent::KeyboardLayoutChange:
2892 //LYXERR0("keyboard change");
2893 if (currentView() && currentView()->currentBufferView())
2894 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2899 return QApplication::event(e);
2904 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2907 return QApplication::notify(receiver, event);
2909 catch (ExceptionMessage const & e) {
2911 case ErrorException:
2913 setQuitOnLastWindowClosed(false);
2915 Alert::error(e.title_, e.details_);
2917 // Properly crash in debug mode in order to get a useful backtrace.
2920 // In release mode, try to exit gracefully.
2922 // FIXME: GCC 7 thinks we can fall through here. Can we?
2924 case BufferException: {
2925 if (!current_view_ || !current_view_->documentBufferView())
2927 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2928 docstring details = e.details_ + '\n';
2929 details += buf->emergencyWrite();
2930 theBufferList().release(buf);
2931 details += "\n" + _("The current document was closed.");
2932 Alert::error(e.title_, details);
2935 case WarningException:
2936 Alert::warning(e.title_, e.details_);
2940 catch (exception const & e) {
2941 docstring s = _("LyX has caught an exception, it will now "
2942 "attempt to save all unsaved documents and exit."
2944 s += from_ascii(e.what());
2945 Alert::error(_("Software exception Detected"), s);
2949 docstring s = _("LyX has caught some really weird exception, it will "
2950 "now attempt to save all unsaved documents and exit.");
2951 Alert::error(_("Software exception Detected"), s);
2958 bool GuiApplication::isInDarkMode()
2960 return colorCache().isDarkMode();
2964 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2966 QColor const & qcol = d->color_cache_.get(col);
2967 if (!qcol.isValid()) {
2973 rgbcol.r = qcol.red();
2974 rgbcol.g = qcol.green();
2975 rgbcol.b = qcol.blue();
2980 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2982 QColor const qcol(lcolor.getX11HexName(col).c_str());
2983 if (!qcol.isValid()) {
2989 rgbcol.r = qcol.red();
2990 rgbcol.g = qcol.green();
2991 rgbcol.b = qcol.blue();
2996 string const GuiApplication::hexName(ColorCode col)
2998 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3002 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3004 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3005 d->socket_notifiers_[fd] = sn;
3006 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3010 void GuiApplication::socketDataReceived(int fd)
3012 d->socket_notifiers_[fd]->func_();
3016 void GuiApplication::unregisterSocketCallback(int fd)
3018 d->socket_notifiers_.take(fd)->setEnabled(false);
3022 void GuiApplication::commitData(QSessionManager & sm)
3024 /** The implementation is required to avoid an application exit
3025 ** when session state save is triggered by session manager.
3026 ** The default implementation sends a close event to all
3027 ** visible top level widgets when session management allows
3029 ** We are changing that to check the state of each buffer in all
3030 ** views and ask the users what to do if buffers are dirty.
3031 ** Furthermore, we save the session state.
3032 ** We do NOT close the views here since the user still can cancel
3033 ** the logout process (see #9277); also, this would hide LyX from
3034 ** an OSes own session handling (application restoration).
3036 #ifdef QT_NO_SESSIONMANAGER
3038 #warning Qt is compiled without session manager
3040 #pragma message("warning: Qt is compiled without session manager")
3044 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3052 void GuiApplication::unregisterView(GuiView * gv)
3054 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3055 d->views_.remove(gv->id());
3056 if (current_view_ == gv)
3057 current_view_ = nullptr;
3062 bool GuiApplication::closeAllViews()
3064 if (d->views_.empty())
3067 // When a view/window was closed before without quitting LyX, there
3068 // are already entries in the lastOpened list.
3069 theSession().lastOpened().clear();
3071 QList<GuiView *> const views = d->views_.values();
3072 for (GuiView * view : views) {
3073 if (!view->closeScheduled())
3082 bool GuiApplication::prepareAllViewsForLogout()
3084 if (d->views_.empty())
3087 QList<GuiView *> const views = d->views_.values();
3088 for (GuiView * view : views) {
3089 if (!view->prepareAllBuffersForLogout())
3097 GuiView & GuiApplication::view(int id) const
3099 LAPPERR(d->views_.contains(id));
3100 return *d->views_.value(id);
3104 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3106 QList<GuiView *> const views = d->views_.values();
3107 for (GuiView * view : views)
3108 view->hideDialog(name, inset);
3112 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3114 Buffer const * buf = nullptr;
3115 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3116 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3117 if (Buffer const * ptr = (*it)->updateInset(inset))
3124 bool GuiApplication::searchMenu(FuncRequest const & func,
3125 docstring_list & names) const
3127 BufferView * bv = nullptr;
3129 bv = current_view_->currentBufferView();
3130 return d->menus_.searchMenu(func, names, bv);
3134 bool GuiApplication::hasBufferView() const
3136 return (current_view_ && current_view_->currentBufferView());
3140 // Ensure that a file is read only once (prevents include loops)
3141 static QStringList uifiles;
3142 // store which ui files define Toolbars
3143 static QStringList toolbar_uifiles;
3146 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3157 LexerKeyword uitags[] = {
3158 { "format", ui_format },
3159 { "include", ui_include },
3160 { "menuset", ui_menuset },
3161 { "toolbars", ui_toolbars },
3162 { "toolbarset", ui_toolbarset }
3166 lex.setFile(ui_path);
3168 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3172 if (lyxerr.debugging(Debug::PARSER))
3173 lex.printTable(lyxerr);
3176 // format before introduction of format tag
3177 unsigned int format = 0;
3178 while (lex.isOK()) {
3179 int const status = lex.lex();
3181 // we have to do this check here, outside the switch,
3182 // because otherwise we would start reading include files,
3183 // e.g., if the first tag we hit was an include tag.
3184 if (status == ui_format)
3186 format = lex.getInteger();
3190 // this will trigger unless the first tag we hit is a format
3191 // tag, with the right format.
3192 if (format != LFUN_FORMAT)
3193 return FormatMismatch;
3196 case Lexer::LEX_FEOF:
3201 QString const file = toqstr(lex.getString());
3202 bool const success = readUIFile(file, true);
3204 LYXERR0("Failed to read included file: " << fromqstr(file));
3211 d->menus_.read(lex);
3215 d->toolbars_.readToolbars(lex);
3219 d->toolbars_.readToolbarSettings(lex);
3220 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3224 if (!rtrim(lex.getString()).empty())
3225 lex.printError("LyX::ReadUIFile: "
3226 "Unknown menu tag: `$$Token'");
3228 LYXERR0("Error with status: " << status);
3234 return (error ? ReadError : ReadOK);
3238 bool GuiApplication::readUIFile(QString const & name, bool include)
3240 LYXERR(Debug::INIT, "About to read " << name << "...");
3244 ui_path = libFileSearch("ui", name, "inc");
3245 if (ui_path.empty())
3246 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3248 ui_path = libFileSearch("ui", name, "ui");
3251 if (ui_path.empty()) {
3252 static const QString defaultUIFile = "default";
3253 LYXERR(Debug::INIT, "Could not find " << name);
3255 Alert::warning(_("Could not find UI definition file"),
3256 bformat(_("Error while reading the included file\n%1$s\n"
3257 "Please check your installation."), qstring_to_ucs4(name)));
3260 if (name == defaultUIFile) {
3261 LYXERR(Debug::INIT, "Could not find default UI file!!");
3262 Alert::warning(_("Could not find default UI file"),
3263 _("LyX could not find the default UI file!\n"
3264 "Please check your installation."));
3267 Alert::warning(_("Could not find UI definition file"),
3268 bformat(_("Error while reading the configuration file\n%1$s\n"
3269 "Falling back to default.\n"
3270 "Please look under Tools>Preferences>User Interface and\n"
3271 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3272 return readUIFile(defaultUIFile, false);
3275 QString const uifile = toqstr(ui_path.absFileName());
3276 if (uifiles.contains(uifile)) {
3278 // We are reading again the top uifile so reset the safeguard:
3281 d->toolbars_.reset();
3283 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3284 << "Is this an include loop?");
3288 uifiles.push_back(uifile);
3290 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3292 ReturnValues retval = readUIFile(ui_path);
3294 if (retval == FormatMismatch) {
3295 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3296 TempFile tmp("convertXXXXXX.ui");
3297 FileName const tempfile = tmp.name();
3298 bool const success = prefs2prefs(ui_path, tempfile, true);
3300 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3301 " to format " << LFUN_FORMAT << ".");
3303 retval = readUIFile(tempfile);
3307 if (retval != ReadOK) {
3308 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3316 settings.beginGroup("ui_files");
3317 bool touched = false;
3318 for (int i = 0; i != uifiles.size(); ++i) {
3319 QFileInfo fi(uifiles[i]);
3320 QDateTime const date_value = fi.lastModified();
3321 QString const name_key = QString::number(i);
3322 // if an ui file which defines Toolbars has changed,
3323 // we have to reset the settings
3324 if (toolbar_uifiles.contains(uifiles[i])
3325 && (!settings.contains(name_key)
3326 || settings.value(name_key).toString() != uifiles[i]
3327 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3329 settings.setValue(name_key, uifiles[i]);
3330 settings.setValue(name_key + "/date", date_value);
3333 settings.endGroup();
3335 settings.remove("views");
3341 void GuiApplication::onLastWindowClosed()
3343 if (d->global_menubar_)
3344 d->global_menubar_->grabKeyboard();
3348 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3349 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3351 std::string name = "unknown";
3353 case Qt::ApplicationSuspended:
3354 name = "ApplicationSuspended";
3356 case Qt::ApplicationHidden:
3357 name = "ApplicationHidden";
3359 case Qt::ApplicationInactive:
3360 name = "ApplicationInactive";
3362 case Qt::ApplicationActive:
3363 name = "ApplicationActive";
3364 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3365 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3366 if (d->views_.empty() && d->last_state_ == state) {
3367 LYXERR(Debug::GUI, "Open new window...");
3372 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3373 d->last_state_ = state;
3378 void GuiApplication::startLongOperation() {
3379 d->key_checker_.start();
3383 bool GuiApplication::longOperationCancelled() {
3384 return d->key_checker_.pressed();
3388 void GuiApplication::stopLongOperation() {
3389 d->key_checker_.stop();
3393 bool GuiApplication::longOperationStarted() {
3394 return d->key_checker_.started();
3398 ////////////////////////////////////////////////////////////////////////
3400 // X11 specific stuff goes here...
3403 bool GuiApplication::x11EventFilter(XEvent * xev)
3408 switch (xev->type) {
3409 case SelectionRequest: {
3410 if (xev->xselectionrequest.selection != XA_PRIMARY)
3412 LYXERR(Debug::SELECTION, "X requested selection.");
3413 BufferView * bv = current_view_->currentBufferView();
3415 docstring const sel = bv->requestSelection();
3417 d->selection_.put(sel);
3418 // Refresh the selection request timestamp.
3419 // We have to do this by ourselves as Qt seems
3420 // not doing that, maybe because of our
3421 // "persistent selection" implementation
3422 // (see comments in GuiSelection.cpp).
3423 XSelectionEvent nev;
3424 nev.type = SelectionNotify;
3425 nev.display = xev->xselectionrequest.display;
3426 nev.requestor = xev->xselectionrequest.requestor;
3427 nev.selection = xev->xselectionrequest.selection;
3428 nev.target = xev->xselectionrequest.target;
3429 nev.property = 0L; // None
3430 nev.time = CurrentTime;
3431 XSendEvent(QX11Info::display(),
3432 nev.requestor, False, 0,
3433 reinterpret_cast<XEvent *>(&nev));
3439 case SelectionClear: {
3440 if (xev->xselectionclear.selection != XA_PRIMARY)
3442 LYXERR(Debug::SELECTION, "Lost selection.");
3443 BufferView * bv = current_view_->currentBufferView();
3445 bv->clearSelection();
3451 #elif defined(QPA_XCB)
3452 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3453 void * message, long *)
3455 if (!current_view_ || eventType != "xcb_generic_event_t")
3458 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3460 switch (ev->response_type) {
3461 case XCB_SELECTION_REQUEST: {
3462 xcb_selection_request_event_t * srev =
3463 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3464 if (srev->selection != XCB_ATOM_PRIMARY)
3466 LYXERR(Debug::SELECTION, "X requested selection.");
3467 BufferView * bv = current_view_->currentBufferView();
3469 docstring const sel = bv->requestSelection();
3471 d->selection_.put(sel);
3472 #ifdef HAVE_QT5_X11_EXTRAS
3473 // Refresh the selection request timestamp.
3474 // We have to do this by ourselves as Qt seems
3475 // not doing that, maybe because of our
3476 // "persistent selection" implementation
3477 // (see comments in GuiSelection.cpp).
3478 // It is expected that every X11 event is
3479 // 32 bytes long, even if not all 32 bytes are
3481 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3482 struct alignas(32) padded_event
3483 : xcb_selection_notify_event_t {};
3484 padded_event nev = {};
3485 nev.response_type = XCB_SELECTION_NOTIFY;
3486 nev.requestor = srev->requestor;
3487 nev.selection = srev->selection;
3488 nev.target = srev->target;
3489 nev.property = XCB_NONE;
3490 nev.time = XCB_CURRENT_TIME;
3491 xcb_connection_t * con = QX11Info::connection();
3492 xcb_send_event(con, 0, srev->requestor,
3493 XCB_EVENT_MASK_NO_EVENT,
3494 reinterpret_cast<char const *>(&nev));
3502 case XCB_SELECTION_CLEAR: {
3503 xcb_selection_clear_event_t * scev =
3504 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3505 if (scev->selection != XCB_ATOM_PRIMARY)
3507 LYXERR(Debug::SELECTION, "Lost selection.");
3508 BufferView * bv = current_view_->currentBufferView();
3510 bv->clearSelection();
3518 } // namespace frontend
3521 void hideDialogs(std::string const & name, Inset * inset)
3524 frontend::guiApp->hideDialogs(name, inset);
3528 ////////////////////////////////////////////////////////////////////
3532 ////////////////////////////////////////////////////////////////////
3534 frontend::FontLoader & theFontLoader()
3536 LAPPERR(frontend::guiApp);
3537 return frontend::guiApp->fontLoader();
3541 frontend::FontMetrics const & theFontMetrics(Font const & f)
3543 return theFontMetrics(f.fontInfo());
3547 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3549 LAPPERR(frontend::guiApp);
3550 return frontend::guiApp->fontLoader().metrics(f);
3554 ////////////////////////////////////////////////////////////////////
3558 ////////////////////////////////////////////////////////////////////
3560 frontend::Clipboard & theClipboard()
3562 LAPPERR(frontend::guiApp);
3563 return frontend::guiApp->clipboard();
3567 frontend::Selection & theSelection()
3569 LAPPERR(frontend::guiApp);
3570 return frontend::guiApp->selection();
3576 #include "moc_GuiApplication.cpp"