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>
109 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
110 #include <QRandomGenerator>
113 #include <QSessionManager>
115 #include <QSocketNotifier>
116 #include <QSortFilterProxyModel>
117 #include <QStandardItemModel>
119 #include <QTranslator>
120 #include <QThreadPool>
124 #include <X11/Xatom.h>
125 #include <X11/Xlib.h>
129 #elif defined(QPA_XCB)
131 #ifdef HAVE_QT5_X11_EXTRAS
132 #include <QtX11Extras/QX11Info>
136 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
137 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
138 #if (QT_VERSION < 0x050000)
139 #include <QWindowsMime>
140 #define QWINDOWSMIME QWindowsMime
143 #define QWINDOWSMIME QWinMime
153 #include <QMacPasteboardMime>
161 using namespace lyx::support;
166 frontend::Application * createApplication(int & argc, char * argv[])
168 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
169 // prune -geometry argument(s) by shifting
170 // the following ones 2 places down.
171 for (int i = 0 ; i < argc ; ++i) {
172 if (strcmp(argv[i], "-geometry") == 0) {
173 int const remove = (i+1) < argc ? 2 : 1;
175 for (int j = i; j < argc; ++j)
176 argv[j] = argv[j + remove];
182 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
183 // On Windows, allow bringing the LyX window to top
184 AllowSetForegroundWindow(ASFW_ANY);
188 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
189 // macOS does it by itself.
190 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
191 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
192 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
193 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
194 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
195 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
198 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
199 // HighDPI scale factor policy must be set before QGuiApplication is created
200 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
201 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
205 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
206 // I'd rather do that in the constructor, but I do not think that
207 // the palette is accessible there.
208 guiApp->colorCache().setPalette(guiApp->palette());
217 if (lyxrc.gui_language == "auto") {
218 theLocale = QLocale::system();
219 code = fromqstr(theLocale.name());
221 Language const * l = languages.getLanguage(lyxrc.gui_language);
222 code = l ? l->code() : "C";
223 theLocale = QLocale(toqstr(code));
225 // Qt tries to outsmart us and transforms en_US to C.
226 Messages::guiLanguage((code == "C") ? "en_US" : code);
227 QLocale::setDefault(theLocale);
228 setlocale(LC_NUMERIC, "C");
235 /// Return the list of loadable formats.
236 vector<string> loadableImageFormats()
240 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
242 LYXERR(Debug::GRAPHICS,
243 "\nThe image loader can load the following directly:\n");
245 if (qt_formats.empty())
246 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
248 bool jpeg_found = false;
249 bool jpg_found = false;
250 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
252 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
254 string ext = ascii_lowercase((const char *) *it);
262 else if (ext == "jpg") {
267 else if (lyxrc.use_converter_cache &&
268 (ext == "svg" || ext == "svgz") &&
269 theConverters().isReachable("svg", "png"))
270 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
271 // the SVG as in the output. However we require that the converter
272 // cache is enabled since this is expensive. We also require that
273 // an explicit svg->png converter is defined, since the default
274 // converter could produce bad quality as well. This assumes that
275 // png can always be loaded.
284 ////////////////////////////////////////////////////////////////////////
286 // Icon loading support code
288 ////////////////////////////////////////////////////////////////////////
298 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
300 return lhs.key < rhs.key;
306 CompareKey(QString const & name) : name_(name) {}
307 bool operator()(ImgMap const & other) const { return other.key == name_; }
313 // this must be sorted alphabetically
314 // Upper case comes before lower case
315 // Please don't change the formatting, this list is parsed by
316 // development/tools/generate_symbols_images.py.
317 ImgMap sorted_img_map[] = {
318 { "Arrownot", "arrownot2"},
319 { "Arrowvert", "arrowvert2"},
320 { "Bowtie", "bowtie2" },
322 { "Bumpeq", "bumpeq2" },
323 { "CIRCLE", "circle3" },
325 { "CheckedBox", "checkedbox2" },
326 { "Circle", "circle2" },
327 { "Colonapprox", "colonapprox2" },
328 { "Coloneq", "coloneq2" },
329 { "Coloneqq", "coloneqq2" },
330 { "Colonsim", "colonsim2" },
332 { "DOWNarrow", "downarrow3" },
333 { "Delta", "delta2" },
334 { "Diamond", "diamond2" },
335 { "Doteq", "doteq2" },
336 { "Downarrow", "downarrow2" },
337 { "Eqcolon", "eqcolon2" },
338 { "Eqqcolon", "eqqcolon2" },
339 { "Gamma", "gamma2" },
341 { "LEFTCIRCLE", "leftcircle3" },
342 { "LEFTarrow", "leftarrow3" },
343 { "LEFTcircle", "leftcircle4" },
345 { "Lambda", "lambda2" },
347 { "Leftarrow", "leftarrow2" },
348 { "Leftcircle", "leftcircle2" },
349 { "Leftrightarrow", "leftrightarrow2" },
350 { "Longarrownot", "longarrownot2"},
351 { "Longleftarrow", "longleftarrow2" },
352 { "Longleftrightarrow", "longleftrightarrow2" },
353 { "Longmapsfrom", "longmapsfrom2"},
354 { "Longmapsto", "longmapsto2"},
355 { "Longrightarrow", "longrightarrow2" },
356 { "Mapsfrom", "mapsfrom2"},
357 { "Mapsfromchar", "mapsfromchar2"},
358 { "Mapsto", "mapsto2"},
359 { "Mapstochar", "mapstochar2"},
360 { "Omega", "omega2" },
365 { "RIGHTCIRCLE", "rightcircle3" },
366 { "RIGHTarrow", "rightarrow3" },
367 { "RIGHTcircle", "rightcircle4" },
369 { "Rightarrow", "rightarrow2" },
370 { "Rightcircle", "rightcircle2" },
371 { "Sigma", "sigma2" },
372 { "Square", "square2" },
373 { "Subset", "subset2" },
374 { "Supset", "supset2" },
375 { "Theta", "theta2" },
376 { "Thorn", "thorn2" },
377 { "UParrow", "uparrow3" },
378 { "Uparrow", "uparrow2" },
379 { "Updownarrow", "updownarrow2" },
380 { "Upsilon", "upsilon2" },
381 { "Vdash", "vdash3" },
386 { "lVert", "vert2" },
388 { "nLeftarrow", "nleftarrow2" },
389 { "nLeftrightarrow", "nleftrightarrow2" },
390 { "nRightarrow", "nrightarrow2" },
391 { "nVDash", "nvdash3" },
392 { "nVdash", "nvdash4" },
393 { "nvDash", "nvdash2" },
394 { "rVert", "vert2" },
396 { "textrm \\AA", "textrm_AA"},
397 { "textrm \\O", "textrm_O"},
398 { "vDash", "vdash2" },
399 { "varDelta", "vardelta2" },
400 { "varGamma", "vargamma2" },
401 { "varLambda", "varlambda2" },
402 { "varOmega", "varomega2" },
403 { "varPhi", "varphi2" },
404 { "varPi", "varpi2" },
405 { "varPsi", "varpsi2" },
406 { "varSigma", "varsigma2" },
407 { "varTheta", "vartheta2" },
408 { "varUpsilon", "varupsilon2" },
409 { "varXi", "varxi2" }
413 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
415 // This list specifies which system's theme icon is related to which lyx
416 // command. It was based on:
417 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
418 // this must be sorted alphabetically
419 // Upper case comes before lower case
420 ImgMap sorted_theme_icon_map[] = {
421 { "bookmark-goto 0", "go-jump" },
422 { "buffer-new", "document-new" },
423 { "buffer-write", "document-save" },
424 { "buffer-write-as", "document-save-as" },
425 { "buffer-zoom-in", "zoom-in" },
426 { "buffer-zoom-out", "zoom-out" },
427 { "copy", "edit-copy" },
428 { "cut", "edit-cut" },
429 { "depth-decrement", "format-indent-less" },
430 { "depth-increment", "format-indent-more" },
431 { "dialog-show spellchecker", "tools-check-spelling" },
432 { "dialog-show-new-inset graphics", "insert-image" },
433 { "dialog-toggle findreplaceadv", "edit-find-replace" },
434 { "file-open", "document-open" },
435 { "font-bold", "format-text-bold" },
436 { "font-ital", "format-text-italic" },
437 { "font-strikeout", "format-text-strikethrough" },
438 { "font-underline", "format-text-underline" },
439 { "lyx-quit", "application-exit" },
440 { "paste", "edit-paste" },
441 { "redo", "edit-redo" },
442 { "undo", "edit-undo" },
443 { "window-close", "window-close" },
444 { "window-new", "window-new" }
447 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
450 QString findImg(QString const & name)
452 ImgMap const * const begin = sorted_img_map;
453 ImgMap const * const end = begin + nr_sorted_img_map;
454 LATTEST(sorted(begin, end));
456 ImgMap const * const it = find_if(begin, end, CompareKey(name));
460 img_name = it->value;
463 img_name.replace('_', "underscore");
464 img_name.replace(' ', '_');
466 // This way we can have "math-delim { }" on the toolbar.
467 img_name.replace('(', "lparen");
468 img_name.replace(')', "rparen");
469 img_name.replace('[', "lbracket");
470 img_name.replace(']', "rbracket");
471 img_name.replace('{', "lbrace");
472 img_name.replace('}', "rbrace");
473 img_name.replace('|', "bars");
474 img_name.replace(',', "thinspace");
475 img_name.replace(':', "mediumspace");
476 img_name.replace(';', "thickspace");
477 img_name.replace('!', "negthinspace");
480 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
481 << "Looking for math icon called \"" << img_name << '"');
488 QString themeIconName(QString const & action)
490 ImgMap const * const begin = sorted_theme_icon_map;
491 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
492 LASSERT(sorted(begin, end), /**/);
494 ImgMap const * const it = find_if(begin, end, CompareKey(action));
502 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
507 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
509 if (!f.argument().empty()) {
510 // if there are arguments, first search an icon which name is the full thing
511 QString name = lfunname + ' ' + toqstr(f.argument());
512 name.replace(' ', '_');
513 name.replace(';', '_');
514 name.replace('\\', "backslash");
515 // avoid duplication for these
516 name.replace("dialog-toggle", "dialog-show");
519 // then special default icon for some lfuns
520 switch (f.action()) {
521 case LFUN_MATH_INSERT:
522 names << "math/" + findImg(toqstr(f.argument()).mid(1));
524 case LFUN_MATH_DELIM:
525 case LFUN_MATH_BIGDELIM:
526 names << "math/" + findImg(toqstr(f.argument()));
529 names << "commands/" + toqstr(f.argument());
531 case LFUN_COMMAND_ALTERNATIVES: {
532 // use the first of the alternative commands
534 docstring dummy = split(f.argument(), firstcom, ';');
535 QString name1 = toqstr(firstcom);
536 name1.replace(' ', '_');
537 name1.replace(';', '_');
538 name1.replace('\\', "backslash");
547 // next thing to try is function name alone
550 // and finally maybe the unknown icon
554 search_mode const mode = theGuiApp()->imageSearchMode();
555 // The folders where icons are searched for
556 QStringList imagedirs;
557 imagedirs << "images/ipa/" << "images/";
558 // This is used to search for rtl version of icons which have the +rrtl suffix.
559 QStringList suffixes;
562 suffixes << QString();
564 for (QString const & imagedir : imagedirs)
565 for (QString const & name : names)
566 for (QString const & suffix : suffixes) {
567 QString id = imagedir;
568 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
569 if (fname.exists()) {
570 docstring const fpath = fname.absoluteFilePath();
571 res.filepath = toqstr(fname.absFileName());
572 // these icons are subject to inversion in dark mode
573 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
574 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
575 res.swap = rtl && suffix.isEmpty();
580 LYXERR(Debug::GUI, "Cannot find icon for command \""
581 << lyxaction.getActionName(f.action())
582 << '(' << to_utf8(f.argument()) << ")\"");
588 QPixmap prepareForDarkMode(QPixmap pixmap)
590 QPalette palette = QPalette();
591 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
592 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
594 // guess whether we are in dark mode
595 if (text_color.black() > bg_color.black())
596 // not in dark mode, do nothing
599 // create a layer with black text turned to QPalette::WindowText
600 QPixmap black_overlay(pixmap.size());
601 black_overlay.fill(text_color);
602 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
604 // create a layer with blue text turned to lighter blue
605 QPixmap blue_overlay(pixmap.size());
606 QColor math_blue(0, 0, 255);
607 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
608 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
610 // create a layer with ("latex") red text turned to lighter red
611 QPixmap red_overlay(pixmap.size());
612 QColor math_red(128, 0, 0);
613 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
614 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
616 // put layers on top of existing pixmap
617 QPainter painter(&pixmap);
618 painter.drawPixmap(pixmap.rect(), black_overlay);
619 painter.drawPixmap(pixmap.rect(), blue_overlay);
620 painter.drawPixmap(pixmap.rect(), red_overlay);
626 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
628 QString imagedir = path;
629 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
630 QString fpath = toqstr(fname.absFileName());
631 QPixmap pixmap = QPixmap();
633 if (pixmap.load(fpath)) {
634 if (fpath.contains("math") || fpath.contains("ipa")
635 || fpath.contains("bullets"))
636 return prepareForDarkMode(pixmap);
640 bool const list = ext.contains(",");
641 LYXERR(Debug::GUI, "Cannot load pixmap \""
642 << path << "/" << name << "." << (list ? "{" : "") << ext
643 << (list ? "}" : "") << "\".");
649 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
651 #if (QT_VERSION >= 0x040600)
652 if (lyxrc.use_system_theme_icons) {
653 // use the icons from system theme that are available
654 QString action = toqstr(lyxaction.getActionName(f.action()));
655 if (!f.argument().empty())
656 action += " " + toqstr(f.argument());
657 QString const theme_icon = themeIconName(action);
658 if (QIcon::hasThemeIcon(theme_icon)) {
659 QIcon const thmicn = QIcon::fromTheme(theme_icon);
660 if (!thmicn.isNull())
666 IconInfo icondata = iconInfo(f, unknown, rtl);
667 if (icondata.filepath.isEmpty())
670 //LYXERR(Debug::GUI, "Found icon: " << icon);
671 QPixmap pixmap = QPixmap();
672 if (!pixmap.load(icondata.filepath)) {
673 LYXERR0("Cannot load icon " << icondata.filepath << ".");
678 pixmap = prepareForDarkMode(pixmap);
681 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
683 return QIcon(pixmap);
687 ////////////////////////////////////////////////////////////////////////
689 // LyX server support code.
691 ////////////////////////////////////////////////////////////////////////
693 class SocketNotifier : public QSocketNotifier
696 /// connect a connection notification from the LyXServerSocket
697 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
698 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
702 /// The callback function
703 Application::SocketCallback func_;
707 class GuiTranslator : public QTranslator
710 GuiTranslator(QObject * parent = nullptr)
711 : QTranslator(parent)
714 QString translate(const char * /* context */,
715 const char *sourceText,
716 #if QT_VERSION >= 0x050000
717 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
719 const char * /*comment*/ = 0) const override
722 // Here we declare the strings that need to be translated from Qt own GUI
723 // This is needed to include these strings to po files
727 _("Restore Defaults");
730 // Already in po: "Cancel", "&Cancel"
731 _("Apply"); // Already in po: "&Apply"
732 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
735 docstring s = getGuiMessages().getIfFound(sourceText);
736 // This test should eventually be removed when translations are updated
738 LYXERR(Debug::LOCALE, "Missing translation for `"
739 << string(sourceText) << "'");
745 ////////////////////////////////////////////////////////////////////////
747 // Mac specific stuff goes here...
749 ////////////////////////////////////////////////////////////////////////
752 // QMacPasteboardMimeGraphics can only be compiled on Mac.
754 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
757 QMacPasteboardMimeGraphics()
758 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
761 QString convertorName() { return "Graphics"; }
763 QString flavorFor(QString const & mime)
765 LYXERR(Debug::ACTION, "flavorFor " << mime);
766 if (mime == pdfMimeType())
767 return QLatin1String("com.adobe.pdf");
771 QString mimeFor(QString flav)
773 LYXERR(Debug::ACTION, "mimeFor " << flav);
774 if (flav == QLatin1String("com.adobe.pdf"))
775 return pdfMimeType();
779 bool canConvert(QString const & mime, QString flav)
781 return mimeFor(flav) == mime;
784 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
788 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
792 QList<QByteArray> convertFromMime(QString const & /*mime*/,
793 QVariant data, QString /*flav*/)
795 QList<QByteArray> ret;
796 ret.append(data.toByteArray());
802 ///////////////////////////////////////////////////////////////
804 // You can find more platform specific stuff at the end of this file...
806 ///////////////////////////////////////////////////////////////
808 ////////////////////////////////////////////////////////////////////////
809 // Windows specific stuff goes here...
811 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
812 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
813 // QWindowsMimeMetafile can only be compiled on Windows.
815 static FORMATETC cfFromMime(QString const & mimetype)
818 if (mimetype == emfMimeType()) {
819 formatetc.cfFormat = CF_ENHMETAFILE;
820 formatetc.tymed = TYMED_ENHMF;
821 } else if (mimetype == wmfMimeType()) {
822 formatetc.cfFormat = CF_METAFILEPICT;
823 formatetc.tymed = TYMED_MFPICT;
826 formatetc.dwAspect = DVASPECT_CONTENT;
827 formatetc.lindex = -1;
832 class QWindowsMimeMetafile : public QWINDOWSMIME {
834 QWindowsMimeMetafile() {}
836 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
837 QMimeData const * /*mimedata*/) const override
842 bool canConvertToMime(QString const & mimetype,
843 IDataObject * pDataObj) const override
845 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
847 FORMATETC formatetc = cfFromMime(mimetype);
848 return pDataObj->QueryGetData(&formatetc) == S_OK;
851 bool convertFromMime(FORMATETC const & /*formatetc*/,
852 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
857 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
858 QVariant::Type /*preferredType*/) const override
861 if (!canConvertToMime(mimetype, pDataObj))
864 FORMATETC formatetc = cfFromMime(mimetype);
866 if (pDataObj->GetData(&formatetc, &s) != S_OK)
870 if (s.tymed == TYMED_ENHMF) {
871 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
872 data.resize(dataSize);
873 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
874 (LPBYTE)data.data());
875 } else if (s.tymed == TYMED_MFPICT) {
876 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
877 data.resize(dataSize);
878 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
879 (LPBYTE)data.data());
882 ReleaseStgMedium(&s);
888 QVector<FORMATETC> formatsForMime(QString const & mimetype,
889 QMimeData const * /*mimedata*/) const override
891 QVector<FORMATETC> formats;
892 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
893 formats += cfFromMime(mimetype);
897 QString mimeForFormat(FORMATETC const & formatetc) const override
899 switch (formatetc.cfFormat) {
901 return emfMimeType();
902 case CF_METAFILEPICT:
903 return wmfMimeType();
913 /// Allows to check whether ESC was pressed during a long operation
914 class KeyChecker : public QObject {
919 KeyChecker() : pressed_(false), started_(false) {}
922 QCoreApplication::instance()->installEventFilter(this);
927 QCoreApplication::instance()->removeEventFilter(this);
931 QCoreApplication::processEvents();
934 bool started() const {
937 bool eventFilter(QObject *obj, QEvent *event) override {
938 LYXERR(Debug::ACTION, "Event Type: " << event->type());
939 switch (event->type()) {
943 case QEvent::UpdateRequest:
944 case QEvent::CursorChange:
945 case QEvent::ActionChanged:
946 case QEvent::EnabledChange:
947 case QEvent::SockAct:
950 case QEvent::ToolTipChange:
951 case QEvent::LayoutRequest:
952 case QEvent::MetaCall:
953 return QObject::eventFilter(obj, event);
955 // FIXME Blocking all these events is a bad idea.
956 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
957 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
965 ////////////////////////////////////////////////////////////////////////
966 // GuiApplication::Private definition and implementation.
967 ////////////////////////////////////////////////////////////////////////
969 struct GuiApplication::Private
971 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
972 global_menubar_(nullptr)
973 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
974 , last_state_(Qt::ApplicationInactive)
977 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
978 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
979 /// WMF Mime handler for Windows clipboard.
980 wmf_mime_ = new QWindowsMimeMetafile;
983 initKeySequences(&theTopLevelKeymap());
986 void initKeySequences(KeyMap * kb)
988 keyseq = KeySequence(kb, kb);
989 cancel_meta_seq = KeySequence(kb, kb);
993 QSortFilterProxyModel * language_model_;
995 GuiClipboard clipboard_;
997 GuiSelection selection_;
999 FontLoader font_loader_;
1001 ColorCache color_cache_;
1002 /// the built-in Qt translation mechanism
1003 QTranslator qt_trans_;
1004 /// LyX gettext-based translation for Qt elements
1005 GuiTranslator gui_trans_;
1007 QHash<int, SocketNotifier *> socket_notifiers_;
1011 /// The global instance
1014 /// this timer is used for any regular events one wants to
1015 /// perform. at present it is used to check if forked processes
1017 QTimer general_timer_;
1019 /// delayed FuncRequests
1020 std::queue<FuncRequest> func_request_queue_;
1025 KeySequence cancel_meta_seq;
1027 KeyModifier meta_fake_bit;
1029 /// The result of last dispatch action
1030 DispatchResult dispatch_result_;
1032 /// Multiple views container.
1034 * Warning: This must not be a smart pointer as the destruction of the
1035 * object is handled by Qt when the view is closed
1036 * \sa Qt::WA_DeleteOnClose attribute.
1038 QHash<int, GuiView *> views_;
1040 /// Only used on mac.
1041 QMenuBar * global_menubar_;
1042 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1043 /// Holds previous application state on Mac
1044 Qt::ApplicationState last_state_;
1048 /// Linkback mime handler for MacOSX.
1049 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1052 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1053 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1054 /// WMF Mime handler for Windows clipboard.
1055 QWindowsMimeMetafile * wmf_mime_;
1059 /// Allows to check whether ESC was pressed during a long operation
1060 KeyChecker key_checker_;
1064 GuiApplication * guiApp;
1066 GuiApplication::~GuiApplication()
1069 closeAllLinkBackLinks();
1075 GuiApplication::GuiApplication(int & argc, char ** argv)
1076 : QApplication(argc, argv), current_view_(nullptr),
1077 d(new GuiApplication::Private)
1079 QString app_name = "LyX";
1080 QCoreApplication::setOrganizationName(app_name);
1081 QCoreApplication::setOrganizationDomain("lyx.org");
1082 QCoreApplication::setApplicationName(lyx_package);
1083 #if QT_VERSION >= 0x050000
1084 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1087 #if QT_VERSION >= 0x050700
1088 setDesktopFileName(lyx_package);
1091 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1092 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1094 qsrand(QDateTime::currentDateTime().toTime_t());
1097 // Install LyX translator for missing Qt translations
1098 installTranslator(&d->gui_trans_);
1099 // Install Qt native translator for GUI elements.
1100 installTranslator(&d->qt_trans_);
1103 // Enable reception of XCB events.
1104 installNativeEventFilter(this);
1107 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1108 // lyxrc setting for this in order to let the application stay resident.
1109 // But then we need some kind of dock icon, at least on Windows.
1111 if (lyxrc.quit_on_last_window_closed)
1112 setQuitOnLastWindowClosed(false);
1115 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1116 // seems to be the default case for applications like LyX.
1117 setQuitOnLastWindowClosed(false);
1120 appleCleanupEditMenu();
1121 appleCleanupViewMenu();
1122 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1123 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1124 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1128 #if defined(Q_WS_X11) || defined(QPA_XCB)
1129 // doubleClickInterval() is 400 ms on X11 which is just too long.
1130 // On Windows and Mac OS X, the operating system's value is used.
1131 // On Microsoft Windows, calling this function sets the double
1132 // click interval for all applications. So we don't!
1133 QApplication::setDoubleClickInterval(300);
1136 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1138 // needs to be done before reading lyxrc
1140 lyxrc.dpi = (w.physicalDpiX() + w.physicalDpiY()) / 2;
1144 // Initialize RC Fonts
1145 if (lyxrc.roman_font_name.empty())
1146 lyxrc.roman_font_name = fromqstr(romanFontName());
1148 if (lyxrc.sans_font_name.empty())
1149 lyxrc.sans_font_name = fromqstr(sansFontName());
1151 if (lyxrc.typewriter_font_name.empty())
1152 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1154 #if (QT_VERSION >= 0x050000)
1155 // Qt4 does this in event(), see below.
1156 // Track change of keyboard
1157 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1160 d->general_timer_.setInterval(500);
1161 connect(&d->general_timer_, SIGNAL(timeout()),
1162 this, SLOT(handleRegularEvents()));
1163 d->general_timer_.start();
1165 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1166 // This is clearly not enough in a time where we use threads for
1167 // document preview and/or export. 20 should be OK.
1168 QThreadPool::globalInstance()->setMaxThreadCount(20);
1170 // make sure tooltips are formatted
1171 installEventFilter(new ToolTipFormatter(this));
1175 GuiApplication * theGuiApp()
1177 return dynamic_cast<GuiApplication *>(theApp());
1181 #if QT_VERSION < 0x050000
1182 // Emulate platformName() for Qt4
1184 // FIXME: when ditching this method, remove all tests
1185 // platformName() == "qt4x11"
1187 QString GuiApplication::platformName() const
1189 # if defined(Q_WS_X11)
1190 // Note that this one does not really exist
1192 # elif defined(Q_OS_MAC)
1194 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1197 LYXERR0("Unknown platform!");
1204 double GuiApplication::pixelRatio() const
1206 #if QT_VERSION >= 0x050000
1207 return qt_scale_factor * devicePixelRatio();
1214 void GuiApplication::clearSession()
1221 docstring Application::iconName(FuncRequest const & f, bool unknown)
1223 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1227 docstring Application::mathIcon(docstring const & c)
1229 return qstring_to_ucs4(findImg(toqstr(c)));
1233 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1237 BufferView * bv = nullptr;
1238 BufferView * doc_bv = nullptr;
1240 if (cmd.action() == LFUN_NOACTION) {
1241 status.message(from_utf8(N_("Nothing to do")));
1242 status.setEnabled(false);
1245 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1246 status.setUnknown(true);
1247 status.message(from_utf8(N_("Unknown action")));
1248 status.setEnabled(false);
1251 // Does the GuiApplication know something?
1252 else if (getStatus(cmd, status)) { }
1254 // If we do not have a GuiView, then other functions are disabled
1255 else if (!current_view_)
1256 status.setEnabled(false);
1258 // Does the GuiView know something?
1259 else if (current_view_->getStatus(cmd, status)) { }
1261 // In LyX/Mac, when a dialog is open, the menus of the
1262 // application can still be accessed without giving focus to
1263 // the main window. In this case, we want to disable the menu
1264 // entries that are buffer or view-related.
1265 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1267 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1268 status.setEnabled(false);
1271 // If we do not have a BufferView, then other functions are disabled
1272 else if (!(bv = current_view_->currentBufferView()))
1273 status.setEnabled(false);
1275 // Does the current BufferView know something?
1276 else if (bv->getStatus(cmd, status)) { }
1278 // Does the current Buffer know something?
1279 else if (bv->buffer().getStatus(cmd, status)) { }
1281 // If we do not have a document BufferView, different from the
1282 // current BufferView, then other functions are disabled
1283 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1284 status.setEnabled(false);
1286 // Does the document Buffer know something?
1287 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1290 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1291 status.message(from_utf8(N_("Command not handled")));
1292 status.setEnabled(false);
1295 // the default error message if we disable the command
1296 if (!status.enabled() && status.message().empty())
1297 status.message(from_utf8(N_("Command disabled")));
1303 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1305 // I would really like to avoid having this switch and rather try to
1306 // encode this in the function itself.
1307 // -- And I'd rather let an inset decide which LFUNs it is willing
1308 // to handle (Andre')
1310 switch (cmd.action()) {
1312 // This could be used for the no-GUI version. The GUI version is handled in
1313 // GuiView::getStatus(). See above.
1315 case LFUN_BUFFER_WRITE:
1316 case LFUN_BUFFER_WRITE_AS:
1317 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1318 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1319 enable = b && (b->isUnnamed() || !b->isClean());
1324 case LFUN_BOOKMARK_GOTO: {
1325 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1326 enable = theSession().bookmarks().isValid(num);
1330 case LFUN_BOOKMARK_CLEAR:
1331 enable = theSession().bookmarks().hasValid();
1334 // this one is difficult to get right. As a half-baked
1335 // solution, we consider only the first action of the sequence
1336 case LFUN_COMMAND_SEQUENCE: {
1337 // argument contains ';'-terminated commands
1338 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1339 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1340 func.setOrigin(cmd.origin());
1341 flag = getStatus(func);
1345 // we want to check if at least one of these is enabled
1346 case LFUN_COMMAND_ALTERNATIVES: {
1347 // argument contains ';'-terminated commands
1348 string arg = to_utf8(cmd.argument());
1349 while (!arg.empty()) {
1351 arg = split(arg, first, ';');
1352 FuncRequest func(lyxaction.lookupFunc(first));
1353 func.setOrigin(cmd.origin());
1354 flag = getStatus(func);
1355 // if this one is enabled, the whole thing is
1364 string name = to_utf8(cmd.argument());
1365 if (theTopLevelCmdDef().lock(name, func)) {
1366 func.setOrigin(cmd.origin());
1367 flag = getStatus(func);
1368 theTopLevelCmdDef().release(name);
1370 // catch recursion or unknown command
1371 // definition. all operations until the
1372 // recursion or unknown command definition
1373 // occurs are performed, so set the state to
1380 case LFUN_IF_RELATIVES: {
1381 string const lfun = to_utf8(cmd.argument());
1382 BufferView const * bv =
1383 current_view_ ? current_view_->currentBufferView() : nullptr;
1384 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1388 FuncRequest func(lyxaction.lookupFunc(lfun));
1389 func.setOrigin(cmd.origin());
1390 flag = getStatus(func);
1394 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1396 case LFUN_PREFERENCES_SAVE:
1397 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1398 case LFUN_DEBUG_LEVEL_SET:
1399 // these are handled in our dispatch()
1402 case LFUN_WINDOW_CLOSE:
1403 enable = !d->views_.empty();
1406 case LFUN_BUFFER_NEW:
1407 case LFUN_BUFFER_NEW_TEMPLATE:
1408 case LFUN_FILE_OPEN:
1409 case LFUN_LYXFILES_OPEN:
1410 case LFUN_HELP_OPEN:
1411 case LFUN_SCREEN_FONT_UPDATE:
1412 case LFUN_SET_COLOR:
1413 case LFUN_WINDOW_NEW:
1415 case LFUN_LYXRC_APPLY:
1416 case LFUN_COMMAND_PREFIX:
1418 case LFUN_META_PREFIX:
1419 case LFUN_RECONFIGURE:
1420 case LFUN_SERVER_GET_FILENAME:
1421 case LFUN_SERVER_NOTIFY:
1425 case LFUN_BUFFER_FORALL: {
1426 if (theBufferList().empty()) {
1427 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1428 flag.setEnabled(false);
1432 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1433 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1434 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1435 flag.setEnabled(false);
1440 case LFUN_DIALOG_SHOW: {
1441 string const name = cmd.getArg(0);
1442 return name == "aboutlyx"
1443 || name == "lyxfiles"
1445 || name == "texinfo"
1446 || name == "progress"
1447 || name == "compare";
1455 flag.setEnabled(false);
1459 /// make a post-dispatch status message
1460 static docstring makeDispatchMessage(docstring const & msg,
1461 FuncRequest const & cmd)
1463 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1464 || cmd.origin() == FuncRequest::TOOLBAR
1465 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1467 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1468 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1472 docstring dispatch_msg = msg;
1473 if (!dispatch_msg.empty())
1474 dispatch_msg += ' ';
1476 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1478 bool argsadded = false;
1480 if (!cmd.argument().empty()) {
1481 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1482 comname += ' ' + cmd.argument();
1486 docstring const shortcuts = theTopLevelKeymap().
1487 printBindings(cmd, KeySequence::ForGui);
1489 if (!shortcuts.empty())
1490 comname += ": " + shortcuts;
1491 else if (!argsadded && !cmd.argument().empty())
1492 comname += ' ' + cmd.argument();
1494 if (!comname.empty()) {
1495 comname = rtrim(comname);
1496 dispatch_msg += '(' + rtrim(comname) + ')';
1498 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1499 return dispatch_msg;
1503 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1507 Buffer * buffer = nullptr;
1508 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1509 //setCurrentView(cmd.view_origin); //does not work
1511 dr.setMessage(_("Wrong focus!"));
1512 d->dispatch_result_ = dr;
1513 return d->dispatch_result_;
1515 if (current_view_ && current_view_->currentBufferView()) {
1516 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1517 buffer = ¤t_view_->currentBufferView()->buffer();
1520 dr.screenUpdate(Update::FitCursor);
1522 // All the code is kept inside the undo group because
1523 // updateBuffer can create undo actions (see #11292)
1524 UndoGroupHelper ugh(buffer);
1526 if (dr.screenUpdate() & Update::ForceAll) {
1527 for (Buffer const * b : theBufferList())
1529 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1532 updateCurrentView(cmd, dr);
1535 d->dispatch_result_ = dr;
1536 return d->dispatch_result_;
1540 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1545 BufferView * bv = current_view_->currentBufferView();
1547 if (dr.needBufferUpdate()) {
1548 bv->cursor().clearBufferUpdate();
1549 bv->buffer().updateBuffer();
1551 // BufferView::update() updates the ViewMetricsInfo and
1552 // also initializes the position cache for all insets in
1553 // (at least partially) visible top-level paragraphs.
1554 // We will redraw the screen only if needed.
1555 bv->processUpdateFlags(dr.screenUpdate());
1557 // Do we have a selection?
1558 theSelection().haveSelection(bv->cursor().selection());
1561 current_view_->restartCaret();
1563 if (dr.needMessageUpdate()) {
1564 // Some messages may already be translated, so we cannot use _()
1565 current_view_->message(makeDispatchMessage(
1566 translateIfPossible(dr.message()), cmd));
1571 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1572 bool switchToBuffer)
1574 if (!theSession().bookmarks().isValid(idx))
1576 BookmarksSection::Bookmark const & bm =
1577 theSession().bookmarks().bookmark(idx);
1578 LASSERT(!bm.filename.empty(), return);
1579 string const file = bm.filename.absFileName();
1580 // if the file is not opened, open it.
1581 if (!theBufferList().exists(bm.filename)) {
1583 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1587 // open may fail, so we need to test it again
1588 if (!theBufferList().exists(bm.filename))
1591 // bm can be changed when saving
1592 BookmarksSection::Bookmark tmp = bm;
1594 // Special case idx == 0 used for back-from-back jump navigation
1596 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1598 // if the current buffer is not that one, switch to it.
1599 BufferView * doc_bv = current_view_ ?
1600 current_view_->documentBufferView() : nullptr;
1601 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1602 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1603 if (switchToBuffer) {
1604 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1607 doc_bv = current_view_->documentBufferView();
1612 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1613 if (!doc_bv || !doc_bv->moveToPosition(
1614 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1617 Cursor & cur = doc_bv->cursor();
1618 if (old && cur != *old)
1619 notifyCursorLeavesOrEnters(*old, cur);
1625 // Cursor jump succeeded!
1626 pit_type new_pit = cur.pit();
1627 pos_type new_pos = cur.pos();
1628 int new_id = cur.paragraph().id();
1630 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1631 // see http://www.lyx.org/trac/ticket/3092
1632 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1633 || bm.top_id != new_id) {
1634 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1635 new_pit, new_pos, new_id);
1639 // This function runs "configure" and then rereads lyx.defaults to
1640 // reconfigure the automatic settings.
1641 void GuiApplication::reconfigure(string const & option)
1643 // emit message signal.
1645 current_view_->message(_("Running configure..."));
1647 // Run configure in user lyx directory
1648 string const lock_file = package().getConfigureLockName();
1649 int fd = fileLock(lock_file.c_str());
1650 int const ret = package().reconfigureUserLyXDir(option);
1651 // emit message signal.
1653 current_view_->message(_("Reloading configuration..."));
1654 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1655 // Re-read packages.lst
1656 LaTeXPackages::getAvailable();
1657 fileUnlock(fd, lock_file.c_str());
1660 Alert::information(_("System reconfiguration failed"),
1661 _("The system reconfiguration has failed.\n"
1662 "Default textclass is used but LyX may\n"
1663 "not be able to work properly.\n"
1664 "Please reconfigure again if needed."));
1666 Alert::information(_("System reconfigured"),
1667 _("The system has been reconfigured.\n"
1668 "You need to restart LyX to make use of any\n"
1669 "updated document class specifications."));
1672 void GuiApplication::validateCurrentView()
1674 if (!d->views_.empty() && !current_view_) {
1675 // currently at least one view exists but no view has the focus.
1676 // choose the last view to make it current.
1677 // a view without any open document is preferred.
1678 GuiView * candidate = nullptr;
1679 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1680 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1681 for (; it != end; ++it) {
1683 if (!candidate->documentBufferView())
1686 setCurrentView(candidate);
1690 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1692 string const argument = to_utf8(cmd.argument());
1693 FuncCode const action = cmd.action();
1695 LYXERR(Debug::ACTION, "cmd: " << cmd);
1697 // we have not done anything wrong yet.
1700 FuncStatus const flag = getStatus(cmd);
1701 if (!flag.enabled()) {
1702 // We cannot use this function here
1703 LYXERR(Debug::ACTION, "action "
1704 << lyxaction.getActionName(action)
1705 << " [" << action << "] is disabled at this location");
1706 dr.setMessage(flag.message());
1708 dr.dispatched(false);
1709 dr.screenUpdate(Update::None);
1710 dr.clearBufferUpdate();
1714 if (cmd.origin() == FuncRequest::LYXSERVER) {
1715 if (current_view_ && current_view_->currentBufferView())
1716 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1717 // we will also need to redraw the screen at the end
1718 dr.screenUpdate(Update::FitCursor);
1721 // Assumes that the action will be dispatched.
1722 dr.dispatched(true);
1724 switch (cmd.action()) {
1726 case LFUN_WINDOW_NEW:
1727 createView(toqstr(cmd.argument()));
1730 case LFUN_WINDOW_CLOSE:
1731 // FIXME: this is done also in GuiView::closeBuffer()!
1732 // update bookmark pit of the current buffer before window close
1733 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1734 gotoBookmark(i, false, false);
1735 // clear the last opened list, because
1736 // maybe this will end the session
1737 theSession().lastOpened().clear();
1738 // check for valid current_view_
1739 validateCurrentView();
1741 current_view_->closeScheduled();
1745 // quitting is triggered by the gui code
1746 // (leaving the event loop).
1748 current_view_->message(from_utf8(N_("Exiting.")));
1749 if (closeAllViews())
1753 case LFUN_SCREEN_FONT_UPDATE: {
1754 // handle the screen font changes.
1755 /* FIXME: this only updates the current document, whereas all
1756 * documents should see their metrics updated.
1758 d->font_loader_.update();
1759 dr.screenUpdate(Update::Force | Update::FitCursor);
1763 case LFUN_BUFFER_NEW:
1764 validateCurrentView();
1766 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1767 createView(QString(), false); // keep hidden
1768 current_view_->newDocument(to_utf8(cmd.argument()));
1769 current_view_->show();
1770 setActiveWindow(current_view_);
1772 current_view_->newDocument(to_utf8(cmd.argument()));
1776 case LFUN_BUFFER_NEW_TEMPLATE: {
1777 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1778 string const temp = cmd.getArg(1);
1779 validateCurrentView();
1781 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1783 current_view_->newDocument(file, temp, true);
1784 if (!current_view_->documentBufferView())
1785 current_view_->close();
1787 current_view_->newDocument(file, temp, true);
1792 case LFUN_FILE_OPEN: {
1793 // FIXME: normally the code below is not needed, since getStatus makes sure that
1794 // current_view_ is not null.
1795 validateCurrentView();
1796 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1797 string const fname = trim(to_utf8(cmd.argument()), "\"");
1798 bool const is_open = FileName::isAbsolute(fname)
1799 && theBufferList().getBuffer(FileName(fname));
1801 || (!lyxrc.open_buffers_in_tabs
1802 && current_view_->documentBufferView() != nullptr
1804 // We want the ui session to be saved per document and not per
1805 // window number. The filename crc is a good enough identifier.
1806 createView(support::checksum(fname));
1807 current_view_->openDocument(fname);
1808 if (!current_view_->documentBufferView())
1809 current_view_->close();
1810 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1811 current_view_->raise();
1812 current_view_->activateWindow();
1813 current_view_->showNormal();
1816 current_view_->openDocument(fname);
1817 if (cmd.origin() == FuncRequest::LYXSERVER) {
1818 current_view_->raise();
1819 current_view_->activateWindow();
1820 current_view_->showNormal();
1826 case LFUN_HELP_OPEN: {
1827 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1828 if (current_view_ == nullptr)
1830 string const arg = to_utf8(cmd.argument());
1832 current_view_->message(_("Missing argument"));
1835 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1837 fname = i18nLibFileSearch("examples", arg, "lyx");
1839 if (fname.empty()) {
1840 lyxerr << "LyX: unable to find documentation file `"
1841 << arg << "'. Bad installation?" << endl;
1844 current_view_->message(bformat(_("Opening help file %1$s..."),
1845 makeDisplayPath(fname.absFileName())));
1846 Buffer * buf = current_view_->loadDocument(fname, false);
1848 buf->setReadonly(!current_view_->develMode());
1852 case LFUN_LYXFILES_OPEN: {
1853 // This is the actual reason for this method (#12106).
1854 validateCurrentView();
1856 || (!lyxrc.open_buffers_in_tabs
1857 && current_view_->documentBufferView() != nullptr))
1859 string arg = to_utf8(cmd.argument());
1863 if (arg != "templates" && arg != "examples") {
1864 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1867 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1871 case LFUN_SET_COLOR: {
1872 string const lyx_name = cmd.getArg(0);
1873 string x11_name = cmd.getArg(1);
1874 string x11_darkname = cmd.getArg(2);
1875 if (lyx_name.empty() || x11_name.empty()) {
1877 current_view_->message(
1878 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1883 // FIXME: The graphics cache no longer has a changeDisplay method.
1884 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1885 bool const graphicsbg_changed =
1886 lyx_name == graphicsbg && x11_name != graphicsbg;
1887 if (graphicsbg_changed)
1888 graphics::GCache::get().changeDisplay(true);
1891 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1892 x11_darkname = x11_name;
1895 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1897 current_view_->message(
1898 bformat(_("Set-color \"%1$s\" failed "
1899 "- color is undefined or "
1900 "may not be redefined"),
1901 from_utf8(lyx_name)));
1904 // Make sure we don't keep old colors in cache.
1905 d->color_cache_.clear();
1906 // Update the current view
1907 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1911 case LFUN_LYXRC_APPLY: {
1912 // reset active key sequences, since the bindings
1913 // are updated (bug 6064)
1915 LyXRC const lyxrc_orig = lyxrc;
1917 istringstream ss(to_utf8(cmd.argument()));
1918 bool const success = lyxrc.read(ss);
1921 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1922 << "Unable to read lyxrc data"
1927 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1929 // If the request comes from the minibuffer, then we can't reset
1930 // the GUI, since that would destroy the minibuffer itself and
1931 // cause a crash, since we are currently in one of the methods of
1932 // GuiCommandBuffer. See bug #8540.
1933 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1936 // FIXME Unfortunately, that leaves a bug here, since we cannot
1937 // reset the GUI in this case. If the changes to lyxrc affected the
1938 // UI, then, nothing would happen. This seems fairly unlikely, but
1939 // it definitely is a bug.
1941 dr.forceBufferUpdate();
1945 case LFUN_COMMAND_PREFIX:
1946 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1951 d->meta_fake_bit = NoModifier;
1952 GuiView * gv = currentView();
1953 if (gv && gv->currentBufferView())
1954 // cancel any selection
1955 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1956 dr.setMessage(from_ascii(N_("Cancel")));
1959 case LFUN_META_PREFIX:
1960 d->meta_fake_bit = AltModifier;
1961 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1964 // --- Menus -----------------------------------------------
1965 case LFUN_RECONFIGURE:
1966 // argument is any additional parameter to the configure.py command
1967 reconfigure(to_utf8(cmd.argument()));
1970 // --- lyxserver commands ----------------------------
1971 case LFUN_SERVER_GET_FILENAME: {
1972 if (current_view_ && current_view_->documentBufferView()) {
1973 docstring const fname = from_utf8(
1974 current_view_->documentBufferView()->buffer().absFileName());
1975 dr.setMessage(fname);
1976 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1978 dr.setMessage(docstring());
1979 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1984 case LFUN_SERVER_NOTIFY: {
1985 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1986 dr.setMessage(dispatch_buffer);
1987 theServer().notifyClient(to_utf8(dispatch_buffer));
1991 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1992 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1998 string rest = split(argument, countstr, ' ');
1999 int const count = convert<int>(countstr);
2000 // an arbitrary number to limit number of iterations
2001 int const max_iter = 10000;
2002 if (count > max_iter) {
2003 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2006 for (int i = 0; i < count; ++i) {
2007 FuncRequest lfun = lyxaction.lookupFunc(rest);
2008 lfun.allowAsync(false);
2015 case LFUN_COMMAND_SEQUENCE: {
2016 // argument contains ';'-terminated commands
2017 string arg = argument;
2018 // FIXME: this LFUN should also work without any view.
2019 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2020 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2021 // This handles undo groups automagically
2022 UndoGroupHelper ugh(buffer);
2023 while (!arg.empty()) {
2025 arg = split(arg, first, ';');
2026 FuncRequest func(lyxaction.lookupFunc(first));
2027 func.allowAsync(false);
2028 func.setOrigin(cmd.origin());
2034 case LFUN_BUFFER_FORALL: {
2035 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2036 funcToRun.allowAsync(false);
2038 map<Buffer *, GuiView *> views_lVisible;
2039 map<GuiView *, Buffer *> activeBuffers;
2041 QList<GuiView *> allViews = d->views_.values();
2043 // this for does not modify any buffer. It just collects info on local
2044 // visibility of buffers and on which buffer is active in each view.
2045 Buffer * const last = theBufferList().last();
2046 for(GuiView * view : allViews) {
2047 // all of the buffers might be locally hidden. That is, there is no
2049 if (!view || !view->currentBufferView())
2050 activeBuffers[view] = nullptr;
2052 activeBuffers[view] = &view->currentBufferView()->buffer();
2054 // find out if each is locally visible or locally hidden.
2055 // we don't use a for loop as the buffer list cycles.
2056 Buffer * b = theBufferList().first();
2058 bool const locallyVisible = view && view->workArea(*b);
2059 if (locallyVisible) {
2060 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2061 // only need to overwrite/add if we don't already know a buffer is globally
2062 // visible or we do know but we would prefer to dispatch LFUN from the
2063 // current view because of cursor position issues.
2064 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2065 views_lVisible[b] = view;
2069 b = theBufferList().next(b);
2073 GuiView * const homeView = currentView();
2074 Buffer * b = theBufferList().first();
2075 Buffer * nextBuf = nullptr;
2076 int numProcessed = 0;
2079 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2081 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2083 // first change to a view where b is locally visible, preferably current_view_.
2084 GuiView * const vLv = views_lVisible[b];
2086 lyx::dispatch(funcToRun);
2094 // put things back to how they were (if possible).
2095 for (GuiView * view : allViews) {
2096 Buffer * originalBuf = activeBuffers[view];
2097 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2098 if (theBufferList().isLoaded(originalBuf))
2099 view->setBuffer(originalBuf);
2101 homeView->setFocus();
2103 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2107 case LFUN_COMMAND_ALTERNATIVES: {
2108 // argument contains ';'-terminated commands
2109 string arg = argument;
2110 while (!arg.empty()) {
2112 arg = split(arg, first, ';');
2113 FuncRequest func(lyxaction.lookupFunc(first));
2114 func.setOrigin(cmd.origin());
2115 FuncStatus const stat = getStatus(func);
2116 if (stat.enabled()) {
2126 if (theTopLevelCmdDef().lock(argument, func)) {
2127 func.setOrigin(cmd.origin());
2129 theTopLevelCmdDef().release(argument);
2131 if (func.action() == LFUN_UNKNOWN_ACTION) {
2132 // unknown command definition
2133 lyxerr << "Warning: unknown command definition `"
2137 // recursion detected
2138 lyxerr << "Warning: Recursion in the command definition `"
2139 << argument << "' detected"
2146 case LFUN_IF_RELATIVES: {
2147 string const lfun = to_utf8(cmd.argument());
2148 FuncRequest func(lyxaction.lookupFunc(lfun));
2149 func.setOrigin(cmd.origin());
2150 FuncStatus const stat = getStatus(func);
2151 if (stat.enabled()) {
2158 case LFUN_PREFERENCES_SAVE:
2159 lyxrc.write(support::makeAbsPath("preferences",
2160 package().user_support().absFileName()), false);
2163 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2164 string const fname = addName(addPath(package().user_support().absFileName(),
2165 "templates/"), "defaults.lyx");
2166 Buffer defaults(fname);
2168 istringstream ss(argument);
2173 // We need to make sure that, after we recreat the DocumentClass,
2174 // which we do in readHeader, we apply it to the document itself.
2175 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2176 int const unknown_tokens = defaults.readHeader(lex);
2177 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2178 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2179 cap::switchBetweenClasses(olddc, newdc, theinset);
2181 if (unknown_tokens != 0) {
2182 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2183 << unknown_tokens << " unknown token"
2184 << (unknown_tokens == 1 ? "" : "s")
2188 if (defaults.writeFile(FileName(defaults.absFileName())))
2189 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2190 makeDisplayPath(fname)));
2193 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2198 case LFUN_BOOKMARK_GOTO:
2199 // go to bookmark, open unopened file and switch to buffer if necessary
2200 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2201 dr.screenUpdate(Update::Force | Update::FitCursor);
2204 case LFUN_BOOKMARK_CLEAR:
2205 theSession().bookmarks().clear();
2206 dr.screenUpdate(Update::Force);
2209 case LFUN_DEBUG_LEVEL_SET:
2210 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2213 case LFUN_DIALOG_SHOW: {
2214 string const name = cmd.getArg(0);
2216 if ( name == "aboutlyx"
2218 || name == "texinfo"
2219 || name == "progress"
2220 || name == "compare")
2222 // work around: on Mac OS the application
2223 // is not terminated when closing the last view.
2224 // Create a new one to be able to dispatch the
2225 // LFUN_DIALOG_SHOW to this view.
2226 if (current_view_ == nullptr)
2232 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2235 current_view_->dispatch(cmd, dr);
2239 if (current_view_ && current_view_->isFullScreen()) {
2240 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2241 current_view_->menuBar()->hide();
2244 if (cmd.origin() == FuncRequest::LYXSERVER)
2245 updateCurrentView(cmd, dr);
2249 docstring GuiApplication::viewStatusMessage()
2251 // When meta-fake key is pressed, show the key sequence so far + "M-".
2252 if (d->meta_fake_bit != NoModifier)
2253 return d->keyseq.print(KeySequence::ForGui) + "M-";
2255 // Else, when a non-complete key sequence is pressed,
2256 // show the available options.
2257 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2258 return d->keyseq.printOptions(true);
2264 string GuiApplication::inputLanguageCode() const
2266 #if (QT_VERSION < 0x050000)
2267 QLocale loc = keyboardInputLocale();
2269 QLocale loc = inputMethod()->locale();
2271 //LYXERR0("input lang = " << fromqstr(loc.name()));
2272 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2276 void GuiApplication::onLocaleChanged()
2278 //LYXERR0("Change language to " << inputLanguage()->lang());
2279 if (currentView() && currentView()->currentBufferView())
2280 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2284 void GuiApplication::handleKeyFunc(FuncCode action)
2288 if (d->keyseq.length())
2290 GuiView * gv = currentView();
2291 LASSERT(gv && gv->currentBufferView(), return);
2292 BufferView * bv = gv->currentBufferView();
2293 bv->getIntl().getTransManager().deadkey(
2294 c, get_accent(action).accent, bv->cursor().innerText(),
2296 // Need to clear, in case the minibuffer calls these
2299 // copied verbatim from do_accent_char
2300 bv->cursor().resetAnchor();
2304 //Keep this in sync with GuiApplication::processKeySym below
2305 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2306 KeyModifier state) const
2308 // Do nothing if we have nothing
2309 if (!keysym.isOK() || keysym.isModifier())
2311 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2313 FuncRequest func = seq.addkey(keysym, state);
2314 // When not cancel or meta-fake, do the normal lookup.
2315 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2317 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2319 // Maybe user can only reach the key via holding down shift.
2320 // Let's see. But only if shift is the only modifier
2321 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2322 // If addkey looked up a command and did not find further commands then
2323 // seq has been reset at this point
2324 func = seq.addkey(keysym, NoModifier);
2326 LYXERR(Debug::KEY, " Key (queried) [action="
2327 << lyxaction.getActionName(func.action()) << "]["
2328 << seq.print(KeySequence::Portable) << ']');
2329 return func.action() != LFUN_UNKNOWN_ACTION;
2333 //Keep this in sync with GuiApplication::queryKeySym above
2334 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2336 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2338 // Do nothing if we have nothing (JMarc)
2339 if (!keysym.isOK() || keysym.isModifier()) {
2341 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2343 current_view_->restartCaret();
2347 char_type encoded_last_key = keysym.getUCSEncoded();
2349 // Do a one-deep top-level lookup for
2350 // cancel and meta-fake keys. RVDK_PATCH_5
2351 d->cancel_meta_seq.reset();
2353 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2354 LYXERR(Debug::KEY, "action first set to ["
2355 << lyxaction.getActionName(func.action()) << ']');
2357 // When not cancel or meta-fake, do the normal lookup.
2358 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2359 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2360 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2361 // remove Caps Lock and Mod2 as a modifiers
2362 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2363 LYXERR(Debug::KEY, "action now set to ["
2364 << lyxaction.getActionName(func.action()) << ']');
2367 // Don't remove this unless you know what you are doing.
2368 d->meta_fake_bit = NoModifier;
2370 // Can this happen now ?
2371 if (func.action() == LFUN_NOACTION)
2372 func = FuncRequest(LFUN_COMMAND_PREFIX);
2374 LYXERR(Debug::KEY, " Key [action="
2375 << lyxaction.getActionName(func.action()) << "]["
2376 << d->keyseq.print(KeySequence::Portable) << ']');
2378 // already here we know if it any point in going further
2379 // why not return already here if action == -1 and
2380 // num_bytes == 0? (Lgb)
2382 if (d->keyseq.length() > 1 && current_view_)
2383 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2386 // Maybe user can only reach the key via holding down shift.
2387 // Let's see. But only if shift is the only modifier
2388 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2389 LYXERR(Debug::KEY, "Trying without shift");
2390 // If addkey looked up a command and did not find further commands then
2391 // seq has been reset at this point
2392 func = d->keyseq.addkey(keysym, NoModifier);
2393 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2396 if (func.action() == LFUN_UNKNOWN_ACTION) {
2397 // We didn't match any of the key sequences.
2398 // See if it's normal insertable text not already
2399 // covered by a binding
2400 if (keysym.isText() && d->keyseq.length() == 1) {
2401 // Non-printable characters (such as ASCII control characters)
2402 // must not be inserted (#5704)
2403 if (!isPrintable(encoded_last_key)) {
2404 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2406 current_view_->restartCaret();
2409 // The following modifier check is not needed on Mac.
2410 // The keysym is either not text or it is different
2411 // from the non-modifier keysym. See #9875 for the
2412 // broken alt-modifier effect of having this code active.
2413 #if !defined(Q_OS_MAC)
2414 // If a non-Shift Modifier is used we have a non-bound key sequence
2415 // (such as Alt+j = j). This should be omitted (#5575).
2416 // On Windows, AltModifier and ControlModifier are both
2417 // set when AltGr is pressed. Therefore, in order to not
2418 // break AltGr-bound symbols (see #5575 for details),
2419 // unbound Ctrl+Alt key sequences are allowed.
2420 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2421 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2422 && !(state & AltModifier && state & ControlModifier)
2426 if (current_view_) {
2427 current_view_->message(_("Unknown function."));
2428 current_view_->restartCaret();
2433 // Since all checks above were passed, we now really have text that
2434 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2435 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2437 LYXERR(Debug::KEY, "isText() is true, inserting.");
2438 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2440 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2441 if (current_view_) {
2442 current_view_->message(_("Unknown function."));
2443 current_view_->restartCaret();
2449 if (func.action() == LFUN_SELF_INSERT) {
2450 if (encoded_last_key != 0) {
2451 docstring const arg(1, encoded_last_key);
2452 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2453 FuncRequest::KEYBOARD));
2454 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2457 processFuncRequest(func);
2461 void GuiApplication::processFuncRequest(FuncRequest const & func)
2463 lyx::dispatch(func);
2467 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2469 addToFuncRequestQueue(func);
2470 processFuncRequestQueueAsync();
2474 void GuiApplication::processFuncRequestQueue()
2476 while (!d->func_request_queue_.empty()) {
2477 // take the item from the stack _before_ processing the
2478 // request in order to avoid race conditions from nested
2479 // or parallel requests (see #10406)
2480 FuncRequest const fr(d->func_request_queue_.front());
2481 d->func_request_queue_.pop();
2482 processFuncRequest(fr);
2487 void GuiApplication::processFuncRequestQueueAsync()
2489 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2493 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2495 d->func_request_queue_.push(func);
2499 void GuiApplication::resetGui()
2501 // Set the language defined by the user.
2505 if (!readUIFile(toqstr(lyxrc.ui_file)))
2506 // Gives some error box here.
2509 if (d->global_menubar_)
2510 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2512 QHash<int, GuiView *>::iterator it;
2513 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2516 gv->setLayoutDirection(layoutDirection());
2520 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2524 bool GuiApplication::rtlContext() const
2526 if (current_view_ && current_view_->currentBufferView()) {
2527 BufferView const * bv = current_view_->currentBufferView();
2528 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2530 return layoutDirection() == Qt::RightToLeft;
2534 void GuiApplication::createView(int view_id)
2536 createView(QString(), true, view_id);
2540 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2543 // release the keyboard which might have been grabbed by the global
2544 // menubar on Mac to catch shortcuts even without any GuiView.
2545 if (d->global_menubar_)
2546 d->global_menubar_->releaseKeyboard();
2550 while (d->views_.find(id) != d->views_.end())
2553 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2554 GuiView * view = new GuiView(id);
2555 // `view' is the new current_view_. Tell coverity that is is not 0.
2556 LATTEST(current_view_);
2558 d->views_[id] = view;
2562 setActiveWindow(view);
2565 if (!geometry_arg.isEmpty()) {
2566 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2570 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2571 re.indexIn(geometry_arg);
2572 w = re.cap(1).toInt();
2573 h = re.cap(2).toInt();
2574 x = re.cap(3).toInt();
2575 y = re.cap(4).toInt();
2576 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2577 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2578 // Set initial geometry such that we can get the frame size.
2579 view->setGeometry(x, y, w, h);
2580 int framewidth = view->geometry().x() - view->x();
2581 int titleheight = view->geometry().y() - view->y();
2582 // Negative displacements must be interpreted as distances
2583 // from the right or bottom screen borders.
2584 if (sx == '-' || sy == '-') {
2585 QRect rec = QApplication::desktop()->screenGeometry();
2587 x += rec.width() - w - framewidth;
2589 y += rec.height() - h - titleheight;
2590 view->setGeometry(x, y, w, h);
2592 // Make sure that the left and top frame borders are visible.
2593 if (view->x() < 0 || view->y() < 0) {
2598 view->setGeometry(x, y, w, h);
2606 bool GuiApplication::unhide(Buffer * buf)
2610 currentView()->setBuffer(buf, false);
2615 Clipboard & GuiApplication::clipboard()
2617 return d->clipboard_;
2621 Selection & GuiApplication::selection()
2623 return d->selection_;
2627 FontLoader & GuiApplication::fontLoader()
2629 return d->font_loader_;
2633 Toolbars const & GuiApplication::toolbars() const
2635 return d->toolbars_;
2639 Toolbars & GuiApplication::toolbars()
2641 return d->toolbars_;
2645 Menus const & GuiApplication::menus() const
2651 Menus & GuiApplication::menus()
2657 QList<int> GuiApplication::viewIds() const
2659 return d->views_.keys();
2663 ColorCache & GuiApplication::colorCache()
2665 return d->color_cache_;
2669 int GuiApplication::exec()
2671 // asynchronously handle batch commands. This event will be in
2672 // the event queue in front of other asynchronous events. Hence,
2673 // we can assume in the latter that the gui is setup already.
2674 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2676 return QApplication::exec();
2680 void GuiApplication::exit(int status)
2682 QApplication::exit(status);
2686 void GuiApplication::setGuiLanguage()
2690 // install translation file for Qt built-in dialogs
2691 QString const language_name = QString("qt_") + theLocale.name();
2692 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2693 // Short-named translator can be loaded from a long name, but not the
2694 // opposite. Therefore, long name should be used without truncation.
2695 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2696 if (!d->qt_trans_.load(language_name,
2697 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2698 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2701 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2705 switch (theLocale.language()) {
2706 case QLocale::Arabic :
2707 case QLocale::Hebrew :
2708 case QLocale::Persian :
2709 case QLocale::Urdu :
2710 setLayoutDirection(Qt::RightToLeft);
2713 setLayoutDirection(Qt::LeftToRight);
2718 void GuiApplication::execBatchCommands()
2723 if (!readUIFile(toqstr(lyxrc.ui_file)))
2724 // Gives some error box here.
2728 #if QT_VERSION > 0x040600
2729 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2731 #if QT_VERSION > 0x050100
2732 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2734 // Create the global default menubar which is shown for the dialogs
2735 // and if no GuiView is visible.
2736 // This must be done after the session was recovered to know the "last files".
2737 d->global_menubar_ = new QMenuBar(0);
2738 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2741 lyx::execBatchCommands();
2745 QAbstractItemModel * GuiApplication::languageModel()
2747 if (d->language_model_)
2748 return d->language_model_;
2750 QStandardItemModel * lang_model = new QStandardItemModel(this);
2751 lang_model->insertColumns(0, 3);
2752 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2753 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2754 Languages::const_iterator it = lyx::languages.begin();
2755 Languages::const_iterator end = lyx::languages.end();
2756 for (; it != end; ++it) {
2757 int current_row = lang_model->rowCount();
2758 lang_model->insertRows(current_row, 1);
2759 QModelIndex pl_item = lang_model->index(current_row, 0);
2760 QModelIndex sp_item = lang_model->index(current_row, 1);
2761 QModelIndex th_item = lang_model->index(current_row, 2);
2762 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2763 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2764 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2765 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2766 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2767 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2768 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2769 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2770 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2771 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2773 d->language_model_ = new QSortFilterProxyModel(this);
2774 d->language_model_->setSourceModel(lang_model);
2775 d->language_model_->setSortLocaleAware(true);
2776 return d->language_model_;
2780 void GuiApplication::restoreGuiSession()
2782 if (!lyxrc.load_session)
2785 Session & session = theSession();
2786 LastOpenedSection::LastOpened const & lastopened =
2787 session.lastOpened().getfiles();
2789 validateCurrentView();
2791 FileName active_file;
2792 // do not add to the lastfile list since these files are restored from
2793 // last session, and should be already there (regular files), or should
2794 // not be added at all (help files).
2795 for (auto const & last : lastopened) {
2796 FileName const & file_name = last.file_name;
2797 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2798 && current_view_->documentBufferView() != nullptr)) {
2799 string const & fname = file_name.absFileName();
2800 createView(support::checksum(fname));
2802 current_view_->loadDocument(file_name, false);
2805 active_file = file_name;
2808 // Restore last active buffer
2809 Buffer * buffer = theBufferList().getBuffer(active_file);
2810 if (buffer && current_view_)
2811 current_view_->setBuffer(buffer);
2813 // clear this list to save a few bytes of RAM
2814 session.lastOpened().clear();
2818 QString const GuiApplication::romanFontName()
2821 font.setStyleHint(QFont::Serif);
2822 font.setFamily("serif");
2824 return QFontInfo(font).family();
2828 QString const GuiApplication::sansFontName()
2831 font.setStyleHint(QFont::SansSerif);
2832 font.setFamily("sans");
2834 return QFontInfo(font).family();
2838 QString const GuiApplication::typewriterFontName()
2840 return QFontInfo(typewriterSystemFont()).family();
2845 // We cannot use QFont::fixedPitch() because it doesn't
2846 // return the fact but only if it is requested.
2847 static bool isFixedPitch(const QFont & font) {
2848 const QFontInfo fi(font);
2849 return fi.fixedPitch();
2854 QFont const GuiApplication::typewriterSystemFont()
2856 #if QT_VERSION >= 0x050200
2857 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2859 QFont font("monospace");
2861 if (!isFixedPitch(font)) {
2862 // try to enforce a real monospaced font
2863 font.setStyleHint(QFont::Monospace);
2864 if (!isFixedPitch(font)) {
2865 font.setStyleHint(QFont::TypeWriter);
2866 if (!isFixedPitch(font)) font.setFamily("courier");
2870 // On a Mac the result is too small and it's not practical to
2871 // rely on Qtconfig utility to change the system settings of Qt.
2872 font.setPointSize(12);
2878 void GuiApplication::handleRegularEvents()
2880 ForkedCallsController::handleCompletedProcesses();
2884 bool GuiApplication::event(QEvent * e)
2887 case QEvent::FileOpen: {
2888 // Open a file; this happens only on Mac OS X for now.
2890 // We do this asynchronously because on startup the batch
2891 // commands are not executed here yet and the gui is not ready
2893 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2894 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2895 processFuncRequestAsync(fr);
2899 #if (QT_VERSION < 0x050000)
2900 // Qt5 uses a signal for that, see above.
2901 case QEvent::KeyboardLayoutChange:
2902 //LYXERR0("keyboard change");
2903 if (currentView() && currentView()->currentBufferView())
2904 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2909 return QApplication::event(e);
2914 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2917 return QApplication::notify(receiver, event);
2919 catch (ExceptionMessage const & e) {
2921 case ErrorException:
2923 setQuitOnLastWindowClosed(false);
2925 Alert::error(e.title_, e.details_);
2927 // Properly crash in debug mode in order to get a useful backtrace.
2930 // In release mode, try to exit gracefully.
2932 // FIXME: GCC 7 thinks we can fall through here. Can we?
2934 case BufferException: {
2935 if (!current_view_ || !current_view_->documentBufferView())
2937 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2938 docstring details = e.details_ + '\n';
2939 details += buf->emergencyWrite();
2940 theBufferList().release(buf);
2941 details += "\n" + _("The current document was closed.");
2942 Alert::error(e.title_, details);
2945 case WarningException:
2946 Alert::warning(e.title_, e.details_);
2950 catch (exception const & e) {
2951 docstring s = _("LyX has caught an exception, it will now "
2952 "attempt to save all unsaved documents and exit."
2954 s += from_ascii(e.what());
2955 Alert::error(_("Software exception Detected"), s);
2959 docstring s = _("LyX has caught some really weird exception, it will "
2960 "now attempt to save all unsaved documents and exit.");
2961 Alert::error(_("Software exception Detected"), s);
2968 bool GuiApplication::isInDarkMode()
2970 return colorCache().isDarkMode();
2974 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2976 QColor const & qcol = d->color_cache_.get(col);
2977 if (!qcol.isValid()) {
2983 rgbcol.r = qcol.red();
2984 rgbcol.g = qcol.green();
2985 rgbcol.b = qcol.blue();
2990 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2992 QColor const qcol(lcolor.getX11HexName(col).c_str());
2993 if (!qcol.isValid()) {
2999 rgbcol.r = qcol.red();
3000 rgbcol.g = qcol.green();
3001 rgbcol.b = qcol.blue();
3006 string const GuiApplication::hexName(ColorCode col)
3008 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3012 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3014 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3015 d->socket_notifiers_[fd] = sn;
3016 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3020 void GuiApplication::socketDataReceived(int fd)
3022 d->socket_notifiers_[fd]->func_();
3026 void GuiApplication::unregisterSocketCallback(int fd)
3028 d->socket_notifiers_.take(fd)->setEnabled(false);
3032 void GuiApplication::commitData(QSessionManager & sm)
3034 /** The implementation is required to avoid an application exit
3035 ** when session state save is triggered by session manager.
3036 ** The default implementation sends a close event to all
3037 ** visible top level widgets when session management allows
3039 ** We are changing that to check the state of each buffer in all
3040 ** views and ask the users what to do if buffers are dirty.
3041 ** Furthermore, we save the session state.
3042 ** We do NOT close the views here since the user still can cancel
3043 ** the logout process (see #9277); also, this would hide LyX from
3044 ** an OSes own session handling (application restoration).
3046 #ifdef QT_NO_SESSIONMANAGER
3048 #warning Qt is compiled without session manager
3050 #pragma message("warning: Qt is compiled without session manager")
3054 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3062 void GuiApplication::unregisterView(GuiView * gv)
3064 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3065 d->views_.remove(gv->id());
3066 if (current_view_ == gv)
3067 current_view_ = nullptr;
3072 bool GuiApplication::closeAllViews()
3074 if (d->views_.empty())
3077 // When a view/window was closed before without quitting LyX, there
3078 // are already entries in the lastOpened list.
3079 theSession().lastOpened().clear();
3081 QList<GuiView *> const views = d->views_.values();
3082 for (GuiView * view : views) {
3083 if (!view->closeScheduled())
3092 bool GuiApplication::prepareAllViewsForLogout()
3094 if (d->views_.empty())
3097 QList<GuiView *> const views = d->views_.values();
3098 for (GuiView * view : views) {
3099 if (!view->prepareAllBuffersForLogout())
3107 GuiView & GuiApplication::view(int id) const
3109 LAPPERR(d->views_.contains(id));
3110 return *d->views_.value(id);
3114 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3116 QList<GuiView *> const views = d->views_.values();
3117 for (GuiView * view : views)
3118 view->hideDialog(name, inset);
3122 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3124 Buffer const * buf = nullptr;
3125 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3126 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3127 if (Buffer const * ptr = (*it)->updateInset(inset))
3134 bool GuiApplication::searchMenu(FuncRequest const & func,
3135 docstring_list & names) const
3137 BufferView * bv = nullptr;
3139 bv = current_view_->currentBufferView();
3140 return d->menus_.searchMenu(func, names, bv);
3144 bool GuiApplication::hasBufferView() const
3146 return (current_view_ && current_view_->currentBufferView());
3150 // Ensure that a file is read only once (prevents include loops)
3151 static QStringList uifiles;
3152 // store which ui files define Toolbars
3153 static QStringList toolbar_uifiles;
3156 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3167 LexerKeyword uitags[] = {
3168 { "format", ui_format },
3169 { "include", ui_include },
3170 { "menuset", ui_menuset },
3171 { "toolbars", ui_toolbars },
3172 { "toolbarset", ui_toolbarset }
3176 lex.setFile(ui_path);
3178 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3182 if (lyxerr.debugging(Debug::PARSER))
3183 lex.printTable(lyxerr);
3186 // format before introduction of format tag
3187 unsigned int format = 0;
3188 while (lex.isOK()) {
3189 int const status = lex.lex();
3191 // we have to do this check here, outside the switch,
3192 // because otherwise we would start reading include files,
3193 // e.g., if the first tag we hit was an include tag.
3194 if (status == ui_format)
3196 format = lex.getInteger();
3200 // this will trigger unless the first tag we hit is a format
3201 // tag, with the right format.
3202 if (format != LFUN_FORMAT)
3203 return FormatMismatch;
3206 case Lexer::LEX_FEOF:
3211 QString const file = toqstr(lex.getString());
3212 bool const success = readUIFile(file, true);
3214 LYXERR0("Failed to read included file: " << fromqstr(file));
3221 d->menus_.read(lex);
3225 d->toolbars_.readToolbars(lex);
3229 d->toolbars_.readToolbarSettings(lex);
3230 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3234 if (!rtrim(lex.getString()).empty())
3235 lex.printError("LyX::ReadUIFile: "
3236 "Unknown menu tag: `$$Token'");
3238 LYXERR0("Error with status: " << status);
3244 return (error ? ReadError : ReadOK);
3248 bool GuiApplication::readUIFile(QString const & name, bool include)
3250 LYXERR(Debug::INIT, "About to read " << name << "...");
3254 ui_path = libFileSearch("ui", name, "inc");
3255 if (ui_path.empty())
3256 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3258 ui_path = libFileSearch("ui", name, "ui");
3261 if (ui_path.empty()) {
3262 static const QString defaultUIFile = "default";
3263 LYXERR(Debug::INIT, "Could not find " << name);
3265 Alert::warning(_("Could not find UI definition file"),
3266 bformat(_("Error while reading the included file\n%1$s\n"
3267 "Please check your installation."), qstring_to_ucs4(name)));
3270 if (name == defaultUIFile) {
3271 LYXERR(Debug::INIT, "Could not find default UI file!!");
3272 Alert::warning(_("Could not find default UI file"),
3273 _("LyX could not find the default UI file!\n"
3274 "Please check your installation."));
3277 Alert::warning(_("Could not find UI definition file"),
3278 bformat(_("Error while reading the configuration file\n%1$s\n"
3279 "Falling back to default.\n"
3280 "Please look under Tools>Preferences>User Interface and\n"
3281 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3282 return readUIFile(defaultUIFile, false);
3285 QString const uifile = toqstr(ui_path.absFileName());
3286 if (uifiles.contains(uifile)) {
3288 // We are reading again the top uifile so reset the safeguard:
3291 d->toolbars_.reset();
3293 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3294 << "Is this an include loop?");
3298 uifiles.push_back(uifile);
3300 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3302 ReturnValues retval = readUIFile(ui_path);
3304 if (retval == FormatMismatch) {
3305 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3306 TempFile tmp("convertXXXXXX.ui");
3307 FileName const tempfile = tmp.name();
3308 bool const success = prefs2prefs(ui_path, tempfile, true);
3310 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3311 " to format " << LFUN_FORMAT << ".");
3313 retval = readUIFile(tempfile);
3317 if (retval != ReadOK) {
3318 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3326 settings.beginGroup("ui_files");
3327 bool touched = false;
3328 for (int i = 0; i != uifiles.size(); ++i) {
3329 QFileInfo fi(uifiles[i]);
3330 QDateTime const date_value = fi.lastModified();
3331 QString const name_key = QString::number(i);
3332 // if an ui file which defines Toolbars has changed,
3333 // we have to reset the settings
3334 if (toolbar_uifiles.contains(uifiles[i])
3335 && (!settings.contains(name_key)
3336 || settings.value(name_key).toString() != uifiles[i]
3337 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3339 settings.setValue(name_key, uifiles[i]);
3340 settings.setValue(name_key + "/date", date_value);
3343 settings.endGroup();
3345 settings.remove("views");
3351 void GuiApplication::onLastWindowClosed()
3353 if (d->global_menubar_)
3354 d->global_menubar_->grabKeyboard();
3358 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3359 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3361 std::string name = "unknown";
3363 case Qt::ApplicationSuspended:
3364 name = "ApplicationSuspended";
3366 case Qt::ApplicationHidden:
3367 name = "ApplicationHidden";
3369 case Qt::ApplicationInactive:
3370 name = "ApplicationInactive";
3372 case Qt::ApplicationActive:
3373 name = "ApplicationActive";
3374 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3375 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3376 if (d->views_.empty() && d->last_state_ == state) {
3377 LYXERR(Debug::GUI, "Open new window...");
3382 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3383 d->last_state_ = state;
3388 void GuiApplication::startLongOperation() {
3389 d->key_checker_.start();
3393 bool GuiApplication::longOperationCancelled() {
3394 return d->key_checker_.pressed();
3398 void GuiApplication::stopLongOperation() {
3399 d->key_checker_.stop();
3403 bool GuiApplication::longOperationStarted() {
3404 return d->key_checker_.started();
3408 ////////////////////////////////////////////////////////////////////////
3410 // X11 specific stuff goes here...
3413 bool GuiApplication::x11EventFilter(XEvent * xev)
3418 switch (xev->type) {
3419 case SelectionRequest: {
3420 if (xev->xselectionrequest.selection != XA_PRIMARY)
3422 LYXERR(Debug::SELECTION, "X requested selection.");
3423 BufferView * bv = current_view_->currentBufferView();
3425 docstring const sel = bv->requestSelection();
3427 d->selection_.put(sel);
3428 // Refresh the selection request timestamp.
3429 // We have to do this by ourselves as Qt seems
3430 // not doing that, maybe because of our
3431 // "persistent selection" implementation
3432 // (see comments in GuiSelection.cpp).
3433 XSelectionEvent nev;
3434 nev.type = SelectionNotify;
3435 nev.display = xev->xselectionrequest.display;
3436 nev.requestor = xev->xselectionrequest.requestor;
3437 nev.selection = xev->xselectionrequest.selection;
3438 nev.target = xev->xselectionrequest.target;
3439 nev.property = 0L; // None
3440 nev.time = CurrentTime;
3441 XSendEvent(QX11Info::display(),
3442 nev.requestor, False, 0,
3443 reinterpret_cast<XEvent *>(&nev));
3449 case SelectionClear: {
3450 if (xev->xselectionclear.selection != XA_PRIMARY)
3452 LYXERR(Debug::SELECTION, "Lost selection.");
3453 BufferView * bv = current_view_->currentBufferView();
3455 bv->clearSelection();
3461 #elif defined(QPA_XCB)
3462 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3463 void * message, long *)
3465 if (!current_view_ || eventType != "xcb_generic_event_t")
3468 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3470 switch (ev->response_type) {
3471 case XCB_SELECTION_REQUEST: {
3472 xcb_selection_request_event_t * srev =
3473 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3474 if (srev->selection != XCB_ATOM_PRIMARY)
3476 LYXERR(Debug::SELECTION, "X requested selection.");
3477 BufferView * bv = current_view_->currentBufferView();
3479 docstring const sel = bv->requestSelection();
3481 d->selection_.put(sel);
3482 #ifdef HAVE_QT5_X11_EXTRAS
3483 // Refresh the selection request timestamp.
3484 // We have to do this by ourselves as Qt seems
3485 // not doing that, maybe because of our
3486 // "persistent selection" implementation
3487 // (see comments in GuiSelection.cpp).
3488 // It is expected that every X11 event is
3489 // 32 bytes long, even if not all 32 bytes are
3491 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3492 struct alignas(32) padded_event
3493 : xcb_selection_notify_event_t {};
3494 padded_event nev = {};
3495 nev.response_type = XCB_SELECTION_NOTIFY;
3496 nev.requestor = srev->requestor;
3497 nev.selection = srev->selection;
3498 nev.target = srev->target;
3499 nev.property = XCB_NONE;
3500 nev.time = XCB_CURRENT_TIME;
3501 xcb_connection_t * con = QX11Info::connection();
3502 xcb_send_event(con, 0, srev->requestor,
3503 XCB_EVENT_MASK_NO_EVENT,
3504 reinterpret_cast<char const *>(&nev));
3512 case XCB_SELECTION_CLEAR: {
3513 xcb_selection_clear_event_t * scev =
3514 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3515 if (scev->selection != XCB_ATOM_PRIMARY)
3517 LYXERR(Debug::SELECTION, "Lost selection.");
3518 BufferView * bv = current_view_->currentBufferView();
3520 bv->clearSelection();
3528 } // namespace frontend
3531 void hideDialogs(std::string const & name, Inset * inset)
3534 frontend::guiApp->hideDialogs(name, inset);
3538 ////////////////////////////////////////////////////////////////////
3542 ////////////////////////////////////////////////////////////////////
3544 frontend::FontLoader & theFontLoader()
3546 LAPPERR(frontend::guiApp);
3547 return frontend::guiApp->fontLoader();
3551 frontend::FontMetrics const & theFontMetrics(Font const & f)
3553 return theFontMetrics(f.fontInfo());
3557 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3559 LAPPERR(frontend::guiApp);
3560 return frontend::guiApp->fontLoader().metrics(f);
3564 ////////////////////////////////////////////////////////////////////
3568 ////////////////////////////////////////////////////////////////////
3570 frontend::Clipboard & theClipboard()
3572 LAPPERR(frontend::guiApp);
3573 return frontend::guiApp->clipboard();
3577 frontend::Selection & theSelection()
3579 LAPPERR(frontend::guiApp);
3580 return frontend::guiApp->selection();
3586 #include "moc_GuiApplication.cpp"