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 #if QT_VERSION < 0x060000
93 #include <QDesktopWidget>
96 #include <QFileOpenEvent>
98 #include <QFontDatabase>
101 #include <QImageReader>
104 #include <QLibraryInfo>
111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
112 #include <QRandomGenerator>
115 #include <QSessionManager>
117 #include <QSocketNotifier>
118 #include <QSortFilterProxyModel>
119 #include <QStandardItemModel>
121 #include <QTranslator>
122 #include <QThreadPool>
126 #include <X11/Xatom.h>
127 #include <X11/Xlib.h>
131 #elif defined(QPA_XCB)
133 #ifdef HAVE_QT5_X11_EXTRAS
134 #include <QtX11Extras/QX11Info>
138 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
139 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
140 #if (QT_VERSION < 0x050000)
141 #include <QWindowsMime>
142 #define QWINDOWSMIME QWindowsMime
143 #define QVARIANTTYPE QVariant::Type
144 #elif (QT_VERSION >= 0x060000)
145 #include <QtGui/private/qguiapplication_p.h>
146 #include <QtGui/private/qwindowsmime_p.h>
147 #include <QtGui/qpa/qplatformintegration.h>
148 #define QWINDOWSMIME QWindowsMime
149 #define QVARIANTTYPE QMetaType
150 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
151 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
154 #define QWINDOWSMIME QWinMime
155 #define QVARIANTTYPE QVariant::Type
164 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
165 #include <QMacPasteboardMime>
173 using namespace lyx::support;
178 frontend::Application * createApplication(int & argc, char * argv[])
180 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
181 // prune -geometry argument(s) by shifting
182 // the following ones 2 places down.
183 for (int i = 0 ; i < argc ; ++i) {
184 if (strcmp(argv[i], "-geometry") == 0) {
185 int const remove = (i+1) < argc ? 2 : 1;
187 for (int j = i; j < argc; ++j)
188 argv[j] = argv[j + remove];
194 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
195 // On Windows, allow bringing the LyX window to top
196 AllowSetForegroundWindow(ASFW_ANY);
200 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
201 // macOS does it by itself.
202 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
203 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
204 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
205 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
206 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
207 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
210 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
211 // HighDPI scale factor policy must be set before QGuiApplication is created
212 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
213 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
217 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
218 // I'd rather do that in the constructor, but I do not think that
219 // the palette is accessible there.
220 guiApp->colorCache().setPalette(guiApp->palette());
229 if (lyxrc.gui_language == "auto") {
230 theLocale = QLocale::system();
231 code = fromqstr(theLocale.name());
233 Language const * l = languages.getLanguage(lyxrc.gui_language);
234 code = l ? l->code() : "C";
235 theLocale = QLocale(toqstr(code));
237 // Qt tries to outsmart us and transforms en_US to C.
238 Messages::guiLanguage((code == "C") ? "en_US" : code);
239 QLocale::setDefault(theLocale);
240 setlocale(LC_NUMERIC, "C");
247 /// Return the list of loadable formats.
248 vector<string> loadableImageFormats()
252 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
254 LYXERR(Debug::GRAPHICS,
255 "\nThe image loader can load the following directly:\n");
257 if (qt_formats.empty())
258 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
260 bool jpeg_found = false;
261 bool jpg_found = false;
262 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
264 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
266 string ext = ascii_lowercase((const char *) *it);
274 else if (ext == "jpg") {
279 else if (lyxrc.use_converter_cache &&
280 (ext == "svg" || ext == "svgz") &&
281 theConverters().isReachable("svg", "png"))
282 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
283 // the SVG as in the output. However we require that the converter
284 // cache is enabled since this is expensive. We also require that
285 // an explicit svg->png converter is defined, since the default
286 // converter could produce bad quality as well. This assumes that
287 // png can always be loaded.
296 ////////////////////////////////////////////////////////////////////////
298 // Icon loading support code
300 ////////////////////////////////////////////////////////////////////////
310 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
312 return lhs.key < rhs.key;
318 CompareKey(QString const & name) : name_(name) {}
319 bool operator()(ImgMap const & other) const { return other.key == name_; }
325 // this must be sorted alphabetically
326 // Upper case comes before lower case
327 // Please don't change the formatting, this list is parsed by
328 // development/tools/generate_symbols_images.py.
329 ImgMap sorted_img_map[] = {
330 { "Arrownot", "arrownot2"},
331 { "Arrowvert", "arrowvert2"},
332 { "Bowtie", "bowtie2" },
334 { "Bumpeq", "bumpeq2" },
335 { "CIRCLE", "circle3" },
337 { "CheckedBox", "checkedbox2" },
338 { "Circle", "circle2" },
339 { "Colonapprox", "colonapprox2" },
340 { "Coloneq", "coloneq2" },
341 { "Coloneqq", "coloneqq2" },
342 { "Colonsim", "colonsim2" },
344 { "DOWNarrow", "downarrow3" },
345 { "Delta", "delta2" },
346 { "Diamond", "diamond2" },
347 { "Doteq", "doteq2" },
348 { "Downarrow", "downarrow2" },
349 { "Eqcolon", "eqcolon2" },
350 { "Eqqcolon", "eqqcolon2" },
351 { "Gamma", "gamma2" },
353 { "LEFTCIRCLE", "leftcircle3" },
354 { "LEFTarrow", "leftarrow3" },
355 { "LEFTcircle", "leftcircle4" },
357 { "Lambda", "lambda2" },
359 { "Leftarrow", "leftarrow2" },
360 { "Leftcircle", "leftcircle2" },
361 { "Leftrightarrow", "leftrightarrow2" },
362 { "Longarrownot", "longarrownot2"},
363 { "Longleftarrow", "longleftarrow2" },
364 { "Longleftrightarrow", "longleftrightarrow2" },
365 { "Longmapsfrom", "longmapsfrom2"},
366 { "Longmapsto", "longmapsto2"},
367 { "Longrightarrow", "longrightarrow2" },
368 { "Mapsfrom", "mapsfrom2"},
369 { "Mapsfromchar", "mapsfromchar2"},
370 { "Mapsto", "mapsto2"},
371 { "Mapstochar", "mapstochar2"},
372 { "Omega", "omega2" },
377 { "RIGHTCIRCLE", "rightcircle3" },
378 { "RIGHTarrow", "rightarrow3" },
379 { "RIGHTcircle", "rightcircle4" },
381 { "Rightarrow", "rightarrow2" },
382 { "Rightcircle", "rightcircle2" },
383 { "Sigma", "sigma2" },
384 { "Square", "square2" },
385 { "Subset", "subset2" },
386 { "Supset", "supset2" },
387 { "Theta", "theta2" },
388 { "Thorn", "thorn2" },
389 { "UParrow", "uparrow3" },
390 { "Uparrow", "uparrow2" },
391 { "Updownarrow", "updownarrow2" },
392 { "Upsilon", "upsilon2" },
393 { "Vdash", "vdash3" },
398 { "lVert", "vert2" },
400 { "nLeftarrow", "nleftarrow2" },
401 { "nLeftrightarrow", "nleftrightarrow2" },
402 { "nRightarrow", "nrightarrow2" },
403 { "nVDash", "nvdash3" },
404 { "nVdash", "nvdash4" },
405 { "nvDash", "nvdash2" },
406 { "rVert", "vert2" },
408 { "textrm \\AA", "textrm_AA"},
409 { "textrm \\O", "textrm_O"},
410 { "vDash", "vdash2" },
411 { "varDelta", "vardelta2" },
412 { "varGamma", "vargamma2" },
413 { "varLambda", "varlambda2" },
414 { "varOmega", "varomega2" },
415 { "varPhi", "varphi2" },
416 { "varPi", "varpi2" },
417 { "varPsi", "varpsi2" },
418 { "varSigma", "varsigma2" },
419 { "varTheta", "vartheta2" },
420 { "varUpsilon", "varupsilon2" },
421 { "varXi", "varxi2" }
425 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
427 // This list specifies which system's theme icon is related to which lyx
428 // command. It was based on:
429 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
430 // this must be sorted alphabetically
431 // Upper case comes before lower case
432 ImgMap sorted_theme_icon_map[] = {
433 { "bookmark-goto 0", "go-jump" },
434 { "buffer-new", "document-new" },
435 { "buffer-write", "document-save" },
436 { "buffer-write-as", "document-save-as" },
437 { "buffer-zoom-in", "zoom-in" },
438 { "buffer-zoom-out", "zoom-out" },
439 { "copy", "edit-copy" },
440 { "cut", "edit-cut" },
441 { "depth-decrement", "format-indent-less" },
442 { "depth-increment", "format-indent-more" },
443 { "dialog-show spellchecker", "tools-check-spelling" },
444 { "dialog-show-new-inset graphics", "insert-image" },
445 { "dialog-toggle findreplaceadv", "edit-find-replace" },
446 { "file-open", "document-open" },
447 { "font-bold", "format-text-bold" },
448 { "font-ital", "format-text-italic" },
449 { "font-strikeout", "format-text-strikethrough" },
450 { "font-underline", "format-text-underline" },
451 { "lyx-quit", "application-exit" },
452 { "paste", "edit-paste" },
453 { "redo", "edit-redo" },
454 { "undo", "edit-undo" },
455 { "window-close", "window-close" },
456 { "window-new", "window-new" }
459 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
462 QString findImg(QString const & name)
464 ImgMap const * const begin = sorted_img_map;
465 ImgMap const * const end = begin + nr_sorted_img_map;
466 LATTEST(sorted(begin, end));
468 ImgMap const * const it = find_if(begin, end, CompareKey(name));
472 img_name = it->value;
475 img_name.replace('_', "underscore");
476 img_name.replace(' ', '_');
478 // This way we can have "math-delim { }" on the toolbar.
479 img_name.replace('(', "lparen");
480 img_name.replace(')', "rparen");
481 img_name.replace('[', "lbracket");
482 img_name.replace(']', "rbracket");
483 img_name.replace('{', "lbrace");
484 img_name.replace('}', "rbrace");
485 img_name.replace('|', "bars");
486 img_name.replace(',', "thinspace");
487 img_name.replace(':', "mediumspace");
488 img_name.replace(';', "thickspace");
489 img_name.replace('!', "negthinspace");
492 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
493 << "Looking for math icon called \"" << img_name << '"');
500 QString themeIconName(QString const & action)
502 ImgMap const * const begin = sorted_theme_icon_map;
503 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
504 LASSERT(sorted(begin, end), /**/);
506 ImgMap const * const it = find_if(begin, end, CompareKey(action));
514 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
519 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
521 if (!f.argument().empty()) {
522 // if there are arguments, first search an icon which name is the full thing
523 QString name = lfunname + ' ' + toqstr(f.argument());
524 name.replace(' ', '_');
525 name.replace(';', '_');
526 name.replace('\\', "backslash");
527 // avoid duplication for these
528 name.replace("dialog-toggle", "dialog-show");
531 // then special default icon for some lfuns
532 switch (f.action()) {
533 case LFUN_MATH_INSERT:
534 names << "math/" + findImg(toqstr(f.argument()).mid(1));
536 case LFUN_MATH_DELIM:
537 case LFUN_MATH_BIGDELIM:
538 names << "math/" + findImg(toqstr(f.argument()));
541 names << "commands/" + toqstr(f.argument());
543 case LFUN_COMMAND_ALTERNATIVES: {
544 // use the first of the alternative commands
546 docstring dummy = split(f.argument(), firstcom, ';');
547 QString name1 = toqstr(firstcom);
548 name1.replace(' ', '_');
549 name1.replace(';', '_');
550 name1.replace('\\', "backslash");
559 // next thing to try is function name alone
562 // and finally maybe the unknown icon
566 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
567 // The folders where icons are searched for
568 QStringList imagedirs;
569 imagedirs << "images/ipa/" << "images/";
570 // This is used to search for rtl version of icons which have the +rtl suffix.
571 QStringList suffixes;
574 suffixes << QString();
576 for (QString const & imagedir : imagedirs)
577 for (QString const & name : names)
578 for (QString const & suffix : suffixes) {
579 QString id = imagedir;
580 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
581 if (fname.exists()) {
582 docstring const fpath = fname.absoluteFilePath();
583 res.filepath = toqstr(fname.absFileName());
584 // these icons are subject to inversion in dark mode
585 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
586 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
587 res.swap = rtl && suffix.isEmpty();
592 LYXERR(Debug::GUI, "Cannot find icon for command \""
593 << lyxaction.getActionName(f.action())
594 << '(' << to_utf8(f.argument()) << ")\"");
600 QPixmap prepareForDarkMode(QPixmap pixmap)
602 QPalette palette = QPalette();
603 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
604 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
606 // guess whether we are in dark mode
607 if (text_color.black() > bg_color.black())
608 // not in dark mode, do nothing
611 // create a layer with black text turned to QPalette::WindowText
612 QPixmap black_overlay(pixmap.size());
613 black_overlay.fill(text_color);
614 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
616 // create a layer with blue text turned to lighter blue
617 QPixmap blue_overlay(pixmap.size());
618 QColor math_blue(0, 0, 255);
619 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
620 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
622 // create a layer with ("latex") red text turned to lighter red
623 QPixmap red_overlay(pixmap.size());
624 QColor math_red(128, 0, 0);
625 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
626 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
628 // put layers on top of existing pixmap
629 QPainter painter(&pixmap);
630 painter.drawPixmap(pixmap.rect(), black_overlay);
631 painter.drawPixmap(pixmap.rect(), blue_overlay);
632 painter.drawPixmap(pixmap.rect(), red_overlay);
638 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
640 QString imagedir = path;
641 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
642 QString fpath = toqstr(fname.absFileName());
643 QPixmap pixmap = QPixmap();
645 if (pixmap.load(fpath)) {
646 if (fpath.contains("math") || fpath.contains("ipa")
647 || fpath.contains("bullets"))
648 return prepareForDarkMode(pixmap);
652 bool const list = ext.contains(",");
653 LYXERR(Debug::GUI, "Cannot load pixmap \""
654 << path << "/" << name << "." << (list ? "{" : "") << ext
655 << (list ? "}" : "") << "\".");
661 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
663 #if (QT_VERSION >= 0x040600)
664 if (lyxrc.use_system_theme_icons) {
665 // use the icons from system theme that are available
666 QString action = toqstr(lyxaction.getActionName(f.action()));
667 if (!f.argument().empty())
668 action += " " + toqstr(f.argument());
669 QString const theme_icon = themeIconName(action);
670 if (QIcon::hasThemeIcon(theme_icon)) {
671 QIcon const thmicn = QIcon::fromTheme(theme_icon);
672 if (!thmicn.isNull())
678 IconInfo icondata = iconInfo(f, unknown, rtl);
679 if (icondata.filepath.isEmpty())
682 //LYXERR(Debug::GUI, "Found icon: " << icon);
683 QPixmap pixmap = QPixmap();
684 if (!pixmap.load(icondata.filepath)) {
685 LYXERR0("Cannot load icon " << icondata.filepath << ".");
690 pixmap = prepareForDarkMode(pixmap);
693 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
695 return QIcon(pixmap);
699 ////////////////////////////////////////////////////////////////////////
701 // LyX server support code.
703 ////////////////////////////////////////////////////////////////////////
705 class SocketNotifier : public QSocketNotifier
708 /// connect a connection notification from the LyXServerSocket
709 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
710 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
714 /// The callback function
715 Application::SocketCallback func_;
719 class GuiTranslator : public QTranslator
722 GuiTranslator(QObject * parent = nullptr)
723 : QTranslator(parent)
726 QString translate(const char * /* context */,
727 const char *sourceText,
728 #if QT_VERSION >= 0x050000
729 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
731 const char * /*comment*/ = 0) const override
734 // Here we declare the strings that need to be translated from Qt own GUI
735 // This is needed to include these strings to po files
739 _("Restore Defaults");
742 // Already in po: "Cancel", "&Cancel"
743 _("Apply"); // Already in po: "&Apply"
744 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
747 docstring s = getGuiMessages().getIfFound(sourceText);
748 // This test should eventually be removed when translations are updated
750 LYXERR(Debug::LOCALE, "Missing translation for `"
751 << string(sourceText) << "'");
757 ////////////////////////////////////////////////////////////////////////
759 // Mac specific stuff goes here...
761 ////////////////////////////////////////////////////////////////////////
763 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
764 // QMacPasteboardMimeGraphics can only be compiled on Mac.
766 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
769 QMacPasteboardMimeGraphics()
770 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
773 QString convertorName() { return "Graphics"; }
775 QString flavorFor(QString const & mime)
777 LYXERR(Debug::ACTION, "flavorFor " << mime);
778 if (mime == pdfMimeType())
779 return QLatin1String("com.adobe.pdf");
783 QString mimeFor(QString flav)
785 LYXERR(Debug::ACTION, "mimeFor " << flav);
786 if (flav == QLatin1String("com.adobe.pdf"))
787 return pdfMimeType();
791 bool canConvert(QString const & mime, QString flav)
793 return mimeFor(flav) == mime;
796 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
800 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
804 QList<QByteArray> convertFromMime(QString const & /*mime*/,
805 QVariant data, QString /*flav*/)
807 QList<QByteArray> ret;
808 ret.append(data.toByteArray());
814 ///////////////////////////////////////////////////////////////
816 // You can find more platform specific stuff at the end of this file...
818 ///////////////////////////////////////////////////////////////
820 ////////////////////////////////////////////////////////////////////////
821 // Windows specific stuff goes here...
823 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
824 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
825 // QWindowsMimeMetafile can only be compiled on Windows.
827 static FORMATETC cfFromMime(QString const & mimetype)
830 if (mimetype == emfMimeType()) {
831 formatetc.cfFormat = CF_ENHMETAFILE;
832 formatetc.tymed = TYMED_ENHMF;
833 } else if (mimetype == wmfMimeType()) {
834 formatetc.cfFormat = CF_METAFILEPICT;
835 formatetc.tymed = TYMED_MFPICT;
838 formatetc.dwAspect = DVASPECT_CONTENT;
839 formatetc.lindex = -1;
844 class QWindowsMimeMetafile : public QWINDOWSMIME {
846 QWindowsMimeMetafile() {}
848 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
849 QMimeData const * /*mimedata*/) const override
854 bool canConvertToMime(QString const & mimetype,
855 IDataObject * pDataObj) const override
857 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
859 FORMATETC formatetc = cfFromMime(mimetype);
860 return pDataObj->QueryGetData(&formatetc) == S_OK;
863 bool convertFromMime(FORMATETC const & /*formatetc*/,
864 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
869 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
870 QVARIANTTYPE /*preferredType*/) const override
873 if (!canConvertToMime(mimetype, pDataObj))
876 FORMATETC formatetc = cfFromMime(mimetype);
878 if (pDataObj->GetData(&formatetc, &s) != S_OK)
882 if (s.tymed == TYMED_ENHMF) {
883 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
884 data.resize(dataSize);
885 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
886 (LPBYTE)data.data());
887 } else if (s.tymed == TYMED_MFPICT) {
888 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
889 data.resize(dataSize);
890 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
891 (LPBYTE)data.data());
894 ReleaseStgMedium(&s);
900 QVector<FORMATETC> formatsForMime(QString const & mimetype,
901 QMimeData const * /*mimedata*/) const override
903 QVector<FORMATETC> formats;
904 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
905 formats += cfFromMime(mimetype);
909 QString mimeForFormat(FORMATETC const & formatetc) const override
911 switch (formatetc.cfFormat) {
913 return emfMimeType();
914 case CF_METAFILEPICT:
915 return wmfMimeType();
925 /// Allows to check whether ESC was pressed during a long operation
926 class KeyChecker : public QObject {
931 KeyChecker() : pressed_(false), started_(false) {}
934 QCoreApplication::instance()->installEventFilter(this);
939 QCoreApplication::instance()->removeEventFilter(this);
943 QCoreApplication::processEvents();
946 bool started() const {
949 bool eventFilter(QObject *obj, QEvent *event) override {
950 LYXERR(Debug::ACTION, "Event Type: " << event->type());
951 switch (event->type()) {
955 case QEvent::UpdateRequest:
956 case QEvent::CursorChange:
957 case QEvent::ActionChanged:
958 case QEvent::EnabledChange:
959 case QEvent::SockAct:
962 case QEvent::ToolTipChange:
963 case QEvent::LayoutRequest:
964 case QEvent::MetaCall:
965 return QObject::eventFilter(obj, event);
967 // FIXME Blocking all these events is a bad idea.
968 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
969 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
977 ////////////////////////////////////////////////////////////////////////
978 // GuiApplication::Private definition and implementation.
979 ////////////////////////////////////////////////////////////////////////
981 struct GuiApplication::Private
983 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
984 global_menubar_(nullptr)
985 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
986 , last_state_(Qt::ApplicationInactive)
989 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
990 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
991 /// WMF Mime handler for Windows clipboard.
992 wmf_mime_ = new QWindowsMimeMetafile;
993 #if (QT_VERSION >= 0x060000)
994 win_app_ = dynamic_cast<QWindowsApplication *>
995 (QGuiApplicationPrivate::platformIntegration());
996 win_app_->registerMime(wmf_mime_);
1000 initKeySequences(&theTopLevelKeymap());
1003 #if (QT_VERSION >= 0x060000)
1004 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1007 win_app_->unregisterMime(wmf_mime_);
1012 void initKeySequences(KeyMap * kb)
1014 keyseq = KeySequence(kb, kb);
1015 cancel_meta_seq = KeySequence(kb, kb);
1019 QSortFilterProxyModel * language_model_;
1021 GuiClipboard clipboard_;
1023 GuiSelection selection_;
1025 FontLoader font_loader_;
1027 ColorCache color_cache_;
1028 /// the built-in Qt translation mechanism
1029 QTranslator qt_trans_;
1030 /// LyX gettext-based translation for Qt elements
1031 GuiTranslator gui_trans_;
1033 QHash<int, SocketNotifier *> socket_notifiers_;
1037 /// The global instance
1040 /// this timer is used for any regular events one wants to
1041 /// perform. at present it is used to check if forked processes
1043 QTimer general_timer_;
1045 /// delayed FuncRequests
1046 std::queue<FuncRequest> func_request_queue_;
1051 KeySequence cancel_meta_seq;
1053 KeyModifier meta_fake_bit;
1055 /// The result of last dispatch action
1056 DispatchResult dispatch_result_;
1058 /// Multiple views container.
1060 * Warning: This must not be a smart pointer as the destruction of the
1061 * object is handled by Qt when the view is closed
1062 * \sa Qt::WA_DeleteOnClose attribute.
1064 QHash<int, GuiView *> views_;
1066 /// Only used on mac.
1067 QMenuBar * global_menubar_;
1068 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1069 /// Holds previous application state on Mac
1070 Qt::ApplicationState last_state_;
1073 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1074 /// Linkback mime handler for MacOSX.
1075 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1078 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1079 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1080 /// WMF Mime handler for Windows clipboard.
1081 QWindowsMimeMetafile * wmf_mime_;
1082 #if (QT_VERSION >= 0x060000)
1083 QWindowsApplication * win_app_;
1088 /// Allows to check whether ESC was pressed during a long operation
1089 KeyChecker key_checker_;
1093 GuiApplication * guiApp;
1095 GuiApplication::~GuiApplication()
1098 closeAllLinkBackLinks();
1104 GuiApplication::GuiApplication(int & argc, char ** argv)
1105 : QApplication(argc, argv), current_view_(nullptr),
1106 d(new GuiApplication::Private)
1108 QString app_name = "LyX";
1109 QCoreApplication::setOrganizationName(app_name);
1110 QCoreApplication::setOrganizationDomain("lyx.org");
1111 QCoreApplication::setApplicationName(lyx_package);
1112 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1113 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1116 #if QT_VERSION >= 0x050700
1117 setDesktopFileName(lyx_package);
1120 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1121 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1123 qsrand(QDateTime::currentDateTime().toTime_t());
1126 // Install LyX translator for missing Qt translations
1127 installTranslator(&d->gui_trans_);
1128 // Install Qt native translator for GUI elements.
1129 installTranslator(&d->qt_trans_);
1132 // Enable reception of XCB events.
1133 installNativeEventFilter(this);
1136 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1137 // lyxrc setting for this in order to let the application stay resident.
1138 // But then we need some kind of dock icon, at least on Windows.
1140 if (lyxrc.quit_on_last_window_closed)
1141 setQuitOnLastWindowClosed(false);
1144 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1145 // seems to be the default case for applications like LyX.
1146 setQuitOnLastWindowClosed(false);
1149 appleCleanupEditMenu();
1150 appleCleanupViewMenu();
1151 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1152 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1153 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1157 #if defined(Q_WS_X11) || defined(QPA_XCB)
1158 // doubleClickInterval() is 400 ms on X11 which is just too long.
1159 // On Windows and Mac OS X, the operating system's value is used.
1160 // On Microsoft Windows, calling this function sets the double
1161 // click interval for all applications. So we don't!
1162 QApplication::setDoubleClickInterval(300);
1165 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1167 // needs to be done before reading lyxrc
1169 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1173 // Initialize RC Fonts
1174 if (lyxrc.roman_font_name.empty())
1175 lyxrc.roman_font_name = fromqstr(romanFontName());
1177 if (lyxrc.sans_font_name.empty())
1178 lyxrc.sans_font_name = fromqstr(sansFontName());
1180 if (lyxrc.typewriter_font_name.empty())
1181 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1183 #if (QT_VERSION >= 0x050000)
1184 // Qt4 does this in event(), see below.
1185 // Track change of keyboard
1186 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1189 d->general_timer_.setInterval(500);
1190 connect(&d->general_timer_, SIGNAL(timeout()),
1191 this, SLOT(handleRegularEvents()));
1192 d->general_timer_.start();
1194 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1195 // This is clearly not enough in a time where we use threads for
1196 // document preview and/or export. 20 should be OK.
1197 QThreadPool::globalInstance()->setMaxThreadCount(20);
1199 // make sure tooltips are formatted
1200 installEventFilter(new ToolTipFormatter(this));
1204 GuiApplication * theGuiApp()
1206 return dynamic_cast<GuiApplication *>(theApp());
1210 #if QT_VERSION < 0x050000
1211 // Emulate platformName() for Qt4
1213 // FIXME: when ditching this method, remove all tests
1214 // platformName() == "qt4x11"
1216 QString GuiApplication::platformName() const
1218 # if defined(Q_WS_X11)
1219 // Note that this one does not really exist
1221 # elif defined(Q_OS_MAC)
1223 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1226 LYXERR0("Unknown platform!");
1233 double GuiApplication::pixelRatio() const
1235 #if QT_VERSION >= 0x050000
1236 return qt_scale_factor * devicePixelRatio();
1243 void GuiApplication::clearSession()
1250 docstring Application::iconName(FuncRequest const & f, bool unknown)
1252 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1256 docstring Application::mathIcon(docstring const & c)
1258 return qstring_to_ucs4(findImg(toqstr(c)));
1262 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1266 BufferView * bv = nullptr;
1267 BufferView * doc_bv = nullptr;
1269 if (cmd.action() == LFUN_NOACTION) {
1270 status.message(from_utf8(N_("Nothing to do")));
1271 status.setEnabled(false);
1274 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1275 status.setUnknown(true);
1276 status.message(from_utf8(N_("Unknown action")));
1277 status.setEnabled(false);
1280 // Does the GuiApplication know something?
1281 else if (getStatus(cmd, status)) { }
1283 // If we do not have a GuiView, then other functions are disabled
1284 else if (!current_view_)
1285 status.setEnabled(false);
1287 // Does the GuiView know something?
1288 else if (current_view_->getStatus(cmd, status)) { }
1290 // In LyX/Mac, when a dialog is open, the menus of the
1291 // application can still be accessed without giving focus to
1292 // the main window. In this case, we want to disable the menu
1293 // entries that are buffer or view-related.
1294 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1296 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1297 status.setEnabled(false);
1300 // If we do not have a BufferView, then other functions are disabled
1301 else if (!(bv = current_view_->currentBufferView()))
1302 status.setEnabled(false);
1304 // Does the current BufferView know something?
1305 else if (bv->getStatus(cmd, status)) { }
1307 // Does the current Buffer know something?
1308 else if (bv->buffer().getStatus(cmd, status)) { }
1310 // If we do not have a document BufferView, different from the
1311 // current BufferView, then other functions are disabled
1312 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1313 status.setEnabled(false);
1315 // Does the document Buffer know something?
1316 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1319 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1320 status.message(from_utf8(N_("Command not handled")));
1321 status.setEnabled(false);
1324 // the default error message if we disable the command
1325 if (!status.enabled() && status.message().empty())
1326 status.message(from_utf8(N_("Command disabled")));
1332 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1334 // I would really like to avoid having this switch and rather try to
1335 // encode this in the function itself.
1336 // -- And I'd rather let an inset decide which LFUNs it is willing
1337 // to handle (Andre')
1339 switch (cmd.action()) {
1341 // This could be used for the no-GUI version. The GUI version is handled in
1342 // GuiView::getStatus(). See above.
1344 case LFUN_BUFFER_WRITE:
1345 case LFUN_BUFFER_WRITE_AS:
1346 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1347 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1348 enable = b && (b->isUnnamed() || !b->isClean());
1353 case LFUN_BOOKMARK_GOTO: {
1354 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1355 enable = theSession().bookmarks().isValid(num);
1359 case LFUN_BOOKMARK_CLEAR:
1360 enable = theSession().bookmarks().hasValid();
1363 // this one is difficult to get right. As a half-baked
1364 // solution, we consider only the first action of the sequence
1365 case LFUN_COMMAND_SEQUENCE: {
1366 // argument contains ';'-terminated commands
1367 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1368 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1369 func.setOrigin(cmd.origin());
1370 flag = getStatus(func);
1374 // we want to check if at least one of these is enabled
1375 case LFUN_COMMAND_ALTERNATIVES: {
1376 // argument contains ';'-terminated commands
1377 string arg = to_utf8(cmd.argument());
1378 while (!arg.empty()) {
1380 arg = split(arg, first, ';');
1381 FuncRequest func(lyxaction.lookupFunc(first));
1382 func.setOrigin(cmd.origin());
1383 flag = getStatus(func);
1384 // if this one is enabled, the whole thing is
1393 string name = to_utf8(cmd.argument());
1394 if (theTopLevelCmdDef().lock(name, func)) {
1395 func.setOrigin(cmd.origin());
1396 flag = getStatus(func);
1397 theTopLevelCmdDef().release(name);
1399 // catch recursion or unknown command
1400 // definition. all operations until the
1401 // recursion or unknown command definition
1402 // occurs are performed, so set the state to
1409 case LFUN_IF_RELATIVES: {
1410 string const lfun = to_utf8(cmd.argument());
1411 BufferView const * bv =
1412 current_view_ ? current_view_->currentBufferView() : nullptr;
1413 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1417 FuncRequest func(lyxaction.lookupFunc(lfun));
1418 func.setOrigin(cmd.origin());
1419 flag = getStatus(func);
1423 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1425 case LFUN_PREFERENCES_SAVE:
1426 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1427 // these are handled in our dispatch()
1430 case LFUN_DEBUG_LEVEL_SET: {
1431 string bad = Debug::badValue(to_utf8(cmd.argument()));
1432 enable = bad.empty();
1434 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1438 case LFUN_WINDOW_CLOSE:
1439 enable = !d->views_.empty();
1442 case LFUN_BUFFER_NEW:
1443 case LFUN_BUFFER_NEW_TEMPLATE:
1444 case LFUN_FILE_OPEN:
1445 case LFUN_LYXFILES_OPEN:
1446 case LFUN_HELP_OPEN:
1447 case LFUN_SCREEN_FONT_UPDATE:
1448 case LFUN_SET_COLOR:
1449 case LFUN_WINDOW_NEW:
1451 case LFUN_LYXRC_APPLY:
1452 case LFUN_COMMAND_PREFIX:
1454 case LFUN_META_PREFIX:
1455 case LFUN_RECONFIGURE:
1456 case LFUN_SERVER_GET_FILENAME:
1457 case LFUN_SERVER_NOTIFY:
1461 case LFUN_BUFFER_FORALL: {
1462 if (theBufferList().empty()) {
1463 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1464 flag.setEnabled(false);
1468 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1469 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1470 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1471 flag.setEnabled(false);
1476 case LFUN_DIALOG_SHOW: {
1477 string const name = cmd.getArg(0);
1478 return name == "aboutlyx"
1479 || name == "lyxfiles"
1481 || name == "texinfo"
1482 || name == "progress"
1483 || name == "compare";
1491 flag.setEnabled(false);
1495 /// make a post-dispatch status message
1496 static docstring makeDispatchMessage(docstring const & msg,
1497 FuncRequest const & cmd)
1499 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1500 || cmd.origin() == FuncRequest::TOOLBAR
1501 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1503 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1504 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1508 docstring dispatch_msg = msg;
1509 if (!dispatch_msg.empty())
1510 dispatch_msg += ' ';
1512 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1514 bool argsadded = false;
1516 if (!cmd.argument().empty()) {
1517 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1518 comname += ' ' + cmd.argument();
1522 docstring const shortcuts = theTopLevelKeymap().
1523 printBindings(cmd, KeySequence::ForGui);
1525 if (!shortcuts.empty())
1526 comname += ": " + shortcuts;
1527 else if (!argsadded && !cmd.argument().empty())
1528 comname += ' ' + cmd.argument();
1530 if (!comname.empty()) {
1531 comname = rtrim(comname);
1532 dispatch_msg += '(' + rtrim(comname) + ')';
1534 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1535 return dispatch_msg;
1539 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1543 Buffer * buffer = nullptr;
1544 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1545 //setCurrentView(cmd.view_origin); //does not work
1547 dr.setMessage(_("Wrong focus!"));
1548 d->dispatch_result_ = dr;
1549 return d->dispatch_result_;
1551 if (current_view_ && current_view_->currentBufferView()) {
1552 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1553 buffer = ¤t_view_->currentBufferView()->buffer();
1556 dr.screenUpdate(Update::FitCursor);
1558 // All the code is kept inside the undo group because
1559 // updateBuffer can create undo actions (see #11292)
1560 UndoGroupHelper ugh(buffer);
1562 if (dr.screenUpdate() & Update::ForceAll) {
1563 for (Buffer const * b : theBufferList())
1565 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1568 updateCurrentView(cmd, dr);
1571 d->dispatch_result_ = dr;
1572 return d->dispatch_result_;
1576 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1581 BufferView * bv = current_view_->currentBufferView();
1583 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1584 bv->cursor().clearBufferUpdate();
1585 bv->buffer().updateBuffer();
1587 // BufferView::update() updates the ViewMetricsInfo and
1588 // also initializes the position cache for all insets in
1589 // (at least partially) visible top-level paragraphs.
1590 // We will redraw the screen only if needed.
1591 bv->processUpdateFlags(dr.screenUpdate());
1593 // Do we have a selection?
1594 theSelection().haveSelection(bv->cursor().selection());
1597 current_view_->restartCaret();
1599 if (dr.needMessageUpdate()) {
1600 // Some messages may already be translated, so we cannot use _()
1601 current_view_->message(makeDispatchMessage(
1602 translateIfPossible(dr.message()), cmd));
1607 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1608 bool switchToBuffer)
1610 if (!theSession().bookmarks().isValid(idx))
1612 BookmarksSection::Bookmark const & bm =
1613 theSession().bookmarks().bookmark(idx);
1614 LASSERT(!bm.filename.empty(), return);
1615 string const file = bm.filename.absFileName();
1616 // if the file is not opened, open it.
1617 if (!theBufferList().exists(bm.filename)) {
1619 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1623 // open may fail, so we need to test it again
1624 if (!theBufferList().exists(bm.filename))
1627 // bm can be changed when saving
1628 BookmarksSection::Bookmark tmp = bm;
1630 // Special case idx == 0 used for back-from-back jump navigation
1632 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1634 // if the current buffer is not that one, switch to it.
1635 BufferView * doc_bv = current_view_ ?
1636 current_view_->documentBufferView() : nullptr;
1637 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1638 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1639 if (switchToBuffer) {
1640 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1643 doc_bv = current_view_->documentBufferView();
1648 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1649 if (!doc_bv || !doc_bv->moveToPosition(
1650 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1653 Cursor & cur = doc_bv->cursor();
1654 if (old && cur != *old)
1655 notifyCursorLeavesOrEnters(*old, cur);
1661 // Cursor jump succeeded!
1662 pit_type new_pit = cur.pit();
1663 pos_type new_pos = cur.pos();
1664 int new_id = cur.paragraph().id();
1666 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1667 // see http://www.lyx.org/trac/ticket/3092
1668 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1669 || bm.top_id != new_id) {
1670 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1671 new_pit, new_pos, new_id);
1675 // This function runs "configure" and then rereads lyx.defaults to
1676 // reconfigure the automatic settings.
1677 void GuiApplication::reconfigure(string const & option)
1679 // emit message signal.
1680 if (current_view_) {
1681 current_view_->message(_("Running configure..."));
1682 current_view_->setCursor(Qt::WaitCursor);
1685 // Run configure in user lyx directory
1686 string const lock_file = package().getConfigureLockName();
1687 int fd = fileLock(lock_file.c_str());
1688 int const ret = package().reconfigureUserLyXDir(option);
1689 // emit message signal.
1691 current_view_->message(_("Reloading configuration..."));
1692 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1693 // Re-read packages.lst
1694 LaTeXPackages::getAvailable();
1695 fileUnlock(fd, lock_file.c_str());
1698 current_view_->unsetCursor();
1701 Alert::information(_("System reconfiguration failed"),
1702 _("The system reconfiguration has failed.\n"
1703 "Default textclass is used but LyX may\n"
1704 "not be able to work properly.\n"
1705 "Please reconfigure again if needed."));
1707 Alert::information(_("System reconfigured"),
1708 _("The system has been reconfigured.\n"
1709 "You need to restart LyX to make use of any\n"
1710 "updated document class specifications."));
1713 void GuiApplication::validateCurrentView()
1715 if (!d->views_.empty() && !current_view_) {
1716 // currently at least one view exists but no view has the focus.
1717 // choose the last view to make it current.
1718 // a view without any open document is preferred.
1719 GuiView * candidate = nullptr;
1720 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1721 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1722 for (; it != end; ++it) {
1724 if (!candidate->documentBufferView())
1727 setCurrentView(candidate);
1731 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1733 string const argument = to_utf8(cmd.argument());
1734 FuncCode const action = cmd.action();
1736 LYXERR(Debug::ACTION, "cmd: " << cmd);
1738 // we have not done anything wrong yet.
1741 FuncStatus const flag = getStatus(cmd);
1742 if (!flag.enabled()) {
1743 // We cannot use this function here
1744 LYXERR(Debug::ACTION, "action "
1745 << lyxaction.getActionName(action)
1746 << " [" << action << "] is disabled at this location");
1747 dr.setMessage(flag.message());
1749 dr.dispatched(false);
1750 dr.screenUpdate(Update::None);
1751 dr.clearBufferUpdate();
1755 if (cmd.origin() == FuncRequest::LYXSERVER) {
1756 if (current_view_ && current_view_->currentBufferView())
1757 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1758 // we will also need to redraw the screen at the end
1759 dr.screenUpdate(Update::FitCursor);
1762 // Assumes that the action will be dispatched.
1763 dr.dispatched(true);
1765 switch (cmd.action()) {
1767 case LFUN_WINDOW_NEW:
1768 createView(toqstr(cmd.argument()));
1771 case LFUN_WINDOW_CLOSE:
1772 // FIXME: this is done also in GuiView::closeBuffer()!
1773 // update bookmark pit of the current buffer before window close
1774 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1775 gotoBookmark(i, false, false);
1776 // clear the last opened list, because
1777 // maybe this will end the session
1778 theSession().lastOpened().clear();
1779 // check for valid current_view_
1780 validateCurrentView();
1782 current_view_->closeScheduled();
1786 // quitting is triggered by the gui code
1787 // (leaving the event loop).
1789 current_view_->message(from_utf8(N_("Exiting.")));
1790 if (closeAllViews())
1794 case LFUN_SCREEN_FONT_UPDATE: {
1795 // handle the screen font changes.
1796 /* FIXME: this only updates the current document, whereas all
1797 * documents should see their metrics updated.
1799 d->font_loader_.update();
1800 dr.screenUpdate(Update::Force | Update::FitCursor);
1804 case LFUN_BUFFER_NEW:
1805 validateCurrentView();
1807 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1808 createView(QString(), false); // keep hidden
1809 current_view_->newDocument(to_utf8(cmd.argument()));
1810 current_view_->show();
1811 setActiveWindow(current_view_);
1813 current_view_->newDocument(to_utf8(cmd.argument()));
1817 case LFUN_BUFFER_NEW_TEMPLATE: {
1818 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1819 string const temp = cmd.getArg(1);
1820 validateCurrentView();
1822 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1824 current_view_->newDocument(file, temp, true);
1825 if (!current_view_->documentBufferView())
1826 current_view_->close();
1828 current_view_->newDocument(file, temp, true);
1833 case LFUN_FILE_OPEN: {
1834 // FIXME: normally the code below is not needed, since getStatus makes sure that
1835 // current_view_ is not null.
1836 validateCurrentView();
1837 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1838 string const fname = trim(to_utf8(cmd.argument()), "\"");
1839 bool const is_open = FileName::isAbsolute(fname)
1840 && theBufferList().getBuffer(FileName(fname));
1842 || (!lyxrc.open_buffers_in_tabs
1843 && current_view_->documentBufferView() != nullptr
1845 // We want the ui session to be saved per document and not per
1846 // window number. The filename crc is a good enough identifier.
1847 createView(support::checksum(fname));
1848 current_view_->openDocument(fname);
1849 if (!current_view_->documentBufferView())
1850 current_view_->close();
1851 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1852 current_view_->raise();
1853 current_view_->activateWindow();
1854 current_view_->showNormal();
1857 current_view_->openDocument(fname);
1858 if (cmd.origin() == FuncRequest::LYXSERVER) {
1859 current_view_->raise();
1860 current_view_->activateWindow();
1861 current_view_->showNormal();
1867 case LFUN_HELP_OPEN: {
1868 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1869 if (current_view_ == nullptr)
1871 string const arg = to_utf8(cmd.argument());
1873 current_view_->message(_("Missing argument"));
1876 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1878 fname = i18nLibFileSearch("examples", arg, "lyx");
1880 if (fname.empty()) {
1881 lyxerr << "LyX: unable to find documentation file `"
1882 << arg << "'. Bad installation?" << endl;
1885 current_view_->message(bformat(_("Opening help file %1$s..."),
1886 makeDisplayPath(fname.absFileName())));
1887 Buffer * buf = current_view_->loadDocument(fname, false);
1889 buf->setReadonly(!current_view_->develMode());
1893 case LFUN_LYXFILES_OPEN: {
1894 // This is the actual reason for this method (#12106).
1895 validateCurrentView();
1897 || (!lyxrc.open_buffers_in_tabs
1898 && current_view_->documentBufferView() != nullptr))
1900 string arg = to_utf8(cmd.argument());
1904 if (arg != "templates" && arg != "examples") {
1905 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1908 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1912 case LFUN_SET_COLOR: {
1913 string const lyx_name = cmd.getArg(0);
1914 string x11_name = cmd.getArg(1);
1915 string x11_darkname = cmd.getArg(2);
1916 if (lyx_name.empty() || x11_name.empty()) {
1918 current_view_->message(
1919 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1924 // FIXME: The graphics cache no longer has a changeDisplay method.
1925 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1926 bool const graphicsbg_changed =
1927 lyx_name == graphicsbg && x11_name != graphicsbg;
1928 if (graphicsbg_changed)
1929 graphics::GCache::get().changeDisplay(true);
1932 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1933 x11_darkname = x11_name;
1936 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1938 current_view_->message(
1939 bformat(_("Set-color \"%1$s\" failed "
1940 "- color is undefined or "
1941 "may not be redefined"),
1942 from_utf8(lyx_name)));
1945 // Make sure we don't keep old colors in cache.
1946 d->color_cache_.clear();
1947 // Update the current view
1948 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1952 case LFUN_LYXRC_APPLY: {
1953 // reset active key sequences, since the bindings
1954 // are updated (bug 6064)
1956 LyXRC const lyxrc_orig = lyxrc;
1958 istringstream ss(to_utf8(cmd.argument()));
1959 bool const success = lyxrc.read(ss);
1962 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1963 << "Unable to read lyxrc data"
1968 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1970 // If the request comes from the minibuffer, then we can't reset
1971 // the GUI, since that would destroy the minibuffer itself and
1972 // cause a crash, since we are currently in one of the methods of
1973 // GuiCommandBuffer. See bug #8540.
1974 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1977 // FIXME Unfortunately, that leaves a bug here, since we cannot
1978 // reset the GUI in this case. If the changes to lyxrc affected the
1979 // UI, then, nothing would happen. This seems fairly unlikely, but
1980 // it definitely is a bug.
1982 dr.forceBufferUpdate();
1986 case LFUN_COMMAND_PREFIX:
1987 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1992 d->meta_fake_bit = NoModifier;
1993 GuiView * gv = currentView();
1994 if (gv && gv->currentBufferView())
1995 // cancel any selection
1996 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1997 dr.setMessage(from_ascii(N_("Cancel")));
2000 case LFUN_META_PREFIX:
2001 d->meta_fake_bit = AltModifier;
2002 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2005 // --- Menus -----------------------------------------------
2006 case LFUN_RECONFIGURE:
2007 // argument is any additional parameter to the configure.py command
2008 reconfigure(to_utf8(cmd.argument()));
2011 // --- lyxserver commands ----------------------------
2012 case LFUN_SERVER_GET_FILENAME: {
2013 if (current_view_ && current_view_->documentBufferView()) {
2014 docstring const fname = from_utf8(
2015 current_view_->documentBufferView()->buffer().absFileName());
2016 dr.setMessage(fname);
2017 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2019 dr.setMessage(docstring());
2020 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2025 case LFUN_SERVER_NOTIFY: {
2026 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2027 dr.setMessage(dispatch_buffer);
2028 theServer().notifyClient(to_utf8(dispatch_buffer));
2032 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2033 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2039 string rest = split(argument, countstr, ' ');
2040 int const count = convert<int>(countstr);
2041 // an arbitrary number to limit number of iterations
2042 int const max_iter = 10000;
2043 if (count > max_iter) {
2044 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2047 for (int i = 0; i < count; ++i) {
2048 FuncRequest lfun = lyxaction.lookupFunc(rest);
2049 lfun.allowAsync(false);
2056 case LFUN_COMMAND_SEQUENCE: {
2057 // argument contains ';'-terminated commands
2058 string arg = argument;
2059 // FIXME: this LFUN should also work without any view.
2060 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2061 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2062 // This handles undo groups automagically
2063 UndoGroupHelper ugh(buffer);
2064 while (!arg.empty()) {
2066 arg = split(arg, first, ';');
2067 FuncRequest func(lyxaction.lookupFunc(first));
2068 func.allowAsync(false);
2069 func.setOrigin(cmd.origin());
2075 case LFUN_BUFFER_FORALL: {
2076 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2077 funcToRun.allowAsync(false);
2079 map<Buffer *, GuiView *> views_lVisible;
2080 map<GuiView *, Buffer *> activeBuffers;
2082 QList<GuiView *> allViews = d->views_.values();
2084 // this for does not modify any buffer. It just collects info on local
2085 // visibility of buffers and on which buffer is active in each view.
2086 Buffer * const last = theBufferList().last();
2087 for(GuiView * view : allViews) {
2088 // all of the buffers might be locally hidden. That is, there is no
2090 if (!view || !view->currentBufferView())
2091 activeBuffers[view] = nullptr;
2093 activeBuffers[view] = &view->currentBufferView()->buffer();
2095 // find out if each is locally visible or locally hidden.
2096 // we don't use a for loop as the buffer list cycles.
2097 Buffer * b = theBufferList().first();
2099 bool const locallyVisible = view && view->workArea(*b);
2100 if (locallyVisible) {
2101 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2102 // only need to overwrite/add if we don't already know a buffer is globally
2103 // visible or we do know but we would prefer to dispatch LFUN from the
2104 // current view because of cursor position issues.
2105 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2106 views_lVisible[b] = view;
2110 b = theBufferList().next(b);
2114 GuiView * const homeView = currentView();
2115 Buffer * b = theBufferList().first();
2116 Buffer * nextBuf = nullptr;
2117 int numProcessed = 0;
2120 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2122 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2124 // first change to a view where b is locally visible, preferably current_view_.
2125 GuiView * const vLv = views_lVisible[b];
2127 lyx::dispatch(funcToRun);
2135 // put things back to how they were (if possible).
2136 for (GuiView * view : allViews) {
2137 Buffer * originalBuf = activeBuffers[view];
2138 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2139 if (theBufferList().isLoaded(originalBuf))
2140 view->setBuffer(originalBuf);
2142 homeView->setFocus();
2144 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2148 case LFUN_COMMAND_ALTERNATIVES: {
2149 // argument contains ';'-terminated commands
2150 string arg = argument;
2151 while (!arg.empty()) {
2153 arg = split(arg, first, ';');
2154 FuncRequest func(lyxaction.lookupFunc(first));
2155 func.setOrigin(cmd.origin());
2156 FuncStatus const stat = getStatus(func);
2157 if (stat.enabled()) {
2167 if (theTopLevelCmdDef().lock(argument, func)) {
2168 func.setOrigin(cmd.origin());
2170 theTopLevelCmdDef().release(argument);
2172 if (func.action() == LFUN_UNKNOWN_ACTION) {
2173 // unknown command definition
2174 lyxerr << "Warning: unknown command definition `"
2178 // recursion detected
2179 lyxerr << "Warning: Recursion in the command definition `"
2180 << argument << "' detected"
2187 case LFUN_IF_RELATIVES: {
2188 string const lfun = to_utf8(cmd.argument());
2189 FuncRequest func(lyxaction.lookupFunc(lfun));
2190 func.setOrigin(cmd.origin());
2191 FuncStatus const stat = getStatus(func);
2192 if (stat.enabled()) {
2199 case LFUN_PREFERENCES_SAVE:
2200 lyxrc.write(support::makeAbsPath("preferences",
2201 package().user_support().absFileName()), false);
2204 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2205 string const fname = addName(addPath(package().user_support().absFileName(),
2206 "templates/"), "defaults.lyx");
2207 Buffer defaults(fname);
2209 istringstream ss(argument);
2214 // We need to make sure that, after we recreat the DocumentClass,
2215 // which we do in readHeader, we apply it to the document itself.
2216 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2217 int const unknown_tokens = defaults.readHeader(lex);
2218 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2219 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2220 cap::switchBetweenClasses(olddc, newdc, theinset);
2222 if (unknown_tokens != 0) {
2223 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2224 << unknown_tokens << " unknown token"
2225 << (unknown_tokens == 1 ? "" : "s")
2229 if (defaults.writeFile(FileName(defaults.absFileName())))
2230 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2231 makeDisplayPath(fname)));
2234 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2239 case LFUN_BOOKMARK_GOTO:
2240 // go to bookmark, open unopened file and switch to buffer if necessary
2241 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2242 dr.screenUpdate(Update::Force | Update::FitCursor);
2245 case LFUN_BOOKMARK_CLEAR:
2246 theSession().bookmarks().clear();
2247 dr.screenUpdate(Update::Force);
2250 case LFUN_DEBUG_LEVEL_SET:
2251 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2254 case LFUN_DIALOG_SHOW: {
2255 string const name = cmd.getArg(0);
2257 if ( name == "aboutlyx"
2259 || name == "texinfo"
2260 || name == "progress"
2261 || name == "compare")
2263 // work around: on Mac OS the application
2264 // is not terminated when closing the last view.
2265 // Create a new one to be able to dispatch the
2266 // LFUN_DIALOG_SHOW to this view.
2267 if (current_view_ == nullptr)
2273 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2276 current_view_->dispatch(cmd, dr);
2280 if (current_view_ && current_view_->isFullScreen()) {
2281 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2282 current_view_->menuBar()->hide();
2285 if (cmd.origin() == FuncRequest::LYXSERVER)
2286 updateCurrentView(cmd, dr);
2290 docstring GuiApplication::viewStatusMessage()
2292 // When meta-fake key is pressed, show the key sequence so far + "M-".
2293 if (d->meta_fake_bit != NoModifier)
2294 return d->keyseq.print(KeySequence::ForGui) + "M-";
2296 // Else, when a non-complete key sequence is pressed,
2297 // show the available options.
2298 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2299 return d->keyseq.printOptions(true);
2305 string GuiApplication::inputLanguageCode() const
2307 #if (QT_VERSION < 0x050000)
2308 QLocale loc = keyboardInputLocale();
2310 QLocale loc = inputMethod()->locale();
2312 //LYXERR0("input lang = " << fromqstr(loc.name()));
2313 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2317 void GuiApplication::onLocaleChanged()
2319 //LYXERR0("Change language to " << inputLanguage()->lang());
2320 if (currentView() && currentView()->currentBufferView())
2321 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2325 void GuiApplication::onPaletteChanged()
2327 colorCache().setPalette(palette());
2331 void GuiApplication::handleKeyFunc(FuncCode action)
2335 if (d->keyseq.length())
2337 GuiView * gv = currentView();
2338 LASSERT(gv && gv->currentBufferView(), return);
2339 BufferView * bv = gv->currentBufferView();
2340 bv->getIntl().getTransManager().deadkey(
2341 c, get_accent(action).accent, bv->cursor().innerText(),
2343 // Need to clear, in case the minibuffer calls these
2346 // copied verbatim from do_accent_char
2347 bv->cursor().resetAnchor();
2351 //Keep this in sync with GuiApplication::processKeySym below
2352 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2353 KeyModifier state) const
2355 // Do nothing if we have nothing
2356 if (!keysym.isOK() || keysym.isModifier())
2358 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2360 FuncRequest func = seq.addkey(keysym, state);
2361 // When not cancel or meta-fake, do the normal lookup.
2362 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2364 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2366 // Maybe user can only reach the key via holding down shift.
2367 // Let's see. But only if shift is the only modifier
2368 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2369 // If addkey looked up a command and did not find further commands then
2370 // seq has been reset at this point
2371 func = seq.addkey(keysym, NoModifier);
2373 LYXERR(Debug::KEY, " Key (queried) [action="
2374 << lyxaction.getActionName(func.action()) << "]["
2375 << seq.print(KeySequence::Portable) << ']');
2376 return func.action() != LFUN_UNKNOWN_ACTION;
2380 //Keep this in sync with GuiApplication::queryKeySym above
2381 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2383 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2385 // Do nothing if we have nothing (JMarc)
2386 if (!keysym.isOK() || keysym.isModifier()) {
2388 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2390 current_view_->restartCaret();
2394 char_type encoded_last_key = keysym.getUCSEncoded();
2396 // Do a one-deep top-level lookup for
2397 // cancel and meta-fake keys. RVDK_PATCH_5
2398 d->cancel_meta_seq.reset();
2400 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2401 LYXERR(Debug::KEY, "action first set to ["
2402 << lyxaction.getActionName(func.action()) << ']');
2404 // When not cancel or meta-fake, do the normal lookup.
2405 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2406 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2407 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2408 // remove Caps Lock and Mod2 as a modifiers
2409 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2410 LYXERR(Debug::KEY, "action now set to ["
2411 << lyxaction.getActionName(func.action()) << ']');
2414 // Don't remove this unless you know what you are doing.
2415 d->meta_fake_bit = NoModifier;
2417 // Can this happen now ?
2418 if (func.action() == LFUN_NOACTION)
2419 func = FuncRequest(LFUN_COMMAND_PREFIX);
2421 LYXERR(Debug::KEY, " Key [action="
2422 << lyxaction.getActionName(func.action()) << "]["
2423 << d->keyseq.print(KeySequence::Portable) << ']');
2425 // already here we know if it any point in going further
2426 // why not return already here if action == -1 and
2427 // num_bytes == 0? (Lgb)
2429 if (d->keyseq.length() > 1 && current_view_)
2430 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2433 // Maybe user can only reach the key via holding down shift.
2434 // Let's see. But only if shift is the only modifier
2435 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2436 LYXERR(Debug::KEY, "Trying without shift");
2437 // If addkey looked up a command and did not find further commands then
2438 // seq has been reset at this point
2439 func = d->keyseq.addkey(keysym, NoModifier);
2440 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2443 if (func.action() == LFUN_UNKNOWN_ACTION) {
2444 // We didn't match any of the key sequences.
2445 // See if it's normal insertable text not already
2446 // covered by a binding
2447 if (keysym.isText() && d->keyseq.length() == 1) {
2448 // Non-printable characters (such as ASCII control characters)
2449 // must not be inserted (#5704)
2450 if (!isPrintable(encoded_last_key)) {
2451 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2453 current_view_->restartCaret();
2456 // The following modifier check is not needed on Mac.
2457 // The keysym is either not text or it is different
2458 // from the non-modifier keysym. See #9875 for the
2459 // broken alt-modifier effect of having this code active.
2460 #if !defined(Q_OS_MAC)
2461 // If a non-Shift Modifier is used we have a non-bound key sequence
2462 // (such as Alt+j = j). This should be omitted (#5575).
2463 // On Windows, AltModifier and ControlModifier are both
2464 // set when AltGr is pressed. Therefore, in order to not
2465 // break AltGr-bound symbols (see #5575 for details),
2466 // unbound Ctrl+Alt key sequences are allowed.
2467 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2468 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2469 && !(state & AltModifier && state & ControlModifier)
2473 if (current_view_) {
2474 current_view_->message(_("Unknown function."));
2475 current_view_->restartCaret();
2480 // Since all checks above were passed, we now really have text that
2481 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2482 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2484 LYXERR(Debug::KEY, "isText() is true, inserting.");
2485 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2487 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2488 if (current_view_) {
2489 current_view_->message(_("Unknown function."));
2490 current_view_->restartCaret();
2496 if (func.action() == LFUN_SELF_INSERT) {
2497 if (encoded_last_key != 0) {
2498 docstring const arg(1, encoded_last_key);
2499 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2500 FuncRequest::KEYBOARD));
2501 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2504 processFuncRequest(func);
2508 void GuiApplication::processFuncRequest(FuncRequest const & func)
2510 lyx::dispatch(func);
2514 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2516 addToFuncRequestQueue(func);
2517 processFuncRequestQueueAsync();
2521 void GuiApplication::processFuncRequestQueue()
2523 while (!d->func_request_queue_.empty()) {
2524 // take the item from the stack _before_ processing the
2525 // request in order to avoid race conditions from nested
2526 // or parallel requests (see #10406)
2527 FuncRequest const fr(d->func_request_queue_.front());
2528 d->func_request_queue_.pop();
2529 processFuncRequest(fr);
2534 void GuiApplication::processFuncRequestQueueAsync()
2536 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2540 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2542 d->func_request_queue_.push(func);
2546 void GuiApplication::resetGui()
2548 // Set the language defined by the user.
2552 if (!readUIFile(toqstr(lyxrc.ui_file)))
2553 // Gives some error box here.
2556 if (d->global_menubar_)
2557 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2559 QHash<int, GuiView *>::iterator it;
2560 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2563 gv->setLayoutDirection(layoutDirection());
2567 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2571 bool GuiApplication::rtlContext() const
2573 if (current_view_ && current_view_->currentBufferView()) {
2574 BufferView const * bv = current_view_->currentBufferView();
2575 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2577 return layoutDirection() == Qt::RightToLeft;
2581 void GuiApplication::createView(int view_id)
2583 createView(QString(), true, view_id);
2587 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2590 // release the keyboard which might have been grabbed by the global
2591 // menubar on Mac to catch shortcuts even without any GuiView.
2592 if (d->global_menubar_)
2593 d->global_menubar_->releaseKeyboard();
2597 while (d->views_.find(id) != d->views_.end())
2600 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2601 GuiView * view = new GuiView(id);
2602 // `view' is the new current_view_. Tell coverity that is is not 0.
2603 LATTEST(current_view_);
2605 d->views_[id] = view;
2609 setActiveWindow(view);
2612 if (!geometry_arg.isEmpty()) {
2613 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2617 #if QT_VERSION < 0x060000
2618 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2619 re.indexIn(geometry_arg);
2620 w = re.cap(1).toInt();
2621 h = re.cap(2).toInt();
2622 x = re.cap(3).toInt();
2623 y = re.cap(4).toInt();
2624 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2625 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2627 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2628 QRegularExpressionMatch match = re.match(geometry_arg);
2629 w = match.captured(1).toInt();
2630 h = match.captured(2).toInt();
2631 x = match.captured(3).toInt();
2632 y = match.captured(4).toInt();
2633 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2634 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2636 // Set initial geometry such that we can get the frame size.
2637 view->setGeometry(x, y, w, h);
2638 int framewidth = view->geometry().x() - view->x();
2639 int titleheight = view->geometry().y() - view->y();
2640 // Negative displacements must be interpreted as distances
2641 // from the right or bottom screen borders.
2642 if (sx == '-' || sy == '-') {
2643 #if QT_VERSION < 0x060000
2644 QRect rec = QApplication::desktop()->screenGeometry();
2646 QRect rec = QGuiApplication::primaryScreen()->geometry();
2649 x += rec.width() - w - framewidth;
2651 y += rec.height() - h - titleheight;
2652 view->setGeometry(x, y, w, h);
2654 // Make sure that the left and top frame borders are visible.
2655 if (view->x() < 0 || view->y() < 0) {
2660 view->setGeometry(x, y, w, h);
2668 bool GuiApplication::unhide(Buffer * buf)
2672 currentView()->setBuffer(buf, false);
2677 Clipboard & GuiApplication::clipboard()
2679 return d->clipboard_;
2683 Selection & GuiApplication::selection()
2685 return d->selection_;
2689 FontLoader & GuiApplication::fontLoader()
2691 return d->font_loader_;
2695 Toolbars const & GuiApplication::toolbars() const
2697 return d->toolbars_;
2701 Toolbars & GuiApplication::toolbars()
2703 return d->toolbars_;
2707 Menus const & GuiApplication::menus() const
2713 Menus & GuiApplication::menus()
2719 bool GuiApplication::needsBackingStore() const
2721 /* Qt on macOS and Wayland does not respect the
2722 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2723 * store at each update. Therefore, we use our own backing store
2724 * in these two cases. It is also possible to force the use of the
2725 * backing store for cases like x11 with transparent WM themes.
2727 return platformName() == "cocoa" || platformName().contains("wayland");
2731 QList<int> GuiApplication::viewIds() const
2733 return d->views_.keys();
2737 ColorCache & GuiApplication::colorCache()
2739 return d->color_cache_;
2743 int GuiApplication::exec()
2745 // asynchronously handle batch commands. This event will be in
2746 // the event queue in front of other asynchronous events. Hence,
2747 // we can assume in the latter that the gui is setup already.
2748 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2750 return QApplication::exec();
2754 void GuiApplication::exit(int status)
2756 QApplication::exit(status);
2760 void GuiApplication::setGuiLanguage()
2764 // install translation file for Qt built-in dialogs
2765 QString const language_name = QString("qt_") + theLocale.name();
2766 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2767 // Short-named translator can be loaded from a long name, but not the
2768 // opposite. Therefore, long name should be used without truncation.
2769 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2770 if (!d->qt_trans_.load(language_name,
2771 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2772 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2774 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2776 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2779 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2783 switch (theLocale.language()) {
2784 case QLocale::Arabic :
2785 case QLocale::Hebrew :
2786 case QLocale::Persian :
2787 case QLocale::Urdu :
2788 setLayoutDirection(Qt::RightToLeft);
2791 setLayoutDirection(Qt::LeftToRight);
2796 void GuiApplication::execBatchCommands()
2801 if (!readUIFile(toqstr(lyxrc.ui_file)))
2802 // Gives some error box here.
2806 #if QT_VERSION > 0x040600
2807 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2809 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2810 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2812 // Create the global default menubar which is shown for the dialogs
2813 // and if no GuiView is visible.
2814 // This must be done after the session was recovered to know the "last files".
2815 d->global_menubar_ = new QMenuBar(0);
2816 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2819 lyx::execBatchCommands();
2823 QAbstractItemModel * GuiApplication::languageModel()
2825 if (d->language_model_)
2826 return d->language_model_;
2828 QStandardItemModel * lang_model = new QStandardItemModel(this);
2829 lang_model->insertColumns(0, 3);
2830 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2831 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2832 Languages::const_iterator it = lyx::languages.begin();
2833 Languages::const_iterator end = lyx::languages.end();
2834 for (; it != end; ++it) {
2835 int current_row = lang_model->rowCount();
2836 lang_model->insertRows(current_row, 1);
2837 QModelIndex pl_item = lang_model->index(current_row, 0);
2838 QModelIndex sp_item = lang_model->index(current_row, 1);
2839 QModelIndex th_item = lang_model->index(current_row, 2);
2840 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2841 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2842 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2843 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2844 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2845 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2846 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2847 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2848 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2849 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2851 d->language_model_ = new QSortFilterProxyModel(this);
2852 d->language_model_->setSourceModel(lang_model);
2853 d->language_model_->setSortLocaleAware(true);
2854 return d->language_model_;
2858 void GuiApplication::restoreGuiSession()
2860 if (!lyxrc.load_session)
2863 Session & session = theSession();
2864 LastOpenedSection::LastOpened const & lastopened =
2865 session.lastOpened().getfiles();
2867 validateCurrentView();
2869 FileName active_file;
2870 // do not add to the lastfile list since these files are restored from
2871 // last session, and should be already there (regular files), or should
2872 // not be added at all (help files).
2873 for (auto const & last : lastopened) {
2874 FileName const & file_name = last.file_name;
2875 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2876 && current_view_->documentBufferView() != nullptr)) {
2877 string const & fname = file_name.absFileName();
2878 createView(support::checksum(fname));
2880 current_view_->loadDocument(file_name, false);
2883 active_file = file_name;
2886 // Restore last active buffer
2887 Buffer * buffer = theBufferList().getBuffer(active_file);
2888 if (buffer && current_view_)
2889 current_view_->setBuffer(buffer);
2891 // clear this list to save a few bytes of RAM
2892 session.lastOpened().clear();
2896 QString const GuiApplication::romanFontName()
2899 font.setStyleHint(QFont::Serif);
2900 font.setFamily("serif");
2902 return QFontInfo(font).family();
2906 QString const GuiApplication::sansFontName()
2909 font.setStyleHint(QFont::SansSerif);
2910 font.setFamily("sans");
2912 return QFontInfo(font).family();
2916 QString const GuiApplication::typewriterFontName()
2918 return QFontInfo(typewriterSystemFont()).family();
2923 // We cannot use QFont::fixedPitch() because it doesn't
2924 // return the fact but only if it is requested.
2925 static bool isFixedPitch(const QFont & font) {
2926 const QFontInfo fi(font);
2927 return fi.fixedPitch();
2932 QFont const GuiApplication::typewriterSystemFont()
2934 #if QT_VERSION >= 0x050200
2935 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2937 QFont font("monospace");
2939 if (!isFixedPitch(font)) {
2940 // try to enforce a real monospaced font
2941 font.setStyleHint(QFont::Monospace);
2942 if (!isFixedPitch(font)) {
2943 font.setStyleHint(QFont::TypeWriter);
2944 if (!isFixedPitch(font)) font.setFamily("courier");
2948 // On a Mac the result is too small and it's not practical to
2949 // rely on Qtconfig utility to change the system settings of Qt.
2950 font.setPointSize(12);
2956 void GuiApplication::handleRegularEvents()
2958 ForkedCallsController::handleCompletedProcesses();
2962 bool GuiApplication::event(QEvent * e)
2965 case QEvent::FileOpen: {
2966 // Open a file; this happens only on Mac OS X for now.
2968 // We do this asynchronously because on startup the batch
2969 // commands are not executed here yet and the gui is not ready
2971 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2972 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2973 processFuncRequestAsync(fr);
2977 #if (QT_VERSION < 0x050000)
2978 // Qt5 uses a signal for that, see above.
2979 case QEvent::KeyboardLayoutChange:
2980 //LYXERR0("keyboard change");
2981 if (currentView() && currentView()->currentBufferView())
2982 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2986 case QEvent::ApplicationPaletteChange: {
2987 // runtime switch from/to dark mode
2989 return QApplication::event(e);
2992 return QApplication::event(e);
2997 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3000 return QApplication::notify(receiver, event);
3002 catch (ExceptionMessage const & e) {
3004 case ErrorException:
3006 setQuitOnLastWindowClosed(false);
3008 Alert::error(e.title_, e.details_);
3010 // Properly crash in debug mode in order to get a useful backtrace.
3013 // In release mode, try to exit gracefully.
3015 // FIXME: GCC 7 thinks we can fall through here. Can we?
3017 case BufferException: {
3018 if (!current_view_ || !current_view_->documentBufferView())
3020 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3021 docstring details = e.details_ + '\n';
3022 details += buf->emergencyWrite();
3023 theBufferList().release(buf);
3024 details += "\n" + _("The current document was closed.");
3025 Alert::error(e.title_, details);
3028 case WarningException:
3029 Alert::warning(e.title_, e.details_);
3033 catch (exception const & e) {
3034 docstring s = _("LyX has caught an exception, it will now "
3035 "attempt to save all unsaved documents and exit."
3037 s += from_ascii(e.what());
3038 Alert::error(_("Software exception Detected"), s);
3042 docstring s = _("LyX has caught some really weird exception, it will "
3043 "now attempt to save all unsaved documents and exit.");
3044 Alert::error(_("Software exception Detected"), s);
3051 bool GuiApplication::isInDarkMode()
3053 return colorCache().isDarkMode();
3057 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3059 QColor const & qcol = d->color_cache_.get(col);
3060 if (!qcol.isValid()) {
3066 rgbcol.r = qcol.red();
3067 rgbcol.g = qcol.green();
3068 rgbcol.b = qcol.blue();
3073 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3075 QColor const qcol(lcolor.getX11HexName(col).c_str());
3076 if (!qcol.isValid()) {
3082 rgbcol.r = qcol.red();
3083 rgbcol.g = qcol.green();
3084 rgbcol.b = qcol.blue();
3089 string const GuiApplication::hexName(ColorCode col)
3091 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3095 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3097 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3098 d->socket_notifiers_[fd] = sn;
3099 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3103 void GuiApplication::socketDataReceived(int fd)
3105 d->socket_notifiers_[fd]->func_();
3109 void GuiApplication::unregisterSocketCallback(int fd)
3111 d->socket_notifiers_.take(fd)->setEnabled(false);
3115 void GuiApplication::commitData(QSessionManager & sm)
3117 /** The implementation is required to avoid an application exit
3118 ** when session state save is triggered by session manager.
3119 ** The default implementation sends a close event to all
3120 ** visible top level widgets when session management allows
3122 ** We are changing that to check the state of each buffer in all
3123 ** views and ask the users what to do if buffers are dirty.
3124 ** Furthermore, we save the session state.
3125 ** We do NOT close the views here since the user still can cancel
3126 ** the logout process (see #9277); also, this would hide LyX from
3127 ** an OSes own session handling (application restoration).
3129 #ifdef QT_NO_SESSIONMANAGER
3131 #warning Qt is compiled without session manager
3133 #pragma message("warning: Qt is compiled without session manager")
3137 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3145 void GuiApplication::unregisterView(GuiView * gv)
3147 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3148 d->views_.remove(gv->id());
3149 if (current_view_ == gv)
3150 current_view_ = nullptr;
3155 bool GuiApplication::closeAllViews()
3157 if (d->views_.empty())
3160 // When a view/window was closed before without quitting LyX, there
3161 // are already entries in the lastOpened list.
3162 theSession().lastOpened().clear();
3164 QList<GuiView *> const views = d->views_.values();
3165 for (GuiView * view : views) {
3166 if (!view->closeScheduled())
3175 bool GuiApplication::prepareAllViewsForLogout()
3177 if (d->views_.empty())
3180 QList<GuiView *> const views = d->views_.values();
3181 for (GuiView * view : views) {
3182 if (!view->prepareAllBuffersForLogout())
3190 GuiView & GuiApplication::view(int id) const
3192 LAPPERR(d->views_.contains(id));
3193 return *d->views_.value(id);
3197 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3199 QList<GuiView *> const views = d->views_.values();
3200 for (GuiView * view : views)
3201 view->hideDialog(name, inset);
3205 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3207 Buffer const * buf = nullptr;
3208 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3209 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3210 if (Buffer const * ptr = (*it)->updateInset(inset))
3217 bool GuiApplication::searchMenu(FuncRequest const & func,
3218 docstring_list & names) const
3220 BufferView * bv = nullptr;
3222 bv = current_view_->currentBufferView();
3223 return d->menus_.searchMenu(func, names, bv);
3227 bool GuiApplication::hasBufferView() const
3229 return (current_view_ && current_view_->currentBufferView());
3233 // Ensure that a file is read only once (prevents include loops)
3234 static QStringList uifiles;
3235 // store which ui files define Toolbars
3236 static QStringList toolbar_uifiles;
3239 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3250 LexerKeyword uitags[] = {
3251 { "format", ui_format },
3252 { "include", ui_include },
3253 { "menuset", ui_menuset },
3254 { "toolbars", ui_toolbars },
3255 { "toolbarset", ui_toolbarset }
3259 lex.setFile(ui_path);
3261 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3265 if (lyxerr.debugging(Debug::PARSER))
3266 lex.printTable(lyxerr);
3269 // format before introduction of format tag
3270 unsigned int format = 0;
3271 while (lex.isOK()) {
3272 int const status = lex.lex();
3274 // we have to do this check here, outside the switch,
3275 // because otherwise we would start reading include files,
3276 // e.g., if the first tag we hit was an include tag.
3277 if (status == ui_format)
3279 format = lex.getInteger();
3283 // this will trigger unless the first tag we hit is a format
3284 // tag, with the right format.
3285 if (format != LFUN_FORMAT)
3286 return FormatMismatch;
3289 case Lexer::LEX_FEOF:
3294 QString const file = toqstr(lex.getString());
3295 bool const success = readUIFile(file, true);
3297 LYXERR0("Failed to read included file: " << fromqstr(file));
3304 d->menus_.read(lex);
3308 d->toolbars_.readToolbars(lex);
3312 d->toolbars_.readToolbarSettings(lex);
3313 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3317 if (!rtrim(lex.getString()).empty())
3318 lex.printError("LyX::ReadUIFile: "
3319 "Unknown menu tag: `$$Token'");
3321 LYXERR0("Error with status: " << status);
3327 return (error ? ReadError : ReadOK);
3331 bool GuiApplication::readUIFile(QString const & name, bool include)
3333 LYXERR(Debug::INIT, "About to read " << name << "...");
3337 ui_path = libFileSearch("ui", name, "inc");
3338 if (ui_path.empty())
3339 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3341 ui_path = libFileSearch("ui", name, "ui");
3344 if (ui_path.empty()) {
3345 static const QString defaultUIFile = "default";
3346 LYXERR(Debug::INIT, "Could not find " << name);
3348 Alert::warning(_("Could not find UI definition file"),
3349 bformat(_("Error while reading the included file\n%1$s\n"
3350 "Please check your installation."), qstring_to_ucs4(name)));
3353 if (name == defaultUIFile) {
3354 LYXERR(Debug::INIT, "Could not find default UI file!!");
3355 Alert::warning(_("Could not find default UI file"),
3356 _("LyX could not find the default UI file!\n"
3357 "Please check your installation."));
3360 Alert::warning(_("Could not find UI definition file"),
3361 bformat(_("Error while reading the configuration file\n%1$s\n"
3362 "Falling back to default.\n"
3363 "Please look under Tools>Preferences>User Interface and\n"
3364 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3365 return readUIFile(defaultUIFile, false);
3368 QString const uifile = toqstr(ui_path.absFileName());
3369 if (uifiles.contains(uifile)) {
3371 // We are reading again the top uifile so reset the safeguard:
3374 d->toolbars_.reset();
3376 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3377 << "Is this an include loop?");
3381 uifiles.push_back(uifile);
3383 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3385 ReturnValues retval = readUIFile(ui_path);
3387 if (retval == FormatMismatch) {
3388 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3389 TempFile tmp("convertXXXXXX.ui");
3390 FileName const tempfile = tmp.name();
3391 bool const success = prefs2prefs(ui_path, tempfile, true);
3393 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3394 " to format " << LFUN_FORMAT << ".");
3396 retval = readUIFile(tempfile);
3400 if (retval != ReadOK) {
3401 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3409 settings.beginGroup("ui_files");
3410 bool touched = false;
3411 for (int i = 0; i != uifiles.size(); ++i) {
3412 QFileInfo fi(uifiles[i]);
3413 QDateTime const date_value = fi.lastModified();
3414 QString const name_key = QString::number(i);
3415 // if an ui file which defines Toolbars has changed,
3416 // we have to reset the settings
3417 if (toolbar_uifiles.contains(uifiles[i])
3418 && (!settings.contains(name_key)
3419 || settings.value(name_key).toString() != uifiles[i]
3420 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3422 settings.setValue(name_key, uifiles[i]);
3423 settings.setValue(name_key + "/date", date_value);
3426 settings.endGroup();
3428 settings.remove("views");
3434 void GuiApplication::onLastWindowClosed()
3436 if (d->global_menubar_)
3437 d->global_menubar_->grabKeyboard();
3441 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3442 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3444 std::string name = "unknown";
3446 case Qt::ApplicationSuspended:
3447 name = "ApplicationSuspended";
3449 case Qt::ApplicationHidden:
3450 name = "ApplicationHidden";
3452 case Qt::ApplicationInactive:
3453 name = "ApplicationInactive";
3455 case Qt::ApplicationActive:
3456 name = "ApplicationActive";
3457 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3458 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3459 if (d->views_.empty() && d->last_state_ == state) {
3460 LYXERR(Debug::GUI, "Open new window...");
3465 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3466 d->last_state_ = state;
3471 void GuiApplication::startLongOperation() {
3472 d->key_checker_.start();
3476 bool GuiApplication::longOperationCancelled() {
3477 return d->key_checker_.pressed();
3481 void GuiApplication::stopLongOperation() {
3482 d->key_checker_.stop();
3486 bool GuiApplication::longOperationStarted() {
3487 return d->key_checker_.started();
3491 ////////////////////////////////////////////////////////////////////////
3493 // X11 specific stuff goes here...
3496 bool GuiApplication::x11EventFilter(XEvent * xev)
3501 switch (xev->type) {
3502 case SelectionRequest: {
3503 if (xev->xselectionrequest.selection != XA_PRIMARY)
3505 LYXERR(Debug::SELECTION, "X requested selection.");
3506 BufferView * bv = current_view_->currentBufferView();
3508 docstring const sel = bv->requestSelection();
3510 d->selection_.put(sel);
3511 // Refresh the selection request timestamp.
3512 // We have to do this by ourselves as Qt seems
3513 // not doing that, maybe because of our
3514 // "persistent selection" implementation
3515 // (see comments in GuiSelection.cpp).
3516 XSelectionEvent nev;
3517 nev.type = SelectionNotify;
3518 nev.display = xev->xselectionrequest.display;
3519 nev.requestor = xev->xselectionrequest.requestor;
3520 nev.selection = xev->xselectionrequest.selection;
3521 nev.target = xev->xselectionrequest.target;
3522 nev.property = 0L; // None
3523 nev.time = CurrentTime;
3524 XSendEvent(QX11Info::display(),
3525 nev.requestor, False, 0,
3526 reinterpret_cast<XEvent *>(&nev));
3532 case SelectionClear: {
3533 if (xev->xselectionclear.selection != XA_PRIMARY)
3535 LYXERR(Debug::SELECTION, "Lost selection.");
3536 BufferView * bv = current_view_->currentBufferView();
3538 bv->clearSelection();
3544 #elif defined(QPA_XCB)
3545 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3546 void * message, long *)
3548 if (!current_view_ || eventType != "xcb_generic_event_t")
3551 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3553 switch (ev->response_type) {
3554 case XCB_SELECTION_REQUEST: {
3555 xcb_selection_request_event_t * srev =
3556 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3557 if (srev->selection != XCB_ATOM_PRIMARY)
3559 LYXERR(Debug::SELECTION, "X requested selection.");
3560 BufferView * bv = current_view_->currentBufferView();
3562 docstring const sel = bv->requestSelection();
3564 d->selection_.put(sel);
3565 #ifdef HAVE_QT5_X11_EXTRAS
3566 // Refresh the selection request timestamp.
3567 // We have to do this by ourselves as Qt seems
3568 // not doing that, maybe because of our
3569 // "persistent selection" implementation
3570 // (see comments in GuiSelection.cpp).
3571 // It is expected that every X11 event is
3572 // 32 bytes long, even if not all 32 bytes are
3574 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3575 struct alignas(32) padded_event
3576 : xcb_selection_notify_event_t {};
3577 padded_event nev = {};
3578 nev.response_type = XCB_SELECTION_NOTIFY;
3579 nev.requestor = srev->requestor;
3580 nev.selection = srev->selection;
3581 nev.target = srev->target;
3582 nev.property = XCB_NONE;
3583 nev.time = XCB_CURRENT_TIME;
3584 xcb_connection_t * con = QX11Info::connection();
3585 xcb_send_event(con, 0, srev->requestor,
3586 XCB_EVENT_MASK_NO_EVENT,
3587 reinterpret_cast<char const *>(&nev));
3595 case XCB_SELECTION_CLEAR: {
3596 xcb_selection_clear_event_t * scev =
3597 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3598 if (scev->selection != XCB_ATOM_PRIMARY)
3600 LYXERR(Debug::SELECTION, "Lost selection.");
3601 BufferView * bv = current_view_->currentBufferView();
3603 bv->clearSelection();
3611 } // namespace frontend
3614 void hideDialogs(std::string const & name, Inset * inset)
3617 frontend::guiApp->hideDialogs(name, inset);
3621 ////////////////////////////////////////////////////////////////////
3625 ////////////////////////////////////////////////////////////////////
3627 frontend::FontLoader & theFontLoader()
3629 LAPPERR(frontend::guiApp);
3630 return frontend::guiApp->fontLoader();
3634 frontend::FontMetrics const & theFontMetrics(Font const & f)
3636 return theFontMetrics(f.fontInfo());
3640 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3642 LAPPERR(frontend::guiApp);
3643 return frontend::guiApp->fontLoader().metrics(f);
3647 ////////////////////////////////////////////////////////////////////
3651 ////////////////////////////////////////////////////////////////////
3653 frontend::Clipboard & theClipboard()
3655 LAPPERR(frontend::guiApp);
3656 return frontend::guiApp->clipboard();
3660 frontend::Selection & theSelection()
3662 LAPPERR(frontend::guiApp);
3663 return frontend::guiApp->selection();
3669 #include "moc_GuiApplication.cpp"