2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
23 #include "qt_helpers.h"
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
37 #include "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/environment.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/ForkedCalls.h"
70 #include "support/gettext.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/lyxalgo.h" // sorted
74 #include "support/textutils.h"
75 #include "support/Messages.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/TempFile.h"
81 #include "support/AppleScript.h"
82 #include "support/AppleSupport.h"
83 #include "support/linkback/LinkBackProxy.h"
92 #if QT_VERSION < 0x060000
93 #include <QDesktopWidget>
96 #include <QFileOpenEvent>
98 #include <QFontDatabase>
101 #include <QImageReader>
104 #include <QLibraryInfo>
111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
112 #include <QRandomGenerator>
115 #include <QSessionManager>
117 #include <QSocketNotifier>
118 #include <QSortFilterProxyModel>
119 #include <QStandardItemModel>
121 #include <QTranslator>
122 #include <QThreadPool>
126 #include <X11/Xatom.h>
127 #include <X11/Xlib.h>
131 #elif defined(QPA_XCB)
133 #ifdef HAVE_QT5_X11_EXTRAS
134 #include <QtX11Extras/QX11Info>
138 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
139 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
140 #if (QT_VERSION < 0x050000)
141 #include <QWindowsMime>
142 #define QWINDOWSMIME QWindowsMime
143 #define QVARIANTTYPE QVariant::Type
144 #elif (QT_VERSION >= 0x060000)
145 #include <QtGui/private/qguiapplication_p.h>
146 #include <QtGui/private/qwindowsmime_p.h>
147 #include <QtGui/qpa/qplatformintegration.h>
148 #define QWINDOWSMIME QWindowsMime
149 #define QVARIANTTYPE QMetaType
150 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
151 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
154 #define QWINDOWSMIME QWinMime
155 #define QVARIANTTYPE QVariant::Type
164 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
165 #include <QMacPasteboardMime>
173 using namespace lyx::support;
178 frontend::Application * createApplication(int & argc, char * argv[])
180 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
181 // prune -geometry argument(s) by shifting
182 // the following ones 2 places down.
183 for (int i = 0 ; i < argc ; ++i) {
184 if (strcmp(argv[i], "-geometry") == 0) {
185 int const remove = (i+1) < argc ? 2 : 1;
187 for (int j = i; j < argc; ++j)
188 argv[j] = argv[j + remove];
194 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
195 // On Windows, allow bringing the LyX window to top
196 AllowSetForegroundWindow(ASFW_ANY);
200 #if defined(Q_OS_MAC)
201 int const cursor_time_on = NSTextInsertionPointBlinkPeriodOn();
202 int const cursor_time_off = NSTextInsertionPointBlinkPeriodOff();
203 if (cursor_time_on > 0 && cursor_time_off > 0) {
204 QApplication::setCursorFlashTime(cursor_time_on + cursor_time_off);
205 } else if (cursor_time_on <= 0 && cursor_time_off > 0) {
206 // Off is set and On is undefined of zero
207 QApplication::setCursorFlashTime(0);
208 } else if (cursor_time_off <= 0 && cursor_time_on > 0) {
209 // On is set and Off is undefined of zero
210 QApplication::setCursorFlashTime(0);
214 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
215 // macOS does it by itself.
216 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
217 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
218 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
219 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
220 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
221 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
224 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
225 // HighDPI scale factor policy must be set before QGuiApplication is created
226 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
227 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
231 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
232 // I'd rather do that in the constructor, but I do not think that
233 // the palette is accessible there.
234 guiApp->colorCache().setPalette(guiApp->palette());
243 if (lyxrc.gui_language == "auto") {
244 theLocale = QLocale::system();
245 code = fromqstr(theLocale.name());
247 Language const * l = languages.getLanguage(lyxrc.gui_language);
248 code = l ? l->code() : "C";
249 theLocale = QLocale(toqstr(code));
251 // Qt tries to outsmart us and transforms en_US to C.
252 Messages::guiLanguage((code == "C") ? "en_US" : code);
253 QLocale::setDefault(theLocale);
254 setlocale(LC_NUMERIC, "C");
261 /// Return the list of loadable formats.
262 vector<string> loadableImageFormats()
266 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
268 LYXERR(Debug::GRAPHICS,
269 "\nThe image loader can load the following directly:\n");
271 if (qt_formats.empty())
272 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
274 bool jpeg_found = false;
275 bool jpg_found = false;
276 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
278 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
280 string ext = ascii_lowercase((const char *) *it);
288 else if (ext == "jpg") {
293 else if (lyxrc.use_converter_cache &&
294 (ext == "svg" || ext == "svgz") &&
295 theConverters().isReachable("svg", "png"))
296 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
297 // the SVG as in the output. However we require that the converter
298 // cache is enabled since this is expensive. We also require that
299 // an explicit svg->png converter is defined, since the default
300 // converter could produce bad quality as well. This assumes that
301 // png can always be loaded.
310 ////////////////////////////////////////////////////////////////////////
312 // Icon loading support code
314 ////////////////////////////////////////////////////////////////////////
324 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
326 return lhs.key < rhs.key;
332 CompareKey(QString const & name) : name_(name) {}
333 bool operator()(ImgMap const & other) const { return other.key == name_; }
339 // this must be sorted alphabetically
340 // Upper case comes before lower case
341 // Please don't change the formatting, this list is parsed by
342 // development/tools/generate_symbols_images.py.
343 ImgMap sorted_img_map[] = {
344 { "Arrownot", "arrownot2"},
345 { "Arrowvert", "arrowvert2"},
346 { "Bowtie", "bowtie2" },
348 { "Bumpeq", "bumpeq2" },
349 { "CIRCLE", "circle3" },
351 { "CheckedBox", "checkedbox2" },
352 { "Circle", "circle2" },
353 { "Colonapprox", "colonapprox2" },
354 { "Coloneq", "coloneq2" },
355 { "Coloneqq", "coloneqq2" },
356 { "Colonsim", "colonsim2" },
358 { "DOWNarrow", "downarrow3" },
359 { "Delta", "delta2" },
360 { "Diamond", "diamond2" },
361 { "Doteq", "doteq2" },
362 { "Downarrow", "downarrow2" },
363 { "Eqcolon", "eqcolon2" },
364 { "Eqqcolon", "eqqcolon2" },
365 { "Gamma", "gamma2" },
367 { "LEFTCIRCLE", "leftcircle3" },
368 { "LEFTarrow", "leftarrow3" },
369 { "LEFTcircle", "leftcircle4" },
371 { "Lambda", "lambda2" },
373 { "Leftarrow", "leftarrow2" },
374 { "Leftcircle", "leftcircle2" },
375 { "Leftrightarrow", "leftrightarrow2" },
376 { "Longarrownot", "longarrownot2"},
377 { "Longleftarrow", "longleftarrow2" },
378 { "Longleftrightarrow", "longleftrightarrow2" },
379 { "Longmapsfrom", "longmapsfrom2"},
380 { "Longmapsto", "longmapsto2"},
381 { "Longrightarrow", "longrightarrow2" },
382 { "Mapsfrom", "mapsfrom2"},
383 { "Mapsfromchar", "mapsfromchar2"},
384 { "Mapsto", "mapsto2"},
385 { "Mapstochar", "mapstochar2"},
386 { "Omega", "omega2" },
391 { "RIGHTCIRCLE", "rightcircle3" },
392 { "RIGHTarrow", "rightarrow3" },
393 { "RIGHTcircle", "rightcircle4" },
395 { "Rightarrow", "rightarrow2" },
396 { "Rightcircle", "rightcircle2" },
397 { "Sigma", "sigma2" },
398 { "Square", "square2" },
399 { "Subset", "subset2" },
400 { "Supset", "supset2" },
401 { "Theta", "theta2" },
402 { "Thorn", "thorn2" },
403 { "UParrow", "uparrow3" },
404 { "Uparrow", "uparrow2" },
405 { "Updownarrow", "updownarrow2" },
406 { "Upsilon", "upsilon2" },
407 { "Vdash", "vdash3" },
412 { "lVert", "vert2" },
414 { "nLeftarrow", "nleftarrow2" },
415 { "nLeftrightarrow", "nleftrightarrow2" },
416 { "nRightarrow", "nrightarrow2" },
417 { "nVDash", "nvdash3" },
418 { "nVdash", "nvdash4" },
419 { "nvDash", "nvdash2" },
420 { "rVert", "vert2" },
422 { "textrm \\AA", "textrm_AA"},
423 { "textrm \\O", "textrm_O"},
424 { "vDash", "vdash2" },
425 { "varDelta", "vardelta2" },
426 { "varGamma", "vargamma2" },
427 { "varLambda", "varlambda2" },
428 { "varOmega", "varomega2" },
429 { "varPhi", "varphi2" },
430 { "varPi", "varpi2" },
431 { "varPsi", "varpsi2" },
432 { "varSigma", "varsigma2" },
433 { "varTheta", "vartheta2" },
434 { "varUpsilon", "varupsilon2" },
435 { "varXi", "varxi2" }
439 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
441 // This list specifies which system's theme icon is related to which lyx
442 // command. It was based on:
443 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
444 // this must be sorted alphabetically
445 // Upper case comes before lower case
446 ImgMap sorted_theme_icon_map[] = {
447 { "bookmark-goto 0", "go-jump" },
448 { "buffer-new", "document-new" },
449 { "buffer-write", "document-save" },
450 { "buffer-write-as", "document-save-as" },
451 { "buffer-zoom-in", "zoom-in" },
452 { "buffer-zoom-out", "zoom-out" },
453 { "copy", "edit-copy" },
454 { "cut", "edit-cut" },
455 { "depth-decrement", "format-indent-less" },
456 { "depth-increment", "format-indent-more" },
457 { "dialog-show spellchecker", "tools-check-spelling" },
458 { "dialog-show-new-inset graphics", "insert-image" },
459 { "dialog-toggle findreplaceadv", "edit-find-replace" },
460 { "file-open", "document-open" },
461 { "font-bold", "format-text-bold" },
462 { "font-ital", "format-text-italic" },
463 { "font-strikeout", "format-text-strikethrough" },
464 { "font-underline", "format-text-underline" },
465 { "lyx-quit", "application-exit" },
466 { "paste", "edit-paste" },
467 { "redo", "edit-redo" },
468 { "undo", "edit-undo" },
469 { "window-close", "window-close" },
470 { "window-new", "window-new" }
473 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
476 QString findImg(QString const & name)
478 ImgMap const * const begin = sorted_img_map;
479 ImgMap const * const end = begin + nr_sorted_img_map;
480 LATTEST(sorted(begin, end));
482 ImgMap const * const it = find_if(begin, end, CompareKey(name));
486 img_name = it->value;
489 img_name.replace('_', "underscore");
490 img_name.replace(' ', '_');
492 // This way we can have "math-delim { }" on the toolbar.
493 img_name.replace('(', "lparen");
494 img_name.replace(')', "rparen");
495 img_name.replace('[', "lbracket");
496 img_name.replace(']', "rbracket");
497 img_name.replace('{', "lbrace");
498 img_name.replace('}', "rbrace");
499 img_name.replace('|', "bars");
500 img_name.replace(',', "thinspace");
501 img_name.replace(':', "mediumspace");
502 img_name.replace(';', "thickspace");
503 img_name.replace('!', "negthinspace");
506 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
507 << "Looking for math icon called \"" << img_name << '"');
514 QString themeIconName(QString const & action)
516 ImgMap const * const begin = sorted_theme_icon_map;
517 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
518 LASSERT(sorted(begin, end), /**/);
520 ImgMap const * const it = find_if(begin, end, CompareKey(action));
530 /* Get aliases for icon name. This allows to avoid duplication of
531 * icons when new versions of functions are introduced for the
532 * toolbar. A good example is the introduction of layout-toggle in
534 * The file is parsed by Lexer. Each line is of the form
535 * <original substring> <replacement substring>
537 * The return value is another icon file name that can be queried.
539 // FIXME: consider using regular expressions.
540 QString getAlias(QString name) {
541 static bool has_aliases = false;
542 static vector <pair<QString,QString>> aliases;
543 // Initialize aliases list (once).
545 FileName alfile = libFileSearch("images", "icon.aliases");
546 if (alfile.exists()) {
553 aliases.push_back({toqstr(from), toqstr(to)});
558 // check for the following aliases
559 for (auto alias : aliases) {
560 if (name.contains(alias.first))
561 name.replace(alias.first, alias.second);
569 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
574 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
576 if (!f.argument().empty()) {
577 // if there are arguments, first search an icon which name is the full thing
578 QString name = lfunname + ' ' + toqstr(f.argument());
579 name.replace(' ', '_');
580 name.replace(';', '_');
581 name.replace('\\', "backslash");
583 QString alias = getAlias(name);
587 // then special default icon for some lfuns
588 switch (f.action()) {
589 case LFUN_MATH_INSERT:
590 names << "math/" + findImg(toqstr(f.argument()).mid(1));
592 case LFUN_MATH_DELIM:
593 case LFUN_MATH_BIGDELIM:
594 names << "math/" + findImg(toqstr(f.argument()));
597 names << "commands/" + toqstr(f.argument());
599 case LFUN_COMMAND_ALTERNATIVES: {
600 // use the first of the alternative commands
602 docstring dummy = split(f.argument(), firstcom, ';');
603 QString name1 = toqstr(firstcom);
604 name1.replace(' ', '_');
605 name1.replace(';', '_');
606 name1.replace('\\', "backslash");
615 // next thing to try is function name alone
617 QString alias = getAlias(lfunname);
618 if (alias != lfunname)
621 // and finally maybe the unknown icon
625 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
626 // The folders where icons are searched for
627 QStringList imagedirs;
628 imagedirs << "images/ipa/" << "images/";
629 // This is used to search for rtl version of icons which have the +rtl suffix.
630 QStringList suffixes;
633 suffixes << QString();
635 for (QString const & imagedir : imagedirs)
636 for (QString const & name : names)
637 for (QString const & suffix : suffixes) {
638 QString id = imagedir;
639 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
640 if (fname.exists()) {
641 docstring const fpath = fname.absoluteFilePath();
642 res.filepath = toqstr(fname.absFileName());
643 // these icons are subject to inversion in dark mode
644 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
645 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
646 res.swap = rtl && suffix.isEmpty();
651 LYXERR(Debug::GUI, "Cannot find icon for command \""
652 << lyxaction.getActionName(f.action())
653 << '(' << to_utf8(f.argument()) << ")\"");
659 QPixmap prepareForDarkMode(QPixmap pixmap)
661 QPalette palette = QPalette();
662 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
663 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
665 // guess whether we are in dark mode
666 if (text_color.black() > bg_color.black())
667 // not in dark mode, do nothing
670 // create a layer with black text turned to QPalette::WindowText
671 QPixmap black_overlay(pixmap.size());
672 black_overlay.fill(text_color);
673 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
675 // create a layer with blue text turned to lighter blue
676 QPixmap blue_overlay(pixmap.size());
677 QColor math_blue(0, 0, 255);
678 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
679 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
681 // create a layer with ("latex") red text turned to lighter red
682 QPixmap red_overlay(pixmap.size());
683 QColor math_red(128, 0, 0);
684 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
685 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
687 // put layers on top of existing pixmap
688 QPainter painter(&pixmap);
689 painter.drawPixmap(pixmap.rect(), black_overlay);
690 painter.drawPixmap(pixmap.rect(), blue_overlay);
691 painter.drawPixmap(pixmap.rect(), red_overlay);
697 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
699 QString imagedir = path;
700 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
701 QString fpath = toqstr(fname.absFileName());
702 QPixmap pixmap = QPixmap();
704 if (pixmap.load(fpath)) {
705 if (fpath.contains("math") || fpath.contains("ipa")
706 || fpath.contains("bullets"))
707 return prepareForDarkMode(pixmap);
711 bool const list = ext.contains(",");
712 LYXERR(Debug::GUI, "Cannot load pixmap \""
713 << path << "/" << name << "." << (list ? "{" : "") << ext
714 << (list ? "}" : "") << "\".");
720 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
722 #if (QT_VERSION >= 0x040600)
723 if (lyxrc.use_system_theme_icons) {
724 // use the icons from system theme that are available
725 QString action = toqstr(lyxaction.getActionName(f.action()));
726 if (!f.argument().empty())
727 action += " " + toqstr(f.argument());
728 QString const theme_icon = themeIconName(action);
729 if (QIcon::hasThemeIcon(theme_icon)) {
730 QIcon const thmicn = QIcon::fromTheme(theme_icon);
731 if (!thmicn.isNull())
737 IconInfo icondata = iconInfo(f, unknown, rtl);
738 if (icondata.filepath.isEmpty())
741 //LYXERR(Debug::GUI, "Found icon: " << icon);
742 QPixmap pixmap = QPixmap();
743 if (!pixmap.load(icondata.filepath)) {
744 LYXERR0("Cannot load icon " << icondata.filepath << ".");
749 pixmap = prepareForDarkMode(pixmap);
752 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
754 return QIcon(pixmap);
758 ////////////////////////////////////////////////////////////////////////
760 // LyX server support code.
762 ////////////////////////////////////////////////////////////////////////
764 class SocketNotifier : public QSocketNotifier
767 /// connect a connection notification from the LyXServerSocket
768 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
769 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
773 /// The callback function
774 Application::SocketCallback func_;
778 class GuiTranslator : public QTranslator
781 GuiTranslator(QObject * parent = nullptr)
782 : QTranslator(parent)
785 QString translate(const char * /* context */,
786 const char *sourceText,
787 #if QT_VERSION >= 0x050000
788 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
790 const char * /*comment*/ = 0) const override
793 // Here we declare the strings that need to be translated from Qt own GUI
794 // This is needed to include these strings to po files
798 _("Restore Defaults");
801 // Already in po: "Cancel", "&Cancel"
802 _("Apply"); // Already in po: "&Apply"
803 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
806 docstring s = getGuiMessages().getIfFound(sourceText);
807 // This test should eventually be removed when translations are updated
809 LYXERR(Debug::LOCALE, "Missing translation for `"
810 << string(sourceText) << "'");
816 ////////////////////////////////////////////////////////////////////////
818 // Mac specific stuff goes here...
820 ////////////////////////////////////////////////////////////////////////
822 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
823 // QMacPasteboardMimeGraphics can only be compiled on Mac.
825 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
828 QMacPasteboardMimeGraphics()
829 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
832 QString convertorName() { return "Graphics"; }
834 QString flavorFor(QString const & mime)
836 LYXERR(Debug::ACTION, "flavorFor " << mime);
837 if (mime == pdfMimeType())
838 return QLatin1String("com.adobe.pdf");
842 QString mimeFor(QString flav)
844 LYXERR(Debug::ACTION, "mimeFor " << flav);
845 if (flav == QLatin1String("com.adobe.pdf"))
846 return pdfMimeType();
850 bool canConvert(QString const & mime, QString flav)
852 return mimeFor(flav) == mime;
855 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
859 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
863 QList<QByteArray> convertFromMime(QString const & /*mime*/,
864 QVariant data, QString /*flav*/)
866 QList<QByteArray> ret;
867 ret.append(data.toByteArray());
873 ///////////////////////////////////////////////////////////////
875 // You can find more platform specific stuff at the end of this file...
877 ///////////////////////////////////////////////////////////////
879 ////////////////////////////////////////////////////////////////////////
880 // Windows specific stuff goes here...
882 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
883 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
884 // QWindowsMimeMetafile can only be compiled on Windows.
886 static FORMATETC cfFromMime(QString const & mimetype)
889 if (mimetype == emfMimeType()) {
890 formatetc.cfFormat = CF_ENHMETAFILE;
891 formatetc.tymed = TYMED_ENHMF;
892 } else if (mimetype == wmfMimeType()) {
893 formatetc.cfFormat = CF_METAFILEPICT;
894 formatetc.tymed = TYMED_MFPICT;
897 formatetc.dwAspect = DVASPECT_CONTENT;
898 formatetc.lindex = -1;
903 class QWindowsMimeMetafile : public QWINDOWSMIME {
905 QWindowsMimeMetafile() {}
907 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
908 QMimeData const * /*mimedata*/) const override
913 bool canConvertToMime(QString const & mimetype,
914 IDataObject * pDataObj) const override
916 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
918 FORMATETC formatetc = cfFromMime(mimetype);
919 return pDataObj->QueryGetData(&formatetc) == S_OK;
922 bool convertFromMime(FORMATETC const & /*formatetc*/,
923 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
928 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
929 QVARIANTTYPE /*preferredType*/) const override
932 if (!canConvertToMime(mimetype, pDataObj))
935 FORMATETC formatetc = cfFromMime(mimetype);
937 if (pDataObj->GetData(&formatetc, &s) != S_OK)
941 if (s.tymed == TYMED_ENHMF) {
942 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
943 data.resize(dataSize);
944 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
945 (LPBYTE)data.data());
946 } else if (s.tymed == TYMED_MFPICT) {
947 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
948 data.resize(dataSize);
949 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
950 (LPBYTE)data.data());
953 ReleaseStgMedium(&s);
959 QVector<FORMATETC> formatsForMime(QString const & mimetype,
960 QMimeData const * /*mimedata*/) const override
962 QVector<FORMATETC> formats;
963 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
964 formats += cfFromMime(mimetype);
968 QString mimeForFormat(FORMATETC const & formatetc) const override
970 switch (formatetc.cfFormat) {
972 return emfMimeType();
973 case CF_METAFILEPICT:
974 return wmfMimeType();
984 /// Allows to check whether ESC was pressed during a long operation
985 class KeyChecker : public QObject {
990 KeyChecker() : pressed_(false), started_(false) {}
993 QCoreApplication::instance()->installEventFilter(this);
998 QCoreApplication::instance()->removeEventFilter(this);
1002 QCoreApplication::processEvents();
1005 bool started() const {
1008 bool eventFilter(QObject *obj, QEvent *event) override {
1009 LYXERR(Debug::ACTION, "Event Type: " << event->type());
1010 switch (event->type()) {
1013 case QEvent::Resize:
1014 case QEvent::UpdateRequest:
1015 case QEvent::CursorChange:
1016 case QEvent::ActionChanged:
1017 case QEvent::EnabledChange:
1018 case QEvent::SockAct:
1021 case QEvent::ToolTipChange:
1022 case QEvent::LayoutRequest:
1023 case QEvent::MetaCall:
1024 return QObject::eventFilter(obj, event);
1026 // FIXME Blocking all these events is a bad idea.
1027 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1028 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1036 ////////////////////////////////////////////////////////////////////////
1037 // GuiApplication::Private definition and implementation.
1038 ////////////////////////////////////////////////////////////////////////
1040 struct GuiApplication::Private
1042 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1043 global_menubar_(nullptr)
1044 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1045 , last_state_(Qt::ApplicationInactive)
1048 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1049 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1050 /// WMF Mime handler for Windows clipboard.
1051 wmf_mime_ = new QWindowsMimeMetafile;
1052 #if (QT_VERSION >= 0x060000)
1053 win_app_ = dynamic_cast<QWindowsApplication *>
1054 (QGuiApplicationPrivate::platformIntegration());
1055 win_app_->registerMime(wmf_mime_);
1059 initKeySequences(&theTopLevelKeymap());
1062 #if (QT_VERSION >= 0x060000)
1063 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1066 win_app_->unregisterMime(wmf_mime_);
1071 void initKeySequences(KeyMap * kb)
1073 keyseq = KeySequence(kb, kb);
1074 cancel_meta_seq = KeySequence(kb, kb);
1078 QSortFilterProxyModel * language_model_;
1080 GuiClipboard clipboard_;
1082 GuiSelection selection_;
1084 FontLoader font_loader_;
1086 ColorCache color_cache_;
1087 /// the built-in Qt translation mechanism
1088 QTranslator qt_trans_;
1089 /// LyX gettext-based translation for Qt elements
1090 GuiTranslator gui_trans_;
1092 QHash<int, SocketNotifier *> socket_notifiers_;
1096 /// The global instance
1099 /// this timer is used for any regular events one wants to
1100 /// perform. at present it is used to check if forked processes
1102 QTimer general_timer_;
1104 /// delayed FuncRequests
1105 std::queue<FuncRequest> func_request_queue_;
1110 KeySequence cancel_meta_seq;
1112 KeyModifier meta_fake_bit;
1114 /// The result of last dispatch action
1115 DispatchResult dispatch_result_;
1117 /// Multiple views container.
1119 * Warning: This must not be a smart pointer as the destruction of the
1120 * object is handled by Qt when the view is closed
1121 * \sa Qt::WA_DeleteOnClose attribute.
1123 QHash<int, GuiView *> views_;
1125 /// Only used on mac.
1126 QMenuBar * global_menubar_;
1127 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1128 /// Holds previous application state on Mac
1129 Qt::ApplicationState last_state_;
1132 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1133 /// Linkback mime handler for MacOSX.
1134 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1137 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1138 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1139 /// WMF Mime handler for Windows clipboard.
1140 QWindowsMimeMetafile * wmf_mime_;
1141 #if (QT_VERSION >= 0x060000)
1142 QWindowsApplication * win_app_;
1147 /// Allows to check whether ESC was pressed during a long operation
1148 KeyChecker key_checker_;
1152 GuiApplication * guiApp;
1154 GuiApplication::~GuiApplication()
1157 closeAllLinkBackLinks();
1163 GuiApplication::GuiApplication(int & argc, char ** argv)
1164 : QApplication(argc, argv), current_view_(nullptr),
1165 d(new GuiApplication::Private)
1167 QString app_name = "LyX";
1168 QCoreApplication::setOrganizationName(app_name);
1169 QCoreApplication::setOrganizationDomain("lyx.org");
1170 QCoreApplication::setApplicationName(lyx_package);
1171 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1172 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1175 #if QT_VERSION >= 0x050700
1176 setDesktopFileName(lyx_package);
1179 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1180 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1182 qsrand(QDateTime::currentDateTime().toTime_t());
1185 // Install LyX translator for missing Qt translations
1186 installTranslator(&d->gui_trans_);
1187 // Install Qt native translator for GUI elements.
1188 installTranslator(&d->qt_trans_);
1191 // Enable reception of XCB events.
1192 installNativeEventFilter(this);
1195 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1196 // lyxrc setting for this in order to let the application stay resident.
1197 // But then we need some kind of dock icon, at least on Windows.
1199 if (lyxrc.quit_on_last_window_closed)
1200 setQuitOnLastWindowClosed(false);
1203 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1204 // seems to be the default case for applications like LyX.
1205 setQuitOnLastWindowClosed(false);
1208 appleCleanupEditMenu();
1209 appleCleanupViewMenu();
1210 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1211 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1212 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1216 #if defined(Q_WS_X11) || defined(QPA_XCB)
1217 // doubleClickInterval() is 400 ms on X11 which is just too long.
1218 // On Windows and Mac OS X, the operating system's value is used.
1219 // On Microsoft Windows, calling this function sets the double
1220 // click interval for all applications. So we don't!
1221 QApplication::setDoubleClickInterval(300);
1224 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1226 // needs to be done before reading lyxrc
1228 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1232 // Initialize RC Fonts
1233 if (lyxrc.roman_font_name.empty())
1234 lyxrc.roman_font_name = fromqstr(romanFontName());
1236 if (lyxrc.sans_font_name.empty())
1237 lyxrc.sans_font_name = fromqstr(sansFontName());
1239 if (lyxrc.typewriter_font_name.empty())
1240 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1242 #if (QT_VERSION >= 0x050000)
1243 // Qt4 does this in event(), see below.
1244 // Track change of keyboard
1245 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1248 d->general_timer_.setInterval(500);
1249 connect(&d->general_timer_, SIGNAL(timeout()),
1250 this, SLOT(handleRegularEvents()));
1251 d->general_timer_.start();
1253 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1254 // This is clearly not enough in a time where we use threads for
1255 // document preview and/or export. 20 should be OK.
1256 QThreadPool::globalInstance()->setMaxThreadCount(20);
1258 // make sure tooltips are formatted
1259 installEventFilter(new ToolTipFormatter(this));
1263 GuiApplication * theGuiApp()
1265 return dynamic_cast<GuiApplication *>(theApp());
1269 #if QT_VERSION < 0x050000
1270 // Emulate platformName() for Qt4
1272 // FIXME: when ditching this method, remove all tests
1273 // platformName() == "qt4x11"
1275 QString GuiApplication::platformName() const
1277 # if defined(Q_WS_X11)
1278 // Note that this one does not really exist
1280 # elif defined(Q_OS_MAC)
1282 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1285 LYXERR0("Unknown platform!");
1292 double GuiApplication::pixelRatio() const
1294 #if QT_VERSION >= 0x050000
1295 return qt_scale_factor * devicePixelRatio();
1302 void GuiApplication::clearSession()
1309 docstring Application::iconName(FuncRequest const & f, bool unknown)
1311 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1315 docstring Application::mathIcon(docstring const & c)
1317 return qstring_to_ucs4(findImg(toqstr(c)));
1321 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1325 BufferView * bv = nullptr;
1326 BufferView * doc_bv = nullptr;
1328 if (cmd.action() == LFUN_NOACTION) {
1329 status.message(from_utf8(N_("Nothing to do")));
1330 status.setEnabled(false);
1333 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1334 status.setUnknown(true);
1335 status.message(from_utf8(N_("Unknown action")));
1336 status.setEnabled(false);
1339 // Does the GuiApplication know something?
1340 else if (getStatus(cmd, status)) { }
1342 // If we do not have a GuiView, then other functions are disabled
1343 else if (!current_view_)
1344 status.setEnabled(false);
1346 // Does the GuiView know something?
1347 else if (current_view_->getStatus(cmd, status)) { }
1349 // In LyX/Mac, when a dialog is open, the menus of the
1350 // application can still be accessed without giving focus to
1351 // the main window. In this case, we want to disable the menu
1352 // entries that are buffer or view-related.
1353 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1355 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1356 status.setEnabled(false);
1359 // If we do not have a BufferView, then other functions are disabled
1360 else if (!(bv = current_view_->currentBufferView()))
1361 status.setEnabled(false);
1363 // Does the current BufferView know something?
1364 else if (bv->getStatus(cmd, status)) { }
1366 // Does the current Buffer know something?
1367 else if (bv->buffer().getStatus(cmd, status)) { }
1369 // If we do not have a document BufferView, different from the
1370 // current BufferView, then other functions are disabled
1371 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1372 status.setEnabled(false);
1374 // Does the document Buffer know something?
1375 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1378 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1379 status.message(from_utf8(N_("Command not handled")));
1380 status.setEnabled(false);
1383 // the default error message if we disable the command
1384 if (!status.enabled() && status.message().empty())
1385 status.message(from_utf8(N_("Command disabled")));
1391 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1393 // I would really like to avoid having this switch and rather try to
1394 // encode this in the function itself.
1395 // -- And I'd rather let an inset decide which LFUNs it is willing
1396 // to handle (Andre')
1398 switch (cmd.action()) {
1400 // This could be used for the no-GUI version. The GUI version is handled in
1401 // GuiView::getStatus(). See above.
1403 case LFUN_BUFFER_WRITE:
1404 case LFUN_BUFFER_WRITE_AS:
1405 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1406 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1407 enable = b && (b->isUnnamed() || !b->isClean());
1412 case LFUN_BOOKMARK_GOTO: {
1413 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1414 enable = theSession().bookmarks().isValid(num);
1418 case LFUN_BOOKMARK_CLEAR:
1419 enable = theSession().bookmarks().hasValid();
1422 // this one is difficult to get right. As a half-baked
1423 // solution, we consider only the first action of the sequence
1424 case LFUN_COMMAND_SEQUENCE: {
1425 // argument contains ';'-terminated commands
1426 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1427 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1428 func.setOrigin(cmd.origin());
1429 flag = getStatus(func);
1433 // we want to check if at least one of these is enabled
1434 case LFUN_COMMAND_ALTERNATIVES: {
1435 // argument contains ';'-terminated commands
1436 string arg = to_utf8(cmd.argument());
1437 while (!arg.empty()) {
1439 arg = split(arg, first, ';');
1440 FuncRequest func(lyxaction.lookupFunc(first));
1441 func.setOrigin(cmd.origin());
1442 flag = getStatus(func);
1443 // if this one is enabled, the whole thing is
1452 string name = to_utf8(cmd.argument());
1453 if (theTopLevelCmdDef().lock(name, func)) {
1454 func.setOrigin(cmd.origin());
1455 flag = getStatus(func);
1456 theTopLevelCmdDef().release(name);
1458 // catch recursion or unknown command
1459 // definition. all operations until the
1460 // recursion or unknown command definition
1461 // occurs are performed, so set the state to
1468 case LFUN_IF_RELATIVES: {
1469 string const lfun = to_utf8(cmd.argument());
1470 BufferView const * bv =
1471 current_view_ ? current_view_->currentBufferView() : nullptr;
1472 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1476 FuncRequest func(lyxaction.lookupFunc(lfun));
1477 func.setOrigin(cmd.origin());
1478 flag = getStatus(func);
1482 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1484 case LFUN_PREFERENCES_SAVE:
1485 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1486 // these are handled in our dispatch()
1489 case LFUN_DEBUG_LEVEL_SET: {
1490 string bad = Debug::badValue(to_utf8(cmd.argument()));
1491 enable = bad.empty();
1493 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1497 case LFUN_WINDOW_CLOSE:
1498 enable = !d->views_.empty();
1501 case LFUN_BUFFER_NEW:
1502 case LFUN_BUFFER_NEW_TEMPLATE:
1503 case LFUN_FILE_OPEN:
1504 case LFUN_LYXFILES_OPEN:
1505 case LFUN_HELP_OPEN:
1506 case LFUN_SCREEN_FONT_UPDATE:
1507 case LFUN_SET_COLOR:
1508 case LFUN_WINDOW_NEW:
1510 case LFUN_LYXRC_APPLY:
1511 case LFUN_COMMAND_PREFIX:
1513 case LFUN_META_PREFIX:
1514 case LFUN_RECONFIGURE:
1515 case LFUN_SERVER_GET_FILENAME:
1516 case LFUN_SERVER_NOTIFY:
1520 case LFUN_BUFFER_FORALL: {
1521 if (theBufferList().empty()) {
1522 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1523 flag.setEnabled(false);
1527 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1528 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1529 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1530 flag.setEnabled(false);
1535 case LFUN_DIALOG_SHOW: {
1536 string const name = cmd.getArg(0);
1537 return name == "aboutlyx"
1538 || name == "lyxfiles"
1540 || name == "texinfo"
1541 || name == "progress"
1542 || name == "compare";
1550 flag.setEnabled(false);
1554 /// make a post-dispatch status message
1555 static docstring makeDispatchMessage(docstring const & msg,
1556 FuncRequest const & cmd)
1558 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1559 || cmd.origin() == FuncRequest::TOOLBAR
1560 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1562 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1563 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1567 docstring dispatch_msg = msg;
1568 if (!dispatch_msg.empty())
1569 dispatch_msg += ' ';
1571 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1573 bool argsadded = false;
1575 if (!cmd.argument().empty()) {
1576 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1577 comname += ' ' + cmd.argument();
1581 docstring const shortcuts = theTopLevelKeymap().
1582 printBindings(cmd, KeySequence::ForGui);
1584 if (!shortcuts.empty())
1585 comname += ": " + shortcuts;
1586 else if (!argsadded && !cmd.argument().empty())
1587 comname += ' ' + cmd.argument();
1589 if (!comname.empty()) {
1590 comname = rtrim(comname);
1591 dispatch_msg += '(' + rtrim(comname) + ')';
1593 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1594 return dispatch_msg;
1598 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1602 Buffer * buffer = nullptr;
1603 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1604 //setCurrentView(cmd.view_origin); //does not work
1606 dr.setMessage(_("Wrong focus!"));
1607 d->dispatch_result_ = dr;
1608 return d->dispatch_result_;
1610 if (current_view_ && current_view_->currentBufferView()) {
1611 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1612 buffer = ¤t_view_->currentBufferView()->buffer();
1615 dr.screenUpdate(Update::FitCursor);
1617 // All the code is kept inside the undo group because
1618 // updateBuffer can create undo actions (see #11292)
1619 UndoGroupHelper ugh(buffer);
1621 if (dr.screenUpdate() & Update::ForceAll) {
1622 for (Buffer const * b : theBufferList())
1624 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1627 updateCurrentView(cmd, dr);
1630 d->dispatch_result_ = dr;
1631 return d->dispatch_result_;
1635 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1640 BufferView * bv = current_view_->currentBufferView();
1642 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1643 bv->cursor().clearBufferUpdate();
1644 bv->buffer().updateBuffer();
1646 // BufferView::update() updates the ViewMetricsInfo and
1647 // also initializes the position cache for all insets in
1648 // (at least partially) visible top-level paragraphs.
1649 // We will redraw the screen only if needed.
1650 bv->processUpdateFlags(dr.screenUpdate());
1652 // Do we have a selection?
1653 theSelection().haveSelection(bv->cursor().selection());
1656 current_view_->restartCaret();
1658 if (dr.needMessageUpdate()) {
1659 // Some messages may already be translated, so we cannot use _()
1660 current_view_->message(makeDispatchMessage(
1661 translateIfPossible(dr.message()), cmd));
1666 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1667 bool switchToBuffer)
1669 if (!theSession().bookmarks().isValid(idx))
1671 BookmarksSection::Bookmark const & bm =
1672 theSession().bookmarks().bookmark(idx);
1673 LASSERT(!bm.filename.empty(), return);
1674 string const file = bm.filename.absFileName();
1675 // if the file is not opened, open it.
1676 if (!theBufferList().exists(bm.filename)) {
1678 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1682 // open may fail, so we need to test it again
1683 if (!theBufferList().exists(bm.filename))
1686 // bm can be changed when saving
1687 BookmarksSection::Bookmark tmp = bm;
1689 // Special case idx == 0 used for back-from-back jump navigation
1691 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1693 // if the current buffer is not that one, switch to it.
1694 BufferView * doc_bv = current_view_ ?
1695 current_view_->documentBufferView() : nullptr;
1696 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1697 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1698 if (switchToBuffer) {
1699 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1702 doc_bv = current_view_->documentBufferView();
1707 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1708 if (!doc_bv || !doc_bv->moveToPosition(
1709 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1712 Cursor & cur = doc_bv->cursor();
1713 if (old && cur != *old)
1714 notifyCursorLeavesOrEnters(*old, cur);
1720 // Cursor jump succeeded!
1721 pit_type new_pit = cur.pit();
1722 pos_type new_pos = cur.pos();
1723 int new_id = cur.paragraph().id();
1725 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1726 // see http://www.lyx.org/trac/ticket/3092
1727 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1728 || bm.top_id != new_id) {
1729 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1730 new_pit, new_pos, new_id);
1734 // This function runs "configure" and then rereads lyx.defaults to
1735 // reconfigure the automatic settings.
1736 void GuiApplication::reconfigure(string const & option)
1738 // emit message signal.
1739 if (current_view_) {
1740 current_view_->message(_("Running configure..."));
1741 current_view_->setCursor(Qt::WaitCursor);
1744 // Run configure in user lyx directory
1745 string const lock_file = package().getConfigureLockName();
1746 int fd = fileLock(lock_file.c_str());
1747 int const ret = package().reconfigureUserLyXDir(option);
1748 // emit message signal.
1750 current_view_->message(_("Reloading configuration..."));
1751 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1752 // Re-read packages.lst
1753 LaTeXPackages::getAvailable();
1754 fileUnlock(fd, lock_file.c_str());
1757 current_view_->unsetCursor();
1760 Alert::information(_("System reconfiguration failed"),
1761 _("The system reconfiguration has failed.\n"
1762 "Default textclass is used but LyX may\n"
1763 "not be able to work properly.\n"
1764 "Please reconfigure again if needed."));
1766 Alert::information(_("System reconfigured"),
1767 _("The system has been reconfigured.\n"
1768 "You need to restart LyX to make use of any\n"
1769 "updated document class specifications."));
1772 void GuiApplication::validateCurrentView()
1774 if (!d->views_.empty() && !current_view_) {
1775 // currently at least one view exists but no view has the focus.
1776 // choose the last view to make it current.
1777 // a view without any open document is preferred.
1778 GuiView * candidate = nullptr;
1779 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1780 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1781 for (; it != end; ++it) {
1783 if (!candidate->documentBufferView())
1786 setCurrentView(candidate);
1790 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1792 string const argument = to_utf8(cmd.argument());
1793 FuncCode const action = cmd.action();
1795 LYXERR(Debug::ACTION, "cmd: " << cmd);
1797 // we have not done anything wrong yet.
1800 FuncStatus const flag = getStatus(cmd);
1801 if (!flag.enabled()) {
1802 // We cannot use this function here
1803 LYXERR(Debug::ACTION, "action "
1804 << lyxaction.getActionName(action)
1805 << " [" << action << "] is disabled at this location");
1806 dr.setMessage(flag.message());
1808 dr.dispatched(false);
1809 dr.screenUpdate(Update::None);
1810 dr.clearBufferUpdate();
1814 if (cmd.origin() == FuncRequest::LYXSERVER) {
1815 if (current_view_ && current_view_->currentBufferView())
1816 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1817 // we will also need to redraw the screen at the end
1818 dr.screenUpdate(Update::FitCursor);
1821 // Assumes that the action will be dispatched.
1822 dr.dispatched(true);
1824 switch (cmd.action()) {
1826 case LFUN_WINDOW_NEW:
1827 createView(toqstr(cmd.argument()));
1830 case LFUN_WINDOW_CLOSE:
1831 // FIXME: this is done also in GuiView::closeBuffer()!
1832 // update bookmark pit of the current buffer before window close
1833 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1834 gotoBookmark(i, false, false);
1835 // clear the last opened list, because
1836 // maybe this will end the session
1837 theSession().lastOpened().clear();
1838 // check for valid current_view_
1839 validateCurrentView();
1841 current_view_->closeScheduled();
1845 // quitting is triggered by the gui code
1846 // (leaving the event loop).
1848 current_view_->message(from_utf8(N_("Exiting.")));
1849 if (closeAllViews())
1853 case LFUN_SCREEN_FONT_UPDATE: {
1854 // handle the screen font changes.
1855 /* FIXME: this only updates the current document, whereas all
1856 * documents should see their metrics updated.
1858 d->font_loader_.update();
1859 dr.screenUpdate(Update::Force | Update::FitCursor);
1863 case LFUN_BUFFER_NEW:
1864 validateCurrentView();
1866 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1867 createView(QString(), false); // keep hidden
1868 current_view_->newDocument(to_utf8(cmd.argument()));
1869 current_view_->show();
1870 setActiveWindow(current_view_);
1872 current_view_->newDocument(to_utf8(cmd.argument()));
1876 case LFUN_BUFFER_NEW_TEMPLATE: {
1877 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1878 string const temp = cmd.getArg(1);
1879 validateCurrentView();
1881 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1883 current_view_->newDocument(file, temp, true);
1884 if (!current_view_->documentBufferView())
1885 current_view_->close();
1887 current_view_->newDocument(file, temp, true);
1892 case LFUN_FILE_OPEN: {
1893 // FIXME: normally the code below is not needed, since getStatus makes sure that
1894 // current_view_ is not null.
1895 validateCurrentView();
1896 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1897 string const fname = trim(to_utf8(cmd.argument()), "\"");
1898 bool const is_open = FileName::isAbsolute(fname)
1899 && theBufferList().getBuffer(FileName(fname));
1901 || (!lyxrc.open_buffers_in_tabs
1902 && current_view_->documentBufferView() != nullptr
1904 // We want the ui session to be saved per document and not per
1905 // window number. The filename crc is a good enough identifier.
1906 createView(support::checksum(fname));
1907 current_view_->openDocument(fname);
1908 if (!current_view_->documentBufferView())
1909 current_view_->close();
1910 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1911 current_view_->raise();
1912 current_view_->activateWindow();
1913 current_view_->showNormal();
1916 current_view_->openDocument(fname);
1917 if (cmd.origin() == FuncRequest::LYXSERVER) {
1918 current_view_->raise();
1919 current_view_->activateWindow();
1920 current_view_->showNormal();
1926 case LFUN_HELP_OPEN: {
1927 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1928 if (current_view_ == nullptr)
1930 string const arg = to_utf8(cmd.argument());
1932 current_view_->message(_("Missing argument"));
1935 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1937 fname = i18nLibFileSearch("examples", arg, "lyx");
1939 if (fname.empty()) {
1940 lyxerr << "LyX: unable to find documentation file `"
1941 << arg << "'. Bad installation?" << endl;
1944 current_view_->message(bformat(_("Opening help file %1$s..."),
1945 makeDisplayPath(fname.absFileName())));
1946 Buffer * buf = current_view_->loadDocument(fname, false);
1948 buf->setReadonly(!current_view_->develMode());
1952 case LFUN_LYXFILES_OPEN: {
1953 // This is the actual reason for this method (#12106).
1954 validateCurrentView();
1956 || (!lyxrc.open_buffers_in_tabs
1957 && current_view_->documentBufferView() != nullptr))
1959 string arg = to_utf8(cmd.argument());
1963 if (arg != "templates" && arg != "examples") {
1964 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1967 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1971 case LFUN_SET_COLOR: {
1972 string const lyx_name = cmd.getArg(0);
1973 string x11_name = cmd.getArg(1);
1974 string x11_darkname = cmd.getArg(2);
1975 if (lyx_name.empty() || x11_name.empty()) {
1977 current_view_->message(
1978 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1983 // FIXME: The graphics cache no longer has a changeDisplay method.
1984 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1985 bool const graphicsbg_changed =
1986 lyx_name == graphicsbg && x11_name != graphicsbg;
1987 if (graphicsbg_changed)
1988 graphics::GCache::get().changeDisplay(true);
1991 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1992 x11_darkname = x11_name;
1995 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1997 current_view_->message(
1998 bformat(_("Set-color \"%1$s\" failed "
1999 "- color is undefined or "
2000 "may not be redefined"),
2001 from_utf8(lyx_name)));
2004 // Make sure we don't keep old colors in cache.
2005 d->color_cache_.clear();
2006 // Update the current view
2007 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2011 case LFUN_LYXRC_APPLY: {
2012 // reset active key sequences, since the bindings
2013 // are updated (bug 6064)
2015 LyXRC const lyxrc_orig = lyxrc;
2017 istringstream ss(to_utf8(cmd.argument()));
2018 bool const success = lyxrc.read(ss);
2021 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
2022 << "Unable to read lyxrc data"
2027 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
2029 // If the request comes from the minibuffer, then we can't reset
2030 // the GUI, since that would destroy the minibuffer itself and
2031 // cause a crash, since we are currently in one of the methods of
2032 // GuiCommandBuffer. See bug #8540.
2033 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
2036 // FIXME Unfortunately, that leaves a bug here, since we cannot
2037 // reset the GUI in this case. If the changes to lyxrc affected the
2038 // UI, then, nothing would happen. This seems fairly unlikely, but
2039 // it definitely is a bug.
2041 dr.forceBufferUpdate();
2045 case LFUN_COMMAND_PREFIX:
2046 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2051 d->meta_fake_bit = NoModifier;
2052 GuiView * gv = currentView();
2053 if (gv && gv->currentBufferView())
2054 // cancel any selection
2055 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2056 dr.setMessage(from_ascii(N_("Cancel")));
2059 case LFUN_META_PREFIX:
2060 d->meta_fake_bit = AltModifier;
2061 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2064 // --- Menus -----------------------------------------------
2065 case LFUN_RECONFIGURE:
2066 // argument is any additional parameter to the configure.py command
2067 reconfigure(to_utf8(cmd.argument()));
2070 // --- lyxserver commands ----------------------------
2071 case LFUN_SERVER_GET_FILENAME: {
2072 if (current_view_ && current_view_->documentBufferView()) {
2073 docstring const fname = from_utf8(
2074 current_view_->documentBufferView()->buffer().absFileName());
2075 dr.setMessage(fname);
2076 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2078 dr.setMessage(docstring());
2079 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2084 case LFUN_SERVER_NOTIFY: {
2085 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2086 dr.setMessage(dispatch_buffer);
2087 theServer().notifyClient(to_utf8(dispatch_buffer));
2091 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2092 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2098 string rest = split(argument, countstr, ' ');
2099 int const count = convert<int>(countstr);
2100 // an arbitrary number to limit number of iterations
2101 int const max_iter = 10000;
2102 if (count > max_iter) {
2103 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2106 for (int i = 0; i < count; ++i) {
2107 FuncRequest lfun = lyxaction.lookupFunc(rest);
2108 lfun.allowAsync(false);
2115 case LFUN_COMMAND_SEQUENCE: {
2116 // argument contains ';'-terminated commands
2117 string arg = argument;
2118 // FIXME: this LFUN should also work without any view.
2119 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2120 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2121 // This handles undo groups automagically
2122 UndoGroupHelper ugh(buffer);
2123 while (!arg.empty()) {
2125 arg = split(arg, first, ';');
2126 FuncRequest func(lyxaction.lookupFunc(first));
2127 func.allowAsync(false);
2128 func.setOrigin(cmd.origin());
2134 case LFUN_BUFFER_FORALL: {
2135 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2136 funcToRun.allowAsync(false);
2138 map<Buffer *, GuiView *> views_lVisible;
2139 map<GuiView *, Buffer *> activeBuffers;
2141 QList<GuiView *> allViews = d->views_.values();
2143 // this for does not modify any buffer. It just collects info on local
2144 // visibility of buffers and on which buffer is active in each view.
2145 Buffer * const last = theBufferList().last();
2146 for(GuiView * view : allViews) {
2147 // all of the buffers might be locally hidden. That is, there is no
2149 if (!view || !view->currentBufferView())
2150 activeBuffers[view] = nullptr;
2152 activeBuffers[view] = &view->currentBufferView()->buffer();
2154 // find out if each is locally visible or locally hidden.
2155 // we don't use a for loop as the buffer list cycles.
2156 Buffer * b = theBufferList().first();
2158 bool const locallyVisible = view && view->workArea(*b);
2159 if (locallyVisible) {
2160 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2161 // only need to overwrite/add if we don't already know a buffer is globally
2162 // visible or we do know but we would prefer to dispatch LFUN from the
2163 // current view because of cursor position issues.
2164 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2165 views_lVisible[b] = view;
2169 b = theBufferList().next(b);
2173 GuiView * const homeView = currentView();
2174 Buffer * b = theBufferList().first();
2175 Buffer * nextBuf = nullptr;
2176 int numProcessed = 0;
2179 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2181 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2183 // first change to a view where b is locally visible, preferably current_view_.
2184 GuiView * const vLv = views_lVisible[b];
2186 lyx::dispatch(funcToRun);
2194 // put things back to how they were (if possible).
2195 for (GuiView * view : allViews) {
2196 Buffer * originalBuf = activeBuffers[view];
2197 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2198 if (theBufferList().isLoaded(originalBuf))
2199 view->setBuffer(originalBuf);
2201 homeView->setFocus();
2203 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2207 case LFUN_COMMAND_ALTERNATIVES: {
2208 // argument contains ';'-terminated commands
2209 string arg = argument;
2210 while (!arg.empty()) {
2212 arg = split(arg, first, ';');
2213 FuncRequest func(lyxaction.lookupFunc(first));
2214 func.setOrigin(cmd.origin());
2215 FuncStatus const stat = getStatus(func);
2216 if (stat.enabled()) {
2226 if (theTopLevelCmdDef().lock(argument, func)) {
2227 func.setOrigin(cmd.origin());
2229 theTopLevelCmdDef().release(argument);
2231 if (func.action() == LFUN_UNKNOWN_ACTION) {
2232 // unknown command definition
2233 lyxerr << "Warning: unknown command definition `"
2237 // recursion detected
2238 lyxerr << "Warning: Recursion in the command definition `"
2239 << argument << "' detected"
2246 case LFUN_IF_RELATIVES: {
2247 string const lfun = to_utf8(cmd.argument());
2248 FuncRequest func(lyxaction.lookupFunc(lfun));
2249 func.setOrigin(cmd.origin());
2250 FuncStatus const stat = getStatus(func);
2251 if (stat.enabled()) {
2258 case LFUN_PREFERENCES_SAVE:
2259 lyxrc.write(support::makeAbsPath("preferences",
2260 package().user_support().absFileName()), false);
2263 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2264 string const fname = addName(addPath(package().user_support().absFileName(),
2265 "templates/"), "defaults.lyx");
2266 Buffer defaults(fname);
2268 istringstream ss(argument);
2273 // We need to make sure that, after we recreat the DocumentClass,
2274 // which we do in readHeader, we apply it to the document itself.
2275 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2276 int const unknown_tokens = defaults.readHeader(lex);
2277 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2278 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2279 cap::switchBetweenClasses(olddc, newdc, theinset);
2281 if (unknown_tokens != 0) {
2282 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2283 << unknown_tokens << " unknown token"
2284 << (unknown_tokens == 1 ? "" : "s")
2288 if (defaults.writeFile(FileName(defaults.absFileName())))
2289 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2290 makeDisplayPath(fname)));
2293 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2298 case LFUN_BOOKMARK_GOTO:
2299 // go to bookmark, open unopened file and switch to buffer if necessary
2300 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2301 dr.screenUpdate(Update::Force | Update::FitCursor);
2304 case LFUN_BOOKMARK_CLEAR:
2305 theSession().bookmarks().clear();
2306 dr.screenUpdate(Update::Force);
2309 case LFUN_DEBUG_LEVEL_SET:
2310 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2313 case LFUN_DIALOG_SHOW: {
2314 string const name = cmd.getArg(0);
2316 if ( name == "aboutlyx"
2318 || name == "texinfo"
2319 || name == "progress"
2320 || name == "compare")
2322 // work around: on Mac OS the application
2323 // is not terminated when closing the last view.
2324 // Create a new one to be able to dispatch the
2325 // LFUN_DIALOG_SHOW to this view.
2326 if (current_view_ == nullptr)
2332 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2335 current_view_->dispatch(cmd, dr);
2339 if (current_view_ && current_view_->isFullScreen()) {
2340 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2341 current_view_->menuBar()->hide();
2344 if (cmd.origin() == FuncRequest::LYXSERVER)
2345 updateCurrentView(cmd, dr);
2349 docstring GuiApplication::viewStatusMessage()
2351 // When meta-fake key is pressed, show the key sequence so far + "M-".
2352 if (d->meta_fake_bit != NoModifier)
2353 return d->keyseq.print(KeySequence::ForGui) + "M-";
2355 // Else, when a non-complete key sequence is pressed,
2356 // show the available options.
2357 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2358 return d->keyseq.printOptions(true);
2364 string GuiApplication::inputLanguageCode() const
2366 #if (QT_VERSION < 0x050000)
2367 QLocale loc = keyboardInputLocale();
2369 QLocale loc = inputMethod()->locale();
2371 //LYXERR0("input lang = " << fromqstr(loc.name()));
2372 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2376 void GuiApplication::onLocaleChanged()
2378 //LYXERR0("Change language to " << inputLanguage()->lang());
2379 if (currentView() && currentView()->currentBufferView())
2380 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2384 void GuiApplication::onPaletteChanged()
2386 colorCache().setPalette(palette());
2390 void GuiApplication::handleKeyFunc(FuncCode action)
2394 if (d->keyseq.length())
2396 GuiView * gv = currentView();
2397 LASSERT(gv && gv->currentBufferView(), return);
2398 BufferView * bv = gv->currentBufferView();
2399 bv->getIntl().getTransManager().deadkey(
2400 c, get_accent(action).accent, bv->cursor().innerText(),
2402 // Need to clear, in case the minibuffer calls these
2405 // copied verbatim from do_accent_char
2406 bv->cursor().resetAnchor();
2410 //Keep this in sync with GuiApplication::processKeySym below
2411 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2412 KeyModifier state) const
2414 // Do nothing if we have nothing
2415 if (!keysym.isOK() || keysym.isModifier())
2417 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2419 FuncRequest func = seq.addkey(keysym, state);
2420 // When not cancel or meta-fake, do the normal lookup.
2421 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2423 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2425 // Maybe user can only reach the key via holding down shift.
2426 // Let's see. But only if shift is the only modifier
2427 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2428 // If addkey looked up a command and did not find further commands then
2429 // seq has been reset at this point
2430 func = seq.addkey(keysym, NoModifier);
2432 LYXERR(Debug::KEY, " Key (queried) [action="
2433 << lyxaction.getActionName(func.action()) << "]["
2434 << seq.print(KeySequence::Portable) << ']');
2435 return func.action() != LFUN_UNKNOWN_ACTION;
2439 //Keep this in sync with GuiApplication::queryKeySym above
2440 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2442 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2444 // Do nothing if we have nothing (JMarc)
2445 if (!keysym.isOK() || keysym.isModifier()) {
2447 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2449 current_view_->restartCaret();
2453 char_type encoded_last_key = keysym.getUCSEncoded();
2455 // Do a one-deep top-level lookup for
2456 // cancel and meta-fake keys. RVDK_PATCH_5
2457 d->cancel_meta_seq.reset();
2459 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2460 LYXERR(Debug::KEY, "action first set to ["
2461 << lyxaction.getActionName(func.action()) << ']');
2463 // When not cancel or meta-fake, do the normal lookup.
2464 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2465 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2466 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2467 // remove Caps Lock and Mod2 as a modifiers
2468 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2469 LYXERR(Debug::KEY, "action now set to ["
2470 << lyxaction.getActionName(func.action()) << ']');
2473 // Don't remove this unless you know what you are doing.
2474 d->meta_fake_bit = NoModifier;
2476 // Can this happen now ?
2477 if (func.action() == LFUN_NOACTION)
2478 func = FuncRequest(LFUN_COMMAND_PREFIX);
2480 LYXERR(Debug::KEY, " Key [action="
2481 << lyxaction.getActionName(func.action()) << "]["
2482 << d->keyseq.print(KeySequence::Portable) << ']');
2484 // already here we know if it any point in going further
2485 // why not return already here if action == -1 and
2486 // num_bytes == 0? (Lgb)
2488 if (d->keyseq.length() > 1 && current_view_)
2489 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2492 // Maybe user can only reach the key via holding down shift.
2493 // Let's see. But only if shift is the only modifier
2494 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2495 LYXERR(Debug::KEY, "Trying without shift");
2496 // If addkey looked up a command and did not find further commands then
2497 // seq has been reset at this point
2498 func = d->keyseq.addkey(keysym, NoModifier);
2499 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2502 if (func.action() == LFUN_UNKNOWN_ACTION) {
2503 // We didn't match any of the key sequences.
2504 // See if it's normal insertable text not already
2505 // covered by a binding
2506 if (keysym.isText() && d->keyseq.length() == 1) {
2507 // Non-printable characters (such as ASCII control characters)
2508 // must not be inserted (#5704)
2509 if (!isPrintable(encoded_last_key)) {
2510 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2512 current_view_->restartCaret();
2515 // The following modifier check is not needed on Mac.
2516 // The keysym is either not text or it is different
2517 // from the non-modifier keysym. See #9875 for the
2518 // broken alt-modifier effect of having this code active.
2519 #if !defined(Q_OS_MAC)
2520 // If a non-Shift Modifier is used we have a non-bound key sequence
2521 // (such as Alt+j = j). This should be omitted (#5575).
2522 // On Windows, AltModifier and ControlModifier are both
2523 // set when AltGr is pressed. Therefore, in order to not
2524 // break AltGr-bound symbols (see #5575 for details),
2525 // unbound Ctrl+Alt key sequences are allowed.
2526 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2527 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2528 && !(state & AltModifier && state & ControlModifier)
2532 if (current_view_) {
2533 current_view_->message(_("Unknown function."));
2534 current_view_->restartCaret();
2539 // Since all checks above were passed, we now really have text that
2540 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2541 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2543 LYXERR(Debug::KEY, "isText() is true, inserting.");
2544 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2546 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2547 if (current_view_) {
2548 current_view_->message(_("Unknown function."));
2549 current_view_->restartCaret();
2555 if (func.action() == LFUN_SELF_INSERT) {
2556 if (encoded_last_key != 0) {
2557 docstring const arg(1, encoded_last_key);
2558 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2559 FuncRequest::KEYBOARD));
2560 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2563 processFuncRequest(func);
2567 void GuiApplication::processFuncRequest(FuncRequest const & func)
2569 lyx::dispatch(func);
2573 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2575 addToFuncRequestQueue(func);
2576 processFuncRequestQueueAsync();
2580 void GuiApplication::processFuncRequestQueue()
2582 while (!d->func_request_queue_.empty()) {
2583 // take the item from the stack _before_ processing the
2584 // request in order to avoid race conditions from nested
2585 // or parallel requests (see #10406)
2586 FuncRequest const fr(d->func_request_queue_.front());
2587 d->func_request_queue_.pop();
2588 processFuncRequest(fr);
2593 void GuiApplication::processFuncRequestQueueAsync()
2595 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2599 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2601 d->func_request_queue_.push(func);
2605 void GuiApplication::resetGui()
2607 // Set the language defined by the user.
2611 if (!readUIFile(toqstr(lyxrc.ui_file)))
2612 // Gives some error box here.
2615 if (d->global_menubar_)
2616 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2618 QHash<int, GuiView *>::iterator it;
2619 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2622 gv->setLayoutDirection(layoutDirection());
2626 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2630 bool GuiApplication::rtlContext() const
2632 if (current_view_ && current_view_->currentBufferView()) {
2633 BufferView const * bv = current_view_->currentBufferView();
2634 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2636 return layoutDirection() == Qt::RightToLeft;
2640 void GuiApplication::createView(int view_id)
2642 createView(QString(), true, view_id);
2646 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2649 // release the keyboard which might have been grabbed by the global
2650 // menubar on Mac to catch shortcuts even without any GuiView.
2651 if (d->global_menubar_)
2652 d->global_menubar_->releaseKeyboard();
2656 while (d->views_.find(id) != d->views_.end())
2659 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2660 GuiView * view = new GuiView(id);
2661 // `view' is the new current_view_. Tell coverity that is is not 0.
2662 LATTEST(current_view_);
2664 d->views_[id] = view;
2668 setActiveWindow(view);
2671 if (!geometry_arg.isEmpty()) {
2672 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2676 #if QT_VERSION < 0x060000
2677 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2678 re.indexIn(geometry_arg);
2679 w = re.cap(1).toInt();
2680 h = re.cap(2).toInt();
2681 x = re.cap(3).toInt();
2682 y = re.cap(4).toInt();
2683 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2684 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2686 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2687 QRegularExpressionMatch match = re.match(geometry_arg);
2688 w = match.captured(1).toInt();
2689 h = match.captured(2).toInt();
2690 x = match.captured(3).toInt();
2691 y = match.captured(4).toInt();
2692 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2693 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2695 // Set initial geometry such that we can get the frame size.
2696 view->setGeometry(x, y, w, h);
2697 int framewidth = view->geometry().x() - view->x();
2698 int titleheight = view->geometry().y() - view->y();
2699 // Negative displacements must be interpreted as distances
2700 // from the right or bottom screen borders.
2701 if (sx == '-' || sy == '-') {
2702 #if QT_VERSION < 0x060000
2703 QRect rec = QApplication::desktop()->screenGeometry();
2705 QRect rec = QGuiApplication::primaryScreen()->geometry();
2708 x += rec.width() - w - framewidth;
2710 y += rec.height() - h - titleheight;
2711 view->setGeometry(x, y, w, h);
2713 // Make sure that the left and top frame borders are visible.
2714 if (view->x() < 0 || view->y() < 0) {
2719 view->setGeometry(x, y, w, h);
2727 bool GuiApplication::unhide(Buffer * buf)
2731 currentView()->setBuffer(buf, false);
2736 Clipboard & GuiApplication::clipboard()
2738 return d->clipboard_;
2742 Selection & GuiApplication::selection()
2744 return d->selection_;
2748 FontLoader & GuiApplication::fontLoader()
2750 return d->font_loader_;
2754 Toolbars const & GuiApplication::toolbars() const
2756 return d->toolbars_;
2760 Toolbars & GuiApplication::toolbars()
2762 return d->toolbars_;
2766 Menus const & GuiApplication::menus() const
2772 Menus & GuiApplication::menus()
2778 bool GuiApplication::needsBackingStore() const
2780 /* Qt on macOS and Wayland does not respect the
2781 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2782 * store at each update. Therefore, we use our own backing store
2783 * in these two cases. It is also possible to force the use of the
2784 * backing store for cases like x11 with transparent WM themes.
2786 return platformName() == "cocoa" || platformName().contains("wayland");
2790 QList<int> GuiApplication::viewIds() const
2792 return d->views_.keys();
2796 ColorCache & GuiApplication::colorCache()
2798 return d->color_cache_;
2802 int GuiApplication::exec()
2804 // asynchronously handle batch commands. This event will be in
2805 // the event queue in front of other asynchronous events. Hence,
2806 // we can assume in the latter that the gui is setup already.
2807 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2809 return QApplication::exec();
2813 void GuiApplication::exit(int status)
2815 QApplication::exit(status);
2819 void GuiApplication::setGuiLanguage()
2823 // install translation file for Qt built-in dialogs
2824 QString const language_name = QString("qt_") + theLocale.name();
2825 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2826 // Short-named translator can be loaded from a long name, but not the
2827 // opposite. Therefore, long name should be used without truncation.
2828 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2829 if (!d->qt_trans_.load(language_name,
2830 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2831 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2833 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2835 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2838 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2842 switch (theLocale.language()) {
2843 case QLocale::Arabic :
2844 case QLocale::Hebrew :
2845 case QLocale::Persian :
2846 case QLocale::Urdu :
2847 setLayoutDirection(Qt::RightToLeft);
2850 setLayoutDirection(Qt::LeftToRight);
2855 void GuiApplication::execBatchCommands()
2860 if (!readUIFile(toqstr(lyxrc.ui_file)))
2861 // Gives some error box here.
2865 #if QT_VERSION > 0x040600
2866 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2868 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2869 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2871 // Create the global default menubar which is shown for the dialogs
2872 // and if no GuiView is visible.
2873 // This must be done after the session was recovered to know the "last files".
2874 d->global_menubar_ = new QMenuBar(0);
2875 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2878 lyx::execBatchCommands();
2882 QAbstractItemModel * GuiApplication::languageModel()
2884 if (d->language_model_)
2885 return d->language_model_;
2887 QStandardItemModel * lang_model = new QStandardItemModel(this);
2888 lang_model->insertColumns(0, 3);
2889 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2890 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2891 Languages::const_iterator it = lyx::languages.begin();
2892 Languages::const_iterator end = lyx::languages.end();
2893 for (; it != end; ++it) {
2894 int current_row = lang_model->rowCount();
2895 lang_model->insertRows(current_row, 1);
2896 QModelIndex pl_item = lang_model->index(current_row, 0);
2897 QModelIndex sp_item = lang_model->index(current_row, 1);
2898 QModelIndex th_item = lang_model->index(current_row, 2);
2899 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2900 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2901 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2902 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2903 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2904 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2905 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2906 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2907 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2908 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2910 d->language_model_ = new QSortFilterProxyModel(this);
2911 d->language_model_->setSourceModel(lang_model);
2912 d->language_model_->setSortLocaleAware(true);
2913 return d->language_model_;
2917 void GuiApplication::restoreGuiSession()
2919 if (!lyxrc.load_session)
2922 Session & session = theSession();
2923 LastOpenedSection::LastOpened const & lastopened =
2924 session.lastOpened().getfiles();
2926 validateCurrentView();
2928 FileName active_file;
2929 // do not add to the lastfile list since these files are restored from
2930 // last session, and should be already there (regular files), or should
2931 // not be added at all (help files).
2932 for (auto const & last : lastopened) {
2933 FileName const & file_name = last.file_name;
2934 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2935 && current_view_->documentBufferView() != nullptr)) {
2936 string const & fname = file_name.absFileName();
2937 createView(support::checksum(fname));
2939 current_view_->loadDocument(file_name, false);
2942 active_file = file_name;
2945 // Restore last active buffer
2946 Buffer * buffer = theBufferList().getBuffer(active_file);
2947 if (buffer && current_view_)
2948 current_view_->setBuffer(buffer);
2950 // clear this list to save a few bytes of RAM
2951 session.lastOpened().clear();
2955 QString const GuiApplication::romanFontName()
2958 font.setStyleHint(QFont::Serif);
2959 font.setFamily("serif");
2961 return QFontInfo(font).family();
2965 QString const GuiApplication::sansFontName()
2968 font.setStyleHint(QFont::SansSerif);
2969 font.setFamily("sans");
2971 return QFontInfo(font).family();
2975 QString const GuiApplication::typewriterFontName()
2977 return QFontInfo(typewriterSystemFont()).family();
2982 // We cannot use QFont::fixedPitch() because it doesn't
2983 // return the fact but only if it is requested.
2984 static bool isFixedPitch(const QFont & font) {
2985 const QFontInfo fi(font);
2986 return fi.fixedPitch();
2991 QFont const GuiApplication::typewriterSystemFont()
2993 #if QT_VERSION >= 0x050200
2994 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2996 QFont font("monospace");
2998 if (!isFixedPitch(font)) {
2999 // try to enforce a real monospaced font
3000 font.setStyleHint(QFont::Monospace);
3001 if (!isFixedPitch(font)) {
3002 font.setStyleHint(QFont::TypeWriter);
3003 if (!isFixedPitch(font)) font.setFamily("courier");
3007 // On a Mac the result is too small and it's not practical to
3008 // rely on Qtconfig utility to change the system settings of Qt.
3009 font.setPointSize(12);
3015 void GuiApplication::handleRegularEvents()
3017 ForkedCallsController::handleCompletedProcesses();
3021 bool GuiApplication::event(QEvent * e)
3024 case QEvent::FileOpen: {
3025 // Open a file; this happens only on Mac OS X for now.
3027 // We do this asynchronously because on startup the batch
3028 // commands are not executed here yet and the gui is not ready
3030 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
3031 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
3032 processFuncRequestAsync(fr);
3036 #if (QT_VERSION < 0x050000)
3037 // Qt5 uses a signal for that, see above.
3038 case QEvent::KeyboardLayoutChange:
3039 //LYXERR0("keyboard change");
3040 if (currentView() && currentView()->currentBufferView())
3041 currentView()->currentBufferView()->cursor().setLanguageFromInput();
3045 case QEvent::ApplicationPaletteChange: {
3046 // runtime switch from/to dark mode
3048 return QApplication::event(e);
3051 return QApplication::event(e);
3056 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3059 return QApplication::notify(receiver, event);
3061 catch (ExceptionMessage const & e) {
3063 case ErrorException:
3065 setQuitOnLastWindowClosed(false);
3067 Alert::error(e.title_, e.details_);
3069 // Properly crash in debug mode in order to get a useful backtrace.
3072 // In release mode, try to exit gracefully.
3074 // FIXME: GCC 7 thinks we can fall through here. Can we?
3076 case BufferException: {
3077 if (!current_view_ || !current_view_->documentBufferView())
3079 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3080 docstring details = e.details_ + '\n';
3081 details += buf->emergencyWrite();
3082 theBufferList().release(buf);
3083 details += "\n" + _("The current document was closed.");
3084 Alert::error(e.title_, details);
3087 case WarningException:
3088 Alert::warning(e.title_, e.details_);
3092 catch (exception const & e) {
3093 docstring s = _("LyX has caught an exception, it will now "
3094 "attempt to save all unsaved documents and exit."
3096 s += from_ascii(e.what());
3097 Alert::error(_("Software exception Detected"), s);
3101 docstring s = _("LyX has caught some really weird exception, it will "
3102 "now attempt to save all unsaved documents and exit.");
3103 Alert::error(_("Software exception Detected"), s);
3110 bool GuiApplication::isInDarkMode()
3112 return colorCache().isDarkMode();
3116 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3118 QColor const & qcol = d->color_cache_.get(col);
3119 if (!qcol.isValid()) {
3125 rgbcol.r = qcol.red();
3126 rgbcol.g = qcol.green();
3127 rgbcol.b = qcol.blue();
3132 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3134 QColor const qcol(lcolor.getX11HexName(col).c_str());
3135 if (!qcol.isValid()) {
3141 rgbcol.r = qcol.red();
3142 rgbcol.g = qcol.green();
3143 rgbcol.b = qcol.blue();
3148 string const GuiApplication::hexName(ColorCode col)
3150 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3154 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3156 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3157 d->socket_notifiers_[fd] = sn;
3158 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3162 void GuiApplication::socketDataReceived(int fd)
3164 d->socket_notifiers_[fd]->func_();
3168 void GuiApplication::unregisterSocketCallback(int fd)
3170 d->socket_notifiers_.take(fd)->setEnabled(false);
3174 void GuiApplication::commitData(QSessionManager & sm)
3176 /** The implementation is required to avoid an application exit
3177 ** when session state save is triggered by session manager.
3178 ** The default implementation sends a close event to all
3179 ** visible top level widgets when session management allows
3181 ** We are changing that to check the state of each buffer in all
3182 ** views and ask the users what to do if buffers are dirty.
3183 ** Furthermore, we save the session state.
3184 ** We do NOT close the views here since the user still can cancel
3185 ** the logout process (see #9277); also, this would hide LyX from
3186 ** an OSes own session handling (application restoration).
3188 #ifdef QT_NO_SESSIONMANAGER
3190 #warning Qt is compiled without session manager
3192 #pragma message("warning: Qt is compiled without session manager")
3196 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3204 void GuiApplication::unregisterView(GuiView * gv)
3206 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3207 d->views_.remove(gv->id());
3208 if (current_view_ == gv)
3209 current_view_ = nullptr;
3214 bool GuiApplication::closeAllViews()
3216 if (d->views_.empty())
3219 // When a view/window was closed before without quitting LyX, there
3220 // are already entries in the lastOpened list.
3221 theSession().lastOpened().clear();
3223 QList<GuiView *> const views = d->views_.values();
3224 for (GuiView * view : views) {
3225 if (!view->closeScheduled())
3234 bool GuiApplication::prepareAllViewsForLogout()
3236 if (d->views_.empty())
3239 QList<GuiView *> const views = d->views_.values();
3240 for (GuiView * view : views) {
3241 if (!view->prepareAllBuffersForLogout())
3249 GuiView & GuiApplication::view(int id) const
3251 LAPPERR(d->views_.contains(id));
3252 return *d->views_.value(id);
3256 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3258 QList<GuiView *> const views = d->views_.values();
3259 for (GuiView * view : views)
3260 view->hideDialog(name, inset);
3264 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3266 Buffer const * buf = nullptr;
3267 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3268 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3269 if (Buffer const * ptr = (*it)->updateInset(inset))
3276 bool GuiApplication::searchMenu(FuncRequest const & func,
3277 docstring_list & names) const
3279 BufferView * bv = nullptr;
3281 bv = current_view_->currentBufferView();
3282 return d->menus_.searchMenu(func, names, bv);
3286 bool GuiApplication::hasBufferView() const
3288 return (current_view_ && current_view_->currentBufferView());
3292 // Ensure that a file is read only once (prevents include loops)
3293 static QStringList uifiles;
3294 // store which ui files define Toolbars
3295 static QStringList toolbar_uifiles;
3298 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3309 LexerKeyword uitags[] = {
3310 { "format", ui_format },
3311 { "include", ui_include },
3312 { "menuset", ui_menuset },
3313 { "toolbars", ui_toolbars },
3314 { "toolbarset", ui_toolbarset }
3318 lex.setFile(ui_path);
3320 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3324 if (lyxerr.debugging(Debug::PARSER))
3325 lex.printTable(lyxerr);
3328 // format before introduction of format tag
3329 unsigned int format = 0;
3330 while (lex.isOK()) {
3331 int const status = lex.lex();
3333 // we have to do this check here, outside the switch,
3334 // because otherwise we would start reading include files,
3335 // e.g., if the first tag we hit was an include tag.
3336 if (status == ui_format)
3338 format = lex.getInteger();
3342 // this will trigger unless the first tag we hit is a format
3343 // tag, with the right format.
3344 if (format != LFUN_FORMAT)
3345 return FormatMismatch;
3348 case Lexer::LEX_FEOF:
3353 QString const file = toqstr(lex.getString());
3354 bool const success = readUIFile(file, true);
3356 LYXERR0("Failed to read included file: " << fromqstr(file));
3363 d->menus_.read(lex);
3367 d->toolbars_.readToolbars(lex);
3371 d->toolbars_.readToolbarSettings(lex);
3372 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3376 if (!rtrim(lex.getString()).empty())
3377 lex.printError("LyX::ReadUIFile: "
3378 "Unknown menu tag: `$$Token'");
3380 LYXERR0("Error with status: " << status);
3386 return (error ? ReadError : ReadOK);
3390 bool GuiApplication::readUIFile(QString const & name, bool include)
3392 LYXERR(Debug::INIT, "About to read " << name << "...");
3396 ui_path = libFileSearch("ui", name, "inc");
3397 if (ui_path.empty())
3398 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3400 ui_path = libFileSearch("ui", name, "ui");
3403 if (ui_path.empty()) {
3404 static const QString defaultUIFile = "default";
3405 LYXERR(Debug::INIT, "Could not find " << name);
3407 Alert::warning(_("Could not find UI definition file"),
3408 bformat(_("Error while reading the included file\n%1$s\n"
3409 "Please check your installation."), qstring_to_ucs4(name)));
3412 if (name == defaultUIFile) {
3413 LYXERR(Debug::INIT, "Could not find default UI file!!");
3414 Alert::warning(_("Could not find default UI file"),
3415 _("LyX could not find the default UI file!\n"
3416 "Please check your installation."));
3419 Alert::warning(_("Could not find UI definition file"),
3420 bformat(_("Error while reading the configuration file\n%1$s\n"
3421 "Falling back to default.\n"
3422 "Please look under Tools>Preferences>User Interface and\n"
3423 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3424 return readUIFile(defaultUIFile, false);
3427 QString const uifile = toqstr(ui_path.absFileName());
3428 if (uifiles.contains(uifile)) {
3430 // We are reading again the top uifile so reset the safeguard:
3433 d->toolbars_.reset();
3435 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3436 << "Is this an include loop?");
3440 uifiles.push_back(uifile);
3442 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3444 ReturnValues retval = readUIFile(ui_path);
3446 if (retval == FormatMismatch) {
3447 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3448 TempFile tmp("convertXXXXXX.ui");
3449 FileName const tempfile = tmp.name();
3450 bool const success = prefs2prefs(ui_path, tempfile, true);
3452 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3453 " to format " << LFUN_FORMAT << ".");
3455 retval = readUIFile(tempfile);
3459 if (retval != ReadOK) {
3460 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3468 settings.beginGroup("ui_files");
3469 bool touched = false;
3470 for (int i = 0; i != uifiles.size(); ++i) {
3471 QFileInfo fi(uifiles[i]);
3472 QDateTime const date_value = fi.lastModified();
3473 QString const name_key = QString::number(i);
3474 // if an ui file which defines Toolbars has changed,
3475 // we have to reset the settings
3476 if (toolbar_uifiles.contains(uifiles[i])
3477 && (!settings.contains(name_key)
3478 || settings.value(name_key).toString() != uifiles[i]
3479 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3481 settings.setValue(name_key, uifiles[i]);
3482 settings.setValue(name_key + "/date", date_value);
3485 settings.endGroup();
3487 settings.remove("views");
3493 void GuiApplication::onLastWindowClosed()
3495 if (d->global_menubar_)
3496 d->global_menubar_->grabKeyboard();
3500 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3501 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3503 std::string name = "unknown";
3505 case Qt::ApplicationSuspended:
3506 name = "ApplicationSuspended";
3508 case Qt::ApplicationHidden:
3509 name = "ApplicationHidden";
3511 case Qt::ApplicationInactive:
3512 name = "ApplicationInactive";
3514 case Qt::ApplicationActive:
3515 name = "ApplicationActive";
3516 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3517 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3518 if (d->views_.empty() && d->last_state_ == state) {
3519 LYXERR(Debug::GUI, "Open new window...");
3524 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3525 d->last_state_ = state;
3530 void GuiApplication::startLongOperation() {
3531 d->key_checker_.start();
3535 bool GuiApplication::longOperationCancelled() {
3536 return d->key_checker_.pressed();
3540 void GuiApplication::stopLongOperation() {
3541 d->key_checker_.stop();
3545 bool GuiApplication::longOperationStarted() {
3546 return d->key_checker_.started();
3550 ////////////////////////////////////////////////////////////////////////
3552 // X11 specific stuff goes here...
3555 bool GuiApplication::x11EventFilter(XEvent * xev)
3560 switch (xev->type) {
3561 case SelectionRequest: {
3562 if (xev->xselectionrequest.selection != XA_PRIMARY)
3564 LYXERR(Debug::SELECTION, "X requested selection.");
3565 BufferView * bv = current_view_->currentBufferView();
3567 docstring const sel = bv->requestSelection();
3569 d->selection_.put(sel);
3570 // Refresh the selection request timestamp.
3571 // We have to do this by ourselves as Qt seems
3572 // not doing that, maybe because of our
3573 // "persistent selection" implementation
3574 // (see comments in GuiSelection.cpp).
3575 XSelectionEvent nev;
3576 nev.type = SelectionNotify;
3577 nev.display = xev->xselectionrequest.display;
3578 nev.requestor = xev->xselectionrequest.requestor;
3579 nev.selection = xev->xselectionrequest.selection;
3580 nev.target = xev->xselectionrequest.target;
3581 nev.property = 0L; // None
3582 nev.time = CurrentTime;
3583 XSendEvent(QX11Info::display(),
3584 nev.requestor, False, 0,
3585 reinterpret_cast<XEvent *>(&nev));
3591 case SelectionClear: {
3592 if (xev->xselectionclear.selection != XA_PRIMARY)
3594 LYXERR(Debug::SELECTION, "Lost selection.");
3595 BufferView * bv = current_view_->currentBufferView();
3597 bv->clearSelection();
3603 #elif defined(QPA_XCB)
3604 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3605 void * message, long *)
3607 if (!current_view_ || eventType != "xcb_generic_event_t")
3610 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3612 switch (ev->response_type) {
3613 case XCB_SELECTION_REQUEST: {
3614 xcb_selection_request_event_t * srev =
3615 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3616 if (srev->selection != XCB_ATOM_PRIMARY)
3618 LYXERR(Debug::SELECTION, "X requested selection.");
3619 BufferView * bv = current_view_->currentBufferView();
3621 docstring const sel = bv->requestSelection();
3623 d->selection_.put(sel);
3624 #ifdef HAVE_QT5_X11_EXTRAS
3625 // Refresh the selection request timestamp.
3626 // We have to do this by ourselves as Qt seems
3627 // not doing that, maybe because of our
3628 // "persistent selection" implementation
3629 // (see comments in GuiSelection.cpp).
3630 // It is expected that every X11 event is
3631 // 32 bytes long, even if not all 32 bytes are
3633 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3634 struct alignas(32) padded_event
3635 : xcb_selection_notify_event_t {};
3636 padded_event nev = {};
3637 nev.response_type = XCB_SELECTION_NOTIFY;
3638 nev.requestor = srev->requestor;
3639 nev.selection = srev->selection;
3640 nev.target = srev->target;
3641 nev.property = XCB_NONE;
3642 nev.time = XCB_CURRENT_TIME;
3643 xcb_connection_t * con = QX11Info::connection();
3644 xcb_send_event(con, 0, srev->requestor,
3645 XCB_EVENT_MASK_NO_EVENT,
3646 reinterpret_cast<char const *>(&nev));
3654 case XCB_SELECTION_CLEAR: {
3655 xcb_selection_clear_event_t * scev =
3656 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3657 if (scev->selection != XCB_ATOM_PRIMARY)
3659 LYXERR(Debug::SELECTION, "Lost selection.");
3660 BufferView * bv = current_view_->currentBufferView();
3662 bv->clearSelection();
3670 } // namespace frontend
3673 void hideDialogs(std::string const & name, Inset * inset)
3676 frontend::guiApp->hideDialogs(name, inset);
3680 ////////////////////////////////////////////////////////////////////
3684 ////////////////////////////////////////////////////////////////////
3686 frontend::FontLoader & theFontLoader()
3688 LAPPERR(frontend::guiApp);
3689 return frontend::guiApp->fontLoader();
3693 frontend::FontMetrics const & theFontMetrics(Font const & f)
3695 return theFontMetrics(f.fontInfo());
3699 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3701 LAPPERR(frontend::guiApp);
3702 return frontend::guiApp->fontLoader().metrics(f);
3706 ////////////////////////////////////////////////////////////////////
3710 ////////////////////////////////////////////////////////////////////
3712 frontend::Clipboard & theClipboard()
3714 LAPPERR(frontend::guiApp);
3715 return frontend::guiApp->clipboard();
3719 frontend::Selection & theSelection()
3721 LAPPERR(frontend::guiApp);
3722 return frontend::guiApp->selection();
3728 #include "moc_GuiApplication.cpp"