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/mute_warning.h"
75 #include "support/textutils.h"
76 #include "support/Messages.h"
77 #include "support/os.h"
78 #include "support/Package.h"
79 #include "support/TempFile.h"
82 #include "support/AppleScript.h"
83 #include "support/AppleSupport.h"
84 #include "support/linkback/LinkBackProxy.h"
94 #include <QFileOpenEvent>
96 #include <QFontDatabase>
99 #include <QImageReader>
102 #include <QLibraryInfo>
109 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
110 #include <QRandomGenerator>
113 #include <QSessionManager>
115 #include <QSocketNotifier>
116 #include <QSortFilterProxyModel>
117 #include <QStandardItemModel>
118 #include <QSvgRenderer>
120 #include <QTranslator>
121 #include <QThreadPool>
126 #ifdef HAVE_QT5_X11_EXTRAS
127 #include <QtX11Extras/QX11Info>
131 #if (QT_VERSION >= 0x050400)
132 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
133 #if (QT_VERSION >= 0x060000)
134 #if (QT_VERSION >= 0x060500)
135 #include <QtGui/QWindowsMimeConverter>
136 #define QWINDOWSMIME QWindowsMimeConverter
137 #define QVARIANTTYPE QMetaType
139 #include <QtGui/private/qguiapplication_p.h>
140 #include <QtGui/private/qwindowsmime_p.h>
141 #include <QtGui/qpa/qplatformintegration.h>
142 #define QWINDOWSMIME QWindowsMime
143 #define QVARIANTTYPE QMetaType
144 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
145 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
149 #define QWINDOWSMIME QWinMime
150 #define QVARIANTTYPE QVariant::Type
159 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
160 #include <QMacPasteboardMime>
168 using namespace lyx::support;
173 frontend::Application * createApplication(int & argc, char * argv[])
175 #if !defined(QPA_XCB)
176 // prune -geometry argument(s) by shifting
177 // the following ones 2 places down.
178 for (int i = 0 ; i < argc ; ++i) {
179 if (strcmp(argv[i], "-geometry") == 0) {
180 int const remove = (i+1) < argc ? 2 : 1;
182 for (int j = i; j < argc; ++j)
183 argv[j] = argv[j + remove];
189 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
190 // On Windows, allow bringing the LyX window to top
191 AllowSetForegroundWindow(ASFW_ANY);
195 #if defined(Q_OS_MAC)
196 int const cursor_time_on = NSTextInsertionPointBlinkPeriodOn();
197 int const cursor_time_off = NSTextInsertionPointBlinkPeriodOff();
198 if (cursor_time_on > 0 && cursor_time_off > 0) {
199 QApplication::setCursorFlashTime(cursor_time_on + cursor_time_off);
200 } else if (cursor_time_on <= 0 && cursor_time_off > 0) {
201 // Off is set and On is undefined of zero
202 QApplication::setCursorFlashTime(0);
203 } else if (cursor_time_off <= 0 && cursor_time_on > 0) {
204 // On is set and Off is undefined of zero
205 QApplication::setCursorFlashTime(0);
209 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
210 // macOS does it by itself.
211 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
212 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
213 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
214 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
215 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
216 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
219 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
220 // HighDPI scale factor policy must be set before QGuiApplication is created
221 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
222 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
226 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
227 // I'd rather do that in the constructor, but I do not think that
228 // the palette is accessible there.
229 guiApp->colorCache().setPalette(guiApp->palette());
238 if (lyxrc.gui_language == "auto") {
239 theLocale = QLocale::system();
240 code = fromqstr(theLocale.name());
242 Language const * l = languages.getLanguage(lyxrc.gui_language);
243 code = l ? l->code() : "C";
244 theLocale = QLocale(toqstr(code));
246 // Qt tries to outsmart us and transforms en_US to C.
247 Messages::guiLanguage((code == "C") ? "en_US" : code);
248 QLocale::setDefault(theLocale);
249 setlocale(LC_NUMERIC, "C");
256 /// Return the list of loadable formats.
257 vector<string> loadableImageFormats()
261 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
263 LYXERR(Debug::GRAPHICS,
264 "\nThe image loader can load the following directly:\n");
266 if (qt_formats.empty())
267 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
269 bool jpeg_found = false;
270 bool jpg_found = false;
271 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
273 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
275 string ext = ascii_lowercase((const char *) *it);
283 else if (ext == "jpg") {
288 else if (lyxrc.use_converter_cache &&
289 (ext == "svg" || ext == "svgz") &&
290 theConverters().isReachable("svg", "png"))
291 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
292 // the SVG as in the output. However we require that the converter
293 // cache is enabled since this is expensive. We also require that
294 // an explicit svg->png converter is defined, since the default
295 // converter could produce bad quality as well. This assumes that
296 // png can always be loaded.
305 ////////////////////////////////////////////////////////////////////////
307 // Icon loading support code
309 ////////////////////////////////////////////////////////////////////////
319 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
321 return lhs.key < rhs.key;
327 CompareKey(QString const & name) : name_(name) {}
328 bool operator()(ImgMap const & other) const { return other.key == name_; }
334 // this must be sorted alphabetically
335 // Upper case comes before lower case
336 // Please don't change the formatting, this list is parsed by
337 // development/tools/generate_symbols_images.py.
338 ImgMap sorted_img_map[] = {
339 { "Arrownot", "arrownot2"},
340 { "Arrowvert", "arrowvert2"},
341 { "Bowtie", "bowtie2" },
343 { "Bumpeq", "bumpeq2" },
344 { "CIRCLE", "circle3" },
346 { "CheckedBox", "checkedbox2" },
347 { "Circle", "circle2" },
348 { "Colonapprox", "colonapprox2" },
349 { "Coloneq", "coloneq2" },
350 { "Coloneqq", "coloneqq2" },
351 { "Colonsim", "colonsim2" },
353 { "DOWNarrow", "downarrow3" },
354 { "Delta", "delta2" },
355 { "Diamond", "diamond2" },
356 { "Doteq", "doteq2" },
357 { "Downarrow", "downarrow2" },
358 { "Eqcolon", "eqcolon2" },
359 { "Eqqcolon", "eqqcolon2" },
360 { "Gamma", "gamma2" },
362 { "LEFTCIRCLE", "leftcircle3" },
363 { "LEFTarrow", "leftarrow3" },
364 { "LEFTcircle", "leftcircle4" },
366 { "Lambda", "lambda2" },
368 { "Leftarrow", "leftarrow2" },
369 { "Leftcircle", "leftcircle2" },
370 { "Leftrightarrow", "leftrightarrow2" },
371 { "Longarrownot", "longarrownot2"},
372 { "Longleftarrow", "longleftarrow2" },
373 { "Longleftrightarrow", "longleftrightarrow2" },
374 { "Longmapsfrom", "longmapsfrom2"},
375 { "Longmapsto", "longmapsto2"},
376 { "Longrightarrow", "longrightarrow2" },
377 { "Mapsfrom", "mapsfrom2"},
378 { "Mapsfromchar", "mapsfromchar2"},
379 { "Mapsto", "mapsto2"},
380 { "Mapstochar", "mapstochar2"},
381 { "Omega", "omega2" },
386 { "RIGHTCIRCLE", "rightcircle3" },
387 { "RIGHTarrow", "rightarrow3" },
388 { "RIGHTcircle", "rightcircle4" },
390 { "Rightarrow", "rightarrow2" },
391 { "Rightcircle", "rightcircle2" },
392 { "Sigma", "sigma2" },
393 { "Square", "square2" },
394 { "Subset", "subset2" },
395 { "Supset", "supset2" },
396 { "Theta", "theta2" },
397 { "Thorn", "thorn2" },
398 { "UParrow", "uparrow3" },
399 { "Uparrow", "uparrow2" },
400 { "Updownarrow", "updownarrow2" },
401 { "Upsilon", "upsilon2" },
402 { "Vdash", "vdash3" },
407 { "lVert", "vert2" },
409 { "nLeftarrow", "nleftarrow2" },
410 { "nLeftrightarrow", "nleftrightarrow2" },
411 { "nRightarrow", "nrightarrow2" },
412 { "nVDash", "nvdash3" },
413 { "nVdash", "nvdash4" },
414 { "nvDash", "nvdash2" },
415 { "rVert", "vert2" },
417 { "textrm \\AA", "textrm_AA"},
418 { "textrm \\O", "textrm_O"},
419 { "vDash", "vdash2" },
420 { "varDelta", "vardelta2" },
421 { "varGamma", "vargamma2" },
422 { "varLambda", "varlambda2" },
423 { "varOmega", "varomega2" },
424 { "varPhi", "varphi2" },
425 { "varPi", "varpi2" },
426 { "varPsi", "varpsi2" },
427 { "varSigma", "varsigma2" },
428 { "varTheta", "vartheta2" },
429 { "varUpsilon", "varupsilon2" },
430 { "varXi", "varxi2" }
434 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
436 // This list specifies which system's theme icon is related to which lyx
437 // command. It was based on:
438 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
439 // this must be sorted alphabetically
440 // Upper case comes before lower case
441 ImgMap sorted_theme_icon_map[] = {
442 { "bookmark-goto 0", "go-jump" },
443 { "buffer-new", "document-new" },
444 { "buffer-write", "document-save" },
445 { "buffer-write-as", "document-save-as" },
446 { "buffer-zoom-in", "zoom-in" },
447 { "buffer-zoom-out", "zoom-out" },
448 { "copy", "edit-copy" },
449 { "cut", "edit-cut" },
450 { "depth-decrement", "format-indent-less" },
451 { "depth-increment", "format-indent-more" },
452 { "dialog-show spellchecker", "tools-check-spelling" },
453 { "dialog-show-new-inset graphics", "insert-image" },
454 { "dialog-toggle findreplaceadv", "edit-find-replace" },
455 { "file-open", "document-open" },
456 { "font-bold", "format-text-bold" },
457 { "font-ital", "format-text-italic" },
458 { "font-strikeout", "format-text-strikethrough" },
459 { "font-underline", "format-text-underline" },
460 { "lyx-quit", "application-exit" },
461 { "paste", "edit-paste" },
462 { "redo", "edit-redo" },
463 { "undo", "edit-undo" },
464 { "window-close", "window-close" },
465 { "window-new", "window-new" }
468 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
471 QString findImg(QString const & name)
473 ImgMap const * const begin = sorted_img_map;
474 ImgMap const * const end = begin + nr_sorted_img_map;
475 LATTEST(sorted(begin, end));
477 ImgMap const * const it = find_if(begin, end, CompareKey(name));
481 img_name = it->value;
484 img_name.replace('_', "underscore");
485 img_name.replace(' ', '_');
487 // This way we can have "math-delim { }" on the toolbar.
488 img_name.replace('(', "lparen");
489 img_name.replace(')', "rparen");
490 img_name.replace('[', "lbracket");
491 img_name.replace(']', "rbracket");
492 img_name.replace('{', "lbrace");
493 img_name.replace('}', "rbrace");
494 img_name.replace('|', "bars");
495 img_name.replace(',', "thinspace");
496 img_name.replace(':', "mediumspace");
497 img_name.replace(';', "thickspace");
498 img_name.replace('!', "negthinspace");
501 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
502 << "Looking for math icon called \"" << img_name << '"');
509 QString themeIconName(QString const & action)
511 ImgMap const * const begin = sorted_theme_icon_map;
512 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
513 LASSERT(sorted(begin, end), /**/);
515 ImgMap const * const it = find_if(begin, end, CompareKey(action));
525 /* Get aliases for icon name. This allows to avoid duplication of
526 * icons when new versions of functions are introduced for the
527 * toolbar. A good example is the introduction of layout-toggle in
529 * The file is parsed by Lexer. Each line is of the form
530 * <original substring> <replacement substring>
532 * The return value is another icon file name that can be queried.
534 // FIXME: consider using regular expressions.
535 QString getAlias(QString name) {
536 static bool has_aliases = false;
537 static vector <pair<QString,QString>> aliases;
538 // Initialize aliases list (once).
540 FileName alfile = libFileSearch("images", "icon.aliases");
541 if (alfile.exists()) {
548 aliases.push_back({toqstr(from), toqstr(to)});
553 // check for the following aliases
554 for (auto const & alias : aliases) {
555 if (name.contains(alias.first))
556 name.replace(alias.first, alias.second);
564 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
569 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
571 if (!f.argument().empty()) {
572 // if there are arguments, first search an icon which name is the full thing
573 QString name = lfunname + ' ' + toqstr(f.argument());
574 name.replace(' ', '_');
575 name.replace(';', '_');
576 name.replace('\\', "backslash");
578 QString alias = getAlias(name);
582 // then special default icon for some lfuns
583 switch (f.action()) {
584 case LFUN_MATH_INSERT:
585 names << "math/" + findImg(toqstr(f.argument()).mid(1));
587 case LFUN_MATH_DELIM:
588 case LFUN_MATH_BIGDELIM:
589 names << "math/" + findImg(toqstr(f.argument()));
592 names << "commands/" + toqstr(f.argument());
594 case LFUN_COMMAND_ALTERNATIVES: {
595 // use the first of the alternative commands
597 docstring dummy = split(f.argument(), firstcom, ';');
598 QString name1 = toqstr(firstcom);
599 name1.replace(' ', '_');
600 name1.replace(';', '_');
601 name1.replace('\\', "backslash");
610 // next thing to try is function name alone
612 QString alias = getAlias(lfunname);
613 if (alias != lfunname)
616 // and finally maybe the unknown icon
620 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
621 // The folders where icons are searched for
622 QStringList imagedirs;
623 imagedirs << "images/ipa/" << "images/";
624 // This is used to search for rtl version of icons which have the +rtl suffix.
625 QStringList suffixes;
628 suffixes << QString();
630 for (QString const & imagedir : imagedirs)
631 for (QString const & name : names)
632 for (QString const & suffix : suffixes) {
633 QString id = imagedir;
634 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
635 if (fname.exists()) {
636 docstring const fpath = fname.absoluteFilePath();
637 res.filepath = toqstr(fname.absFileName());
638 // these icons are subject to inversion in dark mode
639 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
640 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
641 res.swap = rtl && suffix.isEmpty();
646 LYXERR(Debug::GUI, "Cannot find icon for command \""
647 << lyxaction.getActionName(f.action())
648 << '(' << to_utf8(f.argument()) << ")\"");
654 QPixmap prepareForDarkMode(QPixmap pixmap)
656 QPalette palette = QPalette();
657 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
658 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
660 // guess whether we are in dark mode
661 if (text_color.black() > bg_color.black())
662 // not in dark mode, do nothing
665 // create a layer with black text turned to QPalette::WindowText
666 QPixmap black_overlay(pixmap.size());
667 black_overlay.fill(text_color);
668 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
670 // create a layer with blue text turned to lighter blue
671 QPixmap blue_overlay(pixmap.size());
672 QColor math_blue(0, 0, 255);
673 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
674 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
676 // create a layer with ("latex") red text turned to lighter red
677 QPixmap red_overlay(pixmap.size());
678 QColor math_red(128, 0, 0);
679 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
680 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
682 // put layers on top of existing pixmap
683 QPainter painter(&pixmap);
684 painter.drawPixmap(pixmap.rect(), black_overlay);
685 painter.drawPixmap(pixmap.rect(), blue_overlay);
686 painter.drawPixmap(pixmap.rect(), red_overlay);
692 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
694 QString imagedir = path;
695 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
696 QString fpath = toqstr(fname.absFileName());
697 QPixmap pixmap = QPixmap();
699 if (pixmap.load(fpath)) {
700 if (fpath.contains("math") || fpath.contains("ipa")
701 || fpath.contains("bullets"))
702 return prepareForDarkMode(pixmap);
706 bool const list = ext.contains(",");
707 LYXERR(Debug::GUI, "Cannot load pixmap \""
708 << path << "/" << name << "." << (list ? "{" : "") << ext
709 << (list ? "}" : "") << "\".");
715 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
717 if (lyxrc.use_system_theme_icons) {
718 // use the icons from system theme that are available
719 QString action = toqstr(lyxaction.getActionName(f.action()));
720 if (!f.argument().empty())
721 action += " " + toqstr(f.argument());
722 QString const theme_icon = themeIconName(action);
723 if (QIcon::hasThemeIcon(theme_icon)) {
724 QIcon const thmicn = QIcon::fromTheme(theme_icon);
725 if (!thmicn.isNull())
730 IconInfo icondata = iconInfo(f, unknown, rtl);
731 if (icondata.filepath.isEmpty())
734 //LYXERR(Debug::GUI, "Found icon: " << icon);
735 QPixmap pixmap = QPixmap();
736 if (!pixmap.load(icondata.filepath)) {
737 LYXERR0("Cannot load icon " << icondata.filepath << ".");
742 pixmap = prepareForDarkMode(pixmap);
745 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
747 return QIcon(pixmap);
751 ////////////////////////////////////////////////////////////////////////
753 // LyX server support code.
755 ////////////////////////////////////////////////////////////////////////
757 class SocketNotifier : public QSocketNotifier
760 /// connect a connection notification from the LyXServerSocket
761 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
762 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
766 /// The callback function
767 Application::SocketCallback func_;
771 class GuiTranslator : public QTranslator
774 GuiTranslator(QObject * parent = nullptr)
775 : QTranslator(parent)
778 QString translate(const char * /* context */,
779 const char *sourceText,
780 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
782 // Here we declare the strings that need to be translated from Qt own GUI
783 // This is needed to include these strings to po files
787 _("Restore Defaults");
790 // Already in po: "Cancel", "&Cancel"
791 _("Apply"); // Already in po: "&Apply"
792 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
795 docstring s = getGuiMessages().getIfFound(sourceText);
796 // This test should eventually be removed when translations are updated
798 LYXERR(Debug::LOCALE, "Missing translation for `"
799 << string(sourceText) << "'");
805 ////////////////////////////////////////////////////////////////////////
807 // Mac specific stuff goes here...
809 ////////////////////////////////////////////////////////////////////////
811 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
812 // QMacPasteboardMimeGraphics can only be compiled on Mac.
814 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
817 QMacPasteboardMimeGraphics()
818 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
821 QString convertorName() { return "Graphics"; }
823 QString flavorFor(QString const & mime)
825 LYXERR(Debug::ACTION, "flavorFor " << mime);
826 if (mime == pdfMimeType())
827 return QLatin1String("com.adobe.pdf");
831 QString mimeFor(QString flav)
833 LYXERR(Debug::ACTION, "mimeFor " << flav);
834 if (flav == QLatin1String("com.adobe.pdf"))
835 return pdfMimeType();
839 bool canConvert(QString const & mime, QString flav)
841 return mimeFor(flav) == mime;
844 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
848 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
852 QList<QByteArray> convertFromMime(QString const & /*mime*/,
853 QVariant data, QString /*flav*/)
855 QList<QByteArray> ret;
856 ret.append(data.toByteArray());
862 ///////////////////////////////////////////////////////////////
864 // You can find more platform specific stuff at the end of this file...
866 ///////////////////////////////////////////////////////////////
868 ////////////////////////////////////////////////////////////////////////
869 // Windows specific stuff goes here...
871 #if (QT_VERSION >= 0x050400)
872 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
873 // QWindowsMimeMetafile can only be compiled on Windows.
875 static FORMATETC cfFromMime(QString const & mimetype)
878 if (mimetype == emfMimeType()) {
879 formatetc.cfFormat = CF_ENHMETAFILE;
880 formatetc.tymed = TYMED_ENHMF;
881 } else if (mimetype == wmfMimeType()) {
882 formatetc.cfFormat = CF_METAFILEPICT;
883 formatetc.tymed = TYMED_MFPICT;
886 formatetc.dwAspect = DVASPECT_CONTENT;
887 formatetc.lindex = -1;
892 class QWindowsMimeMetafile : public QWINDOWSMIME {
894 QWindowsMimeMetafile() {}
896 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
897 QMimeData const * /*mimedata*/) const override
902 bool canConvertToMime(QString const & mimetype,
903 IDataObject * pDataObj) const override
905 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
907 FORMATETC formatetc = cfFromMime(mimetype);
908 return pDataObj->QueryGetData(&formatetc) == S_OK;
911 bool convertFromMime(FORMATETC const & /*formatetc*/,
912 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
917 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
918 QVARIANTTYPE /*preferredType*/) const override
921 if (!canConvertToMime(mimetype, pDataObj))
924 FORMATETC formatetc = cfFromMime(mimetype);
926 if (pDataObj->GetData(&formatetc, &s) != S_OK)
930 if (s.tymed == TYMED_ENHMF) {
931 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
932 data.resize(dataSize);
933 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
934 (LPBYTE)data.data());
935 } else if (s.tymed == TYMED_MFPICT) {
936 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
937 data.resize(dataSize);
938 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
939 (LPBYTE)data.data());
942 ReleaseStgMedium(&s);
948 QVector<FORMATETC> formatsForMime(QString const & mimetype,
949 QMimeData const * /*mimedata*/) const override
951 QVector<FORMATETC> formats;
952 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
953 formats += cfFromMime(mimetype);
957 QString mimeForFormat(FORMATETC const & formatetc) const override
959 switch (formatetc.cfFormat) {
961 return emfMimeType();
962 case CF_METAFILEPICT:
963 return wmfMimeType();
973 /// Allows to check whether ESC was pressed during a long operation
974 class KeyChecker : public QObject {
979 KeyChecker() : pressed_(false), started_(false) {}
982 QCoreApplication::instance()->installEventFilter(this);
987 QCoreApplication::instance()->removeEventFilter(this);
991 QCoreApplication::processEvents();
994 bool started() const {
997 bool eventFilter(QObject *obj, QEvent *event) override {
998 LYXERR(Debug::ACTION, "Event Type: " << event->type());
999 switch (event->type()) {
1002 case QEvent::Resize:
1003 case QEvent::UpdateRequest:
1004 case QEvent::CursorChange:
1005 case QEvent::ActionChanged:
1006 case QEvent::EnabledChange:
1007 case QEvent::SockAct:
1010 case QEvent::ToolTipChange:
1011 case QEvent::LayoutRequest:
1012 case QEvent::MetaCall:
1013 return QObject::eventFilter(obj, event);
1015 // FIXME Blocking all these events is a bad idea.
1016 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1017 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1025 ////////////////////////////////////////////////////////////////////////
1026 // GuiApplication::Private definition and implementation.
1027 ////////////////////////////////////////////////////////////////////////
1029 struct GuiApplication::Private
1031 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1032 global_menubar_(nullptr), last_state_(Qt::ApplicationInactive)
1034 #if (QT_VERSION >= 0x050400)
1035 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1036 /// WMF Mime handler for Windows clipboard.
1037 wmf_mime_ = new QWindowsMimeMetafile;
1038 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1039 win_app_ = dynamic_cast<QWindowsApplication *>
1040 (QGuiApplicationPrivate::platformIntegration());
1041 win_app_->registerMime(wmf_mime_);
1045 initKeySequences(&theTopLevelKeymap());
1048 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1049 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1052 win_app_->unregisterMime(wmf_mime_);
1057 void initKeySequences(KeyMap * kb)
1059 keyseq = KeySequence(kb, kb);
1060 cancel_meta_seq = KeySequence(kb, kb);
1064 QSortFilterProxyModel * language_model_;
1066 GuiClipboard clipboard_;
1068 GuiSelection selection_;
1070 FontLoader font_loader_;
1072 ColorCache color_cache_;
1073 /// the built-in Qt translation mechanism
1074 QTranslator qt_trans_;
1075 /// LyX gettext-based translation for Qt elements
1076 GuiTranslator gui_trans_;
1078 QHash<int, SocketNotifier *> socket_notifiers_;
1082 /// The global instance
1085 /// this timer is used for any regular events one wants to
1086 /// perform. at present it is used to check if forked processes
1088 QTimer general_timer_;
1090 /// delayed FuncRequests
1091 std::queue<FuncRequest> func_request_queue_;
1096 KeySequence cancel_meta_seq;
1098 KeyModifier meta_fake_bit;
1100 /// The result of last dispatch action
1101 DispatchResult dispatch_result_;
1103 /// Multiple views container.
1105 * Warning: This must not be a smart pointer as the destruction of the
1106 * object is handled by Qt when the view is closed
1107 * \sa Qt::WA_DeleteOnClose attribute.
1109 QHash<int, GuiView *> views_;
1111 /// Only used on mac.
1112 QMenuBar * global_menubar_;
1113 /// Holds previous application state on Mac
1114 Qt::ApplicationState last_state_;
1116 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1117 /// Linkback mime handler for MacOSX.
1118 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1121 #if (QT_VERSION >= 0x050400)
1122 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1123 /// WMF Mime handler for Windows clipboard.
1124 QWindowsMimeMetafile * wmf_mime_;
1125 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1126 QWindowsApplication * win_app_;
1131 /// Allows to check whether ESC was pressed during a long operation
1132 KeyChecker key_checker_;
1136 GuiApplication * guiApp;
1138 GuiApplication::~GuiApplication()
1141 closeAllLinkBackLinks();
1147 GuiApplication::GuiApplication(int & argc, char ** argv)
1148 : QApplication(argc, argv), current_view_(nullptr),
1149 d(new GuiApplication::Private)
1151 QString app_name = "LyX";
1152 QCoreApplication::setOrganizationName(app_name);
1153 QCoreApplication::setOrganizationDomain("lyx.org");
1154 QCoreApplication::setApplicationName(lyx_package);
1155 #if QT_VERSION < 0x060000
1156 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1159 #if QT_VERSION >= 0x050700
1160 setDesktopFileName(lyx_package);
1163 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1164 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1166 qsrand(QDateTime::currentDateTime().toTime_t());
1169 // Install LyX translator for missing Qt translations
1170 installTranslator(&d->gui_trans_);
1171 // Install Qt native translator for GUI elements.
1172 installTranslator(&d->qt_trans_);
1175 // Enable reception of XCB events.
1176 installNativeEventFilter(this);
1179 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1180 // lyxrc setting for this in order to let the application stay resident.
1181 // But then we need some kind of dock icon, at least on Windows.
1183 if (lyxrc.quit_on_last_window_closed)
1184 setQuitOnLastWindowClosed(false);
1187 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1188 // seems to be the default case for applications like LyX.
1189 setQuitOnLastWindowClosed(false);
1192 appleCleanupEditMenu();
1193 appleCleanupViewMenu();
1194 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1195 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1198 #if defined(QPA_XCB)
1199 // doubleClickInterval() is 400 ms on X11 which is just too long.
1200 // On Windows and Mac OS X, the operating system's value is used.
1201 // On Microsoft Windows, calling this function sets the double
1202 // click interval for all applications. So we don't!
1203 QApplication::setDoubleClickInterval(300);
1206 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1208 // needs to be done before reading lyxrc
1210 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1214 // Initialize RC Fonts
1215 if (lyxrc.roman_font_name.empty())
1216 lyxrc.roman_font_name = fromqstr(romanFontName());
1218 if (lyxrc.sans_font_name.empty())
1219 lyxrc.sans_font_name = fromqstr(sansFontName());
1221 if (lyxrc.typewriter_font_name.empty())
1222 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1224 // Track change of keyboard
1225 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1227 d->general_timer_.setInterval(500);
1228 connect(&d->general_timer_, SIGNAL(timeout()),
1229 this, SLOT(handleRegularEvents()));
1230 d->general_timer_.start();
1232 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1233 // This is clearly not enough in a time where we use threads for
1234 // document preview and/or export. 20 should be OK.
1235 QThreadPool::globalInstance()->setMaxThreadCount(20);
1237 // make sure tooltips are formatted
1238 installEventFilter(new ToolTipFormatter(this));
1242 GuiApplication * theGuiApp()
1244 return dynamic_cast<GuiApplication *>(theApp());
1248 double GuiApplication::pixelRatio() const
1250 return qt_scale_factor * devicePixelRatio();
1254 void GuiApplication::clearSession()
1261 bool GuiApplication::isBufferBusy(Buffer const * b)
1263 Buffer const * buf = b;
1265 if (GuiView::isBufferBusy(b))
1267 buf = buf->parent();
1273 docstring Application::iconName(FuncRequest const & f, bool unknown)
1275 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1279 docstring Application::mathIcon(docstring const & c)
1281 return qstring_to_ucs4(findImg(toqstr(c)));
1284 void Application::applyPrefs()
1286 if (lyxrc.ui_style != "default")
1287 lyx::frontend::GuiApplication::setStyle(toqstr(lyxrc.ui_style));
1290 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1294 BufferView * bv = nullptr;
1295 BufferView * doc_bv = nullptr;
1297 if (cmd.action() == LFUN_NOACTION) {
1298 status.message(from_utf8(N_("Nothing to do")));
1299 status.setEnabled(false);
1302 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1303 status.setUnknown(true);
1304 status.message(from_utf8(N_("Unknown action")));
1305 status.setEnabled(false);
1308 // Does the GuiApplication know something?
1309 else if (getStatus(cmd, status)) { }
1311 // If we do not have a GuiView, then other functions are disabled
1312 else if (!current_view_)
1313 status.setEnabled(false);
1315 // Does the GuiView know something?
1316 else if (current_view_->getStatus(cmd, status)) { }
1318 // In LyX/Mac, when a dialog is open, the menus of the
1319 // application can still be accessed without giving focus to
1320 // the main window. In this case, we want to disable the menu
1321 // entries that are buffer or view-related.
1322 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1324 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1325 status.setEnabled(false);
1328 // If we do not have a BufferView, then other functions are disabled
1329 else if (!(bv = current_view_->currentBufferView()))
1330 status.setEnabled(false);
1332 // Does the current BufferView know something?
1333 else if (bv->getStatus(cmd, status)) { }
1335 // Does the current Buffer know something?
1336 else if (bv->buffer().getStatus(cmd, status)) { }
1338 // If we do not have a document BufferView, different from the
1339 // current BufferView, then other functions are disabled
1340 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1341 status.setEnabled(false);
1343 // Does the document Buffer know something?
1344 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1347 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1348 status.message(from_utf8(N_("Command not handled")));
1349 status.setEnabled(false);
1352 // the default error message if we disable the command
1353 if (!status.enabled() && status.message().empty())
1354 status.message(from_utf8(N_("Command disabled")));
1360 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1362 // I would really like to avoid having this switch and rather try to
1363 // encode this in the function itself.
1364 // -- And I'd rather let an inset decide which LFUNs it is willing
1365 // to handle (Andre')
1367 switch (cmd.action()) {
1369 // This could be used for the no-GUI version. The GUI version is handled in
1370 // GuiView::getStatus(). See above.
1372 case LFUN_BUFFER_WRITE:
1373 case LFUN_BUFFER_WRITE_AS:
1374 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1375 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1376 enable = b && (b->isUnnamed() || !b->isClean());
1381 case LFUN_BOOKMARK_GOTO: {
1382 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1383 enable = theSession().bookmarks().isValid(num);
1387 case LFUN_BOOKMARK_CLEAR:
1388 enable = theSession().bookmarks().hasValid();
1391 // this one is difficult to get right. As a half-baked
1392 // solution, we consider only the first action of the sequence
1393 case LFUN_COMMAND_SEQUENCE: {
1394 // argument contains ';'-terminated commands
1395 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1396 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1397 func.setOrigin(cmd.origin());
1398 flag = getStatus(func);
1402 // we want to check if at least one of these is enabled
1403 case LFUN_COMMAND_ALTERNATIVES: {
1404 // argument contains ';'-terminated commands
1405 string arg = to_utf8(cmd.argument());
1406 while (!arg.empty()) {
1408 arg = split(arg, first, ';');
1409 FuncRequest func(lyxaction.lookupFunc(first));
1410 func.setOrigin(cmd.origin());
1411 flag = getStatus(func);
1412 // if this one is enabled, the whole thing is
1421 string name = to_utf8(cmd.argument());
1422 if (theTopLevelCmdDef().lock(name, func)) {
1423 func.setOrigin(cmd.origin());
1424 flag = getStatus(func);
1425 theTopLevelCmdDef().release(name);
1427 // catch recursion or unknown command
1428 // definition. all operations until the
1429 // recursion or unknown command definition
1430 // occurs are performed, so set the state to
1437 case LFUN_IF_RELATIVES: {
1438 string const lfun = to_utf8(cmd.argument());
1439 BufferView const * bv =
1440 current_view_ ? current_view_->currentBufferView() : nullptr;
1441 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1445 FuncRequest func(lyxaction.lookupFunc(lfun));
1446 func.setOrigin(cmd.origin());
1447 flag = getStatus(func);
1451 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1453 case LFUN_PREFERENCES_SAVE:
1454 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1455 // these are handled in our dispatch()
1458 case LFUN_DEBUG_LEVEL_SET: {
1459 string bad = Debug::badValue(to_utf8(cmd.argument()));
1460 enable = bad.empty();
1462 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1466 case LFUN_WINDOW_CLOSE:
1467 enable = !d->views_.empty();
1470 case LFUN_BUFFER_NEW:
1471 case LFUN_BUFFER_NEW_TEMPLATE:
1472 case LFUN_FILE_OPEN:
1473 case LFUN_LYXFILES_OPEN:
1474 case LFUN_HELP_OPEN:
1475 case LFUN_SCREEN_FONT_UPDATE:
1476 case LFUN_SET_COLOR:
1477 case LFUN_WINDOW_NEW:
1479 case LFUN_LYXRC_APPLY:
1480 case LFUN_COMMAND_PREFIX:
1482 case LFUN_META_PREFIX:
1483 case LFUN_RECONFIGURE:
1484 case LFUN_SERVER_GET_FILENAME:
1485 case LFUN_SERVER_NOTIFY:
1489 case LFUN_BUFFER_FORALL: {
1490 if (theBufferList().empty()) {
1491 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1492 flag.setEnabled(false);
1496 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1497 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1498 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1499 flag.setEnabled(false);
1504 case LFUN_DIALOG_SHOW: {
1505 string const name = cmd.getArg(0);
1506 return name == "aboutlyx"
1507 || name == "lyxfiles"
1509 || name == "texinfo"
1510 || name == "progress"
1511 || name == "compare";
1519 flag.setEnabled(false);
1523 /// make a post-dispatch status message
1524 static docstring makeDispatchMessage(docstring const & msg,
1525 FuncRequest const & cmd)
1527 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1528 || cmd.origin() == FuncRequest::TOOLBAR
1529 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1531 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1532 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1536 docstring dispatch_msg = msg;
1537 if (!dispatch_msg.empty())
1538 dispatch_msg += ' ';
1540 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1542 bool argsadded = false;
1544 if (!cmd.argument().empty()) {
1545 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1546 comname += ' ' + cmd.argument();
1550 docstring const shortcuts = theTopLevelKeymap().
1551 printBindings(cmd, KeySequence::ForGui);
1553 if (!shortcuts.empty())
1554 comname += ": " + shortcuts;
1555 else if (!argsadded && !cmd.argument().empty())
1556 comname += ' ' + cmd.argument();
1558 if (!comname.empty()) {
1559 comname = rtrim(comname);
1560 dispatch_msg += '(' + rtrim(comname) + ')';
1562 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1563 return dispatch_msg;
1567 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1571 Buffer * buffer = nullptr;
1572 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1573 //setCurrentView(cmd.view_origin); //does not work
1575 dr.setMessage(_("Wrong focus!"));
1576 d->dispatch_result_ = dr;
1577 return d->dispatch_result_;
1579 if (current_view_ && current_view_->currentBufferView()) {
1580 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1581 buffer = ¤t_view_->currentBufferView()->buffer();
1584 dr.screenUpdate(Update::FitCursor);
1586 // All the code is kept inside the undo group because
1587 // updateBuffer can create undo actions (see #11292)
1588 UndoGroupHelper ugh(buffer);
1590 if (dr.screenUpdate() & Update::ForceAll) {
1591 for (Buffer const * b : theBufferList())
1593 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1596 updateCurrentView(cmd, dr);
1599 d->dispatch_result_ = dr;
1600 return d->dispatch_result_;
1604 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1609 BufferView * bv = current_view_->currentBufferView();
1611 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1612 bv->cursor().clearBufferUpdate();
1613 bv->buffer().updateBuffer();
1615 // BufferView::update() updates the ViewMetricsInfo and
1616 // also initializes the position cache for all insets in
1617 // (at least partially) visible top-level paragraphs.
1618 // We will redraw the screen only if needed.
1619 bv->processUpdateFlags(dr.screenUpdate());
1621 // Do we have a selection?
1622 theSelection().haveSelection(bv->cursor().selection());
1625 current_view_->restartCaret();
1627 if (dr.needMessageUpdate()) {
1628 // Some messages may already be translated, so we cannot use _()
1629 current_view_->message(makeDispatchMessage(
1630 translateIfPossible(dr.message()), cmd));
1635 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1636 bool switchToBuffer)
1638 if (!theSession().bookmarks().isValid(idx))
1640 BookmarksSection::Bookmark const & bm =
1641 theSession().bookmarks().bookmark(idx);
1642 LASSERT(!bm.filename.empty(), return);
1643 string const file = bm.filename.absFileName();
1644 // if the file is not opened, open it.
1645 if (!theBufferList().exists(bm.filename)) {
1647 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1651 // open may fail, so we need to test it again
1652 if (!theBufferList().exists(bm.filename))
1655 // bm can be changed when saving
1656 BookmarksSection::Bookmark tmp = bm;
1658 // Special case idx == 0 used for back-from-back jump navigation
1660 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1662 // if the current buffer is not that one, switch to it.
1663 BufferView * doc_bv = current_view_ ?
1664 current_view_->documentBufferView() : nullptr;
1665 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1666 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1667 if (switchToBuffer) {
1668 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1671 doc_bv = current_view_->documentBufferView();
1676 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1677 if (!doc_bv || !doc_bv->moveToPosition(
1678 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1681 Cursor & cur = doc_bv->cursor();
1682 if (old && cur != *old)
1683 notifyCursorLeavesOrEnters(*old, cur);
1689 // Cursor jump succeeded!
1690 pit_type new_pit = cur.pit();
1691 pos_type new_pos = cur.pos();
1692 int new_id = cur.paragraph().id();
1694 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1695 // see http://www.lyx.org/trac/ticket/3092
1696 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1697 || bm.top_id != new_id) {
1698 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1699 new_pit, new_pos, new_id);
1703 // This function runs "configure" and then rereads lyx.defaults to
1704 // reconfigure the automatic settings.
1705 void GuiApplication::reconfigure(string const & option)
1707 // emit message signal.
1708 if (current_view_) {
1709 current_view_->message(_("Running configure..."));
1710 current_view_->setCursor(Qt::WaitCursor);
1713 // Run configure in user lyx directory
1714 string const lock_file = package().getConfigureLockName();
1715 int fd = fileLock(lock_file.c_str());
1716 int const ret = package().reconfigureUserLyXDir(option);
1717 // emit message signal.
1719 current_view_->message(_("Reloading configuration..."));
1720 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1721 // Re-read packages.lst
1722 LaTeXPackages::getAvailable();
1723 fileUnlock(fd, lock_file.c_str());
1726 current_view_->unsetCursor();
1729 Alert::information(_("System reconfiguration failed"),
1730 _("The system reconfiguration has failed.\n"
1731 "Default textclass is used but LyX may\n"
1732 "not be able to work properly.\n"
1733 "Please reconfigure again if needed."));
1735 Alert::information(_("System reconfigured"),
1736 _("The system has been reconfigured.\n"
1737 "You need to restart LyX to make use of any\n"
1738 "updated document class specifications."));
1741 void GuiApplication::validateCurrentView()
1743 if (!d->views_.empty() && !current_view_) {
1744 // currently at least one view exists but no view has the focus.
1745 // choose the last view to make it current.
1746 // a view without any open document is preferred.
1747 GuiView * candidate = nullptr;
1748 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1749 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1750 for (; it != end; ++it) {
1752 if (!candidate->documentBufferView())
1755 setCurrentView(candidate);
1759 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1761 string const argument = to_utf8(cmd.argument());
1762 FuncCode const action = cmd.action();
1764 LYXERR(Debug::ACTION, "cmd: " << cmd);
1766 // we have not done anything wrong yet.
1769 FuncStatus const flag = getStatus(cmd);
1770 if (!flag.enabled()) {
1771 // We cannot use this function here
1772 LYXERR(Debug::ACTION, "action "
1773 << lyxaction.getActionName(action)
1774 << " [" << action << "] is disabled at this location");
1775 dr.setMessage(flag.message());
1777 dr.dispatched(false);
1778 dr.screenUpdate(Update::None);
1779 dr.clearBufferUpdate();
1783 if (cmd.origin() == FuncRequest::LYXSERVER) {
1784 if (current_view_ && current_view_->currentBufferView())
1785 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1786 // we will also need to redraw the screen at the end
1787 dr.screenUpdate(Update::FitCursor);
1790 // Assumes that the action will be dispatched.
1791 dr.dispatched(true);
1793 switch (cmd.action()) {
1795 case LFUN_WINDOW_NEW:
1796 createView(toqstr(cmd.argument()));
1799 case LFUN_WINDOW_CLOSE:
1800 // FIXME: this is done also in GuiView::closeBuffer()!
1801 // update bookmark pit of the current buffer before window close
1802 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1803 gotoBookmark(i, false, false);
1804 // clear the last opened list, because
1805 // maybe this will end the session
1806 theSession().lastOpened().clear();
1807 // check for valid current_view_
1808 validateCurrentView();
1810 current_view_->closeScheduled();
1814 // quitting is triggered by the gui code
1815 // (leaving the event loop).
1817 current_view_->message(from_utf8(N_("Exiting.")));
1818 if (closeAllViews())
1822 case LFUN_SCREEN_FONT_UPDATE: {
1823 // handle the screen font changes.
1824 /* FIXME: this only updates the current document, whereas all
1825 * documents should see their metrics updated.
1827 d->font_loader_.update();
1828 dr.screenUpdate(Update::Force | Update::FitCursor);
1832 case LFUN_BUFFER_NEW:
1833 validateCurrentView();
1835 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1836 createView(QString(), false); // keep hidden
1837 current_view_->newDocument(to_utf8(cmd.argument()));
1838 current_view_->show();
1839 current_view_->activateWindow();
1841 current_view_->newDocument(to_utf8(cmd.argument()));
1845 case LFUN_BUFFER_NEW_TEMPLATE: {
1846 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1847 string const temp = cmd.getArg(1);
1848 validateCurrentView();
1850 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1852 current_view_->newDocument(file, temp, true);
1853 if (!current_view_->documentBufferView())
1854 current_view_->close();
1856 current_view_->newDocument(file, temp, true);
1861 case LFUN_FILE_OPEN: {
1862 // FIXME: normally the code below is not needed, since getStatus makes sure that
1863 // current_view_ is not null.
1864 validateCurrentView();
1865 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1866 string const fname = trim(to_utf8(cmd.argument()), "\"");
1867 bool const is_open = FileName::isAbsolute(fname)
1868 && theBufferList().getBuffer(FileName(fname));
1870 || (!lyxrc.open_buffers_in_tabs
1871 && current_view_->documentBufferView() != nullptr
1873 // We want the ui session to be saved per document and not per
1874 // window number. The filename crc is a good enough identifier.
1875 createView(support::checksum(fname));
1876 current_view_->openDocuments(fname, cmd.origin());
1877 if (!current_view_->documentBufferView())
1878 current_view_->close();
1879 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1880 current_view_->raise();
1881 current_view_->activateWindow();
1882 current_view_->showNormal();
1885 current_view_->openDocuments(fname, cmd.origin());
1886 if (cmd.origin() == FuncRequest::LYXSERVER) {
1887 current_view_->raise();
1888 current_view_->activateWindow();
1889 current_view_->showNormal();
1895 case LFUN_HELP_OPEN: {
1896 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1897 if (current_view_ == nullptr)
1899 string const arg = to_utf8(cmd.argument());
1901 current_view_->message(_("Missing argument"));
1904 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1906 fname = i18nLibFileSearch("examples", arg, "lyx");
1908 if (fname.empty()) {
1909 lyxerr << "LyX: unable to find documentation file `"
1910 << arg << "'. Bad installation?" << endl;
1913 current_view_->message(bformat(_("Opening help file %1$s..."),
1914 makeDisplayPath(fname.absFileName())));
1915 Buffer * buf = current_view_->loadDocument(fname, false);
1917 buf->setReadonly(!current_view_->develMode());
1921 case LFUN_LYXFILES_OPEN: {
1922 string arg = to_utf8(cmd.argument());
1926 if (arg != "templates" && arg != "examples") {
1927 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1930 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1934 case LFUN_SET_COLOR: {
1935 string const lyx_name = cmd.getArg(0);
1936 string x11_name = cmd.getArg(1);
1937 string x11_darkname = cmd.getArg(2);
1938 if (lyx_name.empty() || x11_name.empty()) {
1940 current_view_->message(
1941 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1946 // FIXME: The graphics cache no longer has a changeDisplay method.
1947 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1948 bool const graphicsbg_changed =
1949 lyx_name == graphicsbg && x11_name != graphicsbg;
1950 if (graphicsbg_changed)
1951 graphics::GCache::get().changeDisplay(true);
1954 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1955 x11_darkname = x11_name;
1958 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1960 current_view_->message(
1961 bformat(_("Set-color \"%1$s\" failed "
1962 "- color is undefined or "
1963 "may not be redefined"),
1964 from_utf8(lyx_name)));
1967 // Make sure we don't keep old colors in cache.
1968 d->color_cache_.clear();
1969 // Update the current view
1970 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1974 case LFUN_LYXRC_APPLY: {
1975 // reset active key sequences, since the bindings
1976 // are updated (bug 6064)
1978 LyXRC const lyxrc_orig = lyxrc;
1980 istringstream ss(to_utf8(cmd.argument()));
1981 bool const success = lyxrc.read(ss);
1984 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1985 << "Unable to read lyxrc data"
1990 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1992 // If the request comes from the minibuffer, then we can't reset
1993 // the GUI, since that would destroy the minibuffer itself and
1994 // cause a crash, since we are currently in one of the methods of
1995 // GuiCommandBuffer. See bug #8540.
1996 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1999 // FIXME Unfortunately, that leaves a bug here, since we cannot
2000 // reset the GUI in this case. If the changes to lyxrc affected the
2001 // UI, then, nothing would happen. This seems fairly unlikely, but
2002 // it definitely is a bug.
2004 dr.forceBufferUpdate();
2008 case LFUN_COMMAND_PREFIX:
2009 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2014 d->meta_fake_bit = NoModifier;
2015 GuiView * gv = currentView();
2016 if (gv && gv->currentBufferView())
2017 // cancel any selection
2018 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2019 dr.setMessage(from_ascii(N_("Cancel")));
2022 case LFUN_META_PREFIX:
2023 d->meta_fake_bit = AltModifier;
2024 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2027 // --- Menus -----------------------------------------------
2028 case LFUN_RECONFIGURE:
2029 // argument is any additional parameter to the configure.py command
2030 reconfigure(to_utf8(cmd.argument()));
2033 // --- lyxserver commands ----------------------------
2034 case LFUN_SERVER_GET_FILENAME: {
2035 if (current_view_ && current_view_->documentBufferView()) {
2036 docstring const fname = from_utf8(
2037 current_view_->documentBufferView()->buffer().absFileName());
2038 dr.setMessage(fname);
2039 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2041 dr.setMessage(docstring());
2042 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2047 case LFUN_SERVER_NOTIFY: {
2048 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2049 dr.setMessage(dispatch_buffer);
2050 theServer().notifyClient(to_utf8(dispatch_buffer));
2054 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2055 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2061 string rest = split(argument, countstr, ' ');
2062 int const count = convert<int>(countstr);
2063 // an arbitrary number to limit number of iterations
2064 int const max_iter = 10000;
2065 if (count > max_iter) {
2066 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2069 for (int i = 0; i < count; ++i) {
2070 FuncRequest lfun = lyxaction.lookupFunc(rest);
2071 lfun.allowAsync(false);
2078 case LFUN_COMMAND_SEQUENCE: {
2079 // argument contains ';'-terminated commands
2080 string arg = argument;
2081 // FIXME: this LFUN should also work without any view.
2082 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2083 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2084 // This handles undo groups automagically
2085 UndoGroupHelper ugh(buffer);
2086 while (!arg.empty()) {
2088 arg = split(arg, first, ';');
2089 FuncRequest func(lyxaction.lookupFunc(first));
2090 func.allowAsync(false);
2091 func.setOrigin(cmd.origin());
2097 case LFUN_BUFFER_FORALL: {
2098 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2099 funcToRun.allowAsync(false);
2101 map<Buffer *, GuiView *> views_lVisible;
2102 map<GuiView *, Buffer *> activeBuffers;
2104 QList<GuiView *> allViews = d->views_.values();
2106 // this for does not modify any buffer. It just collects info on local
2107 // visibility of buffers and on which buffer is active in each view.
2108 Buffer * const last = theBufferList().last();
2109 for(GuiView * view : allViews) {
2110 // all of the buffers might be locally hidden. That is, there is no
2112 if (!view || !view->currentBufferView())
2113 activeBuffers[view] = nullptr;
2115 activeBuffers[view] = &view->currentBufferView()->buffer();
2117 // find out if each is locally visible or locally hidden.
2118 // we don't use a for loop as the buffer list cycles.
2119 Buffer * b = theBufferList().first();
2121 bool const locallyVisible = view && view->workArea(*b);
2122 if (locallyVisible) {
2123 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2124 // only need to overwrite/add if we don't already know a buffer is globally
2125 // visible or we do know but we would prefer to dispatch LFUN from the
2126 // current view because of cursor position issues.
2127 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2128 views_lVisible[b] = view;
2132 b = theBufferList().next(b);
2136 GuiView * const homeView = currentView();
2137 Buffer * b = theBufferList().first();
2138 Buffer * nextBuf = nullptr;
2139 int numProcessed = 0;
2142 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2144 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2146 // first change to a view where b is locally visible, preferably current_view_.
2147 GuiView * const vLv = views_lVisible[b];
2149 lyx::dispatch(funcToRun);
2157 // put things back to how they were (if possible).
2158 for (GuiView * view : allViews) {
2159 Buffer * originalBuf = activeBuffers[view];
2160 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2161 if (theBufferList().isLoaded(originalBuf))
2162 view->setBuffer(originalBuf);
2164 homeView->setFocus();
2166 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2170 case LFUN_COMMAND_ALTERNATIVES: {
2171 // argument contains ';'-terminated commands
2172 string arg = argument;
2173 while (!arg.empty()) {
2175 arg = split(arg, first, ';');
2176 FuncRequest func(lyxaction.lookupFunc(first));
2177 func.setOrigin(cmd.origin());
2178 FuncStatus const stat = getStatus(func);
2179 if (stat.enabled()) {
2189 if (theTopLevelCmdDef().lock(argument, func)) {
2190 func.setOrigin(cmd.origin());
2192 theTopLevelCmdDef().release(argument);
2194 if (func.action() == LFUN_UNKNOWN_ACTION) {
2195 // unknown command definition
2196 lyxerr << "Warning: unknown command definition `"
2200 // recursion detected
2201 lyxerr << "Warning: Recursion in the command definition `"
2202 << argument << "' detected"
2209 case LFUN_IF_RELATIVES: {
2210 string const lfun = to_utf8(cmd.argument());
2211 FuncRequest func(lyxaction.lookupFunc(lfun));
2212 func.setOrigin(cmd.origin());
2213 FuncStatus const stat = getStatus(func);
2214 if (stat.enabled()) {
2221 case LFUN_PREFERENCES_SAVE:
2222 lyxrc.write(support::makeAbsPath("preferences",
2223 package().user_support().absFileName()), false);
2226 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2227 string const fname = addName(addPath(package().user_support().absFileName(),
2228 "templates/"), "defaults.lyx");
2229 Buffer defaults(fname);
2231 istringstream ss(argument);
2236 // We need to make sure that, after we recreat the DocumentClass,
2237 // which we do in readHeader, we apply it to the document itself.
2238 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2239 int const unknown_tokens = defaults.readHeader(lex);
2240 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2241 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2242 cap::switchBetweenClasses(olddc, newdc, theinset);
2244 if (unknown_tokens != 0) {
2245 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2246 << unknown_tokens << " unknown token"
2247 << (unknown_tokens == 1 ? "" : "s")
2251 if (defaults.writeFile(FileName(defaults.absFileName())))
2252 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2253 makeDisplayPath(fname)));
2256 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2261 case LFUN_BOOKMARK_GOTO:
2262 // go to bookmark, open unopened file and switch to buffer if necessary
2263 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2264 dr.screenUpdate(Update::Force | Update::FitCursor);
2267 case LFUN_BOOKMARK_CLEAR:
2268 theSession().bookmarks().clear();
2269 dr.screenUpdate(Update::Force);
2272 case LFUN_DEBUG_LEVEL_SET:
2273 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2276 case LFUN_DIALOG_SHOW: {
2277 string const name = cmd.getArg(0);
2278 // Workaround: on Mac OS the application
2279 // is not terminated when closing the last view.
2280 // With the following dialogs which should still
2281 // be usable, create a new one to be able
2282 // to dispatch LFUN_DIALOG_SHOW to this view.
2283 if (name == "aboutlyx" || name == "compare"
2284 || name == "lyxfiles" || name == "prefs"
2285 || name == "progress" || name == "texinfo")
2287 if (current_view_ == nullptr)
2293 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2296 current_view_->dispatch(cmd, dr);
2300 if (current_view_ && current_view_->isFullScreen()) {
2301 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2302 current_view_->menuBar()->hide();
2305 if (cmd.origin() == FuncRequest::LYXSERVER)
2306 updateCurrentView(cmd, dr);
2310 docstring GuiApplication::viewStatusMessage()
2312 // When meta-fake key is pressed, show the key sequence so far + "M-".
2313 if (d->meta_fake_bit != NoModifier)
2314 return d->keyseq.print(KeySequence::ForGui) + "M-";
2316 // Else, when a non-complete key sequence is pressed,
2317 // show the available options.
2318 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2319 return d->keyseq.printOptions(true);
2325 string GuiApplication::inputLanguageCode() const
2327 QLocale loc = inputMethod()->locale();
2328 //LYXERR0("input lang = " << fromqstr(loc.name()));
2329 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2333 void GuiApplication::onLocaleChanged()
2335 //LYXERR0("Change language to " << inputLanguage()->lang());
2336 if (currentView() && currentView()->currentBufferView())
2337 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2341 void GuiApplication::onPaletteChanged()
2343 colorCache().setPalette(palette());
2347 void GuiApplication::handleKeyFunc(FuncCode action)
2351 if (d->keyseq.length())
2353 GuiView * gv = currentView();
2354 LASSERT(gv && gv->currentBufferView(), return);
2355 BufferView * bv = gv->currentBufferView();
2356 bv->getIntl().getTransManager().deadkey(
2357 c, get_accent(action).accent, bv->cursor().innerText(),
2359 // Need to clear, in case the minibuffer calls these
2362 // copied verbatim from do_accent_char
2363 bv->cursor().resetAnchor();
2367 //Keep this in sync with GuiApplication::processKeySym below
2368 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2369 KeyModifier state) const
2371 // Do nothing if we have nothing
2372 if (!keysym.isOK() || keysym.isModifier())
2374 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2376 FuncRequest func = seq.addkey(keysym, state);
2377 // When not cancel or meta-fake, do the normal lookup.
2378 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2380 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2382 // Maybe user can only reach the key via holding down shift.
2383 // Let's see. But only if shift is the only modifier
2384 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2385 // If addkey looked up a command and did not find further commands then
2386 // seq has been reset at this point
2387 func = seq.addkey(keysym, NoModifier);
2389 LYXERR(Debug::KEY, " Key (queried) [action="
2390 << lyxaction.getActionName(func.action()) << "]["
2391 << seq.print(KeySequence::Portable) << ']');
2392 return func.action() != LFUN_UNKNOWN_ACTION;
2396 //Keep this in sync with GuiApplication::queryKeySym above
2397 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2399 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2401 // Do nothing if we have nothing (JMarc)
2402 if (!keysym.isOK() || keysym.isModifier()) {
2404 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2406 current_view_->restartCaret();
2410 char_type encoded_last_key = keysym.getUCSEncoded();
2412 // Do a one-deep top-level lookup for
2413 // cancel and meta-fake keys. RVDK_PATCH_5
2414 d->cancel_meta_seq.reset();
2416 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2417 LYXERR(Debug::KEY, "action first set to ["
2418 << lyxaction.getActionName(func.action()) << ']');
2420 // When not cancel or meta-fake, do the normal lookup.
2421 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2422 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2423 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2424 // remove Caps Lock and Mod2 as a modifiers
2425 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2426 LYXERR(Debug::KEY, "action now set to ["
2427 << lyxaction.getActionName(func.action()) << ']');
2430 // Don't remove this unless you know what you are doing.
2431 d->meta_fake_bit = NoModifier;
2433 // Can this happen now ?
2434 if (func.action() == LFUN_NOACTION)
2435 func = FuncRequest(LFUN_COMMAND_PREFIX);
2437 LYXERR(Debug::KEY, " Key [action="
2438 << lyxaction.getActionName(func.action()) << "]["
2439 << d->keyseq.print(KeySequence::Portable) << ']');
2441 // already here we know if it any point in going further
2442 // why not return already here if action == -1 and
2443 // num_bytes == 0? (Lgb)
2445 if (d->keyseq.length() > 1 && current_view_)
2446 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2449 // Maybe user can only reach the key via holding down shift.
2450 // Let's see. But only if shift is the only modifier
2451 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2452 LYXERR(Debug::KEY, "Trying without shift");
2453 // If addkey looked up a command and did not find further commands then
2454 // seq has been reset at this point
2455 func = d->keyseq.addkey(keysym, NoModifier);
2456 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2459 if (func.action() == LFUN_UNKNOWN_ACTION) {
2460 // We didn't match any of the key sequences.
2461 // See if it's normal insertable text not already
2462 // covered by a binding
2463 if (keysym.isText() && d->keyseq.length() == 1) {
2464 // Non-printable characters (such as ASCII control characters)
2465 // must not be inserted (#5704)
2466 if (!isPrintable(encoded_last_key)) {
2467 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2469 current_view_->restartCaret();
2472 // The following modifier check is not needed on Mac.
2473 // The keysym is either not text or it is different
2474 // from the non-modifier keysym. See #9875 for the
2475 // broken alt-modifier effect of having this code active.
2476 #if !defined(Q_OS_MAC)
2477 // If a non-Shift Modifier is used we have a non-bound key sequence
2478 // (such as Alt+j = j). This should be omitted (#5575).
2479 // On Windows, AltModifier and ControlModifier are both
2480 // set when AltGr is pressed. Therefore, in order to not
2481 // break AltGr-bound symbols (see #5575 for details),
2482 // unbound Ctrl+Alt key sequences are allowed.
2483 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2484 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2485 && !(state & AltModifier && state & ControlModifier)
2489 if (current_view_) {
2490 current_view_->message(_("Unknown function."));
2491 current_view_->restartCaret();
2496 // Since all checks above were passed, we now really have text that
2497 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2498 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2500 LYXERR(Debug::KEY, "isText() is true, inserting.");
2501 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2503 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2504 if (current_view_) {
2505 current_view_->message(_("Unknown function."));
2506 current_view_->restartCaret();
2512 if (func.action() == LFUN_SELF_INSERT) {
2513 if (encoded_last_key != 0) {
2514 docstring const arg(1, encoded_last_key);
2515 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2516 FuncRequest::KEYBOARD));
2517 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2520 processFuncRequest(func);
2524 void GuiApplication::processFuncRequest(FuncRequest const & func)
2526 lyx::dispatch(func);
2530 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2532 addToFuncRequestQueue(func);
2533 processFuncRequestQueueAsync();
2537 void GuiApplication::processFuncRequestQueue()
2539 while (!d->func_request_queue_.empty()) {
2540 // take the item from the stack _before_ processing the
2541 // request in order to avoid race conditions from nested
2542 // or parallel requests (see #10406)
2543 FuncRequest const fr(d->func_request_queue_.front());
2544 d->func_request_queue_.pop();
2545 processFuncRequest(fr);
2550 void GuiApplication::processFuncRequestQueueAsync()
2552 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2556 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2558 d->func_request_queue_.push(func);
2562 void GuiApplication::resetGui()
2564 // Set the language defined by the user.
2568 if (!readUIFile(toqstr(lyxrc.ui_file)))
2569 // Gives some error box here.
2572 if (d->global_menubar_)
2573 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2575 QHash<int, GuiView *>::iterator it;
2576 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2579 gv->setLayoutDirection(layoutDirection());
2583 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2587 bool GuiApplication::rtlContext() const
2589 if (current_view_ && current_view_->currentBufferView()) {
2590 BufferView const * bv = current_view_->currentBufferView();
2591 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2593 return layoutDirection() == Qt::RightToLeft;
2597 void GuiApplication::createView(int view_id)
2599 createView(QString(), true, view_id);
2603 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2606 // release the keyboard which might have been grabbed by the global
2607 // menubar on Mac to catch shortcuts even without any GuiView.
2608 if (d->global_menubar_)
2609 d->global_menubar_->releaseKeyboard();
2613 while (d->views_.find(id) != d->views_.end())
2616 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2617 GuiView * view = new GuiView(id);
2618 // `view' is the new current_view_. Tell coverity that is is not 0.
2619 LATTEST(current_view_);
2621 d->views_[id] = view;
2625 view->activateWindow();
2628 if (!geometry_arg.isEmpty()) {
2629 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2633 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2634 QRegularExpressionMatch match = re.match(geometry_arg);
2635 w = match.captured(1).toInt();
2636 h = match.captured(2).toInt();
2637 x = match.captured(3).toInt();
2638 y = match.captured(4).toInt();
2639 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2640 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2642 // Set initial geometry such that we can get the frame size.
2643 view->setGeometry(x, y, w, h);
2644 int framewidth = view->geometry().x() - view->x();
2645 int titleheight = view->geometry().y() - view->y();
2646 // Negative displacements must be interpreted as distances
2647 // from the right or bottom screen borders.
2648 if (sx == '-' || sy == '-') {
2649 QRect rec = QGuiApplication::primaryScreen()->geometry();
2651 x += rec.width() - w - framewidth;
2653 y += rec.height() - h - titleheight;
2654 view->setGeometry(x, y, w, h);
2656 // Make sure that the left and top frame borders are visible.
2657 if (view->x() < 0 || view->y() < 0) {
2662 view->setGeometry(x, y, w, h);
2670 bool GuiApplication::unhide(Buffer * buf)
2674 currentView()->setBuffer(buf, false);
2679 QPixmap GuiApplication::getScaledPixmap(QString imagedir, QString name) const
2682 // Consider device/pixel ratio (HiDPI)
2684 dpr = currentView()->devicePixelRatio();
2685 // We render SVG directly for HiDPI scalability
2686 QPixmap pm = getPixmap(imagedir, name, "svgz,png");
2687 FileName fname = imageLibFileSearch(imagedir, name, "svgz,png");
2688 QString fpath = toqstr(fname.absFileName());
2689 if (!fpath.isEmpty() && !fpath.endsWith(".png")) {
2690 QSvgRenderer svgRenderer(fpath);
2691 if (svgRenderer.isValid()) {
2692 pm = QPixmap(pm.size() * dpr);
2693 pm.fill(Qt::transparent);
2694 QPainter painter(&pm);
2695 svgRenderer.render(&painter);
2696 pm.setDevicePixelRatio(dpr);
2703 Clipboard & GuiApplication::clipboard()
2705 return d->clipboard_;
2709 Selection & GuiApplication::selection()
2711 return d->selection_;
2715 FontLoader & GuiApplication::fontLoader()
2717 return d->font_loader_;
2721 Toolbars const & GuiApplication::toolbars() const
2723 return d->toolbars_;
2727 Toolbars & GuiApplication::toolbars()
2729 return d->toolbars_;
2733 Menus const & GuiApplication::menus() const
2739 Menus & GuiApplication::menus()
2745 bool GuiApplication::needsBackingStore() const
2747 /* Qt on macOS and Wayland does not respect the
2748 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2749 * store at each update. Therefore, we use our own backing store
2750 * in these two cases. It is also possible to force the use of the
2751 * backing store for cases like x11 with transparent WM themes.
2753 return platformName() == "cocoa" || platformName().contains("wayland");
2757 QList<int> GuiApplication::viewIds() const
2759 return d->views_.keys();
2763 ColorCache & GuiApplication::colorCache()
2765 return d->color_cache_;
2769 int GuiApplication::exec()
2771 // asynchronously handle batch commands. This event will be in
2772 // the event queue in front of other asynchronous events. Hence,
2773 // we can assume in the latter that the gui is setup already.
2774 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2776 return QApplication::exec();
2780 void GuiApplication::exit(int status)
2782 QApplication::exit(status);
2786 void GuiApplication::setGuiLanguage()
2790 // install translation file for Qt built-in dialogs
2791 QString const language_name = QString("qt_") + theLocale.name();
2792 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2793 // Short-named translator can be loaded from a long name, but not the
2794 // opposite. Therefore, long name should be used without truncation.
2795 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2796 if (!d->qt_trans_.load(language_name,
2797 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2798 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2800 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2802 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2805 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2809 switch (theLocale.language()) {
2810 case QLocale::Arabic :
2811 case QLocale::Hebrew :
2812 case QLocale::Persian :
2813 case QLocale::Urdu :
2814 setLayoutDirection(Qt::RightToLeft);
2817 setLayoutDirection(Qt::LeftToRight);
2822 void GuiApplication::execBatchCommands()
2827 if (!readUIFile(toqstr(lyxrc.ui_file)))
2828 // Gives some error box here.
2832 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2833 # if QT_VERSION < 0x060000
2834 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2836 // Create the global default menubar which is shown for the dialogs
2837 // and if no GuiView is visible.
2838 // This must be done after the session was recovered to know the "last files".
2839 d->global_menubar_ = new QMenuBar(0);
2840 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2843 lyx::execBatchCommands();
2847 QAbstractItemModel * GuiApplication::languageModel()
2849 if (d->language_model_)
2850 return d->language_model_;
2852 QStandardItemModel * lang_model = new QStandardItemModel(this);
2853 lang_model->insertColumns(0, 3);
2854 QIcon speller(guiApp ? guiApp->getScaledPixmap("images/", "dialog-show_spellchecker")
2855 : getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2856 QIcon saurus(guiApp ? guiApp->getScaledPixmap("images/", "thesaurus-entry")
2857 : getPixmap("images/", "thesaurus-entry", "svgz,png"));
2858 Languages::const_iterator it = lyx::languages.begin();
2859 Languages::const_iterator end = lyx::languages.end();
2860 for (; it != end; ++it) {
2861 int current_row = lang_model->rowCount();
2862 lang_model->insertRows(current_row, 1);
2863 QModelIndex pl_item = lang_model->index(current_row, 0);
2864 QModelIndex sp_item = lang_model->index(current_row, 1);
2865 QModelIndex th_item = lang_model->index(current_row, 2);
2866 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2867 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2868 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2869 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2870 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2871 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2872 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2873 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2874 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2875 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2877 d->language_model_ = new QSortFilterProxyModel(this);
2878 d->language_model_->setSourceModel(lang_model);
2879 d->language_model_->setSortLocaleAware(true);
2880 return d->language_model_;
2884 void GuiApplication::restoreGuiSession()
2886 if (!lyxrc.load_session)
2889 Session & session = theSession();
2890 LastOpenedSection::LastOpened const & lastopened =
2891 session.lastOpened().getfiles();
2893 validateCurrentView();
2895 FileName active_file;
2896 // do not add to the lastfile list since these files are restored from
2897 // last session, and should be already there (regular files), or should
2898 // not be added at all (help files).
2899 for (auto const & last : lastopened) {
2900 FileName const & file_name = last.file_name;
2901 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2902 && current_view_->documentBufferView() != nullptr)) {
2903 string const & fname = file_name.absFileName();
2904 createView(support::checksum(fname));
2906 current_view_->loadDocument(file_name, false);
2909 active_file = file_name;
2912 // Restore last active buffer
2913 Buffer * buffer = theBufferList().getBuffer(active_file);
2914 if (buffer && current_view_)
2915 current_view_->setBuffer(buffer);
2917 // clear this list to save a few bytes of RAM
2918 session.lastOpened().clear();
2922 QString const GuiApplication::romanFontName()
2925 font.setStyleHint(QFont::Serif);
2926 font.setFamily("serif");
2928 return QFontInfo(font).family();
2932 QString const GuiApplication::sansFontName()
2935 font.setStyleHint(QFont::SansSerif);
2936 font.setFamily("sans");
2938 return QFontInfo(font).family();
2942 QString const GuiApplication::typewriterFontName()
2944 return QFontInfo(typewriterSystemFont()).family();
2949 // We cannot use QFont::fixedPitch() because it doesn't
2950 // return the fact but only if it is requested.
2951 static bool isFixedPitch(const QFont & font) {
2952 const QFontInfo fi(font);
2953 return fi.fixedPitch();
2958 QFont const GuiApplication::typewriterSystemFont()
2960 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2961 if (!isFixedPitch(font)) {
2962 // try to enforce a real monospaced font
2963 font.setStyleHint(QFont::Monospace);
2964 if (!isFixedPitch(font)) {
2965 font.setStyleHint(QFont::TypeWriter);
2966 if (!isFixedPitch(font)) font.setFamily("courier");
2970 // On a Mac the result is too small and it's not practical to
2971 // rely on Qtconfig utility to change the system settings of Qt.
2972 font.setPointSize(12);
2978 void GuiApplication::handleRegularEvents()
2980 ForkedCallsController::handleCompletedProcesses();
2984 bool GuiApplication::event(QEvent * e)
2987 case QEvent::FileOpen: {
2988 // Open a file; this happens only on Mac OS X for now.
2990 // We do this asynchronously because on startup the batch
2991 // commands are not executed here yet and the gui is not ready
2993 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2994 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2995 processFuncRequestAsync(fr);
2999 case QEvent::ApplicationPaletteChange: {
3000 // runtime switch from/to dark mode
3002 return QApplication::event(e);
3005 return QApplication::event(e);
3010 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3013 return QApplication::notify(receiver, event);
3015 catch (ExceptionMessage const & e) {
3017 case ErrorException:
3019 setQuitOnLastWindowClosed(false);
3021 Alert::error(e.title_, e.details_);
3023 // Properly crash in debug mode in order to get a useful backtrace.
3026 // In release mode, try to exit gracefully.
3028 // FIXME: GCC 7 thinks we can fall through here. Can we?
3030 case BufferException: {
3031 if (!current_view_ || !current_view_->documentBufferView())
3033 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3034 docstring details = e.details_ + '\n';
3035 details += buf->emergencyWrite();
3036 theBufferList().release(buf);
3037 details += "\n" + _("The current document was closed.");
3038 Alert::error(e.title_, details);
3041 case WarningException:
3042 Alert::warning(e.title_, e.details_);
3046 catch (exception const & e) {
3047 docstring s = _("LyX has caught an exception, it will now "
3048 "attempt to save all unsaved documents and exit."
3050 s += from_ascii(e.what());
3051 Alert::error(_("Software exception Detected"), s);
3055 docstring s = _("LyX has caught some really weird exception, it will "
3056 "now attempt to save all unsaved documents and exit.");
3057 Alert::error(_("Software exception Detected"), s);
3064 bool GuiApplication::isInDarkMode()
3066 return colorCache().isDarkMode();
3070 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3072 QColor const & qcol = d->color_cache_.get(col);
3073 if (!qcol.isValid()) {
3079 rgbcol.r = qcol.red();
3080 rgbcol.g = qcol.green();
3081 rgbcol.b = qcol.blue();
3086 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3088 QColor const qcol(lcolor.getX11HexName(col).c_str());
3089 if (!qcol.isValid()) {
3095 rgbcol.r = qcol.red();
3096 rgbcol.g = qcol.green();
3097 rgbcol.b = qcol.blue();
3102 string const GuiApplication::hexName(ColorCode col)
3104 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3108 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3110 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3111 d->socket_notifiers_[fd] = sn;
3112 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3116 void GuiApplication::socketDataReceived(int fd)
3118 d->socket_notifiers_[fd]->func_();
3122 void GuiApplication::unregisterSocketCallback(int fd)
3124 d->socket_notifiers_.take(fd)->setEnabled(false);
3128 void GuiApplication::commitData(QSessionManager & sm)
3130 /** The implementation is required to avoid an application exit
3131 ** when session state save is triggered by session manager.
3132 ** The default implementation sends a close event to all
3133 ** visible top level widgets when session management allows
3135 ** We are changing that to check the state of each buffer in all
3136 ** views and ask the users what to do if buffers are dirty.
3137 ** Furthermore, we save the session state.
3138 ** We do NOT close the views here since the user still can cancel
3139 ** the logout process (see #9277); also, this would hide LyX from
3140 ** an OSes own session handling (application restoration).
3142 #ifdef QT_NO_SESSIONMANAGER
3144 #warning Qt is compiled without session manager
3146 #pragma message("warning: Qt is compiled without session manager")
3150 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3158 void GuiApplication::unregisterView(GuiView * gv)
3160 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3161 d->views_.remove(gv->id());
3162 if (current_view_ == gv)
3163 current_view_ = nullptr;
3168 bool GuiApplication::closeAllViews()
3170 if (d->views_.empty())
3173 // When a view/window was closed before without quitting LyX, there
3174 // are already entries in the lastOpened list.
3175 theSession().lastOpened().clear();
3177 QList<GuiView *> const views = d->views_.values();
3178 for (GuiView * view : views) {
3179 if (!view->closeScheduled())
3188 bool GuiApplication::prepareAllViewsForLogout()
3190 if (d->views_.empty())
3193 QList<GuiView *> const views = d->views_.values();
3194 for (GuiView * view : views) {
3195 if (!view->prepareAllBuffersForLogout())
3203 GuiView & GuiApplication::view(int id) const
3205 LAPPERR(d->views_.contains(id));
3206 return *d->views_.value(id);
3210 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3212 QList<GuiView *> const views = d->views_.values();
3213 for (GuiView * view : views)
3214 view->hideDialog(name, inset);
3218 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3220 Buffer const * buf = nullptr;
3221 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3222 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3223 if (Buffer const * ptr = (*it)->updateInset(inset))
3230 bool GuiApplication::searchMenu(FuncRequest const & func,
3231 docstring_list & names) const
3233 BufferView * bv = nullptr;
3235 bv = current_view_->currentBufferView();
3236 return d->menus_.searchMenu(func, names, bv);
3240 bool GuiApplication::hasBufferView() const
3242 return (current_view_ && current_view_->currentBufferView());
3246 // Ensure that a file is read only once (prevents include loops)
3247 static QStringList uifiles;
3248 // store which ui files define Toolbars
3249 static QStringList toolbar_uifiles;
3252 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3263 LexerKeyword uitags[] = {
3264 { "format", ui_format },
3265 { "include", ui_include },
3266 { "menuset", ui_menuset },
3267 { "toolbars", ui_toolbars },
3268 { "toolbarset", ui_toolbarset }
3272 lex.setFile(ui_path);
3274 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3278 if (lyxerr.debugging(Debug::PARSER))
3279 lex.printTable(lyxerr);
3282 // format before introduction of format tag
3283 unsigned int format = 0;
3284 while (lex.isOK()) {
3285 int const status = lex.lex();
3287 // we have to do this check here, outside the switch,
3288 // because otherwise we would start reading include files,
3289 // e.g., if the first tag we hit was an include tag.
3290 if (status == ui_format)
3292 format = lex.getInteger();
3296 // this will trigger unless the first tag we hit is a format
3297 // tag, with the right format.
3298 if (format != LFUN_FORMAT)
3299 return FormatMismatch;
3302 case Lexer::LEX_FEOF:
3307 QString const file = toqstr(lex.getString());
3308 bool const success = readUIFile(file, true);
3310 LYXERR0("Failed to read included file: " << fromqstr(file));
3317 d->menus_.read(lex);
3321 d->toolbars_.readToolbars(lex);
3325 d->toolbars_.readToolbarSettings(lex);
3326 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3330 if (!rtrim(lex.getString()).empty())
3331 lex.printError("LyX::ReadUIFile: "
3332 "Unknown menu tag: `$$Token'");
3334 LYXERR0("Error with status: " << status);
3340 return (error ? ReadError : ReadOK);
3344 bool GuiApplication::readUIFile(QString const & name, bool include)
3346 LYXERR(Debug::INIT, "About to read " << name << "...");
3350 ui_path = libFileSearch("ui", name, "inc");
3351 if (ui_path.empty())
3352 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3354 ui_path = libFileSearch("ui", name, "ui");
3357 if (ui_path.empty()) {
3358 static const QString defaultUIFile = "default";
3359 LYXERR(Debug::INIT, "Could not find " << name);
3361 Alert::warning(_("Could not find UI definition file"),
3362 bformat(_("Error while reading the included file\n%1$s\n"
3363 "Please check your installation."), qstring_to_ucs4(name)));
3366 if (name == defaultUIFile) {
3367 LYXERR(Debug::INIT, "Could not find default UI file!!");
3368 Alert::warning(_("Could not find default UI file"),
3369 _("LyX could not find the default UI file!\n"
3370 "Please check your installation."));
3373 Alert::warning(_("Could not find UI definition file"),
3374 bformat(_("Error while reading the configuration file\n%1$s\n"
3375 "Falling back to default.\n"
3376 "Please look under Tools>Preferences>User Interface and\n"
3377 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3378 return readUIFile(defaultUIFile, false);
3381 QString const uifile = toqstr(ui_path.absFileName());
3382 if (uifiles.contains(uifile)) {
3384 // We are reading again the top uifile so reset the safeguard:
3387 d->toolbars_.reset();
3389 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3390 << "Is this an include loop?");
3394 uifiles.push_back(uifile);
3396 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3398 ReturnValues retval = readUIFile(ui_path);
3400 if (retval == FormatMismatch) {
3401 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3402 TempFile tmp("convertXXXXXX.ui");
3403 FileName const tempfile = tmp.name();
3404 bool const success = prefs2prefs(ui_path, tempfile, true);
3406 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3407 " to format " << LFUN_FORMAT << ".");
3409 retval = readUIFile(tempfile);
3413 if (retval != ReadOK) {
3414 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3422 settings.beginGroup("ui_files");
3423 bool touched = false;
3424 for (int i = 0; i != uifiles.size(); ++i) {
3425 QFileInfo fi(uifiles[i]);
3426 QDateTime const date_value = fi.lastModified();
3427 QString const name_key = QString::number(i);
3428 // if an ui file which defines Toolbars has changed,
3429 // we have to reset the settings
3430 if (toolbar_uifiles.contains(uifiles[i])
3431 && (!settings.contains(name_key)
3432 || settings.value(name_key).toString() != uifiles[i]
3433 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3435 settings.setValue(name_key, uifiles[i]);
3436 settings.setValue(name_key + "/date", date_value);
3439 settings.endGroup();
3441 settings.remove("views");
3447 void GuiApplication::onLastWindowClosed()
3449 if (d->global_menubar_)
3450 d->global_menubar_->grabKeyboard();
3454 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3456 std::string name = "unknown";
3458 case Qt::ApplicationSuspended:
3459 name = "ApplicationSuspended";
3461 case Qt::ApplicationHidden:
3462 name = "ApplicationHidden";
3464 case Qt::ApplicationInactive:
3465 name = "ApplicationInactive";
3467 case Qt::ApplicationActive:
3468 name = "ApplicationActive";
3469 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3470 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3471 if (d->views_.empty() && d->last_state_ == state) {
3472 LYXERR(Debug::GUI, "Open new window...");
3477 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3478 d->last_state_ = state;
3482 void GuiApplication::startLongOperation() {
3483 d->key_checker_.start();
3487 bool GuiApplication::longOperationCancelled() {
3488 return d->key_checker_.pressed();
3492 void GuiApplication::stopLongOperation() {
3493 d->key_checker_.stop();
3497 bool GuiApplication::longOperationStarted() {
3498 return d->key_checker_.started();
3502 ////////////////////////////////////////////////////////////////////////
3504 // X11 specific stuff goes here...
3506 #if defined(QPA_XCB)
3507 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3508 void * message, QINTPTR *)
3510 if (!current_view_ || eventType != "xcb_generic_event_t")
3513 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3515 switch (ev->response_type) {
3516 case XCB_SELECTION_REQUEST: {
3517 xcb_selection_request_event_t * srev =
3518 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3519 if (srev->selection != XCB_ATOM_PRIMARY)
3521 LYXERR(Debug::SELECTION, "X requested selection.");
3522 BufferView * bv = current_view_->currentBufferView();
3524 docstring const sel = bv->requestSelection();
3526 d->selection_.put(sel);
3527 #ifdef HAVE_QT5_X11_EXTRAS
3528 // Refresh the selection request timestamp.
3529 // We have to do this by ourselves as Qt seems
3530 // not doing that, maybe because of our
3531 // "persistent selection" implementation
3532 // (see comments in GuiSelection.cpp).
3533 // It is expected that every X11 event is
3534 // 32 bytes long, even if not all 32 bytes are
3536 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3537 struct alignas(32) padded_event
3538 : xcb_selection_notify_event_t {};
3539 padded_event nev = {};
3540 nev.response_type = XCB_SELECTION_NOTIFY;
3541 nev.requestor = srev->requestor;
3542 nev.selection = srev->selection;
3543 nev.target = srev->target;
3544 nev.property = XCB_NONE;
3545 nev.time = XCB_CURRENT_TIME;
3546 xcb_connection_t * con = QX11Info::connection();
3547 xcb_send_event(con, 0, srev->requestor,
3548 XCB_EVENT_MASK_NO_EVENT,
3549 reinterpret_cast<char const *>(&nev));
3557 case XCB_SELECTION_CLEAR: {
3558 xcb_selection_clear_event_t * scev =
3559 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3560 if (scev->selection != XCB_ATOM_PRIMARY)
3562 LYXERR(Debug::SELECTION, "Lost selection.");
3563 BufferView * bv = current_view_->currentBufferView();
3565 bv->clearSelection();
3573 } // namespace frontend
3576 void hideDialogs(std::string const & name, Inset * inset)
3579 frontend::guiApp->hideDialogs(name, inset);
3583 ////////////////////////////////////////////////////////////////////
3587 ////////////////////////////////////////////////////////////////////
3589 frontend::FontLoader & theFontLoader()
3591 LAPPERR(frontend::guiApp);
3592 return frontend::guiApp->fontLoader();
3596 frontend::FontMetrics const & theFontMetrics(Font const & f)
3598 return theFontMetrics(f.fontInfo());
3602 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3604 LAPPERR(frontend::guiApp);
3605 return frontend::guiApp->fontLoader().metrics(f);
3609 ////////////////////////////////////////////////////////////////////
3613 ////////////////////////////////////////////////////////////////////
3615 frontend::Clipboard & theClipboard()
3617 LAPPERR(frontend::guiApp);
3618 return frontend::guiApp->clipboard();
3622 frontend::Selection & theSelection()
3624 LAPPERR(frontend::guiApp);
3625 return frontend::guiApp->selection();
3631 #include "moc_GuiApplication.cpp"