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 < 0x060000)
141 #if (QT_VERSION < 0x050000)
142 #include <QWindowsMime>
143 #define QWINDOWSMIME QWindowsMime
146 #define QWINDOWSMIME QWinMime
156 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
157 #include <QMacPasteboardMime>
165 using namespace lyx::support;
170 frontend::Application * createApplication(int & argc, char * argv[])
172 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
173 // prune -geometry argument(s) by shifting
174 // the following ones 2 places down.
175 for (int i = 0 ; i < argc ; ++i) {
176 if (strcmp(argv[i], "-geometry") == 0) {
177 int const remove = (i+1) < argc ? 2 : 1;
179 for (int j = i; j < argc; ++j)
180 argv[j] = argv[j + remove];
186 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
187 // On Windows, allow bringing the LyX window to top
188 AllowSetForegroundWindow(ASFW_ANY);
192 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
193 // macOS does it by itself.
194 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
195 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
196 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
197 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
198 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
199 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
202 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
203 // HighDPI scale factor policy must be set before QGuiApplication is created
204 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
205 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
209 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
210 // I'd rather do that in the constructor, but I do not think that
211 // the palette is accessible there.
212 guiApp->colorCache().setPalette(guiApp->palette());
221 if (lyxrc.gui_language == "auto") {
222 theLocale = QLocale::system();
223 code = fromqstr(theLocale.name());
225 Language const * l = languages.getLanguage(lyxrc.gui_language);
226 code = l ? l->code() : "C";
227 theLocale = QLocale(toqstr(code));
229 // Qt tries to outsmart us and transforms en_US to C.
230 Messages::guiLanguage((code == "C") ? "en_US" : code);
231 QLocale::setDefault(theLocale);
232 setlocale(LC_NUMERIC, "C");
239 /// Return the list of loadable formats.
240 vector<string> loadableImageFormats()
244 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
246 LYXERR(Debug::GRAPHICS,
247 "\nThe image loader can load the following directly:\n");
249 if (qt_formats.empty())
250 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
252 bool jpeg_found = false;
253 bool jpg_found = false;
254 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
256 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
258 string ext = ascii_lowercase((const char *) *it);
266 else if (ext == "jpg") {
271 else if (lyxrc.use_converter_cache &&
272 (ext == "svg" || ext == "svgz") &&
273 theConverters().isReachable("svg", "png"))
274 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
275 // the SVG as in the output. However we require that the converter
276 // cache is enabled since this is expensive. We also require that
277 // an explicit svg->png converter is defined, since the default
278 // converter could produce bad quality as well. This assumes that
279 // png can always be loaded.
288 ////////////////////////////////////////////////////////////////////////
290 // Icon loading support code
292 ////////////////////////////////////////////////////////////////////////
302 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
304 return lhs.key < rhs.key;
310 CompareKey(QString const & name) : name_(name) {}
311 bool operator()(ImgMap const & other) const { return other.key == name_; }
317 // this must be sorted alphabetically
318 // Upper case comes before lower case
319 // Please don't change the formatting, this list is parsed by
320 // development/tools/generate_symbols_images.py.
321 ImgMap sorted_img_map[] = {
322 { "Arrownot", "arrownot2"},
323 { "Arrowvert", "arrowvert2"},
324 { "Bowtie", "bowtie2" },
326 { "Bumpeq", "bumpeq2" },
327 { "CIRCLE", "circle3" },
329 { "CheckedBox", "checkedbox2" },
330 { "Circle", "circle2" },
331 { "Colonapprox", "colonapprox2" },
332 { "Coloneq", "coloneq2" },
333 { "Coloneqq", "coloneqq2" },
334 { "Colonsim", "colonsim2" },
336 { "DOWNarrow", "downarrow3" },
337 { "Delta", "delta2" },
338 { "Diamond", "diamond2" },
339 { "Doteq", "doteq2" },
340 { "Downarrow", "downarrow2" },
341 { "Eqcolon", "eqcolon2" },
342 { "Eqqcolon", "eqqcolon2" },
343 { "Gamma", "gamma2" },
345 { "LEFTCIRCLE", "leftcircle3" },
346 { "LEFTarrow", "leftarrow3" },
347 { "LEFTcircle", "leftcircle4" },
349 { "Lambda", "lambda2" },
351 { "Leftarrow", "leftarrow2" },
352 { "Leftcircle", "leftcircle2" },
353 { "Leftrightarrow", "leftrightarrow2" },
354 { "Longarrownot", "longarrownot2"},
355 { "Longleftarrow", "longleftarrow2" },
356 { "Longleftrightarrow", "longleftrightarrow2" },
357 { "Longmapsfrom", "longmapsfrom2"},
358 { "Longmapsto", "longmapsto2"},
359 { "Longrightarrow", "longrightarrow2" },
360 { "Mapsfrom", "mapsfrom2"},
361 { "Mapsfromchar", "mapsfromchar2"},
362 { "Mapsto", "mapsto2"},
363 { "Mapstochar", "mapstochar2"},
364 { "Omega", "omega2" },
369 { "RIGHTCIRCLE", "rightcircle3" },
370 { "RIGHTarrow", "rightarrow3" },
371 { "RIGHTcircle", "rightcircle4" },
373 { "Rightarrow", "rightarrow2" },
374 { "Rightcircle", "rightcircle2" },
375 { "Sigma", "sigma2" },
376 { "Square", "square2" },
377 { "Subset", "subset2" },
378 { "Supset", "supset2" },
379 { "Theta", "theta2" },
380 { "Thorn", "thorn2" },
381 { "UParrow", "uparrow3" },
382 { "Uparrow", "uparrow2" },
383 { "Updownarrow", "updownarrow2" },
384 { "Upsilon", "upsilon2" },
385 { "Vdash", "vdash3" },
390 { "lVert", "vert2" },
392 { "nLeftarrow", "nleftarrow2" },
393 { "nLeftrightarrow", "nleftrightarrow2" },
394 { "nRightarrow", "nrightarrow2" },
395 { "nVDash", "nvdash3" },
396 { "nVdash", "nvdash4" },
397 { "nvDash", "nvdash2" },
398 { "rVert", "vert2" },
400 { "textrm \\AA", "textrm_AA"},
401 { "textrm \\O", "textrm_O"},
402 { "vDash", "vdash2" },
403 { "varDelta", "vardelta2" },
404 { "varGamma", "vargamma2" },
405 { "varLambda", "varlambda2" },
406 { "varOmega", "varomega2" },
407 { "varPhi", "varphi2" },
408 { "varPi", "varpi2" },
409 { "varPsi", "varpsi2" },
410 { "varSigma", "varsigma2" },
411 { "varTheta", "vartheta2" },
412 { "varUpsilon", "varupsilon2" },
413 { "varXi", "varxi2" }
417 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
419 // This list specifies which system's theme icon is related to which lyx
420 // command. It was based on:
421 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
422 // this must be sorted alphabetically
423 // Upper case comes before lower case
424 ImgMap sorted_theme_icon_map[] = {
425 { "bookmark-goto 0", "go-jump" },
426 { "buffer-new", "document-new" },
427 { "buffer-write", "document-save" },
428 { "buffer-write-as", "document-save-as" },
429 { "buffer-zoom-in", "zoom-in" },
430 { "buffer-zoom-out", "zoom-out" },
431 { "copy", "edit-copy" },
432 { "cut", "edit-cut" },
433 { "depth-decrement", "format-indent-less" },
434 { "depth-increment", "format-indent-more" },
435 { "dialog-show spellchecker", "tools-check-spelling" },
436 { "dialog-show-new-inset graphics", "insert-image" },
437 { "dialog-toggle findreplaceadv", "edit-find-replace" },
438 { "file-open", "document-open" },
439 { "font-bold", "format-text-bold" },
440 { "font-ital", "format-text-italic" },
441 { "font-strikeout", "format-text-strikethrough" },
442 { "font-underline", "format-text-underline" },
443 { "lyx-quit", "application-exit" },
444 { "paste", "edit-paste" },
445 { "redo", "edit-redo" },
446 { "undo", "edit-undo" },
447 { "window-close", "window-close" },
448 { "window-new", "window-new" }
451 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
454 QString findImg(QString const & name)
456 ImgMap const * const begin = sorted_img_map;
457 ImgMap const * const end = begin + nr_sorted_img_map;
458 LATTEST(sorted(begin, end));
460 ImgMap const * const it = find_if(begin, end, CompareKey(name));
464 img_name = it->value;
467 img_name.replace('_', "underscore");
468 img_name.replace(' ', '_');
470 // This way we can have "math-delim { }" on the toolbar.
471 img_name.replace('(', "lparen");
472 img_name.replace(')', "rparen");
473 img_name.replace('[', "lbracket");
474 img_name.replace(']', "rbracket");
475 img_name.replace('{', "lbrace");
476 img_name.replace('}', "rbrace");
477 img_name.replace('|', "bars");
478 img_name.replace(',', "thinspace");
479 img_name.replace(':', "mediumspace");
480 img_name.replace(';', "thickspace");
481 img_name.replace('!', "negthinspace");
484 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
485 << "Looking for math icon called \"" << img_name << '"');
492 QString themeIconName(QString const & action)
494 ImgMap const * const begin = sorted_theme_icon_map;
495 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
496 LASSERT(sorted(begin, end), /**/);
498 ImgMap const * const it = find_if(begin, end, CompareKey(action));
506 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
511 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
513 if (!f.argument().empty()) {
514 // if there are arguments, first search an icon which name is the full thing
515 QString name = lfunname + ' ' + toqstr(f.argument());
516 name.replace(' ', '_');
517 name.replace(';', '_');
518 name.replace('\\', "backslash");
519 // avoid duplication for these
520 name.replace("dialog-toggle", "dialog-show");
523 // then special default icon for some lfuns
524 switch (f.action()) {
525 case LFUN_MATH_INSERT:
526 names << "math/" + findImg(toqstr(f.argument()).mid(1));
528 case LFUN_MATH_DELIM:
529 case LFUN_MATH_BIGDELIM:
530 names << "math/" + findImg(toqstr(f.argument()));
533 names << "commands/" + toqstr(f.argument());
535 case LFUN_COMMAND_ALTERNATIVES: {
536 // use the first of the alternative commands
538 docstring dummy = split(f.argument(), firstcom, ';');
539 QString name1 = toqstr(firstcom);
540 name1.replace(' ', '_');
541 name1.replace(';', '_');
542 name1.replace('\\', "backslash");
551 // next thing to try is function name alone
554 // and finally maybe the unknown icon
558 search_mode const mode = theGuiApp()->imageSearchMode();
559 // The folders where icons are searched for
560 QStringList imagedirs;
561 imagedirs << "images/ipa/" << "images/";
562 // This is used to search for rtl version of icons which have the +rrtl suffix.
563 QStringList suffixes;
566 suffixes << QString();
568 for (QString const & imagedir : imagedirs)
569 for (QString const & name : names)
570 for (QString const & suffix : suffixes) {
571 QString id = imagedir;
572 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
573 if (fname.exists()) {
574 docstring const fpath = fname.absoluteFilePath();
575 res.filepath = toqstr(fname.absFileName());
576 // these icons are subject to inversion in dark mode
577 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
578 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
579 res.swap = rtl && suffix.isEmpty();
584 LYXERR(Debug::GUI, "Cannot find icon for command \""
585 << lyxaction.getActionName(f.action())
586 << '(' << to_utf8(f.argument()) << ")\"");
592 QPixmap prepareForDarkMode(QPixmap pixmap)
594 QPalette palette = QPalette();
595 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
596 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
598 // guess whether we are in dark mode
599 if (text_color.black() > bg_color.black())
600 // not in dark mode, do nothing
603 // create a layer with black text turned to QPalette::WindowText
604 QPixmap black_overlay(pixmap.size());
605 black_overlay.fill(text_color);
606 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
608 // create a layer with blue text turned to lighter blue
609 QPixmap blue_overlay(pixmap.size());
610 QColor math_blue(0, 0, 255);
611 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
612 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
614 // create a layer with ("latex") red text turned to lighter red
615 QPixmap red_overlay(pixmap.size());
616 QColor math_red(128, 0, 0);
617 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
618 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
620 // put layers on top of existing pixmap
621 QPainter painter(&pixmap);
622 painter.drawPixmap(pixmap.rect(), black_overlay);
623 painter.drawPixmap(pixmap.rect(), blue_overlay);
624 painter.drawPixmap(pixmap.rect(), red_overlay);
630 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
632 QString imagedir = path;
633 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
634 QString fpath = toqstr(fname.absFileName());
635 QPixmap pixmap = QPixmap();
637 if (pixmap.load(fpath)) {
638 if (fpath.contains("math") || fpath.contains("ipa")
639 || fpath.contains("bullets"))
640 return prepareForDarkMode(pixmap);
644 bool const list = ext.contains(",");
645 LYXERR(Debug::GUI, "Cannot load pixmap \""
646 << path << "/" << name << "." << (list ? "{" : "") << ext
647 << (list ? "}" : "") << "\".");
653 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
655 #if (QT_VERSION >= 0x040600)
656 if (lyxrc.use_system_theme_icons) {
657 // use the icons from system theme that are available
658 QString action = toqstr(lyxaction.getActionName(f.action()));
659 if (!f.argument().empty())
660 action += " " + toqstr(f.argument());
661 QString const theme_icon = themeIconName(action);
662 if (QIcon::hasThemeIcon(theme_icon)) {
663 QIcon const thmicn = QIcon::fromTheme(theme_icon);
664 if (!thmicn.isNull())
670 IconInfo icondata = iconInfo(f, unknown, rtl);
671 if (icondata.filepath.isEmpty())
674 //LYXERR(Debug::GUI, "Found icon: " << icon);
675 QPixmap pixmap = QPixmap();
676 if (!pixmap.load(icondata.filepath)) {
677 LYXERR0("Cannot load icon " << icondata.filepath << ".");
682 pixmap = prepareForDarkMode(pixmap);
685 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
687 return QIcon(pixmap);
691 ////////////////////////////////////////////////////////////////////////
693 // LyX server support code.
695 ////////////////////////////////////////////////////////////////////////
697 class SocketNotifier : public QSocketNotifier
700 /// connect a connection notification from the LyXServerSocket
701 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
702 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
706 /// The callback function
707 Application::SocketCallback func_;
711 class GuiTranslator : public QTranslator
714 GuiTranslator(QObject * parent = nullptr)
715 : QTranslator(parent)
718 QString translate(const char * /* context */,
719 const char *sourceText,
720 #if QT_VERSION >= 0x050000
721 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
723 const char * /*comment*/ = 0) const override
726 // Here we declare the strings that need to be translated from Qt own GUI
727 // This is needed to include these strings to po files
731 _("Restore Defaults");
734 // Already in po: "Cancel", "&Cancel"
735 _("Apply"); // Already in po: "&Apply"
736 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
739 docstring s = getGuiMessages().getIfFound(sourceText);
740 // This test should eventually be removed when translations are updated
742 LYXERR(Debug::LOCALE, "Missing translation for `"
743 << string(sourceText) << "'");
749 ////////////////////////////////////////////////////////////////////////
751 // Mac specific stuff goes here...
753 ////////////////////////////////////////////////////////////////////////
755 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
756 // QMacPasteboardMimeGraphics can only be compiled on Mac.
758 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
761 QMacPasteboardMimeGraphics()
762 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
765 QString convertorName() { return "Graphics"; }
767 QString flavorFor(QString const & mime)
769 LYXERR(Debug::ACTION, "flavorFor " << mime);
770 if (mime == pdfMimeType())
771 return QLatin1String("com.adobe.pdf");
775 QString mimeFor(QString flav)
777 LYXERR(Debug::ACTION, "mimeFor " << flav);
778 if (flav == QLatin1String("com.adobe.pdf"))
779 return pdfMimeType();
783 bool canConvert(QString const & mime, QString flav)
785 return mimeFor(flav) == mime;
788 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
792 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
796 QList<QByteArray> convertFromMime(QString const & /*mime*/,
797 QVariant data, QString /*flav*/)
799 QList<QByteArray> ret;
800 ret.append(data.toByteArray());
806 ///////////////////////////////////////////////////////////////
808 // You can find more platform specific stuff at the end of this file...
810 ///////////////////////////////////////////////////////////////
812 ////////////////////////////////////////////////////////////////////////
813 // Windows specific stuff goes here...
815 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400 && QT_VERSION < 0x060000)
816 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
817 // QWindowsMimeMetafile can only be compiled on Windows.
819 static FORMATETC cfFromMime(QString const & mimetype)
822 if (mimetype == emfMimeType()) {
823 formatetc.cfFormat = CF_ENHMETAFILE;
824 formatetc.tymed = TYMED_ENHMF;
825 } else if (mimetype == wmfMimeType()) {
826 formatetc.cfFormat = CF_METAFILEPICT;
827 formatetc.tymed = TYMED_MFPICT;
830 formatetc.dwAspect = DVASPECT_CONTENT;
831 formatetc.lindex = -1;
836 class QWindowsMimeMetafile : public QWINDOWSMIME {
838 QWindowsMimeMetafile() {}
840 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
841 QMimeData const * /*mimedata*/) const override
846 bool canConvertToMime(QString const & mimetype,
847 IDataObject * pDataObj) const override
849 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
851 FORMATETC formatetc = cfFromMime(mimetype);
852 return pDataObj->QueryGetData(&formatetc) == S_OK;
855 bool convertFromMime(FORMATETC const & /*formatetc*/,
856 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
861 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
862 QVariant::Type /*preferredType*/) const override
865 if (!canConvertToMime(mimetype, pDataObj))
868 FORMATETC formatetc = cfFromMime(mimetype);
870 if (pDataObj->GetData(&formatetc, &s) != S_OK)
874 if (s.tymed == TYMED_ENHMF) {
875 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
876 data.resize(dataSize);
877 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
878 (LPBYTE)data.data());
879 } else if (s.tymed == TYMED_MFPICT) {
880 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
881 data.resize(dataSize);
882 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
883 (LPBYTE)data.data());
886 ReleaseStgMedium(&s);
892 QVector<FORMATETC> formatsForMime(QString const & mimetype,
893 QMimeData const * /*mimedata*/) const override
895 QVector<FORMATETC> formats;
896 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
897 formats += cfFromMime(mimetype);
901 QString mimeForFormat(FORMATETC const & formatetc) const override
903 switch (formatetc.cfFormat) {
905 return emfMimeType();
906 case CF_METAFILEPICT:
907 return wmfMimeType();
917 /// Allows to check whether ESC was pressed during a long operation
918 class KeyChecker : public QObject {
923 KeyChecker() : pressed_(false), started_(false) {}
926 QCoreApplication::instance()->installEventFilter(this);
931 QCoreApplication::instance()->removeEventFilter(this);
935 QCoreApplication::processEvents();
938 bool started() const {
941 bool eventFilter(QObject *obj, QEvent *event) override {
942 LYXERR(Debug::ACTION, "Event Type: " << event->type());
943 switch (event->type()) {
947 case QEvent::UpdateRequest:
948 case QEvent::CursorChange:
949 case QEvent::ActionChanged:
950 case QEvent::EnabledChange:
951 case QEvent::SockAct:
954 case QEvent::ToolTipChange:
955 case QEvent::LayoutRequest:
956 case QEvent::MetaCall:
957 return QObject::eventFilter(obj, event);
959 // FIXME Blocking all these events is a bad idea.
960 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
961 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
969 ////////////////////////////////////////////////////////////////////////
970 // GuiApplication::Private definition and implementation.
971 ////////////////////////////////////////////////////////////////////////
973 struct GuiApplication::Private
975 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
976 global_menubar_(nullptr)
977 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
978 , last_state_(Qt::ApplicationInactive)
981 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400 && QT_VERSION < 0x060000)
982 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
983 /// WMF Mime handler for Windows clipboard.
984 wmf_mime_ = new QWindowsMimeMetafile;
987 initKeySequences(&theTopLevelKeymap());
990 void initKeySequences(KeyMap * kb)
992 keyseq = KeySequence(kb, kb);
993 cancel_meta_seq = KeySequence(kb, kb);
997 QSortFilterProxyModel * language_model_;
999 GuiClipboard clipboard_;
1001 GuiSelection selection_;
1003 FontLoader font_loader_;
1005 ColorCache color_cache_;
1006 /// the built-in Qt translation mechanism
1007 QTranslator qt_trans_;
1008 /// LyX gettext-based translation for Qt elements
1009 GuiTranslator gui_trans_;
1011 QHash<int, SocketNotifier *> socket_notifiers_;
1015 /// The global instance
1018 /// this timer is used for any regular events one wants to
1019 /// perform. at present it is used to check if forked processes
1021 QTimer general_timer_;
1023 /// delayed FuncRequests
1024 std::queue<FuncRequest> func_request_queue_;
1029 KeySequence cancel_meta_seq;
1031 KeyModifier meta_fake_bit;
1033 /// The result of last dispatch action
1034 DispatchResult dispatch_result_;
1036 /// Multiple views container.
1038 * Warning: This must not be a smart pointer as the destruction of the
1039 * object is handled by Qt when the view is closed
1040 * \sa Qt::WA_DeleteOnClose attribute.
1042 QHash<int, GuiView *> views_;
1044 /// Only used on mac.
1045 QMenuBar * global_menubar_;
1046 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1047 /// Holds previous application state on Mac
1048 Qt::ApplicationState last_state_;
1051 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1052 /// Linkback mime handler for MacOSX.
1053 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1056 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400 && QT_VERSION < 0x060000)
1057 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1058 /// WMF Mime handler for Windows clipboard.
1059 QWindowsMimeMetafile * wmf_mime_;
1063 /// Allows to check whether ESC was pressed during a long operation
1064 KeyChecker key_checker_;
1068 GuiApplication * guiApp;
1070 GuiApplication::~GuiApplication()
1073 closeAllLinkBackLinks();
1079 GuiApplication::GuiApplication(int & argc, char ** argv)
1080 : QApplication(argc, argv), current_view_(nullptr),
1081 d(new GuiApplication::Private)
1083 QString app_name = "LyX";
1084 QCoreApplication::setOrganizationName(app_name);
1085 QCoreApplication::setOrganizationDomain("lyx.org");
1086 QCoreApplication::setApplicationName(lyx_package);
1087 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
1088 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1091 #if QT_VERSION >= 0x050700
1092 setDesktopFileName(lyx_package);
1095 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1096 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1098 qsrand(QDateTime::currentDateTime().toTime_t());
1101 // Install LyX translator for missing Qt translations
1102 installTranslator(&d->gui_trans_);
1103 // Install Qt native translator for GUI elements.
1104 installTranslator(&d->qt_trans_);
1107 // Enable reception of XCB events.
1108 installNativeEventFilter(this);
1111 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1112 // lyxrc setting for this in order to let the application stay resident.
1113 // But then we need some kind of dock icon, at least on Windows.
1115 if (lyxrc.quit_on_last_window_closed)
1116 setQuitOnLastWindowClosed(false);
1119 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1120 // seems to be the default case for applications like LyX.
1121 setQuitOnLastWindowClosed(false);
1124 appleCleanupEditMenu();
1125 appleCleanupViewMenu();
1126 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1127 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1128 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1132 #if defined(Q_WS_X11) || defined(QPA_XCB)
1133 // doubleClickInterval() is 400 ms on X11 which is just too long.
1134 // On Windows and Mac OS X, the operating system's value is used.
1135 // On Microsoft Windows, calling this function sets the double
1136 // click interval for all applications. So we don't!
1137 QApplication::setDoubleClickInterval(300);
1140 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1142 // needs to be done before reading lyxrc
1144 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1148 // Initialize RC Fonts
1149 if (lyxrc.roman_font_name.empty())
1150 lyxrc.roman_font_name = fromqstr(romanFontName());
1152 if (lyxrc.sans_font_name.empty())
1153 lyxrc.sans_font_name = fromqstr(sansFontName());
1155 if (lyxrc.typewriter_font_name.empty())
1156 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1158 #if (QT_VERSION >= 0x050000)
1159 // Qt4 does this in event(), see below.
1160 // Track change of keyboard
1161 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1164 d->general_timer_.setInterval(500);
1165 connect(&d->general_timer_, SIGNAL(timeout()),
1166 this, SLOT(handleRegularEvents()));
1167 d->general_timer_.start();
1169 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1170 // This is clearly not enough in a time where we use threads for
1171 // document preview and/or export. 20 should be OK.
1172 QThreadPool::globalInstance()->setMaxThreadCount(20);
1174 // make sure tooltips are formatted
1175 installEventFilter(new ToolTipFormatter(this));
1179 GuiApplication * theGuiApp()
1181 return dynamic_cast<GuiApplication *>(theApp());
1185 #if QT_VERSION < 0x050000
1186 // Emulate platformName() for Qt4
1188 // FIXME: when ditching this method, remove all tests
1189 // platformName() == "qt4x11"
1191 QString GuiApplication::platformName() const
1193 # if defined(Q_WS_X11)
1194 // Note that this one does not really exist
1196 # elif defined(Q_OS_MAC)
1198 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1201 LYXERR0("Unknown platform!");
1208 double GuiApplication::pixelRatio() const
1210 #if QT_VERSION >= 0x050000
1211 return qt_scale_factor * devicePixelRatio();
1218 void GuiApplication::clearSession()
1225 docstring Application::iconName(FuncRequest const & f, bool unknown)
1227 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1231 docstring Application::mathIcon(docstring const & c)
1233 return qstring_to_ucs4(findImg(toqstr(c)));
1237 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1241 BufferView * bv = nullptr;
1242 BufferView * doc_bv = nullptr;
1244 if (cmd.action() == LFUN_NOACTION) {
1245 status.message(from_utf8(N_("Nothing to do")));
1246 status.setEnabled(false);
1249 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1250 status.setUnknown(true);
1251 status.message(from_utf8(N_("Unknown action")));
1252 status.setEnabled(false);
1255 // Does the GuiApplication know something?
1256 else if (getStatus(cmd, status)) { }
1258 // If we do not have a GuiView, then other functions are disabled
1259 else if (!current_view_)
1260 status.setEnabled(false);
1262 // Does the GuiView know something?
1263 else if (current_view_->getStatus(cmd, status)) { }
1265 // In LyX/Mac, when a dialog is open, the menus of the
1266 // application can still be accessed without giving focus to
1267 // the main window. In this case, we want to disable the menu
1268 // entries that are buffer or view-related.
1269 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1271 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1272 status.setEnabled(false);
1275 // If we do not have a BufferView, then other functions are disabled
1276 else if (!(bv = current_view_->currentBufferView()))
1277 status.setEnabled(false);
1279 // Does the current BufferView know something?
1280 else if (bv->getStatus(cmd, status)) { }
1282 // Does the current Buffer know something?
1283 else if (bv->buffer().getStatus(cmd, status)) { }
1285 // If we do not have a document BufferView, different from the
1286 // current BufferView, then other functions are disabled
1287 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1288 status.setEnabled(false);
1290 // Does the document Buffer know something?
1291 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1294 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1295 status.message(from_utf8(N_("Command not handled")));
1296 status.setEnabled(false);
1299 // the default error message if we disable the command
1300 if (!status.enabled() && status.message().empty())
1301 status.message(from_utf8(N_("Command disabled")));
1307 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1309 // I would really like to avoid having this switch and rather try to
1310 // encode this in the function itself.
1311 // -- And I'd rather let an inset decide which LFUNs it is willing
1312 // to handle (Andre')
1314 switch (cmd.action()) {
1316 // This could be used for the no-GUI version. The GUI version is handled in
1317 // GuiView::getStatus(). See above.
1319 case LFUN_BUFFER_WRITE:
1320 case LFUN_BUFFER_WRITE_AS:
1321 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1322 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1323 enable = b && (b->isUnnamed() || !b->isClean());
1328 case LFUN_BOOKMARK_GOTO: {
1329 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1330 enable = theSession().bookmarks().isValid(num);
1334 case LFUN_BOOKMARK_CLEAR:
1335 enable = theSession().bookmarks().hasValid();
1338 // this one is difficult to get right. As a half-baked
1339 // solution, we consider only the first action of the sequence
1340 case LFUN_COMMAND_SEQUENCE: {
1341 // argument contains ';'-terminated commands
1342 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1343 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1344 func.setOrigin(cmd.origin());
1345 flag = getStatus(func);
1349 // we want to check if at least one of these is enabled
1350 case LFUN_COMMAND_ALTERNATIVES: {
1351 // argument contains ';'-terminated commands
1352 string arg = to_utf8(cmd.argument());
1353 while (!arg.empty()) {
1355 arg = split(arg, first, ';');
1356 FuncRequest func(lyxaction.lookupFunc(first));
1357 func.setOrigin(cmd.origin());
1358 flag = getStatus(func);
1359 // if this one is enabled, the whole thing is
1368 string name = to_utf8(cmd.argument());
1369 if (theTopLevelCmdDef().lock(name, func)) {
1370 func.setOrigin(cmd.origin());
1371 flag = getStatus(func);
1372 theTopLevelCmdDef().release(name);
1374 // catch recursion or unknown command
1375 // definition. all operations until the
1376 // recursion or unknown command definition
1377 // occurs are performed, so set the state to
1384 case LFUN_IF_RELATIVES: {
1385 string const lfun = to_utf8(cmd.argument());
1386 BufferView const * bv =
1387 current_view_ ? current_view_->currentBufferView() : nullptr;
1388 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1392 FuncRequest func(lyxaction.lookupFunc(lfun));
1393 func.setOrigin(cmd.origin());
1394 flag = getStatus(func);
1398 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1400 case LFUN_PREFERENCES_SAVE:
1401 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1402 // these are handled in our dispatch()
1405 case LFUN_DEBUG_LEVEL_SET: {
1406 string bad = Debug::badValue(to_utf8(cmd.argument()));
1407 enable = bad.empty();
1409 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1413 case LFUN_WINDOW_CLOSE:
1414 enable = !d->views_.empty();
1417 case LFUN_BUFFER_NEW:
1418 case LFUN_BUFFER_NEW_TEMPLATE:
1419 case LFUN_FILE_OPEN:
1420 case LFUN_LYXFILES_OPEN:
1421 case LFUN_HELP_OPEN:
1422 case LFUN_SCREEN_FONT_UPDATE:
1423 case LFUN_SET_COLOR:
1424 case LFUN_WINDOW_NEW:
1426 case LFUN_LYXRC_APPLY:
1427 case LFUN_COMMAND_PREFIX:
1429 case LFUN_META_PREFIX:
1430 case LFUN_RECONFIGURE:
1431 case LFUN_SERVER_GET_FILENAME:
1432 case LFUN_SERVER_NOTIFY:
1436 case LFUN_BUFFER_FORALL: {
1437 if (theBufferList().empty()) {
1438 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1439 flag.setEnabled(false);
1443 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1444 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1445 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1446 flag.setEnabled(false);
1451 case LFUN_DIALOG_SHOW: {
1452 string const name = cmd.getArg(0);
1453 return name == "aboutlyx"
1454 || name == "lyxfiles"
1456 || name == "texinfo"
1457 || name == "progress"
1458 || name == "compare";
1466 flag.setEnabled(false);
1470 /// make a post-dispatch status message
1471 static docstring makeDispatchMessage(docstring const & msg,
1472 FuncRequest const & cmd)
1474 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1475 || cmd.origin() == FuncRequest::TOOLBAR
1476 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1478 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1479 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1483 docstring dispatch_msg = msg;
1484 if (!dispatch_msg.empty())
1485 dispatch_msg += ' ';
1487 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1489 bool argsadded = false;
1491 if (!cmd.argument().empty()) {
1492 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1493 comname += ' ' + cmd.argument();
1497 docstring const shortcuts = theTopLevelKeymap().
1498 printBindings(cmd, KeySequence::ForGui);
1500 if (!shortcuts.empty())
1501 comname += ": " + shortcuts;
1502 else if (!argsadded && !cmd.argument().empty())
1503 comname += ' ' + cmd.argument();
1505 if (!comname.empty()) {
1506 comname = rtrim(comname);
1507 dispatch_msg += '(' + rtrim(comname) + ')';
1509 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1510 return dispatch_msg;
1514 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1518 Buffer * buffer = nullptr;
1519 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1520 //setCurrentView(cmd.view_origin); //does not work
1522 dr.setMessage(_("Wrong focus!"));
1523 d->dispatch_result_ = dr;
1524 return d->dispatch_result_;
1526 if (current_view_ && current_view_->currentBufferView()) {
1527 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1528 buffer = ¤t_view_->currentBufferView()->buffer();
1531 dr.screenUpdate(Update::FitCursor);
1533 // All the code is kept inside the undo group because
1534 // updateBuffer can create undo actions (see #11292)
1535 UndoGroupHelper ugh(buffer);
1537 if (dr.screenUpdate() & Update::ForceAll) {
1538 for (Buffer const * b : theBufferList())
1540 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1543 updateCurrentView(cmd, dr);
1546 d->dispatch_result_ = dr;
1547 return d->dispatch_result_;
1551 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1556 BufferView * bv = current_view_->currentBufferView();
1558 if (dr.needBufferUpdate()) {
1559 bv->cursor().clearBufferUpdate();
1560 bv->buffer().updateBuffer();
1562 // BufferView::update() updates the ViewMetricsInfo and
1563 // also initializes the position cache for all insets in
1564 // (at least partially) visible top-level paragraphs.
1565 // We will redraw the screen only if needed.
1566 bv->processUpdateFlags(dr.screenUpdate());
1568 // Do we have a selection?
1569 theSelection().haveSelection(bv->cursor().selection());
1572 current_view_->restartCaret();
1574 if (dr.needMessageUpdate()) {
1575 // Some messages may already be translated, so we cannot use _()
1576 current_view_->message(makeDispatchMessage(
1577 translateIfPossible(dr.message()), cmd));
1582 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1583 bool switchToBuffer)
1585 if (!theSession().bookmarks().isValid(idx))
1587 BookmarksSection::Bookmark const & bm =
1588 theSession().bookmarks().bookmark(idx);
1589 LASSERT(!bm.filename.empty(), return);
1590 string const file = bm.filename.absFileName();
1591 // if the file is not opened, open it.
1592 if (!theBufferList().exists(bm.filename)) {
1594 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1598 // open may fail, so we need to test it again
1599 if (!theBufferList().exists(bm.filename))
1602 // bm can be changed when saving
1603 BookmarksSection::Bookmark tmp = bm;
1605 // Special case idx == 0 used for back-from-back jump navigation
1607 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1609 // if the current buffer is not that one, switch to it.
1610 BufferView * doc_bv = current_view_ ?
1611 current_view_->documentBufferView() : nullptr;
1612 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1613 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1614 if (switchToBuffer) {
1615 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1618 doc_bv = current_view_->documentBufferView();
1623 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1624 if (!doc_bv || !doc_bv->moveToPosition(
1625 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1628 Cursor & cur = doc_bv->cursor();
1629 if (old && cur != *old)
1630 notifyCursorLeavesOrEnters(*old, cur);
1636 // Cursor jump succeeded!
1637 pit_type new_pit = cur.pit();
1638 pos_type new_pos = cur.pos();
1639 int new_id = cur.paragraph().id();
1641 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1642 // see http://www.lyx.org/trac/ticket/3092
1643 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1644 || bm.top_id != new_id) {
1645 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1646 new_pit, new_pos, new_id);
1650 // This function runs "configure" and then rereads lyx.defaults to
1651 // reconfigure the automatic settings.
1652 void GuiApplication::reconfigure(string const & option)
1654 // emit message signal.
1656 current_view_->message(_("Running configure..."));
1658 // Run configure in user lyx directory
1659 string const lock_file = package().getConfigureLockName();
1660 int fd = fileLock(lock_file.c_str());
1661 int const ret = package().reconfigureUserLyXDir(option);
1662 // emit message signal.
1664 current_view_->message(_("Reloading configuration..."));
1665 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1666 // Re-read packages.lst
1667 LaTeXPackages::getAvailable();
1668 fileUnlock(fd, lock_file.c_str());
1671 Alert::information(_("System reconfiguration failed"),
1672 _("The system reconfiguration has failed.\n"
1673 "Default textclass is used but LyX may\n"
1674 "not be able to work properly.\n"
1675 "Please reconfigure again if needed."));
1677 Alert::information(_("System reconfigured"),
1678 _("The system has been reconfigured.\n"
1679 "You need to restart LyX to make use of any\n"
1680 "updated document class specifications."));
1683 void GuiApplication::validateCurrentView()
1685 if (!d->views_.empty() && !current_view_) {
1686 // currently at least one view exists but no view has the focus.
1687 // choose the last view to make it current.
1688 // a view without any open document is preferred.
1689 GuiView * candidate = nullptr;
1690 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1691 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1692 for (; it != end; ++it) {
1694 if (!candidate->documentBufferView())
1697 setCurrentView(candidate);
1701 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1703 string const argument = to_utf8(cmd.argument());
1704 FuncCode const action = cmd.action();
1706 LYXERR(Debug::ACTION, "cmd: " << cmd);
1708 // we have not done anything wrong yet.
1711 FuncStatus const flag = getStatus(cmd);
1712 if (!flag.enabled()) {
1713 // We cannot use this function here
1714 LYXERR(Debug::ACTION, "action "
1715 << lyxaction.getActionName(action)
1716 << " [" << action << "] is disabled at this location");
1717 dr.setMessage(flag.message());
1719 dr.dispatched(false);
1720 dr.screenUpdate(Update::None);
1721 dr.clearBufferUpdate();
1725 if (cmd.origin() == FuncRequest::LYXSERVER) {
1726 if (current_view_ && current_view_->currentBufferView())
1727 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1728 // we will also need to redraw the screen at the end
1729 dr.screenUpdate(Update::FitCursor);
1732 // Assumes that the action will be dispatched.
1733 dr.dispatched(true);
1735 switch (cmd.action()) {
1737 case LFUN_WINDOW_NEW:
1738 createView(toqstr(cmd.argument()));
1741 case LFUN_WINDOW_CLOSE:
1742 // FIXME: this is done also in GuiView::closeBuffer()!
1743 // update bookmark pit of the current buffer before window close
1744 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1745 gotoBookmark(i, false, false);
1746 // clear the last opened list, because
1747 // maybe this will end the session
1748 theSession().lastOpened().clear();
1749 // check for valid current_view_
1750 validateCurrentView();
1752 current_view_->closeScheduled();
1756 // quitting is triggered by the gui code
1757 // (leaving the event loop).
1759 current_view_->message(from_utf8(N_("Exiting.")));
1760 if (closeAllViews())
1764 case LFUN_SCREEN_FONT_UPDATE: {
1765 // handle the screen font changes.
1766 /* FIXME: this only updates the current document, whereas all
1767 * documents should see their metrics updated.
1769 d->font_loader_.update();
1770 dr.screenUpdate(Update::Force | Update::FitCursor);
1774 case LFUN_BUFFER_NEW:
1775 validateCurrentView();
1777 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1778 createView(QString(), false); // keep hidden
1779 current_view_->newDocument(to_utf8(cmd.argument()));
1780 current_view_->show();
1781 setActiveWindow(current_view_);
1783 current_view_->newDocument(to_utf8(cmd.argument()));
1787 case LFUN_BUFFER_NEW_TEMPLATE: {
1788 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1789 string const temp = cmd.getArg(1);
1790 validateCurrentView();
1792 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1794 current_view_->newDocument(file, temp, true);
1795 if (!current_view_->documentBufferView())
1796 current_view_->close();
1798 current_view_->newDocument(file, temp, true);
1803 case LFUN_FILE_OPEN: {
1804 // FIXME: normally the code below is not needed, since getStatus makes sure that
1805 // current_view_ is not null.
1806 validateCurrentView();
1807 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1808 string const fname = trim(to_utf8(cmd.argument()), "\"");
1809 bool const is_open = FileName::isAbsolute(fname)
1810 && theBufferList().getBuffer(FileName(fname));
1812 || (!lyxrc.open_buffers_in_tabs
1813 && current_view_->documentBufferView() != nullptr
1815 // We want the ui session to be saved per document and not per
1816 // window number. The filename crc is a good enough identifier.
1817 createView(support::checksum(fname));
1818 current_view_->openDocument(fname);
1819 if (!current_view_->documentBufferView())
1820 current_view_->close();
1821 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1822 current_view_->raise();
1823 current_view_->activateWindow();
1824 current_view_->showNormal();
1827 current_view_->openDocument(fname);
1828 if (cmd.origin() == FuncRequest::LYXSERVER) {
1829 current_view_->raise();
1830 current_view_->activateWindow();
1831 current_view_->showNormal();
1837 case LFUN_HELP_OPEN: {
1838 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1839 if (current_view_ == nullptr)
1841 string const arg = to_utf8(cmd.argument());
1843 current_view_->message(_("Missing argument"));
1846 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1848 fname = i18nLibFileSearch("examples", arg, "lyx");
1850 if (fname.empty()) {
1851 lyxerr << "LyX: unable to find documentation file `"
1852 << arg << "'. Bad installation?" << endl;
1855 current_view_->message(bformat(_("Opening help file %1$s..."),
1856 makeDisplayPath(fname.absFileName())));
1857 Buffer * buf = current_view_->loadDocument(fname, false);
1859 buf->setReadonly(!current_view_->develMode());
1863 case LFUN_LYXFILES_OPEN: {
1864 // This is the actual reason for this method (#12106).
1865 validateCurrentView();
1867 || (!lyxrc.open_buffers_in_tabs
1868 && current_view_->documentBufferView() != nullptr))
1870 string arg = to_utf8(cmd.argument());
1874 if (arg != "templates" && arg != "examples") {
1875 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1878 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1882 case LFUN_SET_COLOR: {
1883 string const lyx_name = cmd.getArg(0);
1884 string x11_name = cmd.getArg(1);
1885 string x11_darkname = cmd.getArg(2);
1886 if (lyx_name.empty() || x11_name.empty()) {
1888 current_view_->message(
1889 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1894 // FIXME: The graphics cache no longer has a changeDisplay method.
1895 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1896 bool const graphicsbg_changed =
1897 lyx_name == graphicsbg && x11_name != graphicsbg;
1898 if (graphicsbg_changed)
1899 graphics::GCache::get().changeDisplay(true);
1902 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1903 x11_darkname = x11_name;
1906 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1908 current_view_->message(
1909 bformat(_("Set-color \"%1$s\" failed "
1910 "- color is undefined or "
1911 "may not be redefined"),
1912 from_utf8(lyx_name)));
1915 // Make sure we don't keep old colors in cache.
1916 d->color_cache_.clear();
1917 // Update the current view
1918 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1922 case LFUN_LYXRC_APPLY: {
1923 // reset active key sequences, since the bindings
1924 // are updated (bug 6064)
1926 LyXRC const lyxrc_orig = lyxrc;
1928 istringstream ss(to_utf8(cmd.argument()));
1929 bool const success = lyxrc.read(ss);
1932 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1933 << "Unable to read lyxrc data"
1938 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1940 // If the request comes from the minibuffer, then we can't reset
1941 // the GUI, since that would destroy the minibuffer itself and
1942 // cause a crash, since we are currently in one of the methods of
1943 // GuiCommandBuffer. See bug #8540.
1944 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1947 // FIXME Unfortunately, that leaves a bug here, since we cannot
1948 // reset the GUI in this case. If the changes to lyxrc affected the
1949 // UI, then, nothing would happen. This seems fairly unlikely, but
1950 // it definitely is a bug.
1952 dr.forceBufferUpdate();
1956 case LFUN_COMMAND_PREFIX:
1957 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1962 d->meta_fake_bit = NoModifier;
1963 GuiView * gv = currentView();
1964 if (gv && gv->currentBufferView())
1965 // cancel any selection
1966 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1967 dr.setMessage(from_ascii(N_("Cancel")));
1970 case LFUN_META_PREFIX:
1971 d->meta_fake_bit = AltModifier;
1972 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1975 // --- Menus -----------------------------------------------
1976 case LFUN_RECONFIGURE:
1977 // argument is any additional parameter to the configure.py command
1978 reconfigure(to_utf8(cmd.argument()));
1981 // --- lyxserver commands ----------------------------
1982 case LFUN_SERVER_GET_FILENAME: {
1983 if (current_view_ && current_view_->documentBufferView()) {
1984 docstring const fname = from_utf8(
1985 current_view_->documentBufferView()->buffer().absFileName());
1986 dr.setMessage(fname);
1987 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1989 dr.setMessage(docstring());
1990 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1995 case LFUN_SERVER_NOTIFY: {
1996 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1997 dr.setMessage(dispatch_buffer);
1998 theServer().notifyClient(to_utf8(dispatch_buffer));
2002 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2003 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2009 string rest = split(argument, countstr, ' ');
2010 int const count = convert<int>(countstr);
2011 // an arbitrary number to limit number of iterations
2012 int const max_iter = 10000;
2013 if (count > max_iter) {
2014 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2017 for (int i = 0; i < count; ++i) {
2018 FuncRequest lfun = lyxaction.lookupFunc(rest);
2019 lfun.allowAsync(false);
2026 case LFUN_COMMAND_SEQUENCE: {
2027 // argument contains ';'-terminated commands
2028 string arg = argument;
2029 // FIXME: this LFUN should also work without any view.
2030 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2031 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2032 // This handles undo groups automagically
2033 UndoGroupHelper ugh(buffer);
2034 while (!arg.empty()) {
2036 arg = split(arg, first, ';');
2037 FuncRequest func(lyxaction.lookupFunc(first));
2038 func.allowAsync(false);
2039 func.setOrigin(cmd.origin());
2045 case LFUN_BUFFER_FORALL: {
2046 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2047 funcToRun.allowAsync(false);
2049 map<Buffer *, GuiView *> views_lVisible;
2050 map<GuiView *, Buffer *> activeBuffers;
2052 QList<GuiView *> allViews = d->views_.values();
2054 // this for does not modify any buffer. It just collects info on local
2055 // visibility of buffers and on which buffer is active in each view.
2056 Buffer * const last = theBufferList().last();
2057 for(GuiView * view : allViews) {
2058 // all of the buffers might be locally hidden. That is, there is no
2060 if (!view || !view->currentBufferView())
2061 activeBuffers[view] = nullptr;
2063 activeBuffers[view] = &view->currentBufferView()->buffer();
2065 // find out if each is locally visible or locally hidden.
2066 // we don't use a for loop as the buffer list cycles.
2067 Buffer * b = theBufferList().first();
2069 bool const locallyVisible = view && view->workArea(*b);
2070 if (locallyVisible) {
2071 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2072 // only need to overwrite/add if we don't already know a buffer is globally
2073 // visible or we do know but we would prefer to dispatch LFUN from the
2074 // current view because of cursor position issues.
2075 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2076 views_lVisible[b] = view;
2080 b = theBufferList().next(b);
2084 GuiView * const homeView = currentView();
2085 Buffer * b = theBufferList().first();
2086 Buffer * nextBuf = nullptr;
2087 int numProcessed = 0;
2090 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2092 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2094 // first change to a view where b is locally visible, preferably current_view_.
2095 GuiView * const vLv = views_lVisible[b];
2097 lyx::dispatch(funcToRun);
2105 // put things back to how they were (if possible).
2106 for (GuiView * view : allViews) {
2107 Buffer * originalBuf = activeBuffers[view];
2108 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2109 if (theBufferList().isLoaded(originalBuf))
2110 view->setBuffer(originalBuf);
2112 homeView->setFocus();
2114 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2118 case LFUN_COMMAND_ALTERNATIVES: {
2119 // argument contains ';'-terminated commands
2120 string arg = argument;
2121 while (!arg.empty()) {
2123 arg = split(arg, first, ';');
2124 FuncRequest func(lyxaction.lookupFunc(first));
2125 func.setOrigin(cmd.origin());
2126 FuncStatus const stat = getStatus(func);
2127 if (stat.enabled()) {
2137 if (theTopLevelCmdDef().lock(argument, func)) {
2138 func.setOrigin(cmd.origin());
2140 theTopLevelCmdDef().release(argument);
2142 if (func.action() == LFUN_UNKNOWN_ACTION) {
2143 // unknown command definition
2144 lyxerr << "Warning: unknown command definition `"
2148 // recursion detected
2149 lyxerr << "Warning: Recursion in the command definition `"
2150 << argument << "' detected"
2157 case LFUN_IF_RELATIVES: {
2158 string const lfun = to_utf8(cmd.argument());
2159 FuncRequest func(lyxaction.lookupFunc(lfun));
2160 func.setOrigin(cmd.origin());
2161 FuncStatus const stat = getStatus(func);
2162 if (stat.enabled()) {
2169 case LFUN_PREFERENCES_SAVE:
2170 lyxrc.write(support::makeAbsPath("preferences",
2171 package().user_support().absFileName()), false);
2174 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2175 string const fname = addName(addPath(package().user_support().absFileName(),
2176 "templates/"), "defaults.lyx");
2177 Buffer defaults(fname);
2179 istringstream ss(argument);
2184 // We need to make sure that, after we recreat the DocumentClass,
2185 // which we do in readHeader, we apply it to the document itself.
2186 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2187 int const unknown_tokens = defaults.readHeader(lex);
2188 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2189 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2190 cap::switchBetweenClasses(olddc, newdc, theinset);
2192 if (unknown_tokens != 0) {
2193 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2194 << unknown_tokens << " unknown token"
2195 << (unknown_tokens == 1 ? "" : "s")
2199 if (defaults.writeFile(FileName(defaults.absFileName())))
2200 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2201 makeDisplayPath(fname)));
2204 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2209 case LFUN_BOOKMARK_GOTO:
2210 // go to bookmark, open unopened file and switch to buffer if necessary
2211 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2212 dr.screenUpdate(Update::Force | Update::FitCursor);
2215 case LFUN_BOOKMARK_CLEAR:
2216 theSession().bookmarks().clear();
2217 dr.screenUpdate(Update::Force);
2220 case LFUN_DEBUG_LEVEL_SET:
2221 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2224 case LFUN_DIALOG_SHOW: {
2225 string const name = cmd.getArg(0);
2227 if ( name == "aboutlyx"
2229 || name == "texinfo"
2230 || name == "progress"
2231 || name == "compare")
2233 // work around: on Mac OS the application
2234 // is not terminated when closing the last view.
2235 // Create a new one to be able to dispatch the
2236 // LFUN_DIALOG_SHOW to this view.
2237 if (current_view_ == nullptr)
2243 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2246 current_view_->dispatch(cmd, dr);
2250 if (current_view_ && current_view_->isFullScreen()) {
2251 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2252 current_view_->menuBar()->hide();
2255 if (cmd.origin() == FuncRequest::LYXSERVER)
2256 updateCurrentView(cmd, dr);
2260 docstring GuiApplication::viewStatusMessage()
2262 // When meta-fake key is pressed, show the key sequence so far + "M-".
2263 if (d->meta_fake_bit != NoModifier)
2264 return d->keyseq.print(KeySequence::ForGui) + "M-";
2266 // Else, when a non-complete key sequence is pressed,
2267 // show the available options.
2268 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2269 return d->keyseq.printOptions(true);
2275 string GuiApplication::inputLanguageCode() const
2277 #if (QT_VERSION < 0x050000)
2278 QLocale loc = keyboardInputLocale();
2280 QLocale loc = inputMethod()->locale();
2282 //LYXERR0("input lang = " << fromqstr(loc.name()));
2283 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2287 void GuiApplication::onLocaleChanged()
2289 //LYXERR0("Change language to " << inputLanguage()->lang());
2290 if (currentView() && currentView()->currentBufferView())
2291 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2295 void GuiApplication::handleKeyFunc(FuncCode action)
2299 if (d->keyseq.length())
2301 GuiView * gv = currentView();
2302 LASSERT(gv && gv->currentBufferView(), return);
2303 BufferView * bv = gv->currentBufferView();
2304 bv->getIntl().getTransManager().deadkey(
2305 c, get_accent(action).accent, bv->cursor().innerText(),
2307 // Need to clear, in case the minibuffer calls these
2310 // copied verbatim from do_accent_char
2311 bv->cursor().resetAnchor();
2315 //Keep this in sync with GuiApplication::processKeySym below
2316 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2317 KeyModifier state) const
2319 // Do nothing if we have nothing
2320 if (!keysym.isOK() || keysym.isModifier())
2322 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2324 FuncRequest func = seq.addkey(keysym, state);
2325 // When not cancel or meta-fake, do the normal lookup.
2326 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2328 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2330 // Maybe user can only reach the key via holding down shift.
2331 // Let's see. But only if shift is the only modifier
2332 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2333 // If addkey looked up a command and did not find further commands then
2334 // seq has been reset at this point
2335 func = seq.addkey(keysym, NoModifier);
2337 LYXERR(Debug::KEY, " Key (queried) [action="
2338 << lyxaction.getActionName(func.action()) << "]["
2339 << seq.print(KeySequence::Portable) << ']');
2340 return func.action() != LFUN_UNKNOWN_ACTION;
2344 //Keep this in sync with GuiApplication::queryKeySym above
2345 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2347 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2349 // Do nothing if we have nothing (JMarc)
2350 if (!keysym.isOK() || keysym.isModifier()) {
2352 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2354 current_view_->restartCaret();
2358 char_type encoded_last_key = keysym.getUCSEncoded();
2360 // Do a one-deep top-level lookup for
2361 // cancel and meta-fake keys. RVDK_PATCH_5
2362 d->cancel_meta_seq.reset();
2364 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2365 LYXERR(Debug::KEY, "action first set to ["
2366 << lyxaction.getActionName(func.action()) << ']');
2368 // When not cancel or meta-fake, do the normal lookup.
2369 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2370 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2371 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2372 // remove Caps Lock and Mod2 as a modifiers
2373 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2374 LYXERR(Debug::KEY, "action now set to ["
2375 << lyxaction.getActionName(func.action()) << ']');
2378 // Don't remove this unless you know what you are doing.
2379 d->meta_fake_bit = NoModifier;
2381 // Can this happen now ?
2382 if (func.action() == LFUN_NOACTION)
2383 func = FuncRequest(LFUN_COMMAND_PREFIX);
2385 LYXERR(Debug::KEY, " Key [action="
2386 << lyxaction.getActionName(func.action()) << "]["
2387 << d->keyseq.print(KeySequence::Portable) << ']');
2389 // already here we know if it any point in going further
2390 // why not return already here if action == -1 and
2391 // num_bytes == 0? (Lgb)
2393 if (d->keyseq.length() > 1 && current_view_)
2394 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2397 // Maybe user can only reach the key via holding down shift.
2398 // Let's see. But only if shift is the only modifier
2399 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2400 LYXERR(Debug::KEY, "Trying without shift");
2401 // If addkey looked up a command and did not find further commands then
2402 // seq has been reset at this point
2403 func = d->keyseq.addkey(keysym, NoModifier);
2404 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2407 if (func.action() == LFUN_UNKNOWN_ACTION) {
2408 // We didn't match any of the key sequences.
2409 // See if it's normal insertable text not already
2410 // covered by a binding
2411 if (keysym.isText() && d->keyseq.length() == 1) {
2412 // Non-printable characters (such as ASCII control characters)
2413 // must not be inserted (#5704)
2414 if (!isPrintable(encoded_last_key)) {
2415 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2417 current_view_->restartCaret();
2420 // The following modifier check is not needed on Mac.
2421 // The keysym is either not text or it is different
2422 // from the non-modifier keysym. See #9875 for the
2423 // broken alt-modifier effect of having this code active.
2424 #if !defined(Q_OS_MAC)
2425 // If a non-Shift Modifier is used we have a non-bound key sequence
2426 // (such as Alt+j = j). This should be omitted (#5575).
2427 // On Windows, AltModifier and ControlModifier are both
2428 // set when AltGr is pressed. Therefore, in order to not
2429 // break AltGr-bound symbols (see #5575 for details),
2430 // unbound Ctrl+Alt key sequences are allowed.
2431 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2432 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2433 && !(state & AltModifier && state & ControlModifier)
2437 if (current_view_) {
2438 current_view_->message(_("Unknown function."));
2439 current_view_->restartCaret();
2444 // Since all checks above were passed, we now really have text that
2445 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2446 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2448 LYXERR(Debug::KEY, "isText() is true, inserting.");
2449 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2451 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2452 if (current_view_) {
2453 current_view_->message(_("Unknown function."));
2454 current_view_->restartCaret();
2460 if (func.action() == LFUN_SELF_INSERT) {
2461 if (encoded_last_key != 0) {
2462 docstring const arg(1, encoded_last_key);
2463 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2464 FuncRequest::KEYBOARD));
2465 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2468 processFuncRequest(func);
2472 void GuiApplication::processFuncRequest(FuncRequest const & func)
2474 lyx::dispatch(func);
2478 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2480 addToFuncRequestQueue(func);
2481 processFuncRequestQueueAsync();
2485 void GuiApplication::processFuncRequestQueue()
2487 while (!d->func_request_queue_.empty()) {
2488 // take the item from the stack _before_ processing the
2489 // request in order to avoid race conditions from nested
2490 // or parallel requests (see #10406)
2491 FuncRequest const fr(d->func_request_queue_.front());
2492 d->func_request_queue_.pop();
2493 processFuncRequest(fr);
2498 void GuiApplication::processFuncRequestQueueAsync()
2500 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2504 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2506 d->func_request_queue_.push(func);
2510 void GuiApplication::resetGui()
2512 // Set the language defined by the user.
2516 if (!readUIFile(toqstr(lyxrc.ui_file)))
2517 // Gives some error box here.
2520 if (d->global_menubar_)
2521 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2523 QHash<int, GuiView *>::iterator it;
2524 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2527 gv->setLayoutDirection(layoutDirection());
2531 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2535 bool GuiApplication::rtlContext() const
2537 if (current_view_ && current_view_->currentBufferView()) {
2538 BufferView const * bv = current_view_->currentBufferView();
2539 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2541 return layoutDirection() == Qt::RightToLeft;
2545 void GuiApplication::createView(int view_id)
2547 createView(QString(), true, view_id);
2551 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2554 // release the keyboard which might have been grabbed by the global
2555 // menubar on Mac to catch shortcuts even without any GuiView.
2556 if (d->global_menubar_)
2557 d->global_menubar_->releaseKeyboard();
2561 while (d->views_.find(id) != d->views_.end())
2564 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2565 GuiView * view = new GuiView(id);
2566 // `view' is the new current_view_. Tell coverity that is is not 0.
2567 LATTEST(current_view_);
2569 d->views_[id] = view;
2573 setActiveWindow(view);
2576 if (!geometry_arg.isEmpty()) {
2577 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2581 #if QT_VERSION < 0x060000
2582 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2583 re.indexIn(geometry_arg);
2584 w = re.cap(1).toInt();
2585 h = re.cap(2).toInt();
2586 x = re.cap(3).toInt();
2587 y = re.cap(4).toInt();
2588 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2589 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2591 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2592 QRegularExpressionMatch match = re.match(geometry_arg);
2593 w = match.captured(1).toInt();
2594 h = match.captured(2).toInt();
2595 x = match.captured(3).toInt();
2596 y = match.captured(4).toInt();
2597 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2598 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2600 // Set initial geometry such that we can get the frame size.
2601 view->setGeometry(x, y, w, h);
2602 int framewidth = view->geometry().x() - view->x();
2603 int titleheight = view->geometry().y() - view->y();
2604 // Negative displacements must be interpreted as distances
2605 // from the right or bottom screen borders.
2606 if (sx == '-' || sy == '-') {
2607 #if QT_VERSION < 0x060000
2608 QRect rec = QApplication::desktop()->screenGeometry();
2610 QRect rec = QGuiApplication::primaryScreen()->geometry();
2613 x += rec.width() - w - framewidth;
2615 y += rec.height() - h - titleheight;
2616 view->setGeometry(x, y, w, h);
2618 // Make sure that the left and top frame borders are visible.
2619 if (view->x() < 0 || view->y() < 0) {
2624 view->setGeometry(x, y, w, h);
2632 bool GuiApplication::unhide(Buffer * buf)
2636 currentView()->setBuffer(buf, false);
2641 Clipboard & GuiApplication::clipboard()
2643 return d->clipboard_;
2647 Selection & GuiApplication::selection()
2649 return d->selection_;
2653 FontLoader & GuiApplication::fontLoader()
2655 return d->font_loader_;
2659 Toolbars const & GuiApplication::toolbars() const
2661 return d->toolbars_;
2665 Toolbars & GuiApplication::toolbars()
2667 return d->toolbars_;
2671 Menus const & GuiApplication::menus() const
2677 Menus & GuiApplication::menus()
2683 QList<int> GuiApplication::viewIds() const
2685 return d->views_.keys();
2689 ColorCache & GuiApplication::colorCache()
2691 return d->color_cache_;
2695 int GuiApplication::exec()
2697 // asynchronously handle batch commands. This event will be in
2698 // the event queue in front of other asynchronous events. Hence,
2699 // we can assume in the latter that the gui is setup already.
2700 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2702 return QApplication::exec();
2706 void GuiApplication::exit(int status)
2708 QApplication::exit(status);
2712 void GuiApplication::setGuiLanguage()
2716 // install translation file for Qt built-in dialogs
2717 QString const language_name = QString("qt_") + theLocale.name();
2718 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2719 // Short-named translator can be loaded from a long name, but not the
2720 // opposite. Therefore, long name should be used without truncation.
2721 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2722 if (!d->qt_trans_.load(language_name,
2723 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2724 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2726 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2728 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2731 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2735 switch (theLocale.language()) {
2736 case QLocale::Arabic :
2737 case QLocale::Hebrew :
2738 case QLocale::Persian :
2739 case QLocale::Urdu :
2740 setLayoutDirection(Qt::RightToLeft);
2743 setLayoutDirection(Qt::LeftToRight);
2748 void GuiApplication::execBatchCommands()
2753 if (!readUIFile(toqstr(lyxrc.ui_file)))
2754 // Gives some error box here.
2758 #if QT_VERSION > 0x040600
2759 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2761 #if QT_VERSION > 0x050100
2762 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2764 // Create the global default menubar which is shown for the dialogs
2765 // and if no GuiView is visible.
2766 // This must be done after the session was recovered to know the "last files".
2767 d->global_menubar_ = new QMenuBar(0);
2768 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2771 lyx::execBatchCommands();
2775 QAbstractItemModel * GuiApplication::languageModel()
2777 if (d->language_model_)
2778 return d->language_model_;
2780 QStandardItemModel * lang_model = new QStandardItemModel(this);
2781 lang_model->insertColumns(0, 3);
2782 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2783 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2784 Languages::const_iterator it = lyx::languages.begin();
2785 Languages::const_iterator end = lyx::languages.end();
2786 for (; it != end; ++it) {
2787 int current_row = lang_model->rowCount();
2788 lang_model->insertRows(current_row, 1);
2789 QModelIndex pl_item = lang_model->index(current_row, 0);
2790 QModelIndex sp_item = lang_model->index(current_row, 1);
2791 QModelIndex th_item = lang_model->index(current_row, 2);
2792 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2793 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2794 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2795 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2796 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2797 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2798 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2799 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2800 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2801 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2803 d->language_model_ = new QSortFilterProxyModel(this);
2804 d->language_model_->setSourceModel(lang_model);
2805 d->language_model_->setSortLocaleAware(true);
2806 return d->language_model_;
2810 void GuiApplication::restoreGuiSession()
2812 if (!lyxrc.load_session)
2815 Session & session = theSession();
2816 LastOpenedSection::LastOpened const & lastopened =
2817 session.lastOpened().getfiles();
2819 validateCurrentView();
2821 FileName active_file;
2822 // do not add to the lastfile list since these files are restored from
2823 // last session, and should be already there (regular files), or should
2824 // not be added at all (help files).
2825 for (auto const & last : lastopened) {
2826 FileName const & file_name = last.file_name;
2827 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2828 && current_view_->documentBufferView() != nullptr)) {
2829 string const & fname = file_name.absFileName();
2830 createView(support::checksum(fname));
2832 current_view_->loadDocument(file_name, false);
2835 active_file = file_name;
2838 // Restore last active buffer
2839 Buffer * buffer = theBufferList().getBuffer(active_file);
2840 if (buffer && current_view_)
2841 current_view_->setBuffer(buffer);
2843 // clear this list to save a few bytes of RAM
2844 session.lastOpened().clear();
2848 QString const GuiApplication::romanFontName()
2851 font.setStyleHint(QFont::Serif);
2852 font.setFamily("serif");
2854 return QFontInfo(font).family();
2858 QString const GuiApplication::sansFontName()
2861 font.setStyleHint(QFont::SansSerif);
2862 font.setFamily("sans");
2864 return QFontInfo(font).family();
2868 QString const GuiApplication::typewriterFontName()
2870 return QFontInfo(typewriterSystemFont()).family();
2875 // We cannot use QFont::fixedPitch() because it doesn't
2876 // return the fact but only if it is requested.
2877 static bool isFixedPitch(const QFont & font) {
2878 const QFontInfo fi(font);
2879 return fi.fixedPitch();
2884 QFont const GuiApplication::typewriterSystemFont()
2886 #if QT_VERSION >= 0x050200
2887 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2889 QFont font("monospace");
2891 if (!isFixedPitch(font)) {
2892 // try to enforce a real monospaced font
2893 font.setStyleHint(QFont::Monospace);
2894 if (!isFixedPitch(font)) {
2895 font.setStyleHint(QFont::TypeWriter);
2896 if (!isFixedPitch(font)) font.setFamily("courier");
2900 // On a Mac the result is too small and it's not practical to
2901 // rely on Qtconfig utility to change the system settings of Qt.
2902 font.setPointSize(12);
2908 void GuiApplication::handleRegularEvents()
2910 ForkedCallsController::handleCompletedProcesses();
2914 bool GuiApplication::event(QEvent * e)
2917 case QEvent::FileOpen: {
2918 // Open a file; this happens only on Mac OS X for now.
2920 // We do this asynchronously because on startup the batch
2921 // commands are not executed here yet and the gui is not ready
2923 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2924 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2925 processFuncRequestAsync(fr);
2929 #if (QT_VERSION < 0x050000)
2930 // Qt5 uses a signal for that, see above.
2931 case QEvent::KeyboardLayoutChange:
2932 //LYXERR0("keyboard change");
2933 if (currentView() && currentView()->currentBufferView())
2934 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2939 return QApplication::event(e);
2944 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2947 return QApplication::notify(receiver, event);
2949 catch (ExceptionMessage const & e) {
2951 case ErrorException:
2953 setQuitOnLastWindowClosed(false);
2955 Alert::error(e.title_, e.details_);
2957 // Properly crash in debug mode in order to get a useful backtrace.
2960 // In release mode, try to exit gracefully.
2962 // FIXME: GCC 7 thinks we can fall through here. Can we?
2964 case BufferException: {
2965 if (!current_view_ || !current_view_->documentBufferView())
2967 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2968 docstring details = e.details_ + '\n';
2969 details += buf->emergencyWrite();
2970 theBufferList().release(buf);
2971 details += "\n" + _("The current document was closed.");
2972 Alert::error(e.title_, details);
2975 case WarningException:
2976 Alert::warning(e.title_, e.details_);
2980 catch (exception const & e) {
2981 docstring s = _("LyX has caught an exception, it will now "
2982 "attempt to save all unsaved documents and exit."
2984 s += from_ascii(e.what());
2985 Alert::error(_("Software exception Detected"), s);
2989 docstring s = _("LyX has caught some really weird exception, it will "
2990 "now attempt to save all unsaved documents and exit.");
2991 Alert::error(_("Software exception Detected"), s);
2998 bool GuiApplication::isInDarkMode()
3000 return colorCache().isDarkMode();
3004 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3006 QColor const & qcol = d->color_cache_.get(col);
3007 if (!qcol.isValid()) {
3013 rgbcol.r = qcol.red();
3014 rgbcol.g = qcol.green();
3015 rgbcol.b = qcol.blue();
3020 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3022 QColor const qcol(lcolor.getX11HexName(col).c_str());
3023 if (!qcol.isValid()) {
3029 rgbcol.r = qcol.red();
3030 rgbcol.g = qcol.green();
3031 rgbcol.b = qcol.blue();
3036 string const GuiApplication::hexName(ColorCode col)
3038 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3042 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3044 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3045 d->socket_notifiers_[fd] = sn;
3046 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3050 void GuiApplication::socketDataReceived(int fd)
3052 d->socket_notifiers_[fd]->func_();
3056 void GuiApplication::unregisterSocketCallback(int fd)
3058 d->socket_notifiers_.take(fd)->setEnabled(false);
3062 void GuiApplication::commitData(QSessionManager & sm)
3064 /** The implementation is required to avoid an application exit
3065 ** when session state save is triggered by session manager.
3066 ** The default implementation sends a close event to all
3067 ** visible top level widgets when session management allows
3069 ** We are changing that to check the state of each buffer in all
3070 ** views and ask the users what to do if buffers are dirty.
3071 ** Furthermore, we save the session state.
3072 ** We do NOT close the views here since the user still can cancel
3073 ** the logout process (see #9277); also, this would hide LyX from
3074 ** an OSes own session handling (application restoration).
3076 #ifdef QT_NO_SESSIONMANAGER
3078 #warning Qt is compiled without session manager
3080 #pragma message("warning: Qt is compiled without session manager")
3084 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3092 void GuiApplication::unregisterView(GuiView * gv)
3094 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3095 d->views_.remove(gv->id());
3096 if (current_view_ == gv)
3097 current_view_ = nullptr;
3102 bool GuiApplication::closeAllViews()
3104 if (d->views_.empty())
3107 // When a view/window was closed before without quitting LyX, there
3108 // are already entries in the lastOpened list.
3109 theSession().lastOpened().clear();
3111 QList<GuiView *> const views = d->views_.values();
3112 for (GuiView * view : views) {
3113 if (!view->closeScheduled())
3122 bool GuiApplication::prepareAllViewsForLogout()
3124 if (d->views_.empty())
3127 QList<GuiView *> const views = d->views_.values();
3128 for (GuiView * view : views) {
3129 if (!view->prepareAllBuffersForLogout())
3137 GuiView & GuiApplication::view(int id) const
3139 LAPPERR(d->views_.contains(id));
3140 return *d->views_.value(id);
3144 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3146 QList<GuiView *> const views = d->views_.values();
3147 for (GuiView * view : views)
3148 view->hideDialog(name, inset);
3152 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3154 Buffer const * buf = nullptr;
3155 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3156 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3157 if (Buffer const * ptr = (*it)->updateInset(inset))
3164 bool GuiApplication::searchMenu(FuncRequest const & func,
3165 docstring_list & names) const
3167 BufferView * bv = nullptr;
3169 bv = current_view_->currentBufferView();
3170 return d->menus_.searchMenu(func, names, bv);
3174 bool GuiApplication::hasBufferView() const
3176 return (current_view_ && current_view_->currentBufferView());
3180 // Ensure that a file is read only once (prevents include loops)
3181 static QStringList uifiles;
3182 // store which ui files define Toolbars
3183 static QStringList toolbar_uifiles;
3186 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3197 LexerKeyword uitags[] = {
3198 { "format", ui_format },
3199 { "include", ui_include },
3200 { "menuset", ui_menuset },
3201 { "toolbars", ui_toolbars },
3202 { "toolbarset", ui_toolbarset }
3206 lex.setFile(ui_path);
3208 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3212 if (lyxerr.debugging(Debug::PARSER))
3213 lex.printTable(lyxerr);
3216 // format before introduction of format tag
3217 unsigned int format = 0;
3218 while (lex.isOK()) {
3219 int const status = lex.lex();
3221 // we have to do this check here, outside the switch,
3222 // because otherwise we would start reading include files,
3223 // e.g., if the first tag we hit was an include tag.
3224 if (status == ui_format)
3226 format = lex.getInteger();
3230 // this will trigger unless the first tag we hit is a format
3231 // tag, with the right format.
3232 if (format != LFUN_FORMAT)
3233 return FormatMismatch;
3236 case Lexer::LEX_FEOF:
3241 QString const file = toqstr(lex.getString());
3242 bool const success = readUIFile(file, true);
3244 LYXERR0("Failed to read included file: " << fromqstr(file));
3251 d->menus_.read(lex);
3255 d->toolbars_.readToolbars(lex);
3259 d->toolbars_.readToolbarSettings(lex);
3260 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3264 if (!rtrim(lex.getString()).empty())
3265 lex.printError("LyX::ReadUIFile: "
3266 "Unknown menu tag: `$$Token'");
3268 LYXERR0("Error with status: " << status);
3274 return (error ? ReadError : ReadOK);
3278 bool GuiApplication::readUIFile(QString const & name, bool include)
3280 LYXERR(Debug::INIT, "About to read " << name << "...");
3284 ui_path = libFileSearch("ui", name, "inc");
3285 if (ui_path.empty())
3286 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3288 ui_path = libFileSearch("ui", name, "ui");
3291 if (ui_path.empty()) {
3292 static const QString defaultUIFile = "default";
3293 LYXERR(Debug::INIT, "Could not find " << name);
3295 Alert::warning(_("Could not find UI definition file"),
3296 bformat(_("Error while reading the included file\n%1$s\n"
3297 "Please check your installation."), qstring_to_ucs4(name)));
3300 if (name == defaultUIFile) {
3301 LYXERR(Debug::INIT, "Could not find default UI file!!");
3302 Alert::warning(_("Could not find default UI file"),
3303 _("LyX could not find the default UI file!\n"
3304 "Please check your installation."));
3307 Alert::warning(_("Could not find UI definition file"),
3308 bformat(_("Error while reading the configuration file\n%1$s\n"
3309 "Falling back to default.\n"
3310 "Please look under Tools>Preferences>User Interface and\n"
3311 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3312 return readUIFile(defaultUIFile, false);
3315 QString const uifile = toqstr(ui_path.absFileName());
3316 if (uifiles.contains(uifile)) {
3318 // We are reading again the top uifile so reset the safeguard:
3321 d->toolbars_.reset();
3323 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3324 << "Is this an include loop?");
3328 uifiles.push_back(uifile);
3330 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3332 ReturnValues retval = readUIFile(ui_path);
3334 if (retval == FormatMismatch) {
3335 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3336 TempFile tmp("convertXXXXXX.ui");
3337 FileName const tempfile = tmp.name();
3338 bool const success = prefs2prefs(ui_path, tempfile, true);
3340 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3341 " to format " << LFUN_FORMAT << ".");
3343 retval = readUIFile(tempfile);
3347 if (retval != ReadOK) {
3348 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3356 settings.beginGroup("ui_files");
3357 bool touched = false;
3358 for (int i = 0; i != uifiles.size(); ++i) {
3359 QFileInfo fi(uifiles[i]);
3360 QDateTime const date_value = fi.lastModified();
3361 QString const name_key = QString::number(i);
3362 // if an ui file which defines Toolbars has changed,
3363 // we have to reset the settings
3364 if (toolbar_uifiles.contains(uifiles[i])
3365 && (!settings.contains(name_key)
3366 || settings.value(name_key).toString() != uifiles[i]
3367 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3369 settings.setValue(name_key, uifiles[i]);
3370 settings.setValue(name_key + "/date", date_value);
3373 settings.endGroup();
3375 settings.remove("views");
3381 void GuiApplication::onLastWindowClosed()
3383 if (d->global_menubar_)
3384 d->global_menubar_->grabKeyboard();
3388 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3389 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3391 std::string name = "unknown";
3393 case Qt::ApplicationSuspended:
3394 name = "ApplicationSuspended";
3396 case Qt::ApplicationHidden:
3397 name = "ApplicationHidden";
3399 case Qt::ApplicationInactive:
3400 name = "ApplicationInactive";
3402 case Qt::ApplicationActive:
3403 name = "ApplicationActive";
3404 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3405 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3406 if (d->views_.empty() && d->last_state_ == state) {
3407 LYXERR(Debug::GUI, "Open new window...");
3412 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3413 d->last_state_ = state;
3418 void GuiApplication::startLongOperation() {
3419 d->key_checker_.start();
3423 bool GuiApplication::longOperationCancelled() {
3424 return d->key_checker_.pressed();
3428 void GuiApplication::stopLongOperation() {
3429 d->key_checker_.stop();
3433 bool GuiApplication::longOperationStarted() {
3434 return d->key_checker_.started();
3438 ////////////////////////////////////////////////////////////////////////
3440 // X11 specific stuff goes here...
3443 bool GuiApplication::x11EventFilter(XEvent * xev)
3448 switch (xev->type) {
3449 case SelectionRequest: {
3450 if (xev->xselectionrequest.selection != XA_PRIMARY)
3452 LYXERR(Debug::SELECTION, "X requested selection.");
3453 BufferView * bv = current_view_->currentBufferView();
3455 docstring const sel = bv->requestSelection();
3457 d->selection_.put(sel);
3458 // Refresh the selection request timestamp.
3459 // We have to do this by ourselves as Qt seems
3460 // not doing that, maybe because of our
3461 // "persistent selection" implementation
3462 // (see comments in GuiSelection.cpp).
3463 XSelectionEvent nev;
3464 nev.type = SelectionNotify;
3465 nev.display = xev->xselectionrequest.display;
3466 nev.requestor = xev->xselectionrequest.requestor;
3467 nev.selection = xev->xselectionrequest.selection;
3468 nev.target = xev->xselectionrequest.target;
3469 nev.property = 0L; // None
3470 nev.time = CurrentTime;
3471 XSendEvent(QX11Info::display(),
3472 nev.requestor, False, 0,
3473 reinterpret_cast<XEvent *>(&nev));
3479 case SelectionClear: {
3480 if (xev->xselectionclear.selection != XA_PRIMARY)
3482 LYXERR(Debug::SELECTION, "Lost selection.");
3483 BufferView * bv = current_view_->currentBufferView();
3485 bv->clearSelection();
3491 #elif defined(QPA_XCB)
3492 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3493 void * message, long *)
3495 if (!current_view_ || eventType != "xcb_generic_event_t")
3498 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3500 switch (ev->response_type) {
3501 case XCB_SELECTION_REQUEST: {
3502 xcb_selection_request_event_t * srev =
3503 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3504 if (srev->selection != XCB_ATOM_PRIMARY)
3506 LYXERR(Debug::SELECTION, "X requested selection.");
3507 BufferView * bv = current_view_->currentBufferView();
3509 docstring const sel = bv->requestSelection();
3511 d->selection_.put(sel);
3512 #ifdef HAVE_QT5_X11_EXTRAS
3513 // Refresh the selection request timestamp.
3514 // We have to do this by ourselves as Qt seems
3515 // not doing that, maybe because of our
3516 // "persistent selection" implementation
3517 // (see comments in GuiSelection.cpp).
3518 // It is expected that every X11 event is
3519 // 32 bytes long, even if not all 32 bytes are
3521 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3522 struct alignas(32) padded_event
3523 : xcb_selection_notify_event_t {};
3524 padded_event nev = {};
3525 nev.response_type = XCB_SELECTION_NOTIFY;
3526 nev.requestor = srev->requestor;
3527 nev.selection = srev->selection;
3528 nev.target = srev->target;
3529 nev.property = XCB_NONE;
3530 nev.time = XCB_CURRENT_TIME;
3531 xcb_connection_t * con = QX11Info::connection();
3532 xcb_send_event(con, 0, srev->requestor,
3533 XCB_EVENT_MASK_NO_EVENT,
3534 reinterpret_cast<char const *>(&nev));
3542 case XCB_SELECTION_CLEAR: {
3543 xcb_selection_clear_event_t * scev =
3544 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3545 if (scev->selection != XCB_ATOM_PRIMARY)
3547 LYXERR(Debug::SELECTION, "Lost selection.");
3548 BufferView * bv = current_view_->currentBufferView();
3550 bv->clearSelection();
3558 } // namespace frontend
3561 void hideDialogs(std::string const & name, Inset * inset)
3564 frontend::guiApp->hideDialogs(name, inset);
3568 ////////////////////////////////////////////////////////////////////
3572 ////////////////////////////////////////////////////////////////////
3574 frontend::FontLoader & theFontLoader()
3576 LAPPERR(frontend::guiApp);
3577 return frontend::guiApp->fontLoader();
3581 frontend::FontMetrics const & theFontMetrics(Font const & f)
3583 return theFontMetrics(f.fontInfo());
3587 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3589 LAPPERR(frontend::guiApp);
3590 return frontend::guiApp->fontLoader().metrics(f);
3594 ////////////////////////////////////////////////////////////////////
3598 ////////////////////////////////////////////////////////////////////
3600 frontend::Clipboard & theClipboard()
3602 LAPPERR(frontend::guiApp);
3603 return frontend::guiApp->clipboard();
3607 frontend::Selection & theSelection()
3609 LAPPERR(frontend::guiApp);
3610 return frontend::guiApp->selection();
3616 #include "moc_GuiApplication.cpp"