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);
184 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
185 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
186 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
187 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
188 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
191 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
192 // HighDPI scale factor policy must be set before QGuiApplication is created
193 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
194 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
197 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
198 // I'd rather do that in the constructor, but I do not think that
199 // the palette is accessible there.
200 guiApp->colorCache().setPalette(guiApp->palette());
209 if (lyxrc.gui_language == "auto") {
210 theLocale = QLocale::system();
211 code = fromqstr(theLocale.name());
213 Language const * l = languages.getLanguage(lyxrc.gui_language);
214 code = l ? l->code() : "C";
215 theLocale = QLocale(toqstr(code));
217 // Qt tries to outsmart us and transforms en_US to C.
218 Messages::guiLanguage((code == "C") ? "en_US" : code);
219 QLocale::setDefault(theLocale);
220 setlocale(LC_NUMERIC, "C");
227 /// Return the list of loadable formats.
228 vector<string> loadableImageFormats()
232 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
234 LYXERR(Debug::GRAPHICS,
235 "\nThe image loader can load the following directly:\n");
237 if (qt_formats.empty())
238 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
240 bool jpeg_found = false;
241 bool jpg_found = false;
242 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
244 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
246 string ext = ascii_lowercase((const char *) *it);
254 else if (ext == "jpg") {
259 else if (lyxrc.use_converter_cache &&
260 (ext == "svg" || ext == "svgz") &&
261 theConverters().isReachable("svg", "png"))
262 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
263 // the SVG as in the output. However we require that the converter
264 // cache is enabled since this is expensive. We also require that
265 // an explicit svg->png converter is defined, since the default
266 // converter could produce bad quality as well. This assumes that
267 // png can always be loaded.
276 ////////////////////////////////////////////////////////////////////////
278 // Icon loading support code
280 ////////////////////////////////////////////////////////////////////////
290 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
292 return lhs.key < rhs.key;
298 CompareKey(QString const & name) : name_(name) {}
299 bool operator()(ImgMap const & other) const { return other.key == name_; }
305 // this must be sorted alphabetically
306 // Upper case comes before lower case
307 // Please don't change the formatting, this list is parsed by
308 // development/tools/generate_symbols_images.py.
309 ImgMap sorted_img_map[] = {
310 { "Arrownot", "arrownot2"},
311 { "Arrowvert", "arrowvert2"},
312 { "Bowtie", "bowtie2" },
314 { "Bumpeq", "bumpeq2" },
315 { "CIRCLE", "circle3" },
317 { "CheckedBox", "checkedbox2" },
318 { "Circle", "circle2" },
319 { "Colonapprox", "colonapprox2" },
320 { "Coloneq", "coloneq2" },
321 { "Coloneqq", "coloneqq2" },
322 { "Colonsim", "colonsim2" },
324 { "DOWNarrow", "downarrow3" },
325 { "Delta", "delta2" },
326 { "Diamond", "diamond2" },
327 { "Doteq", "doteq2" },
328 { "Downarrow", "downarrow2" },
329 { "Eqcolon", "eqcolon2" },
330 { "Eqqcolon", "eqqcolon2" },
331 { "Gamma", "gamma2" },
333 { "LEFTCIRCLE", "leftcircle3" },
334 { "LEFTarrow", "leftarrow3" },
335 { "LEFTcircle", "leftcircle4" },
337 { "Lambda", "lambda2" },
339 { "Leftarrow", "leftarrow2" },
340 { "Leftcircle", "leftcircle2" },
341 { "Leftrightarrow", "leftrightarrow2" },
342 { "Longarrownot", "longarrownot2"},
343 { "Longleftarrow", "longleftarrow2" },
344 { "Longleftrightarrow", "longleftrightarrow2" },
345 { "Longmapsfrom", "longmapsfrom2"},
346 { "Longmapsto", "longmapsto2"},
347 { "Longrightarrow", "longrightarrow2" },
348 { "Mapsfrom", "mapsfrom2"},
349 { "Mapsfromchar", "mapsfromchar2"},
350 { "Mapsto", "mapsto2"},
351 { "Mapstochar", "mapstochar2"},
352 { "Omega", "omega2" },
357 { "RIGHTCIRCLE", "rightcircle3" },
358 { "RIGHTarrow", "rightarrow3" },
359 { "RIGHTcircle", "rightcircle4" },
361 { "Rightarrow", "rightarrow2" },
362 { "Rightcircle", "rightcircle2" },
363 { "Sigma", "sigma2" },
364 { "Square", "square2" },
365 { "Subset", "subset2" },
366 { "Supset", "supset2" },
367 { "Theta", "theta2" },
368 { "Thorn", "thorn2" },
369 { "UParrow", "uparrow3" },
370 { "Uparrow", "uparrow2" },
371 { "Updownarrow", "updownarrow2" },
372 { "Upsilon", "upsilon2" },
373 { "Vdash", "vdash3" },
378 { "lVert", "vert2" },
380 { "nLeftarrow", "nleftarrow2" },
381 { "nLeftrightarrow", "nleftrightarrow2" },
382 { "nRightarrow", "nrightarrow2" },
383 { "nVDash", "nvdash3" },
384 { "nVdash", "nvdash4" },
385 { "nvDash", "nvdash2" },
386 { "rVert", "vert2" },
388 { "textrm \\AA", "textrm_AA"},
389 { "textrm \\O", "textrm_O"},
390 { "vDash", "vdash2" },
391 { "varDelta", "vardelta2" },
392 { "varGamma", "vargamma2" },
393 { "varLambda", "varlambda2" },
394 { "varOmega", "varomega2" },
395 { "varPhi", "varphi2" },
396 { "varPi", "varpi2" },
397 { "varPsi", "varpsi2" },
398 { "varSigma", "varsigma2" },
399 { "varTheta", "vartheta2" },
400 { "varUpsilon", "varupsilon2" },
401 { "varXi", "varxi2" }
405 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
407 // This list specifies which system's theme icon is related to which lyx
408 // command. It was based on:
409 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
410 // this must be sorted alphabetically
411 // Upper case comes before lower case
412 ImgMap sorted_theme_icon_map[] = {
413 { "bookmark-goto 0", "go-jump" },
414 { "buffer-new", "document-new" },
415 { "buffer-write", "document-save" },
416 { "buffer-write-as", "document-save-as" },
417 { "buffer-zoom-in", "zoom-in" },
418 { "buffer-zoom-out", "zoom-out" },
419 { "copy", "edit-copy" },
420 { "cut", "edit-cut" },
421 { "depth-decrement", "format-indent-less" },
422 { "depth-increment", "format-indent-more" },
423 { "dialog-show spellchecker", "tools-check-spelling" },
424 { "dialog-show-new-inset graphics", "insert-image" },
425 { "dialog-toggle findreplaceadv", "edit-find-replace" },
426 { "file-open", "document-open" },
427 { "font-bold", "format-text-bold" },
428 { "font-ital", "format-text-italic" },
429 { "font-strikeout", "format-text-strikethrough" },
430 { "font-underline", "format-text-underline" },
431 { "lyx-quit", "application-exit" },
432 { "paste", "edit-paste" },
433 { "redo", "edit-redo" },
434 { "undo", "edit-undo" },
435 { "window-close", "window-close" },
436 { "window-new", "window-new" }
439 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
442 QString findImg(QString const & name)
444 ImgMap const * const begin = sorted_img_map;
445 ImgMap const * const end = begin + nr_sorted_img_map;
446 LATTEST(sorted(begin, end));
448 ImgMap const * const it = find_if(begin, end, CompareKey(name));
452 img_name = it->value;
455 img_name.replace('_', "underscore");
456 img_name.replace(' ', '_');
458 // This way we can have "math-delim { }" on the toolbar.
459 img_name.replace('(', "lparen");
460 img_name.replace(')', "rparen");
461 img_name.replace('[', "lbracket");
462 img_name.replace(']', "rbracket");
463 img_name.replace('{', "lbrace");
464 img_name.replace('}', "rbrace");
465 img_name.replace('|', "bars");
466 img_name.replace(',', "thinspace");
467 img_name.replace(':', "mediumspace");
468 img_name.replace(';', "thickspace");
469 img_name.replace('!', "negthinspace");
472 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
473 << "Looking for math icon called \"" << img_name << '"');
480 QString themeIconName(QString const & action)
482 ImgMap const * const begin = sorted_theme_icon_map;
483 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
484 LASSERT(sorted(begin, end), /**/);
486 ImgMap const * const it = find_if(begin, end, CompareKey(action));
494 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
499 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
501 if (!f.argument().empty()) {
502 // if there are arguments, first search an icon which name is the full thing
503 QString name = lfunname + ' ' + toqstr(f.argument());
504 name.replace(' ', '_');
505 name.replace(';', '_');
506 name.replace('\\', "backslash");
507 // avoid duplication for these
508 name.replace("dialog-toggle", "dialog-show");
511 // then special default icon for some lfuns
512 switch (f.action()) {
513 case LFUN_MATH_INSERT:
514 names << "math/" + findImg(toqstr(f.argument()).mid(1));
516 case LFUN_MATH_DELIM:
517 case LFUN_MATH_BIGDELIM:
518 names << "math/" + findImg(toqstr(f.argument()));
521 names << "commands/" + toqstr(f.argument());
523 case LFUN_COMMAND_ALTERNATIVES: {
524 // use the first of the alternative commands
526 docstring dummy = split(f.argument(), firstcom, ';');
527 QString name1 = toqstr(firstcom);
528 name1.replace(' ', '_');
529 name1.replace(';', '_');
530 name1.replace('\\', "backslash");
539 // next thing to try is function name alone
542 // and finally maybe the unknown icon
546 search_mode const mode = theGuiApp()->imageSearchMode();
547 // The folders where icons are searched for
548 QStringList imagedirs;
549 imagedirs << "images/ipa/" << "images/";
550 // This is used to search for rtl version of icons which have the +rrtl suffix.
551 QStringList suffixes;
554 suffixes << QString();
556 for (QString const & imagedir : imagedirs)
557 for (QString const & name : names)
558 for (QString const & suffix : suffixes) {
559 QString id = imagedir;
560 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
561 if (fname.exists()) {
562 docstring const fpath = fname.absoluteFilePath();
563 res.filepath = toqstr(fname.absFileName());
564 // these icons are subject to inversion in dark mode
565 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
566 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
567 res.swap = rtl && suffix.isEmpty();
572 LYXERR(Debug::GUI, "Cannot find icon for command \""
573 << lyxaction.getActionName(f.action())
574 << '(' << to_utf8(f.argument()) << ")\"");
580 QPixmap prepareForDarkMode(QPixmap pixmap)
582 QPalette palette = QPalette();
583 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
584 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
586 // guess whether we are in dark mode
587 if (text_color.black() > bg_color.black())
588 // not in dark mode, do nothing
591 // create a layer with black text turned to QPalette::WindowText
592 QPixmap black_overlay(pixmap.size());
593 black_overlay.fill(text_color);
594 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
596 // create a layer with blue text turned to lighter blue
597 QPixmap blue_overlay(pixmap.size());
598 QColor math_blue(0, 0, 255);
599 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
600 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
602 // create a layer with ("latex") red text turned to lighter red
603 QPixmap red_overlay(pixmap.size());
604 QColor math_red(128, 0, 0);
605 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
606 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
608 // put layers on top of existing pixmap
609 QPainter painter(&pixmap);
610 painter.drawPixmap(pixmap.rect(), black_overlay);
611 painter.drawPixmap(pixmap.rect(), blue_overlay);
612 painter.drawPixmap(pixmap.rect(), red_overlay);
618 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
620 QString imagedir = path;
621 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
622 QString fpath = toqstr(fname.absFileName());
623 QPixmap pixmap = QPixmap();
625 if (pixmap.load(fpath)) {
626 if (fpath.contains("math") || fpath.contains("ipa")
627 || fpath.contains("bullets"))
628 return prepareForDarkMode(pixmap);
632 bool const list = ext.contains(",");
633 LYXERR(Debug::GUI, "Cannot load pixmap \""
634 << path << "/" << name << "." << (list ? "{" : "") << ext
635 << (list ? "}" : "") << "\".");
641 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
643 #if (QT_VERSION >= 0x040600)
644 if (lyxrc.use_system_theme_icons) {
645 // use the icons from system theme that are available
646 QString action = toqstr(lyxaction.getActionName(f.action()));
647 if (!f.argument().empty())
648 action += " " + toqstr(f.argument());
649 QString const theme_icon = themeIconName(action);
650 if (QIcon::hasThemeIcon(theme_icon)) {
651 QIcon const thmicn = QIcon::fromTheme(theme_icon);
652 if (!thmicn.isNull())
658 IconInfo icondata = iconInfo(f, unknown, rtl);
659 if (icondata.filepath.isEmpty())
662 //LYXERR(Debug::GUI, "Found icon: " << icon);
663 QPixmap pixmap = QPixmap();
664 if (!pixmap.load(icondata.filepath)) {
665 LYXERR0("Cannot load icon " << icondata.filepath << ".");
670 pixmap = prepareForDarkMode(pixmap);
673 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
675 return QIcon(pixmap);
679 ////////////////////////////////////////////////////////////////////////
681 // LyX server support code.
683 ////////////////////////////////////////////////////////////////////////
685 class SocketNotifier : public QSocketNotifier
688 /// connect a connection notification from the LyXServerSocket
689 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
690 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
694 /// The callback function
695 Application::SocketCallback func_;
699 class GuiTranslator : public QTranslator
702 GuiTranslator(QObject * parent = nullptr)
703 : QTranslator(parent)
706 QString translate(const char * /* context */,
707 const char *sourceText,
708 #if QT_VERSION >= 0x050000
709 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
711 const char * /*comment*/ = 0) const override
714 // Here we declare the strings that need to be translated from Qt own GUI
715 // This is needed to include these strings to po files
719 _("Restore Defaults");
722 // Already in po: "Cancel", "&Cancel"
723 _("Apply"); // Already in po: "&Apply"
724 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
727 docstring s = getGuiMessages().getIfFound(sourceText);
728 // This test should eventually be removed when translations are updated
730 LYXERR(Debug::LOCALE, "Missing translation for `"
731 << string(sourceText) << "'");
737 ////////////////////////////////////////////////////////////////////////
739 // Mac specific stuff goes here...
741 ////////////////////////////////////////////////////////////////////////
744 // QMacPasteboardMimeGraphics can only be compiled on Mac.
746 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
749 QMacPasteboardMimeGraphics()
750 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
753 QString convertorName() { return "Graphics"; }
755 QString flavorFor(QString const & mime)
757 LYXERR(Debug::ACTION, "flavorFor " << mime);
758 if (mime == pdfMimeType())
759 return QLatin1String("com.adobe.pdf");
763 QString mimeFor(QString flav)
765 LYXERR(Debug::ACTION, "mimeFor " << flav);
766 if (flav == QLatin1String("com.adobe.pdf"))
767 return pdfMimeType();
771 bool canConvert(QString const & mime, QString flav)
773 return mimeFor(flav) == mime;
776 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
780 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
784 QList<QByteArray> convertFromMime(QString const & /*mime*/,
785 QVariant data, QString /*flav*/)
787 QList<QByteArray> ret;
788 ret.append(data.toByteArray());
794 ///////////////////////////////////////////////////////////////
796 // You can find more platform specific stuff at the end of this file...
798 ///////////////////////////////////////////////////////////////
800 ////////////////////////////////////////////////////////////////////////
801 // Windows specific stuff goes here...
803 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
804 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
805 // QWindowsMimeMetafile can only be compiled on Windows.
807 static FORMATETC cfFromMime(QString const & mimetype)
810 if (mimetype == emfMimeType()) {
811 formatetc.cfFormat = CF_ENHMETAFILE;
812 formatetc.tymed = TYMED_ENHMF;
813 } else if (mimetype == wmfMimeType()) {
814 formatetc.cfFormat = CF_METAFILEPICT;
815 formatetc.tymed = TYMED_MFPICT;
818 formatetc.dwAspect = DVASPECT_CONTENT;
819 formatetc.lindex = -1;
824 class QWindowsMimeMetafile : public QWINDOWSMIME {
826 QWindowsMimeMetafile() {}
828 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
829 QMimeData const * /*mimedata*/) const override
834 bool canConvertToMime(QString const & mimetype,
835 IDataObject * pDataObj) const override
837 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
839 FORMATETC formatetc = cfFromMime(mimetype);
840 return pDataObj->QueryGetData(&formatetc) == S_OK;
843 bool convertFromMime(FORMATETC const & /*formatetc*/,
844 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
849 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
850 QVariant::Type /*preferredType*/) const override
853 if (!canConvertToMime(mimetype, pDataObj))
856 FORMATETC formatetc = cfFromMime(mimetype);
858 if (pDataObj->GetData(&formatetc, &s) != S_OK)
862 if (s.tymed == TYMED_ENHMF) {
863 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
864 data.resize(dataSize);
865 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
866 (LPBYTE)data.data());
867 } else if (s.tymed == TYMED_MFPICT) {
868 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
869 data.resize(dataSize);
870 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
871 (LPBYTE)data.data());
874 ReleaseStgMedium(&s);
880 QVector<FORMATETC> formatsForMime(QString const & mimetype,
881 QMimeData const * /*mimedata*/) const override
883 QVector<FORMATETC> formats;
884 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
885 formats += cfFromMime(mimetype);
889 QString mimeForFormat(FORMATETC const & formatetc) const override
891 switch (formatetc.cfFormat) {
893 return emfMimeType();
894 case CF_METAFILEPICT:
895 return wmfMimeType();
905 /// Allows to check whether ESC was pressed during a long operation
906 class KeyChecker : public QObject {
911 KeyChecker() : pressed_(false), started_(false) {}
914 QCoreApplication::instance()->installEventFilter(this);
919 QCoreApplication::instance()->removeEventFilter(this);
923 QCoreApplication::processEvents();
926 bool started() const {
929 bool eventFilter(QObject *obj, QEvent *event) override {
930 LYXERR(Debug::ACTION, "Event Type: " << event->type());
931 switch (event->type()) {
935 case QEvent::UpdateRequest:
936 case QEvent::CursorChange:
937 case QEvent::ActionChanged:
938 case QEvent::EnabledChange:
939 case QEvent::SockAct:
942 case QEvent::ToolTipChange:
943 case QEvent::LayoutRequest:
944 case QEvent::MetaCall:
945 return QObject::eventFilter(obj, event);
947 // FIXME Blocking all these events is a bad idea.
948 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
949 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
957 ////////////////////////////////////////////////////////////////////////
958 // GuiApplication::Private definition and implementation.
959 ////////////////////////////////////////////////////////////////////////
961 struct GuiApplication::Private
963 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
964 global_menubar_(nullptr)
965 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
966 , last_state_(Qt::ApplicationInactive)
969 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
970 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
971 /// WMF Mime handler for Windows clipboard.
972 wmf_mime_ = new QWindowsMimeMetafile;
975 initKeySequences(&theTopLevelKeymap());
978 void initKeySequences(KeyMap * kb)
980 keyseq = KeySequence(kb, kb);
981 cancel_meta_seq = KeySequence(kb, kb);
985 QSortFilterProxyModel * language_model_;
987 GuiClipboard clipboard_;
989 GuiSelection selection_;
991 FontLoader font_loader_;
993 ColorCache color_cache_;
994 /// the built-in Qt translation mechanism
995 QTranslator qt_trans_;
996 /// LyX gettext-based translation for Qt elements
997 GuiTranslator gui_trans_;
999 QHash<int, SocketNotifier *> socket_notifiers_;
1003 /// The global instance
1006 /// this timer is used for any regular events one wants to
1007 /// perform. at present it is used to check if forked processes
1009 QTimer general_timer_;
1011 /// delayed FuncRequests
1012 std::queue<FuncRequest> func_request_queue_;
1017 KeySequence cancel_meta_seq;
1019 KeyModifier meta_fake_bit;
1021 /// The result of last dispatch action
1022 DispatchResult dispatch_result_;
1024 /// Multiple views container.
1026 * Warning: This must not be a smart pointer as the destruction of the
1027 * object is handled by Qt when the view is closed
1028 * \sa Qt::WA_DeleteOnClose attribute.
1030 QHash<int, GuiView *> views_;
1032 /// Only used on mac.
1033 QMenuBar * global_menubar_;
1034 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1035 /// Holds previous application state on Mac
1036 Qt::ApplicationState last_state_;
1040 /// Linkback mime handler for MacOSX.
1041 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1044 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1045 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1046 /// WMF Mime handler for Windows clipboard.
1047 QWindowsMimeMetafile * wmf_mime_;
1051 /// Allows to check whether ESC was pressed during a long operation
1052 KeyChecker key_checker_;
1056 GuiApplication * guiApp;
1058 GuiApplication::~GuiApplication()
1061 closeAllLinkBackLinks();
1067 GuiApplication::GuiApplication(int & argc, char ** argv)
1068 : QApplication(argc, argv), current_view_(nullptr),
1069 d(new GuiApplication::Private)
1071 QString app_name = "LyX";
1072 QCoreApplication::setOrganizationName(app_name);
1073 QCoreApplication::setOrganizationDomain("lyx.org");
1074 QCoreApplication::setApplicationName(lyx_package);
1075 #if QT_VERSION >= 0x050000
1076 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1079 #if QT_VERSION >= 0x050700
1080 setDesktopFileName(lyx_package);
1083 // FIXME Deprecated. Should use QRandomGenerator since 5.10
1084 qsrand(QDateTime::currentDateTime().toTime_t());
1086 // Install LyX translator for missing Qt translations
1087 installTranslator(&d->gui_trans_);
1088 // Install Qt native translator for GUI elements.
1089 installTranslator(&d->qt_trans_);
1092 // Enable reception of XCB events.
1093 installNativeEventFilter(this);
1096 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1097 // lyxrc setting for this in order to let the application stay resident.
1098 // But then we need some kind of dock icon, at least on Windows.
1100 if (lyxrc.quit_on_last_window_closed)
1101 setQuitOnLastWindowClosed(false);
1104 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1105 // seems to be the default case for applications like LyX.
1106 setQuitOnLastWindowClosed(false);
1109 appleCleanupEditMenu();
1110 appleCleanupViewMenu();
1111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1112 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1113 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1117 #if defined(Q_WS_X11) || defined(QPA_XCB)
1118 // doubleClickInterval() is 400 ms on X11 which is just too long.
1119 // On Windows and Mac OS X, the operating system's value is used.
1120 // On Microsoft Windows, calling this function sets the double
1121 // click interval for all applications. So we don't!
1122 QApplication::setDoubleClickInterval(300);
1125 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1127 // needs to be done before reading lyxrc
1129 lyxrc.dpi = (w.physicalDpiX() + w.physicalDpiY()) / 2;
1133 // Initialize RC Fonts
1134 if (lyxrc.roman_font_name.empty())
1135 lyxrc.roman_font_name = fromqstr(romanFontName());
1137 if (lyxrc.sans_font_name.empty())
1138 lyxrc.sans_font_name = fromqstr(sansFontName());
1140 if (lyxrc.typewriter_font_name.empty())
1141 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1143 #if (QT_VERSION >= 0x050000)
1144 // Qt4 does this in event(), see below.
1145 // Track change of keyboard
1146 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1149 d->general_timer_.setInterval(500);
1150 connect(&d->general_timer_, SIGNAL(timeout()),
1151 this, SLOT(handleRegularEvents()));
1152 d->general_timer_.start();
1154 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1155 // This is clearly not enough in a time where we use threads for
1156 // document preview and/or export. 20 should be OK.
1157 QThreadPool::globalInstance()->setMaxThreadCount(20);
1159 // make sure tooltips are formatted
1160 installEventFilter(new ToolTipFormatter(this));
1164 GuiApplication * theGuiApp()
1166 return dynamic_cast<GuiApplication *>(theApp());
1170 #if QT_VERSION < 0x050000
1171 // Emulate platformName() for Qt4
1173 // FIXME: when ditching this method, remove all tests
1174 // platformName() == "qt4x11"
1176 QString GuiApplication::platformName() const
1178 # if defined(Q_WS_X11)
1179 // Note that this one does not really exist
1181 # elif defined(Q_OS_MAC)
1183 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1186 LYXERR0("Unknown platform!");
1193 double GuiApplication::pixelRatio() const
1195 #if QT_VERSION >= 0x050000
1196 return qt_scale_factor * devicePixelRatio();
1203 void GuiApplication::clearSession()
1210 docstring Application::iconName(FuncRequest const & f, bool unknown)
1212 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1216 docstring Application::mathIcon(docstring const & c)
1218 return qstring_to_ucs4(findImg(toqstr(c)));
1222 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1226 BufferView * bv = nullptr;
1227 BufferView * doc_bv = nullptr;
1229 if (cmd.action() == LFUN_NOACTION) {
1230 status.message(from_utf8(N_("Nothing to do")));
1231 status.setEnabled(false);
1234 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1235 status.setUnknown(true);
1236 status.message(from_utf8(N_("Unknown action")));
1237 status.setEnabled(false);
1240 // Does the GuiApplication know something?
1241 else if (getStatus(cmd, status)) { }
1243 // If we do not have a GuiView, then other functions are disabled
1244 else if (!current_view_)
1245 status.setEnabled(false);
1247 // Does the GuiView know something?
1248 else if (current_view_->getStatus(cmd, status)) { }
1250 // In LyX/Mac, when a dialog is open, the menus of the
1251 // application can still be accessed without giving focus to
1252 // the main window. In this case, we want to disable the menu
1253 // entries that are buffer or view-related.
1254 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1256 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1257 status.setEnabled(false);
1260 // If we do not have a BufferView, then other functions are disabled
1261 else if (!(bv = current_view_->currentBufferView()))
1262 status.setEnabled(false);
1264 // Does the current BufferView know something?
1265 else if (bv->getStatus(cmd, status)) { }
1267 // Does the current Buffer know something?
1268 else if (bv->buffer().getStatus(cmd, status)) { }
1270 // If we do not have a document BufferView, different from the
1271 // current BufferView, then other functions are disabled
1272 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1273 status.setEnabled(false);
1275 // Does the document Buffer know something?
1276 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1279 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1280 status.message(from_utf8(N_("Command not handled")));
1281 status.setEnabled(false);
1284 // the default error message if we disable the command
1285 if (!status.enabled() && status.message().empty())
1286 status.message(from_utf8(N_("Command disabled")));
1292 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1294 // I would really like to avoid having this switch and rather try to
1295 // encode this in the function itself.
1296 // -- And I'd rather let an inset decide which LFUNs it is willing
1297 // to handle (Andre')
1299 switch (cmd.action()) {
1301 // This could be used for the no-GUI version. The GUI version is handled in
1302 // GuiView::getStatus(). See above.
1304 case LFUN_BUFFER_WRITE:
1305 case LFUN_BUFFER_WRITE_AS:
1306 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1307 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1308 enable = b && (b->isUnnamed() || !b->isClean());
1313 case LFUN_BOOKMARK_GOTO: {
1314 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1315 enable = theSession().bookmarks().isValid(num);
1319 case LFUN_BOOKMARK_CLEAR:
1320 enable = theSession().bookmarks().hasValid();
1323 // this one is difficult to get right. As a half-baked
1324 // solution, we consider only the first action of the sequence
1325 case LFUN_COMMAND_SEQUENCE: {
1326 // argument contains ';'-terminated commands
1327 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1328 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1329 func.setOrigin(cmd.origin());
1330 flag = getStatus(func);
1334 // we want to check if at least one of these is enabled
1335 case LFUN_COMMAND_ALTERNATIVES: {
1336 // argument contains ';'-terminated commands
1337 string arg = to_utf8(cmd.argument());
1338 while (!arg.empty()) {
1340 arg = split(arg, first, ';');
1341 FuncRequest func(lyxaction.lookupFunc(first));
1342 func.setOrigin(cmd.origin());
1343 flag = getStatus(func);
1344 // if this one is enabled, the whole thing is
1353 string name = to_utf8(cmd.argument());
1354 if (theTopLevelCmdDef().lock(name, func)) {
1355 func.setOrigin(cmd.origin());
1356 flag = getStatus(func);
1357 theTopLevelCmdDef().release(name);
1359 // catch recursion or unknown command
1360 // definition. all operations until the
1361 // recursion or unknown command definition
1362 // occurs are performed, so set the state to
1369 case LFUN_IF_RELATIVES: {
1370 string const lfun = to_utf8(cmd.argument());
1371 BufferView const * bv =
1372 current_view_ ? current_view_->currentBufferView() : nullptr;
1373 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1377 FuncRequest func(lyxaction.lookupFunc(lfun));
1378 func.setOrigin(cmd.origin());
1379 flag = getStatus(func);
1383 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1385 case LFUN_PREFERENCES_SAVE:
1386 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1387 case LFUN_DEBUG_LEVEL_SET:
1388 // these are handled in our dispatch()
1391 case LFUN_WINDOW_CLOSE:
1392 enable = !d->views_.empty();
1395 case LFUN_BUFFER_NEW:
1396 case LFUN_BUFFER_NEW_TEMPLATE:
1397 case LFUN_FILE_OPEN:
1398 case LFUN_LYXFILES_OPEN:
1399 case LFUN_HELP_OPEN:
1400 case LFUN_SCREEN_FONT_UPDATE:
1401 case LFUN_SET_COLOR:
1402 case LFUN_WINDOW_NEW:
1404 case LFUN_LYXRC_APPLY:
1405 case LFUN_COMMAND_PREFIX:
1407 case LFUN_META_PREFIX:
1408 case LFUN_RECONFIGURE:
1409 case LFUN_SERVER_GET_FILENAME:
1410 case LFUN_SERVER_NOTIFY:
1414 case LFUN_BUFFER_FORALL: {
1415 if (theBufferList().empty()) {
1416 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1417 flag.setEnabled(false);
1421 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1422 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1423 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1424 flag.setEnabled(false);
1429 case LFUN_DIALOG_SHOW: {
1430 string const name = cmd.getArg(0);
1431 return name == "aboutlyx"
1432 || name == "lyxfiles"
1434 || name == "texinfo"
1435 || name == "progress"
1436 || name == "compare";
1444 flag.setEnabled(false);
1448 /// make a post-dispatch status message
1449 static docstring makeDispatchMessage(docstring const & msg,
1450 FuncRequest const & cmd)
1452 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1453 || cmd.origin() == FuncRequest::TOOLBAR
1454 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1456 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1457 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1461 docstring dispatch_msg = msg;
1462 if (!dispatch_msg.empty())
1463 dispatch_msg += ' ';
1465 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1467 bool argsadded = false;
1469 if (!cmd.argument().empty()) {
1470 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1471 comname += ' ' + cmd.argument();
1475 docstring const shortcuts = theTopLevelKeymap().
1476 printBindings(cmd, KeySequence::ForGui);
1478 if (!shortcuts.empty())
1479 comname += ": " + shortcuts;
1480 else if (!argsadded && !cmd.argument().empty())
1481 comname += ' ' + cmd.argument();
1483 if (!comname.empty()) {
1484 comname = rtrim(comname);
1485 dispatch_msg += '(' + rtrim(comname) + ')';
1487 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1488 return dispatch_msg;
1492 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1496 Buffer * buffer = nullptr;
1497 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1498 //setCurrentView(cmd.view_origin); //does not work
1500 dr.setMessage(_("Wrong focus!"));
1501 d->dispatch_result_ = dr;
1502 return d->dispatch_result_;
1504 if (current_view_ && current_view_->currentBufferView()) {
1505 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1506 buffer = ¤t_view_->currentBufferView()->buffer();
1509 dr.screenUpdate(Update::FitCursor);
1511 // All the code is kept inside the undo group because
1512 // updateBuffer can create undo actions (see #11292)
1513 UndoGroupHelper ugh(buffer);
1515 if (dr.screenUpdate() & Update::ForceAll) {
1516 for (Buffer const * b : theBufferList())
1518 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1521 updateCurrentView(cmd, dr);
1524 d->dispatch_result_ = dr;
1525 return d->dispatch_result_;
1529 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1534 BufferView * bv = current_view_->currentBufferView();
1536 if (dr.needBufferUpdate()) {
1537 bv->cursor().clearBufferUpdate();
1538 bv->buffer().updateBuffer();
1540 // BufferView::update() updates the ViewMetricsInfo and
1541 // also initializes the position cache for all insets in
1542 // (at least partially) visible top-level paragraphs.
1543 // We will redraw the screen only if needed.
1544 bv->processUpdateFlags(dr.screenUpdate());
1546 // Do we have a selection?
1547 theSelection().haveSelection(bv->cursor().selection());
1550 current_view_->restartCaret();
1552 if (dr.needMessageUpdate()) {
1553 // Some messages may already be translated, so we cannot use _()
1554 current_view_->message(makeDispatchMessage(
1555 translateIfPossible(dr.message()), cmd));
1560 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1561 bool switchToBuffer)
1563 if (!theSession().bookmarks().isValid(idx))
1565 BookmarksSection::Bookmark const & bm =
1566 theSession().bookmarks().bookmark(idx);
1567 LASSERT(!bm.filename.empty(), return);
1568 string const file = bm.filename.absFileName();
1569 // if the file is not opened, open it.
1570 if (!theBufferList().exists(bm.filename)) {
1572 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1576 // open may fail, so we need to test it again
1577 if (!theBufferList().exists(bm.filename))
1580 // bm can be changed when saving
1581 BookmarksSection::Bookmark tmp = bm;
1583 // Special case idx == 0 used for back-from-back jump navigation
1585 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1587 // if the current buffer is not that one, switch to it.
1588 BufferView * doc_bv = current_view_ ?
1589 current_view_->documentBufferView() : nullptr;
1590 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1591 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1592 if (switchToBuffer) {
1593 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1596 doc_bv = current_view_->documentBufferView();
1601 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1602 if (!doc_bv || !doc_bv->moveToPosition(
1603 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1606 Cursor & cur = doc_bv->cursor();
1607 if (old && cur != *old)
1608 notifyCursorLeavesOrEnters(*old, cur);
1614 // Cursor jump succeeded!
1615 pit_type new_pit = cur.pit();
1616 pos_type new_pos = cur.pos();
1617 int new_id = cur.paragraph().id();
1619 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1620 // see http://www.lyx.org/trac/ticket/3092
1621 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1622 || bm.top_id != new_id) {
1623 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1624 new_pit, new_pos, new_id);
1628 // This function runs "configure" and then rereads lyx.defaults to
1629 // reconfigure the automatic settings.
1630 void GuiApplication::reconfigure(string const & option)
1632 // emit message signal.
1634 current_view_->message(_("Running configure..."));
1636 // Run configure in user lyx directory
1637 string const lock_file = package().getConfigureLockName();
1638 int fd = fileLock(lock_file.c_str());
1639 int const ret = package().reconfigureUserLyXDir(option);
1640 // emit message signal.
1642 current_view_->message(_("Reloading configuration..."));
1643 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1644 // Re-read packages.lst
1645 LaTeXPackages::getAvailable();
1646 fileUnlock(fd, lock_file.c_str());
1649 Alert::information(_("System reconfiguration failed"),
1650 _("The system reconfiguration has failed.\n"
1651 "Default textclass is used but LyX may\n"
1652 "not be able to work properly.\n"
1653 "Please reconfigure again if needed."));
1655 Alert::information(_("System reconfigured"),
1656 _("The system has been reconfigured.\n"
1657 "You need to restart LyX to make use of any\n"
1658 "updated document class specifications."));
1661 void GuiApplication::validateCurrentView()
1663 if (!d->views_.empty() && !current_view_) {
1664 // currently at least one view exists but no view has the focus.
1665 // choose the last view to make it current.
1666 // a view without any open document is preferred.
1667 GuiView * candidate = nullptr;
1668 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1669 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1670 for (; it != end; ++it) {
1672 if (!candidate->documentBufferView())
1675 setCurrentView(candidate);
1679 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1681 string const argument = to_utf8(cmd.argument());
1682 FuncCode const action = cmd.action();
1684 LYXERR(Debug::ACTION, "cmd: " << cmd);
1686 // we have not done anything wrong yet.
1689 FuncStatus const flag = getStatus(cmd);
1690 if (!flag.enabled()) {
1691 // We cannot use this function here
1692 LYXERR(Debug::ACTION, "action "
1693 << lyxaction.getActionName(action)
1694 << " [" << action << "] is disabled at this location");
1695 dr.setMessage(flag.message());
1697 dr.dispatched(false);
1698 dr.screenUpdate(Update::None);
1699 dr.clearBufferUpdate();
1703 if (cmd.origin() == FuncRequest::LYXSERVER) {
1704 if (current_view_ && current_view_->currentBufferView())
1705 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1706 // we will also need to redraw the screen at the end
1707 dr.screenUpdate(Update::FitCursor);
1710 // Assumes that the action will be dispatched.
1711 dr.dispatched(true);
1713 switch (cmd.action()) {
1715 case LFUN_WINDOW_NEW:
1716 createView(toqstr(cmd.argument()));
1719 case LFUN_WINDOW_CLOSE:
1720 // FIXME: this is done also in GuiView::closeBuffer()!
1721 // update bookmark pit of the current buffer before window close
1722 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1723 gotoBookmark(i, false, false);
1724 // clear the last opened list, because
1725 // maybe this will end the session
1726 theSession().lastOpened().clear();
1727 // check for valid current_view_
1728 validateCurrentView();
1730 current_view_->closeScheduled();
1734 // quitting is triggered by the gui code
1735 // (leaving the event loop).
1737 current_view_->message(from_utf8(N_("Exiting.")));
1738 if (closeAllViews())
1742 case LFUN_SCREEN_FONT_UPDATE: {
1743 // handle the screen font changes.
1744 /* FIXME: this only updates the current document, whereas all
1745 * documents should see their metrics updated.
1747 d->font_loader_.update();
1748 dr.screenUpdate(Update::Force | Update::FitCursor);
1752 case LFUN_BUFFER_NEW:
1753 validateCurrentView();
1755 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1756 createView(QString(), false); // keep hidden
1757 current_view_->newDocument(to_utf8(cmd.argument()));
1758 current_view_->show();
1759 setActiveWindow(current_view_);
1761 current_view_->newDocument(to_utf8(cmd.argument()));
1765 case LFUN_BUFFER_NEW_TEMPLATE: {
1766 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1767 string const temp = cmd.getArg(1);
1768 validateCurrentView();
1770 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1772 current_view_->newDocument(file, temp, true);
1773 if (!current_view_->documentBufferView())
1774 current_view_->close();
1776 current_view_->newDocument(file, temp, true);
1781 case LFUN_FILE_OPEN: {
1782 // FIXME: normally the code below is not needed, since getStatus makes sure that
1783 // current_view_ is not null.
1784 validateCurrentView();
1785 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1786 string const fname = trim(to_utf8(cmd.argument()), "\"");
1787 bool const is_open = FileName::isAbsolute(fname)
1788 && theBufferList().getBuffer(FileName(fname));
1790 || (!lyxrc.open_buffers_in_tabs
1791 && current_view_->documentBufferView() != nullptr
1793 // We want the ui session to be saved per document and not per
1794 // window number. The filename crc is a good enough identifier.
1795 createView(support::checksum(fname));
1796 current_view_->openDocument(fname);
1797 if (!current_view_->documentBufferView())
1798 current_view_->close();
1799 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1800 current_view_->raise();
1801 current_view_->activateWindow();
1802 current_view_->showNormal();
1805 current_view_->openDocument(fname);
1806 if (cmd.origin() == FuncRequest::LYXSERVER) {
1807 current_view_->raise();
1808 current_view_->activateWindow();
1809 current_view_->showNormal();
1815 case LFUN_HELP_OPEN: {
1816 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1817 if (current_view_ == nullptr)
1819 string const arg = to_utf8(cmd.argument());
1821 current_view_->message(_("Missing argument"));
1824 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1826 fname = i18nLibFileSearch("examples", arg, "lyx");
1828 if (fname.empty()) {
1829 lyxerr << "LyX: unable to find documentation file `"
1830 << arg << "'. Bad installation?" << endl;
1833 current_view_->message(bformat(_("Opening help file %1$s..."),
1834 makeDisplayPath(fname.absFileName())));
1835 Buffer * buf = current_view_->loadDocument(fname, false);
1837 buf->setReadonly(!current_view_->develMode());
1841 case LFUN_LYXFILES_OPEN: {
1842 // This is the actual reason for this method (#12106).
1843 validateCurrentView();
1845 || (!lyxrc.open_buffers_in_tabs
1846 && current_view_->documentBufferView() != nullptr))
1848 string arg = to_utf8(cmd.argument());
1852 if (arg != "templates" && arg != "examples") {
1853 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1856 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1860 case LFUN_SET_COLOR: {
1861 string const lyx_name = cmd.getArg(0);
1862 string x11_name = cmd.getArg(1);
1863 string x11_darkname = cmd.getArg(2);
1864 if (lyx_name.empty() || x11_name.empty()) {
1866 current_view_->message(
1867 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1872 // FIXME: The graphics cache no longer has a changeDisplay method.
1873 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1874 bool const graphicsbg_changed =
1875 lyx_name == graphicsbg && x11_name != graphicsbg;
1876 if (graphicsbg_changed)
1877 graphics::GCache::get().changeDisplay(true);
1880 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1881 x11_darkname = x11_name;
1884 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1886 current_view_->message(
1887 bformat(_("Set-color \"%1$s\" failed "
1888 "- color is undefined or "
1889 "may not be redefined"),
1890 from_utf8(lyx_name)));
1893 // Make sure we don't keep old colors in cache.
1894 d->color_cache_.clear();
1895 // Update the current view
1896 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1900 case LFUN_LYXRC_APPLY: {
1901 // reset active key sequences, since the bindings
1902 // are updated (bug 6064)
1904 LyXRC const lyxrc_orig = lyxrc;
1906 istringstream ss(to_utf8(cmd.argument()));
1907 bool const success = lyxrc.read(ss);
1910 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1911 << "Unable to read lyxrc data"
1916 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1918 // If the request comes from the minibuffer, then we can't reset
1919 // the GUI, since that would destroy the minibuffer itself and
1920 // cause a crash, since we are currently in one of the methods of
1921 // GuiCommandBuffer. See bug #8540.
1922 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1925 // FIXME Unfortunately, that leaves a bug here, since we cannot
1926 // reset the GUI in this case. If the changes to lyxrc affected the
1927 // UI, then, nothing would happen. This seems fairly unlikely, but
1928 // it definitely is a bug.
1930 dr.forceBufferUpdate();
1934 case LFUN_COMMAND_PREFIX:
1935 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1940 d->meta_fake_bit = NoModifier;
1941 GuiView * gv = currentView();
1942 if (gv && gv->currentBufferView())
1943 // cancel any selection
1944 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1945 dr.setMessage(from_ascii(N_("Cancel")));
1948 case LFUN_META_PREFIX:
1949 d->meta_fake_bit = AltModifier;
1950 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1953 // --- Menus -----------------------------------------------
1954 case LFUN_RECONFIGURE:
1955 // argument is any additional parameter to the configure.py command
1956 reconfigure(to_utf8(cmd.argument()));
1959 // --- lyxserver commands ----------------------------
1960 case LFUN_SERVER_GET_FILENAME: {
1961 if (current_view_ && current_view_->documentBufferView()) {
1962 docstring const fname = from_utf8(
1963 current_view_->documentBufferView()->buffer().absFileName());
1964 dr.setMessage(fname);
1965 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1967 dr.setMessage(docstring());
1968 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1973 case LFUN_SERVER_NOTIFY: {
1974 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1975 dr.setMessage(dispatch_buffer);
1976 theServer().notifyClient(to_utf8(dispatch_buffer));
1980 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1981 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1987 string rest = split(argument, countstr, ' ');
1988 int const count = convert<int>(countstr);
1989 // an arbitrary number to limit number of iterations
1990 int const max_iter = 10000;
1991 if (count > max_iter) {
1992 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1995 for (int i = 0; i < count; ++i) {
1996 FuncRequest lfun = lyxaction.lookupFunc(rest);
1997 lfun.allowAsync(false);
2004 case LFUN_COMMAND_SEQUENCE: {
2005 // argument contains ';'-terminated commands
2006 string arg = argument;
2007 // FIXME: this LFUN should also work without any view.
2008 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2009 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2010 // This handles undo groups automagically
2011 UndoGroupHelper ugh(buffer);
2012 while (!arg.empty()) {
2014 arg = split(arg, first, ';');
2015 FuncRequest func(lyxaction.lookupFunc(first));
2016 func.allowAsync(false);
2017 func.setOrigin(cmd.origin());
2023 case LFUN_BUFFER_FORALL: {
2024 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2025 funcToRun.allowAsync(false);
2027 map<Buffer *, GuiView *> views_lVisible;
2028 map<GuiView *, Buffer *> activeBuffers;
2030 QList<GuiView *> allViews = d->views_.values();
2032 // this for does not modify any buffer. It just collects info on local
2033 // visibility of buffers and on which buffer is active in each view.
2034 Buffer * const last = theBufferList().last();
2035 for(GuiView * view : allViews) {
2036 // all of the buffers might be locally hidden. That is, there is no
2038 if (!view || !view->currentBufferView())
2039 activeBuffers[view] = nullptr;
2041 activeBuffers[view] = &view->currentBufferView()->buffer();
2043 // find out if each is locally visible or locally hidden.
2044 // we don't use a for loop as the buffer list cycles.
2045 Buffer * b = theBufferList().first();
2047 bool const locallyVisible = view && view->workArea(*b);
2048 if (locallyVisible) {
2049 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2050 // only need to overwrite/add if we don't already know a buffer is globally
2051 // visible or we do know but we would prefer to dispatch LFUN from the
2052 // current view because of cursor position issues.
2053 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2054 views_lVisible[b] = view;
2058 b = theBufferList().next(b);
2062 GuiView * const homeView = currentView();
2063 Buffer * b = theBufferList().first();
2064 Buffer * nextBuf = nullptr;
2065 int numProcessed = 0;
2068 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2070 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2072 // first change to a view where b is locally visible, preferably current_view_.
2073 GuiView * const vLv = views_lVisible[b];
2075 lyx::dispatch(funcToRun);
2083 // put things back to how they were (if possible).
2084 for (GuiView * view : allViews) {
2085 Buffer * originalBuf = activeBuffers[view];
2086 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2087 if (theBufferList().isLoaded(originalBuf))
2088 view->setBuffer(originalBuf);
2090 homeView->setFocus();
2092 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2096 case LFUN_COMMAND_ALTERNATIVES: {
2097 // argument contains ';'-terminated commands
2098 string arg = argument;
2099 while (!arg.empty()) {
2101 arg = split(arg, first, ';');
2102 FuncRequest func(lyxaction.lookupFunc(first));
2103 func.setOrigin(cmd.origin());
2104 FuncStatus const stat = getStatus(func);
2105 if (stat.enabled()) {
2115 if (theTopLevelCmdDef().lock(argument, func)) {
2116 func.setOrigin(cmd.origin());
2118 theTopLevelCmdDef().release(argument);
2120 if (func.action() == LFUN_UNKNOWN_ACTION) {
2121 // unknown command definition
2122 lyxerr << "Warning: unknown command definition `"
2126 // recursion detected
2127 lyxerr << "Warning: Recursion in the command definition `"
2128 << argument << "' detected"
2135 case LFUN_IF_RELATIVES: {
2136 string const lfun = to_utf8(cmd.argument());
2137 FuncRequest func(lyxaction.lookupFunc(lfun));
2138 func.setOrigin(cmd.origin());
2139 FuncStatus const stat = getStatus(func);
2140 if (stat.enabled()) {
2147 case LFUN_PREFERENCES_SAVE:
2148 lyxrc.write(support::makeAbsPath("preferences",
2149 package().user_support().absFileName()), false);
2152 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2153 string const fname = addName(addPath(package().user_support().absFileName(),
2154 "templates/"), "defaults.lyx");
2155 Buffer defaults(fname);
2157 istringstream ss(argument);
2162 // We need to make sure that, after we recreat the DocumentClass,
2163 // which we do in readHeader, we apply it to the document itself.
2164 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2165 int const unknown_tokens = defaults.readHeader(lex);
2166 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2167 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2168 cap::switchBetweenClasses(olddc, newdc, theinset);
2170 if (unknown_tokens != 0) {
2171 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2172 << unknown_tokens << " unknown token"
2173 << (unknown_tokens == 1 ? "" : "s")
2177 if (defaults.writeFile(FileName(defaults.absFileName())))
2178 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2179 makeDisplayPath(fname)));
2182 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2187 case LFUN_BOOKMARK_GOTO:
2188 // go to bookmark, open unopened file and switch to buffer if necessary
2189 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2190 dr.screenUpdate(Update::Force | Update::FitCursor);
2193 case LFUN_BOOKMARK_CLEAR:
2194 theSession().bookmarks().clear();
2197 case LFUN_DEBUG_LEVEL_SET:
2198 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2201 case LFUN_DIALOG_SHOW: {
2202 string const name = cmd.getArg(0);
2204 if ( name == "aboutlyx"
2206 || name == "texinfo"
2207 || name == "progress"
2208 || name == "compare")
2210 // work around: on Mac OS the application
2211 // is not terminated when closing the last view.
2212 // Create a new one to be able to dispatch the
2213 // LFUN_DIALOG_SHOW to this view.
2214 if (current_view_ == nullptr)
2220 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2223 current_view_->dispatch(cmd, dr);
2227 if (current_view_ && current_view_->isFullScreen()) {
2228 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2229 current_view_->menuBar()->hide();
2232 if (cmd.origin() == FuncRequest::LYXSERVER)
2233 updateCurrentView(cmd, dr);
2237 docstring GuiApplication::viewStatusMessage()
2239 // When meta-fake key is pressed, show the key sequence so far + "M-".
2240 if (d->meta_fake_bit != NoModifier)
2241 return d->keyseq.print(KeySequence::ForGui) + "M-";
2243 // Else, when a non-complete key sequence is pressed,
2244 // show the available options.
2245 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2246 return d->keyseq.printOptions(true);
2252 string GuiApplication::inputLanguageCode() const
2254 #if (QT_VERSION < 0x050000)
2255 QLocale loc = keyboardInputLocale();
2257 QLocale loc = inputMethod()->locale();
2259 //LYXERR0("input lang = " << fromqstr(loc.name()));
2260 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2264 void GuiApplication::onLocaleChanged()
2266 //LYXERR0("Change language to " << inputLanguage()->lang());
2267 if (currentView() && currentView()->currentBufferView())
2268 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2272 void GuiApplication::handleKeyFunc(FuncCode action)
2276 if (d->keyseq.length())
2278 GuiView * gv = currentView();
2279 LASSERT(gv && gv->currentBufferView(), return);
2280 BufferView * bv = gv->currentBufferView();
2281 bv->getIntl().getTransManager().deadkey(
2282 c, get_accent(action).accent, bv->cursor().innerText(),
2284 // Need to clear, in case the minibuffer calls these
2287 // copied verbatim from do_accent_char
2288 bv->cursor().resetAnchor();
2292 //Keep this in sync with GuiApplication::processKeySym below
2293 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2294 KeyModifier state) const
2296 // Do nothing if we have nothing
2297 if (!keysym.isOK() || keysym.isModifier())
2299 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2301 FuncRequest func = seq.addkey(keysym, state);
2302 // When not cancel or meta-fake, do the normal lookup.
2303 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2305 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2307 // Maybe user can only reach the key via holding down shift.
2308 // Let's see. But only if shift is the only modifier
2309 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2310 // If addkey looked up a command and did not find further commands then
2311 // seq has been reset at this point
2312 func = seq.addkey(keysym, NoModifier);
2314 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2315 << seq.print(KeySequence::Portable) << ']');
2316 return func.action() != LFUN_UNKNOWN_ACTION;
2320 //Keep this in sync with GuiApplication::queryKeySym above
2321 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2323 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2325 // Do nothing if we have nothing (JMarc)
2326 if (!keysym.isOK() || keysym.isModifier()) {
2328 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2330 current_view_->restartCaret();
2334 char_type encoded_last_key = keysym.getUCSEncoded();
2336 // Do a one-deep top-level lookup for
2337 // cancel and meta-fake keys. RVDK_PATCH_5
2338 d->cancel_meta_seq.reset();
2340 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2341 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2343 // When not cancel or meta-fake, do the normal lookup.
2344 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2345 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2346 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2347 // remove Caps Lock and Mod2 as a modifiers
2348 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2349 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2352 // Don't remove this unless you know what you are doing.
2353 d->meta_fake_bit = NoModifier;
2355 // Can this happen now ?
2356 if (func.action() == LFUN_NOACTION)
2357 func = FuncRequest(LFUN_COMMAND_PREFIX);
2359 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2360 << d->keyseq.print(KeySequence::Portable) << ']');
2362 // already here we know if it any point in going further
2363 // why not return already here if action == -1 and
2364 // num_bytes == 0? (Lgb)
2366 if (d->keyseq.length() > 1 && current_view_)
2367 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2370 // Maybe user can only reach the key via holding down shift.
2371 // Let's see. But only if shift is the only modifier
2372 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2373 LYXERR(Debug::KEY, "Trying without shift");
2374 // If addkey looked up a command and did not find further commands then
2375 // seq has been reset at this point
2376 func = d->keyseq.addkey(keysym, NoModifier);
2377 LYXERR(Debug::KEY, "Action now " << func.action());
2380 if (func.action() == LFUN_UNKNOWN_ACTION) {
2381 // We didn't match any of the key sequences.
2382 // See if it's normal insertable text not already
2383 // covered by a binding
2384 if (keysym.isText() && d->keyseq.length() == 1) {
2385 // Non-printable characters (such as ASCII control characters)
2386 // must not be inserted (#5704)
2387 if (!isPrintable(encoded_last_key)) {
2388 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2390 current_view_->restartCaret();
2393 // The following modifier check is not needed on Mac.
2394 // The keysym is either not text or it is different
2395 // from the non-modifier keysym. See #9875 for the
2396 // broken alt-modifier effect of having this code active.
2397 #if !defined(Q_OS_MAC)
2398 // If a non-Shift Modifier is used we have a non-bound key sequence
2399 // (such as Alt+j = j). This should be omitted (#5575).
2400 // On Windows, AltModifier and ControlModifier are both
2401 // set when AltGr is pressed. Therefore, in order to not
2402 // break AltGr-bound symbols (see #5575 for details),
2403 // unbound Ctrl+Alt key sequences are allowed.
2404 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2405 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2406 && !(state & AltModifier && state & ControlModifier)
2410 if (current_view_) {
2411 current_view_->message(_("Unknown function."));
2412 current_view_->restartCaret();
2417 // Since all checks above were passed, we now really have text that
2418 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2419 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2421 LYXERR(Debug::KEY, "isText() is true, inserting.");
2422 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2424 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2425 if (current_view_) {
2426 current_view_->message(_("Unknown function."));
2427 current_view_->restartCaret();
2433 if (func.action() == LFUN_SELF_INSERT) {
2434 if (encoded_last_key != 0) {
2435 docstring const arg(1, encoded_last_key);
2436 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2437 FuncRequest::KEYBOARD));
2438 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2441 processFuncRequest(func);
2445 void GuiApplication::processFuncRequest(FuncRequest const & func)
2447 lyx::dispatch(func);
2451 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2453 addToFuncRequestQueue(func);
2454 processFuncRequestQueueAsync();
2458 void GuiApplication::processFuncRequestQueue()
2460 while (!d->func_request_queue_.empty()) {
2461 // take the item from the stack _before_ processing the
2462 // request in order to avoid race conditions from nested
2463 // or parallel requests (see #10406)
2464 FuncRequest const fr(d->func_request_queue_.front());
2465 d->func_request_queue_.pop();
2466 processFuncRequest(fr);
2471 void GuiApplication::processFuncRequestQueueAsync()
2473 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2477 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2479 d->func_request_queue_.push(func);
2483 void GuiApplication::resetGui()
2485 // Set the language defined by the user.
2489 if (!readUIFile(toqstr(lyxrc.ui_file)))
2490 // Gives some error box here.
2493 if (d->global_menubar_)
2494 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2496 QHash<int, GuiView *>::iterator it;
2497 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2500 gv->setLayoutDirection(layoutDirection());
2504 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2508 bool GuiApplication::rtlContext() const
2510 if (current_view_ && current_view_->currentBufferView()) {
2511 BufferView const * bv = current_view_->currentBufferView();
2512 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2514 return layoutDirection() == Qt::RightToLeft;
2518 void GuiApplication::createView(int view_id)
2520 createView(QString(), true, view_id);
2524 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2527 // release the keyboard which might have been grabbed by the global
2528 // menubar on Mac to catch shortcuts even without any GuiView.
2529 if (d->global_menubar_)
2530 d->global_menubar_->releaseKeyboard();
2534 while (d->views_.find(id) != d->views_.end())
2537 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2538 GuiView * view = new GuiView(id);
2539 // `view' is the new current_view_. Tell coverity that is is not 0.
2540 LATTEST(current_view_);
2542 d->views_[id] = view;
2546 setActiveWindow(view);
2549 if (!geometry_arg.isEmpty()) {
2550 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2554 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2555 re.indexIn(geometry_arg);
2556 w = re.cap(1).toInt();
2557 h = re.cap(2).toInt();
2558 x = re.cap(3).toInt();
2559 y = re.cap(4).toInt();
2560 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2561 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2562 // Set initial geometry such that we can get the frame size.
2563 view->setGeometry(x, y, w, h);
2564 int framewidth = view->geometry().x() - view->x();
2565 int titleheight = view->geometry().y() - view->y();
2566 // Negative displacements must be interpreted as distances
2567 // from the right or bottom screen borders.
2568 if (sx == '-' || sy == '-') {
2569 QRect rec = QApplication::desktop()->screenGeometry();
2571 x += rec.width() - w - framewidth;
2573 y += rec.height() - h - titleheight;
2574 view->setGeometry(x, y, w, h);
2576 // Make sure that the left and top frame borders are visible.
2577 if (view->x() < 0 || view->y() < 0) {
2582 view->setGeometry(x, y, w, h);
2590 bool GuiApplication::unhide(Buffer * buf)
2594 currentView()->setBuffer(buf, false);
2599 Clipboard & GuiApplication::clipboard()
2601 return d->clipboard_;
2605 Selection & GuiApplication::selection()
2607 return d->selection_;
2611 FontLoader & GuiApplication::fontLoader()
2613 return d->font_loader_;
2617 Toolbars const & GuiApplication::toolbars() const
2619 return d->toolbars_;
2623 Toolbars & GuiApplication::toolbars()
2625 return d->toolbars_;
2629 Menus const & GuiApplication::menus() const
2635 Menus & GuiApplication::menus()
2641 QList<int> GuiApplication::viewIds() const
2643 return d->views_.keys();
2647 ColorCache & GuiApplication::colorCache()
2649 return d->color_cache_;
2653 int GuiApplication::exec()
2655 // asynchronously handle batch commands. This event will be in
2656 // the event queue in front of other asynchronous events. Hence,
2657 // we can assume in the latter that the gui is setup already.
2658 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2660 return QApplication::exec();
2664 void GuiApplication::exit(int status)
2666 QApplication::exit(status);
2670 void GuiApplication::setGuiLanguage()
2674 // install translation file for Qt built-in dialogs
2675 QString const language_name = QString("qt_") + theLocale.name();
2676 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2677 // Short-named translator can be loaded from a long name, but not the
2678 // opposite. Therefore, long name should be used without truncation.
2679 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2680 if (!d->qt_trans_.load(language_name,
2681 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2682 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2685 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2689 switch (theLocale.language()) {
2690 case QLocale::Arabic :
2691 case QLocale::Hebrew :
2692 case QLocale::Persian :
2693 case QLocale::Urdu :
2694 setLayoutDirection(Qt::RightToLeft);
2697 setLayoutDirection(Qt::LeftToRight);
2702 void GuiApplication::execBatchCommands()
2707 if (!readUIFile(toqstr(lyxrc.ui_file)))
2708 // Gives some error box here.
2712 #if QT_VERSION > 0x040600
2713 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2715 #if QT_VERSION > 0x050100
2716 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2718 // Create the global default menubar which is shown for the dialogs
2719 // and if no GuiView is visible.
2720 // This must be done after the session was recovered to know the "last files".
2721 d->global_menubar_ = new QMenuBar(0);
2722 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2725 lyx::execBatchCommands();
2729 QAbstractItemModel * GuiApplication::languageModel()
2731 if (d->language_model_)
2732 return d->language_model_;
2734 QStandardItemModel * lang_model = new QStandardItemModel(this);
2735 lang_model->insertColumns(0, 3);
2736 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2737 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2738 Languages::const_iterator it = lyx::languages.begin();
2739 Languages::const_iterator end = lyx::languages.end();
2740 for (; it != end; ++it) {
2741 int current_row = lang_model->rowCount();
2742 lang_model->insertRows(current_row, 1);
2743 QModelIndex pl_item = lang_model->index(current_row, 0);
2744 QModelIndex sp_item = lang_model->index(current_row, 1);
2745 QModelIndex th_item = lang_model->index(current_row, 2);
2746 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2747 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2748 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2749 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2750 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2751 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2752 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2753 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2754 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2755 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2757 d->language_model_ = new QSortFilterProxyModel(this);
2758 d->language_model_->setSourceModel(lang_model);
2759 d->language_model_->setSortLocaleAware(true);
2760 return d->language_model_;
2764 void GuiApplication::restoreGuiSession()
2766 if (!lyxrc.load_session)
2769 Session & session = theSession();
2770 LastOpenedSection::LastOpened const & lastopened =
2771 session.lastOpened().getfiles();
2773 validateCurrentView();
2775 FileName active_file;
2776 // do not add to the lastfile list since these files are restored from
2777 // last session, and should be already there (regular files), or should
2778 // not be added at all (help files).
2779 for (auto const & last : lastopened) {
2780 FileName const & file_name = last.file_name;
2781 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2782 && current_view_->documentBufferView() != nullptr)) {
2783 string const & fname = file_name.absFileName();
2784 createView(support::checksum(fname));
2786 current_view_->loadDocument(file_name, false);
2789 active_file = file_name;
2792 // Restore last active buffer
2793 Buffer * buffer = theBufferList().getBuffer(active_file);
2794 if (buffer && current_view_)
2795 current_view_->setBuffer(buffer);
2797 // clear this list to save a few bytes of RAM
2798 session.lastOpened().clear();
2802 QString const GuiApplication::romanFontName()
2805 font.setStyleHint(QFont::Serif);
2806 font.setFamily("serif");
2808 return QFontInfo(font).family();
2812 QString const GuiApplication::sansFontName()
2815 font.setStyleHint(QFont::SansSerif);
2816 font.setFamily("sans");
2818 return QFontInfo(font).family();
2822 QString const GuiApplication::typewriterFontName()
2824 return QFontInfo(typewriterSystemFont()).family();
2829 // We cannot use QFont::fixedPitch() because it doesn't
2830 // return the fact but only if it is requested.
2831 static bool isFixedPitch(const QFont & font) {
2832 const QFontInfo fi(font);
2833 return fi.fixedPitch();
2838 QFont const GuiApplication::typewriterSystemFont()
2840 #if QT_VERSION >= 0x050200
2841 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2843 QFont font("monospace");
2845 if (!isFixedPitch(font)) {
2846 // try to enforce a real monospaced font
2847 font.setStyleHint(QFont::Monospace);
2848 if (!isFixedPitch(font)) {
2849 font.setStyleHint(QFont::TypeWriter);
2850 if (!isFixedPitch(font)) font.setFamily("courier");
2854 // On a Mac the result is too small and it's not practical to
2855 // rely on Qtconfig utility to change the system settings of Qt.
2856 font.setPointSize(12);
2862 void GuiApplication::handleRegularEvents()
2864 ForkedCallsController::handleCompletedProcesses();
2868 bool GuiApplication::event(QEvent * e)
2871 case QEvent::FileOpen: {
2872 // Open a file; this happens only on Mac OS X for now.
2874 // We do this asynchronously because on startup the batch
2875 // commands are not executed here yet and the gui is not ready
2877 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2878 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2879 processFuncRequestAsync(fr);
2883 #if (QT_VERSION < 0x050000)
2884 // Qt5 uses a signal for that, see above.
2885 case QEvent::KeyboardLayoutChange:
2886 //LYXERR0("keyboard change");
2887 if (currentView() && currentView()->currentBufferView())
2888 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2893 return QApplication::event(e);
2898 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2901 return QApplication::notify(receiver, event);
2903 catch (ExceptionMessage const & e) {
2905 case ErrorException:
2907 setQuitOnLastWindowClosed(false);
2909 Alert::error(e.title_, e.details_);
2911 // Properly crash in debug mode in order to get a useful backtrace.
2914 // In release mode, try to exit gracefully.
2916 // FIXME: GCC 7 thinks we can fall through here. Can we?
2918 case BufferException: {
2919 if (!current_view_ || !current_view_->documentBufferView())
2921 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2922 docstring details = e.details_ + '\n';
2923 details += buf->emergencyWrite();
2924 theBufferList().release(buf);
2925 details += "\n" + _("The current document was closed.");
2926 Alert::error(e.title_, details);
2929 case WarningException:
2930 Alert::warning(e.title_, e.details_);
2934 catch (exception const & e) {
2935 docstring s = _("LyX has caught an exception, it will now "
2936 "attempt to save all unsaved documents and exit."
2938 s += from_ascii(e.what());
2939 Alert::error(_("Software exception Detected"), s);
2943 docstring s = _("LyX has caught some really weird exception, it will "
2944 "now attempt to save all unsaved documents and exit.");
2945 Alert::error(_("Software exception Detected"), s);
2952 bool GuiApplication::isInDarkMode()
2954 return colorCache().isDarkMode();
2958 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2960 QColor const & qcol = d->color_cache_.get(col);
2961 if (!qcol.isValid()) {
2967 rgbcol.r = qcol.red();
2968 rgbcol.g = qcol.green();
2969 rgbcol.b = qcol.blue();
2974 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2976 QColor const qcol(lcolor.getX11HexName(col).c_str());
2977 if (!qcol.isValid()) {
2983 rgbcol.r = qcol.red();
2984 rgbcol.g = qcol.green();
2985 rgbcol.b = qcol.blue();
2990 string const GuiApplication::hexName(ColorCode col)
2992 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2996 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2998 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2999 d->socket_notifiers_[fd] = sn;
3000 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3004 void GuiApplication::socketDataReceived(int fd)
3006 d->socket_notifiers_[fd]->func_();
3010 void GuiApplication::unregisterSocketCallback(int fd)
3012 d->socket_notifiers_.take(fd)->setEnabled(false);
3016 void GuiApplication::commitData(QSessionManager & sm)
3018 /** The implementation is required to avoid an application exit
3019 ** when session state save is triggered by session manager.
3020 ** The default implementation sends a close event to all
3021 ** visible top level widgets when session management allows
3023 ** We are changing that to check the state of each buffer in all
3024 ** views and ask the users what to do if buffers are dirty.
3025 ** Furthermore, we save the session state.
3026 ** We do NOT close the views here since the user still can cancel
3027 ** the logout process (see #9277); also, this would hide LyX from
3028 ** an OSes own session handling (application restoration).
3030 #ifdef QT_NO_SESSIONMANAGER
3032 #warning Qt is compiled without session manager
3034 #pragma message("warning: Qt is compiled without session manager")
3038 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3046 void GuiApplication::unregisterView(GuiView * gv)
3048 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3049 d->views_.remove(gv->id());
3050 if (current_view_ == gv)
3051 current_view_ = nullptr;
3056 bool GuiApplication::closeAllViews()
3058 if (d->views_.empty())
3061 // When a view/window was closed before without quitting LyX, there
3062 // are already entries in the lastOpened list.
3063 theSession().lastOpened().clear();
3065 QList<GuiView *> const views = d->views_.values();
3066 for (GuiView * view : views) {
3067 if (!view->closeScheduled())
3076 bool GuiApplication::prepareAllViewsForLogout()
3078 if (d->views_.empty())
3081 QList<GuiView *> const views = d->views_.values();
3082 for (GuiView * view : views) {
3083 if (!view->prepareAllBuffersForLogout())
3091 GuiView & GuiApplication::view(int id) const
3093 LAPPERR(d->views_.contains(id));
3094 return *d->views_.value(id);
3098 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3100 QList<GuiView *> const views = d->views_.values();
3101 for (GuiView * view : views)
3102 view->hideDialog(name, inset);
3106 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3108 Buffer const * buf = nullptr;
3109 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3110 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3111 if (Buffer const * ptr = (*it)->updateInset(inset))
3118 bool GuiApplication::searchMenu(FuncRequest const & func,
3119 docstring_list & names) const
3121 BufferView * bv = nullptr;
3123 bv = current_view_->currentBufferView();
3124 return d->menus_.searchMenu(func, names, bv);
3128 bool GuiApplication::hasBufferView() const
3130 return (current_view_ && current_view_->currentBufferView());
3134 // Ensure that a file is read only once (prevents include loops)
3135 static QStringList uifiles;
3136 // store which ui files define Toolbars
3137 static QStringList toolbar_uifiles;
3140 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3151 LexerKeyword uitags[] = {
3152 { "format", ui_format },
3153 { "include", ui_include },
3154 { "menuset", ui_menuset },
3155 { "toolbars", ui_toolbars },
3156 { "toolbarset", ui_toolbarset }
3160 lex.setFile(ui_path);
3162 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3166 if (lyxerr.debugging(Debug::PARSER))
3167 lex.printTable(lyxerr);
3170 // format before introduction of format tag
3171 unsigned int format = 0;
3172 while (lex.isOK()) {
3173 int const status = lex.lex();
3175 // we have to do this check here, outside the switch,
3176 // because otherwise we would start reading include files,
3177 // e.g., if the first tag we hit was an include tag.
3178 if (status == ui_format)
3180 format = lex.getInteger();
3184 // this will trigger unless the first tag we hit is a format
3185 // tag, with the right format.
3186 if (format != LFUN_FORMAT)
3187 return FormatMismatch;
3190 case Lexer::LEX_FEOF:
3195 QString const file = toqstr(lex.getString());
3196 bool const success = readUIFile(file, true);
3198 LYXERR0("Failed to read included file: " << fromqstr(file));
3205 d->menus_.read(lex);
3209 d->toolbars_.readToolbars(lex);
3213 d->toolbars_.readToolbarSettings(lex);
3214 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3218 if (!rtrim(lex.getString()).empty())
3219 lex.printError("LyX::ReadUIFile: "
3220 "Unknown menu tag: `$$Token'");
3222 LYXERR0("Error with status: " << status);
3228 return (error ? ReadError : ReadOK);
3232 bool GuiApplication::readUIFile(QString const & name, bool include)
3234 LYXERR(Debug::INIT, "About to read " << name << "...");
3238 ui_path = libFileSearch("ui", name, "inc");
3239 if (ui_path.empty())
3240 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3242 ui_path = libFileSearch("ui", name, "ui");
3245 if (ui_path.empty()) {
3246 static const QString defaultUIFile = "default";
3247 LYXERR(Debug::INIT, "Could not find " << name);
3249 Alert::warning(_("Could not find UI definition file"),
3250 bformat(_("Error while reading the included file\n%1$s\n"
3251 "Please check your installation."), qstring_to_ucs4(name)));
3254 if (name == defaultUIFile) {
3255 LYXERR(Debug::INIT, "Could not find default UI file!!");
3256 Alert::warning(_("Could not find default UI file"),
3257 _("LyX could not find the default UI file!\n"
3258 "Please check your installation."));
3261 Alert::warning(_("Could not find UI definition file"),
3262 bformat(_("Error while reading the configuration file\n%1$s\n"
3263 "Falling back to default.\n"
3264 "Please look under Tools>Preferences>User Interface and\n"
3265 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3266 return readUIFile(defaultUIFile, false);
3269 QString const uifile = toqstr(ui_path.absFileName());
3270 if (uifiles.contains(uifile)) {
3272 // We are reading again the top uifile so reset the safeguard:
3275 d->toolbars_.reset();
3277 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3278 << "Is this an include loop?");
3282 uifiles.push_back(uifile);
3284 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3286 ReturnValues retval = readUIFile(ui_path);
3288 if (retval == FormatMismatch) {
3289 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3290 TempFile tmp("convertXXXXXX.ui");
3291 FileName const tempfile = tmp.name();
3292 bool const success = prefs2prefs(ui_path, tempfile, true);
3294 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3295 " to format " << LFUN_FORMAT << ".");
3297 retval = readUIFile(tempfile);
3301 if (retval != ReadOK) {
3302 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3310 settings.beginGroup("ui_files");
3311 bool touched = false;
3312 for (int i = 0; i != uifiles.size(); ++i) {
3313 QFileInfo fi(uifiles[i]);
3314 QDateTime const date_value = fi.lastModified();
3315 QString const name_key = QString::number(i);
3316 // if an ui file which defines Toolbars has changed,
3317 // we have to reset the settings
3318 if (toolbar_uifiles.contains(uifiles[i])
3319 && (!settings.contains(name_key)
3320 || settings.value(name_key).toString() != uifiles[i]
3321 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3323 settings.setValue(name_key, uifiles[i]);
3324 settings.setValue(name_key + "/date", date_value);
3327 settings.endGroup();
3329 settings.remove("views");
3335 void GuiApplication::onLastWindowClosed()
3337 if (d->global_menubar_)
3338 d->global_menubar_->grabKeyboard();
3342 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3343 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3345 std::string name = "unknown";
3347 case Qt::ApplicationSuspended:
3348 name = "ApplicationSuspended";
3350 case Qt::ApplicationHidden:
3351 name = "ApplicationHidden";
3353 case Qt::ApplicationInactive:
3354 name = "ApplicationInactive";
3356 case Qt::ApplicationActive:
3357 name = "ApplicationActive";
3358 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3359 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3360 if (d->views_.empty() && d->last_state_ == state) {
3361 LYXERR(Debug::GUI, "Open new window...");
3366 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3367 d->last_state_ = state;
3372 void GuiApplication::startLongOperation() {
3373 d->key_checker_.start();
3377 bool GuiApplication::longOperationCancelled() {
3378 return d->key_checker_.pressed();
3382 void GuiApplication::stopLongOperation() {
3383 d->key_checker_.stop();
3387 bool GuiApplication::longOperationStarted() {
3388 return d->key_checker_.started();
3392 ////////////////////////////////////////////////////////////////////////
3394 // X11 specific stuff goes here...
3397 bool GuiApplication::x11EventFilter(XEvent * xev)
3402 switch (xev->type) {
3403 case SelectionRequest: {
3404 if (xev->xselectionrequest.selection != XA_PRIMARY)
3406 LYXERR(Debug::SELECTION, "X requested selection.");
3407 BufferView * bv = current_view_->currentBufferView();
3409 docstring const sel = bv->requestSelection();
3411 d->selection_.put(sel);
3412 // Refresh the selection request timestamp.
3413 // We have to do this by ourselves as Qt seems
3414 // not doing that, maybe because of our
3415 // "persistent selection" implementation
3416 // (see comments in GuiSelection.cpp).
3417 XSelectionEvent nev;
3418 nev.type = SelectionNotify;
3419 nev.display = xev->xselectionrequest.display;
3420 nev.requestor = xev->xselectionrequest.requestor;
3421 nev.selection = xev->xselectionrequest.selection;
3422 nev.target = xev->xselectionrequest.target;
3423 nev.property = 0L; // None
3424 nev.time = CurrentTime;
3425 XSendEvent(QX11Info::display(),
3426 nev.requestor, False, 0,
3427 reinterpret_cast<XEvent *>(&nev));
3433 case SelectionClear: {
3434 if (xev->xselectionclear.selection != XA_PRIMARY)
3436 LYXERR(Debug::SELECTION, "Lost selection.");
3437 BufferView * bv = current_view_->currentBufferView();
3439 bv->clearSelection();
3445 #elif defined(QPA_XCB)
3446 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3447 void * message, long *)
3449 if (!current_view_ || eventType != "xcb_generic_event_t")
3452 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3454 switch (ev->response_type) {
3455 case XCB_SELECTION_REQUEST: {
3456 xcb_selection_request_event_t * srev =
3457 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3458 if (srev->selection != XCB_ATOM_PRIMARY)
3460 LYXERR(Debug::SELECTION, "X requested selection.");
3461 BufferView * bv = current_view_->currentBufferView();
3463 docstring const sel = bv->requestSelection();
3465 d->selection_.put(sel);
3466 #ifdef HAVE_QT5_X11_EXTRAS
3467 // Refresh the selection request timestamp.
3468 // We have to do this by ourselves as Qt seems
3469 // not doing that, maybe because of our
3470 // "persistent selection" implementation
3471 // (see comments in GuiSelection.cpp).
3472 // It is expected that every X11 event is
3473 // 32 bytes long, even if not all 32 bytes are
3475 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3476 struct alignas(32) padded_event
3477 : xcb_selection_notify_event_t {};
3478 padded_event nev = {};
3479 nev.response_type = XCB_SELECTION_NOTIFY;
3480 nev.requestor = srev->requestor;
3481 nev.selection = srev->selection;
3482 nev.target = srev->target;
3483 nev.property = XCB_NONE;
3484 nev.time = XCB_CURRENT_TIME;
3485 xcb_connection_t * con = QX11Info::connection();
3486 xcb_send_event(con, 0, srev->requestor,
3487 XCB_EVENT_MASK_NO_EVENT,
3488 reinterpret_cast<char const *>(&nev));
3496 case XCB_SELECTION_CLEAR: {
3497 xcb_selection_clear_event_t * scev =
3498 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3499 if (scev->selection != XCB_ATOM_PRIMARY)
3501 LYXERR(Debug::SELECTION, "Lost selection.");
3502 BufferView * bv = current_view_->currentBufferView();
3504 bv->clearSelection();
3512 } // namespace frontend
3515 void hideDialogs(std::string const & name, Inset * inset)
3518 frontend::guiApp->hideDialogs(name, inset);
3522 ////////////////////////////////////////////////////////////////////
3526 ////////////////////////////////////////////////////////////////////
3528 frontend::FontLoader & theFontLoader()
3530 LAPPERR(frontend::guiApp);
3531 return frontend::guiApp->fontLoader();
3535 frontend::FontMetrics const & theFontMetrics(Font const & f)
3537 return theFontMetrics(f.fontInfo());
3541 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3543 LAPPERR(frontend::guiApp);
3544 return frontend::guiApp->fontLoader().metrics(f);
3548 ////////////////////////////////////////////////////////////////////
3552 ////////////////////////////////////////////////////////////////////
3554 frontend::Clipboard & theClipboard()
3556 LAPPERR(frontend::guiApp);
3557 return frontend::guiApp->clipboard();
3561 frontend::Selection & theSelection()
3563 LAPPERR(frontend::guiApp);
3564 return frontend::guiApp->selection();
3570 #include "moc_GuiApplication.cpp"