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"
50 #include "LyXAction.h"
52 #include "Paragraph.h"
55 #include "SpellChecker.h"
56 #include "Thesaurus.h"
59 #include "insets/InsetText.h"
61 #include "support/checksum.h"
62 #include "support/convert.h"
63 #include "support/debug.h"
64 #include "support/ExceptionMessage.h"
65 #include "support/environment.h"
66 #include "support/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/Lexer.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 devicePixelRatio();
1254 void GuiApplication::clearSession()
1261 docstring Application::iconName(FuncRequest const & f, bool unknown)
1263 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1267 docstring Application::mathIcon(docstring const & c)
1269 return qstring_to_ucs4(findImg(toqstr(c)));
1272 void Application::applyPrefs()
1274 if (lyxrc.ui_style != "default")
1275 lyx::frontend::GuiApplication::setStyle(toqstr(lyxrc.ui_style));
1278 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1282 BufferView * bv = nullptr;
1283 BufferView * doc_bv = nullptr;
1285 if (cmd.action() == LFUN_NOACTION) {
1286 status.message(from_utf8(N_("Nothing to do")));
1287 status.setEnabled(false);
1290 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1291 status.setUnknown(true);
1292 status.message(from_utf8(N_("Unknown action")));
1293 status.setEnabled(false);
1296 // Does the GuiApplication know something?
1297 else if (getStatus(cmd, status)) { }
1299 // If we do not have a GuiView, then other functions are disabled
1300 else if (!current_view_)
1301 status.setEnabled(false);
1303 // Does the GuiView know something?
1304 else if (current_view_->getStatus(cmd, status)) { }
1306 // In LyX/Mac, when a dialog is open, the menus of the
1307 // application can still be accessed without giving focus to
1308 // the main window. In this case, we want to disable the menu
1309 // entries that are buffer or view-related.
1310 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1312 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1313 status.setEnabled(false);
1316 // If we do not have a BufferView, then other functions are disabled
1317 else if (!(bv = current_view_->currentBufferView()))
1318 status.setEnabled(false);
1320 // Does the current BufferView know something?
1321 else if (bv->getStatus(cmd, status)) { }
1323 // Does the current Buffer know something?
1324 else if (bv->buffer().getStatus(cmd, status)) { }
1326 // If we do not have a document BufferView, different from the
1327 // current BufferView, then other functions are disabled
1328 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1329 status.setEnabled(false);
1331 // Does the document Buffer know something?
1332 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1335 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1336 status.message(from_utf8(N_("Command not handled")));
1337 status.setEnabled(false);
1340 // the default error message if we disable the command
1341 if (!status.enabled() && status.message().empty())
1342 status.message(from_utf8(N_("Command disabled")));
1348 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1350 // I would really like to avoid having this switch and rather try to
1351 // encode this in the function itself.
1352 // -- And I'd rather let an inset decide which LFUNs it is willing
1353 // to handle (Andre')
1355 switch (cmd.action()) {
1357 // This could be used for the no-GUI version. The GUI version is handled in
1358 // GuiView::getStatus(). See above.
1360 case LFUN_BUFFER_WRITE:
1361 case LFUN_BUFFER_WRITE_AS:
1362 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1363 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1364 enable = b && (b->isUnnamed() || !b->isClean());
1369 case LFUN_BOOKMARK_GOTO: {
1370 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1371 enable = theSession().bookmarks().isValid(num);
1375 case LFUN_BOOKMARK_CLEAR:
1376 enable = theSession().bookmarks().hasValid();
1379 // this one is difficult to get right. As a half-baked
1380 // solution, we consider only the first action of the sequence
1381 case LFUN_COMMAND_SEQUENCE: {
1382 // argument contains ';'-terminated commands
1383 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1384 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1385 func.setOrigin(cmd.origin());
1386 flag = getStatus(func);
1390 // we want to check if at least one of these is enabled
1391 case LFUN_COMMAND_ALTERNATIVES: {
1392 // argument contains ';'-terminated commands
1393 string arg = to_utf8(cmd.argument());
1394 while (!arg.empty()) {
1396 arg = split(arg, first, ';');
1397 FuncRequest func(lyxaction.lookupFunc(first));
1398 func.setOrigin(cmd.origin());
1399 flag = getStatus(func);
1400 // if this one is enabled, the whole thing is
1409 string name = to_utf8(cmd.argument());
1410 if (theTopLevelCmdDef().lock(name, func)) {
1411 func.setOrigin(cmd.origin());
1412 flag = getStatus(func);
1413 theTopLevelCmdDef().release(name);
1415 // catch recursion or unknown command
1416 // definition. all operations until the
1417 // recursion or unknown command definition
1418 // occurs are performed, so set the state to
1425 case LFUN_IF_RELATIVES: {
1426 string const lfun = to_utf8(cmd.argument());
1427 BufferView const * bv =
1428 current_view_ ? current_view_->currentBufferView() : nullptr;
1429 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1433 FuncRequest func(lyxaction.lookupFunc(lfun));
1434 func.setOrigin(cmd.origin());
1435 flag = getStatus(func);
1439 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1441 case LFUN_PREFERENCES_SAVE:
1442 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1443 // these are handled in our dispatch()
1446 case LFUN_DEBUG_LEVEL_SET: {
1447 string bad = Debug::badValue(to_utf8(cmd.argument()));
1448 enable = bad.empty();
1450 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1454 case LFUN_WINDOW_CLOSE:
1455 enable = !d->views_.empty();
1458 case LFUN_BUFFER_NEW:
1459 case LFUN_BUFFER_NEW_TEMPLATE:
1460 case LFUN_FILE_OPEN:
1461 case LFUN_LYXFILES_OPEN:
1462 case LFUN_HELP_OPEN:
1463 case LFUN_SCREEN_FONT_UPDATE:
1464 case LFUN_SET_COLOR:
1465 case LFUN_WINDOW_NEW:
1467 case LFUN_LYXRC_APPLY:
1468 case LFUN_COMMAND_PREFIX:
1470 case LFUN_META_PREFIX:
1471 case LFUN_RECONFIGURE:
1472 case LFUN_SERVER_GET_FILENAME:
1473 case LFUN_SERVER_NOTIFY:
1477 case LFUN_BUFFER_FORALL: {
1478 if (theBufferList().empty()) {
1479 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1480 flag.setEnabled(false);
1484 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1485 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1486 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1487 flag.setEnabled(false);
1492 case LFUN_DIALOG_SHOW: {
1493 string const name = cmd.getArg(0);
1494 return name == "aboutlyx"
1495 || name == "lyxfiles"
1497 || name == "texinfo"
1498 || name == "progress"
1499 || name == "compare";
1507 flag.setEnabled(false);
1511 /// make a post-dispatch status message
1512 static docstring makeDispatchMessage(docstring const & msg,
1513 FuncRequest const & cmd)
1515 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1516 || cmd.origin() == FuncRequest::TOOLBAR
1517 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1519 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1520 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1524 docstring dispatch_msg = msg;
1525 if (!dispatch_msg.empty())
1526 dispatch_msg += ' ';
1528 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1530 bool argsadded = false;
1532 if (!cmd.argument().empty()) {
1533 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1534 comname += ' ' + cmd.argument();
1538 docstring const shortcuts = theTopLevelKeymap().
1539 printBindings(cmd, KeySequence::ForGui);
1541 if (!shortcuts.empty())
1542 comname += ": " + shortcuts;
1543 else if (!argsadded && !cmd.argument().empty())
1544 comname += ' ' + cmd.argument();
1546 if (!comname.empty()) {
1547 comname = rtrim(comname);
1548 dispatch_msg += '(' + rtrim(comname) + ')';
1550 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1551 return dispatch_msg;
1555 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1559 Buffer * buffer = nullptr;
1560 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1561 //setCurrentView(cmd.view_origin); //does not work
1563 dr.setMessage(_("Wrong focus!"));
1564 d->dispatch_result_ = dr;
1565 return d->dispatch_result_;
1567 if (current_view_ && current_view_->currentBufferView()) {
1568 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1569 buffer = ¤t_view_->currentBufferView()->buffer();
1572 dr.screenUpdate(Update::FitCursor);
1574 // All the code is kept inside the undo group because
1575 // updateBuffer can create undo actions (see #11292)
1576 UndoGroupHelper ugh(buffer);
1578 if (dr.screenUpdate() & Update::ForceAll) {
1579 for (Buffer const * b : theBufferList())
1581 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1584 updateCurrentView(cmd, dr);
1587 d->dispatch_result_ = dr;
1588 return d->dispatch_result_;
1592 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1597 BufferView * bv = current_view_->currentBufferView();
1599 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1600 bv->cursor().clearBufferUpdate();
1601 bv->buffer().updateBuffer();
1603 // BufferView::update() updates the ViewMetricsInfo and
1604 // also initializes the position cache for all insets in
1605 // (at least partially) visible top-level paragraphs.
1606 // We will redraw the screen only if needed.
1607 bv->processUpdateFlags(dr.screenUpdate());
1609 // Do we have a selection?
1610 theSelection().haveSelection(bv->cursor().selection());
1613 current_view_->restartCaret();
1615 if (dr.needMessageUpdate()) {
1616 // Some messages may already be translated, so we cannot use _()
1617 current_view_->message(makeDispatchMessage(
1618 translateIfPossible(dr.message()), cmd));
1623 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1624 bool switchToBuffer)
1626 if (!theSession().bookmarks().isValid(idx))
1628 BookmarksSection::Bookmark const & bm =
1629 theSession().bookmarks().bookmark(idx);
1630 LASSERT(!bm.filename.empty(), return);
1631 string const file = bm.filename.absFileName();
1632 // if the file is not opened, open it.
1633 if (!theBufferList().exists(bm.filename)) {
1635 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1639 // open may fail, so we need to test it again
1640 if (!theBufferList().exists(bm.filename))
1643 // bm can be changed when saving
1644 BookmarksSection::Bookmark tmp = bm;
1646 // Special case idx == 0 used for back-from-back jump navigation
1648 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1650 // if the current buffer is not that one, switch to it.
1651 BufferView * doc_bv = current_view_ ?
1652 current_view_->documentBufferView() : nullptr;
1653 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1654 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1655 if (switchToBuffer) {
1656 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1659 doc_bv = current_view_->documentBufferView();
1664 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1665 if (!doc_bv || !doc_bv->moveToPosition(
1666 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1669 Cursor & cur = doc_bv->cursor();
1670 if (old && cur != *old)
1671 notifyCursorLeavesOrEnters(*old, cur);
1677 // Cursor jump succeeded!
1678 pit_type new_pit = cur.pit();
1679 pos_type new_pos = cur.pos();
1680 int new_id = cur.paragraph().id();
1682 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1683 // see http://www.lyx.org/trac/ticket/3092
1684 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1685 || bm.top_id != new_id) {
1686 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1687 new_pit, new_pos, new_id);
1691 // This function runs "configure" and then rereads lyx.defaults to
1692 // reconfigure the automatic settings.
1693 void GuiApplication::reconfigure(string const & option)
1695 // emit message signal.
1696 if (current_view_) {
1697 current_view_->message(_("Running configure..."));
1698 current_view_->setCursor(Qt::WaitCursor);
1701 // Run configure in user lyx directory
1702 string const lock_file = package().getConfigureLockName();
1703 int fd = fileLock(lock_file.c_str());
1704 int const ret = package().reconfigureUserLyXDir(option);
1705 // emit message signal.
1707 current_view_->message(_("Reloading configuration..."));
1708 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1709 // Re-read packages.lst
1710 LaTeXPackages::getAvailable();
1711 fileUnlock(fd, lock_file.c_str());
1714 current_view_->unsetCursor();
1717 Alert::information(_("System reconfiguration failed"),
1718 _("The system reconfiguration has failed.\n"
1719 "Default textclass is used but LyX may\n"
1720 "not be able to work properly.\n"
1721 "Please reconfigure again if needed."));
1723 Alert::information(_("System reconfigured"),
1724 _("The system has been reconfigured.\n"
1725 "You need to restart LyX to make use of any\n"
1726 "updated document class specifications."));
1729 void GuiApplication::validateCurrentView()
1731 if (!d->views_.empty() && !current_view_) {
1732 // currently at least one view exists but no view has the focus.
1733 // choose the last view to make it current.
1734 // a view without any open document is preferred.
1735 GuiView * candidate = nullptr;
1736 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1737 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1738 for (; it != end; ++it) {
1740 if (!candidate->documentBufferView())
1743 setCurrentView(candidate);
1747 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1749 string const argument = to_utf8(cmd.argument());
1750 FuncCode const action = cmd.action();
1752 LYXERR(Debug::ACTION, "cmd: " << cmd);
1754 // we have not done anything wrong yet.
1757 FuncStatus const flag = getStatus(cmd);
1758 if (!flag.enabled()) {
1759 // We cannot use this function here
1760 LYXERR(Debug::ACTION, "action "
1761 << lyxaction.getActionName(action)
1762 << " [" << action << "] is disabled at this location");
1763 dr.setMessage(flag.message());
1765 dr.dispatched(false);
1766 dr.screenUpdate(Update::None);
1767 dr.clearBufferUpdate();
1771 if (cmd.origin() == FuncRequest::LYXSERVER) {
1772 if (current_view_ && current_view_->currentBufferView())
1773 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1774 // we will also need to redraw the screen at the end
1775 dr.screenUpdate(Update::FitCursor);
1778 // Assumes that the action will be dispatched.
1779 dr.dispatched(true);
1781 switch (cmd.action()) {
1783 case LFUN_WINDOW_NEW:
1784 createView(toqstr(cmd.argument()));
1787 case LFUN_WINDOW_CLOSE:
1788 // FIXME: this is done also in GuiView::closeBuffer()!
1789 // update bookmark pit of the current buffer before window close
1790 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1791 gotoBookmark(i, false, false);
1792 // clear the last opened list, because
1793 // maybe this will end the session
1794 theSession().lastOpened().clear();
1795 // check for valid current_view_
1796 validateCurrentView();
1798 current_view_->closeScheduled();
1802 // quitting is triggered by the gui code
1803 // (leaving the event loop).
1805 current_view_->message(from_utf8(N_("Exiting.")));
1806 if (closeAllViews())
1810 case LFUN_SCREEN_FONT_UPDATE: {
1811 // handle the screen font changes.
1812 /* FIXME: this only updates the current document, whereas all
1813 * documents should see their metrics updated.
1815 d->font_loader_.update();
1816 dr.screenUpdate(Update::Force | Update::FitCursor);
1820 case LFUN_BUFFER_NEW:
1821 validateCurrentView();
1823 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1824 createView(QString(), false); // keep hidden
1825 current_view_->newDocument(to_utf8(cmd.argument()));
1826 current_view_->show();
1827 current_view_->activateWindow();
1829 current_view_->newDocument(to_utf8(cmd.argument()));
1833 case LFUN_BUFFER_NEW_TEMPLATE: {
1834 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1835 string const temp = cmd.getArg(1);
1836 validateCurrentView();
1838 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1840 current_view_->newDocument(file, temp, true);
1841 if (!current_view_->documentBufferView())
1842 current_view_->close();
1844 current_view_->newDocument(file, temp, true);
1849 case LFUN_FILE_OPEN: {
1850 // FIXME: normally the code below is not needed, since getStatus makes sure that
1851 // current_view_ is not null.
1852 validateCurrentView();
1853 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1854 string const fname = trim(to_utf8(cmd.argument()), "\"");
1855 bool const is_open = FileName::isAbsolute(fname)
1856 && theBufferList().getBuffer(FileName(fname));
1858 || (!lyxrc.open_buffers_in_tabs
1859 && current_view_->documentBufferView() != nullptr
1861 // We want the ui session to be saved per document and not per
1862 // window number. The filename crc is a good enough identifier.
1863 createView(support::checksum(fname));
1864 current_view_->openDocuments(fname, cmd.origin());
1865 if (!current_view_->documentBufferView())
1866 current_view_->close();
1867 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1868 current_view_->raise();
1869 current_view_->activateWindow();
1870 current_view_->showNormal();
1873 current_view_->openDocuments(fname, cmd.origin());
1874 if (cmd.origin() == FuncRequest::LYXSERVER) {
1875 current_view_->raise();
1876 current_view_->activateWindow();
1877 current_view_->showNormal();
1883 case LFUN_HELP_OPEN: {
1884 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1885 if (current_view_ == nullptr)
1887 string const arg = to_utf8(cmd.argument());
1889 current_view_->message(_("Missing argument"));
1892 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1894 fname = i18nLibFileSearch("examples", arg, "lyx");
1896 if (fname.empty()) {
1897 lyxerr << "LyX: unable to find documentation file `"
1898 << arg << "'. Bad installation?" << endl;
1901 current_view_->message(bformat(_("Opening help file %1$s..."),
1902 makeDisplayPath(fname.absFileName())));
1903 Buffer * buf = current_view_->loadDocument(fname, false);
1905 buf->setReadonly(!current_view_->develMode());
1909 case LFUN_LYXFILES_OPEN: {
1910 string arg = to_utf8(cmd.argument());
1914 if (arg != "templates" && arg != "examples") {
1915 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1918 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1922 case LFUN_SET_COLOR: {
1923 string const lyx_name = cmd.getArg(0);
1924 string x11_name = cmd.getArg(1);
1925 string x11_darkname = cmd.getArg(2);
1926 if (lyx_name.empty() || x11_name.empty()) {
1928 current_view_->message(
1929 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1934 // FIXME: The graphics cache no longer has a changeDisplay method.
1935 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1936 bool const graphicsbg_changed =
1937 lyx_name == graphicsbg && x11_name != graphicsbg;
1938 if (graphicsbg_changed)
1939 graphics::GCache::get().changeDisplay(true);
1942 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1943 x11_darkname = x11_name;
1946 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1948 current_view_->message(
1949 bformat(_("Set-color \"%1$s\" failed "
1950 "- color is undefined or "
1951 "may not be redefined"),
1952 from_utf8(lyx_name)));
1955 // Make sure we don't keep old colors in cache.
1956 d->color_cache_.clear();
1957 // Update the current view
1958 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1962 case LFUN_LYXRC_APPLY: {
1963 // reset active key sequences, since the bindings
1964 // are updated (bug 6064)
1966 LyXRC const lyxrc_orig = lyxrc;
1968 istringstream ss(to_utf8(cmd.argument()));
1969 bool const success = lyxrc.read(ss);
1972 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1973 << "Unable to read lyxrc data"
1978 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1980 // If the request comes from the minibuffer, then we can't reset
1981 // the GUI, since that would destroy the minibuffer itself and
1982 // cause a crash, since we are currently in one of the methods of
1983 // GuiCommandBuffer. See bug #8540.
1984 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1987 // FIXME Unfortunately, that leaves a bug here, since we cannot
1988 // reset the GUI in this case. If the changes to lyxrc affected the
1989 // UI, then, nothing would happen. This seems fairly unlikely, but
1990 // it definitely is a bug.
1992 dr.forceBufferUpdate();
1996 case LFUN_COMMAND_PREFIX:
1997 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2002 d->meta_fake_bit = NoModifier;
2003 GuiView * gv = currentView();
2004 if (gv && gv->currentBufferView())
2005 // cancel any selection
2006 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2007 dr.setMessage(from_ascii(N_("Cancel")));
2010 case LFUN_META_PREFIX:
2011 d->meta_fake_bit = AltModifier;
2012 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2015 // --- Menus -----------------------------------------------
2016 case LFUN_RECONFIGURE:
2017 // argument is any additional parameter to the configure.py command
2018 reconfigure(to_utf8(cmd.argument()));
2021 // --- lyxserver commands ----------------------------
2022 case LFUN_SERVER_GET_FILENAME: {
2023 if (current_view_ && current_view_->documentBufferView()) {
2024 docstring const fname = from_utf8(
2025 current_view_->documentBufferView()->buffer().absFileName());
2026 dr.setMessage(fname);
2027 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2029 dr.setMessage(docstring());
2030 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2035 case LFUN_SERVER_NOTIFY: {
2036 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2037 dr.setMessage(dispatch_buffer);
2038 theServer().notifyClient(to_utf8(dispatch_buffer));
2042 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2043 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2049 string rest = split(argument, countstr, ' ');
2050 int const count = convert<int>(countstr);
2051 // an arbitrary number to limit number of iterations
2052 int const max_iter = 10000;
2053 if (count > max_iter) {
2054 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2057 for (int i = 0; i < count; ++i) {
2058 FuncRequest lfun = lyxaction.lookupFunc(rest);
2059 lfun.allowAsync(false);
2066 case LFUN_COMMAND_SEQUENCE: {
2067 // argument contains ';'-terminated commands
2068 string arg = argument;
2069 // FIXME: this LFUN should also work without any view.
2070 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2071 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2072 // This handles undo groups automagically
2073 UndoGroupHelper ugh(buffer);
2074 while (!arg.empty()) {
2076 arg = split(arg, first, ';');
2077 FuncRequest func(lyxaction.lookupFunc(first));
2078 func.allowAsync(false);
2079 func.setOrigin(cmd.origin());
2085 case LFUN_BUFFER_FORALL: {
2086 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2087 funcToRun.allowAsync(false);
2089 map<Buffer *, GuiView *> views_lVisible;
2090 map<GuiView *, Buffer *> activeBuffers;
2092 QList<GuiView *> allViews = d->views_.values();
2094 // this for does not modify any buffer. It just collects info on local
2095 // visibility of buffers and on which buffer is active in each view.
2096 Buffer * const last = theBufferList().last();
2097 for(GuiView * view : allViews) {
2098 // all of the buffers might be locally hidden. That is, there is no
2100 if (!view || !view->currentBufferView())
2101 activeBuffers[view] = nullptr;
2103 activeBuffers[view] = &view->currentBufferView()->buffer();
2105 // find out if each is locally visible or locally hidden.
2106 // we don't use a for loop as the buffer list cycles.
2107 Buffer * b = theBufferList().first();
2109 bool const locallyVisible = view && view->workArea(*b);
2110 if (locallyVisible) {
2111 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2112 // only need to overwrite/add if we don't already know a buffer is globally
2113 // visible or we do know but we would prefer to dispatch LFUN from the
2114 // current view because of cursor position issues.
2115 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2116 views_lVisible[b] = view;
2120 b = theBufferList().next(b);
2124 GuiView * const homeView = currentView();
2125 Buffer * b = theBufferList().first();
2126 Buffer * nextBuf = nullptr;
2127 int numProcessed = 0;
2130 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2132 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2134 // first change to a view where b is locally visible, preferably current_view_.
2135 GuiView * const vLv = views_lVisible[b];
2137 lyx::dispatch(funcToRun);
2145 // put things back to how they were (if possible).
2146 for (GuiView * view : allViews) {
2147 Buffer * originalBuf = activeBuffers[view];
2148 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2149 if (theBufferList().isLoaded(originalBuf))
2150 view->setBuffer(originalBuf);
2152 homeView->setFocus();
2154 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2158 case LFUN_COMMAND_ALTERNATIVES: {
2159 // argument contains ';'-terminated commands
2160 string arg = argument;
2161 while (!arg.empty()) {
2163 arg = split(arg, first, ';');
2164 FuncRequest func(lyxaction.lookupFunc(first));
2165 func.setOrigin(cmd.origin());
2166 FuncStatus const stat = getStatus(func);
2167 if (stat.enabled()) {
2177 if (theTopLevelCmdDef().lock(argument, func)) {
2178 func.setOrigin(cmd.origin());
2180 theTopLevelCmdDef().release(argument);
2182 if (func.action() == LFUN_UNKNOWN_ACTION) {
2183 // unknown command definition
2184 lyxerr << "Warning: unknown command definition `"
2188 // recursion detected
2189 lyxerr << "Warning: Recursion in the command definition `"
2190 << argument << "' detected"
2197 case LFUN_IF_RELATIVES: {
2198 string const lfun = to_utf8(cmd.argument());
2199 FuncRequest func(lyxaction.lookupFunc(lfun));
2200 func.setOrigin(cmd.origin());
2201 FuncStatus const stat = getStatus(func);
2202 if (stat.enabled()) {
2209 case LFUN_PREFERENCES_SAVE:
2210 lyxrc.write(support::makeAbsPath("preferences",
2211 package().user_support().absFileName()), false);
2214 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2215 string const fname = addName(addPath(package().user_support().absFileName(),
2216 "templates/"), "defaults.lyx");
2217 Buffer defaults(fname);
2219 istringstream ss(argument);
2224 // We need to make sure that, after we recreat the DocumentClass,
2225 // which we do in readHeader, we apply it to the document itself.
2226 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2227 int const unknown_tokens = defaults.readHeader(lex);
2228 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2229 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2230 cap::switchBetweenClasses(olddc, newdc, theinset);
2232 if (unknown_tokens != 0) {
2233 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2234 << unknown_tokens << " unknown token"
2235 << (unknown_tokens == 1 ? "" : "s")
2239 if (defaults.writeFile(FileName(defaults.absFileName())))
2240 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2241 makeDisplayPath(fname)));
2244 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2249 case LFUN_BOOKMARK_GOTO:
2250 // go to bookmark, open unopened file and switch to buffer if necessary
2251 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2252 dr.screenUpdate(Update::Force | Update::FitCursor);
2255 case LFUN_BOOKMARK_CLEAR:
2256 theSession().bookmarks().clear();
2257 dr.screenUpdate(Update::Force);
2260 case LFUN_DEBUG_LEVEL_SET:
2261 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2264 case LFUN_DIALOG_SHOW: {
2265 string const name = cmd.getArg(0);
2266 // Workaround: on Mac OS the application
2267 // is not terminated when closing the last view.
2268 // With the following dialogs which should still
2269 // be usable, create a new one to be able
2270 // to dispatch LFUN_DIALOG_SHOW to this view.
2271 if (name == "aboutlyx" || name == "compare"
2272 || name == "lyxfiles" || name == "prefs"
2273 || name == "progress" || name == "texinfo")
2275 if (current_view_ == nullptr)
2281 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2284 current_view_->dispatch(cmd, dr);
2288 if (current_view_ && current_view_->isFullScreen()) {
2289 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2290 current_view_->menuBar()->hide();
2293 if (cmd.origin() == FuncRequest::LYXSERVER)
2294 updateCurrentView(cmd, dr);
2298 docstring GuiApplication::viewStatusMessage()
2300 // When meta-fake key is pressed, show the key sequence so far + "M-".
2301 if (d->meta_fake_bit != NoModifier)
2302 return d->keyseq.print(KeySequence::ForGui) + "M-";
2304 // Else, when a non-complete key sequence is pressed,
2305 // show the available options.
2306 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2307 return d->keyseq.printOptions(true);
2313 string GuiApplication::inputLanguageCode() const
2315 QLocale loc = inputMethod()->locale();
2316 //LYXERR0("input lang = " << fromqstr(loc.name()));
2317 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2321 void GuiApplication::onLocaleChanged()
2323 //LYXERR0("Change language to " << inputLanguage()->lang());
2324 if (currentView() && currentView()->currentBufferView())
2325 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2329 void GuiApplication::onPaletteChanged()
2331 colorCache().setPalette(palette());
2335 void GuiApplication::handleKeyFunc(FuncCode action)
2339 if (d->keyseq.length())
2341 GuiView * gv = currentView();
2342 LASSERT(gv && gv->currentBufferView(), return);
2343 BufferView * bv = gv->currentBufferView();
2344 bv->getIntl().getTransManager().deadkey(
2345 c, get_accent(action).accent, bv->cursor().innerText(),
2347 // Need to clear, in case the minibuffer calls these
2350 // copied verbatim from do_accent_char
2351 bv->cursor().resetAnchor();
2355 //Keep this in sync with GuiApplication::processKeySym below
2356 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2357 KeyModifier state) const
2359 // Do nothing if we have nothing
2360 if (!keysym.isOK() || keysym.isModifier())
2362 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2364 FuncRequest func = seq.addkey(keysym, state);
2365 // When not cancel or meta-fake, do the normal lookup.
2366 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2368 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2370 // Maybe user can only reach the key via holding down shift.
2371 // Let's see. But only if shift is the only modifier
2372 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2373 // If addkey looked up a command and did not find further commands then
2374 // seq has been reset at this point
2375 func = seq.addkey(keysym, NoModifier);
2377 LYXERR(Debug::KEY, " Key (queried) [action="
2378 << lyxaction.getActionName(func.action()) << "]["
2379 << seq.print(KeySequence::Portable) << ']');
2380 return func.action() != LFUN_UNKNOWN_ACTION;
2384 //Keep this in sync with GuiApplication::queryKeySym above
2385 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2387 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2389 // Do nothing if we have nothing (JMarc)
2390 if (!keysym.isOK() || keysym.isModifier()) {
2392 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2394 current_view_->restartCaret();
2398 char_type encoded_last_key = keysym.getUCSEncoded();
2400 // Do a one-deep top-level lookup for
2401 // cancel and meta-fake keys. RVDK_PATCH_5
2402 d->cancel_meta_seq.reset();
2404 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2405 LYXERR(Debug::KEY, "action first set to ["
2406 << lyxaction.getActionName(func.action()) << ']');
2408 // When not cancel or meta-fake, do the normal lookup.
2409 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2410 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2411 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2412 // remove Caps Lock and Mod2 as a modifiers
2413 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2414 LYXERR(Debug::KEY, "action now set to ["
2415 << lyxaction.getActionName(func.action()) << ']');
2418 // Don't remove this unless you know what you are doing.
2419 d->meta_fake_bit = NoModifier;
2421 // Can this happen now ?
2422 if (func.action() == LFUN_NOACTION)
2423 func = FuncRequest(LFUN_COMMAND_PREFIX);
2425 LYXERR(Debug::KEY, " Key [action="
2426 << lyxaction.getActionName(func.action()) << "]["
2427 << d->keyseq.print(KeySequence::Portable) << ']');
2429 // already here we know if it any point in going further
2430 // why not return already here if action == -1 and
2431 // num_bytes == 0? (Lgb)
2433 if (d->keyseq.length() > 1 && current_view_)
2434 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2437 // Maybe user can only reach the key via holding down shift.
2438 // Let's see. But only if shift is the only modifier
2439 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2440 LYXERR(Debug::KEY, "Trying without shift");
2441 // If addkey looked up a command and did not find further commands then
2442 // seq has been reset at this point
2443 func = d->keyseq.addkey(keysym, NoModifier);
2444 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2447 if (func.action() == LFUN_UNKNOWN_ACTION) {
2448 // We didn't match any of the key sequences.
2449 // See if it's normal insertable text not already
2450 // covered by a binding
2451 if (keysym.isText() && d->keyseq.length() == 1) {
2452 // Non-printable characters (such as ASCII control characters)
2453 // must not be inserted (#5704)
2454 if (!isPrintable(encoded_last_key)) {
2455 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2457 current_view_->restartCaret();
2460 // The following modifier check is not needed on Mac.
2461 // The keysym is either not text or it is different
2462 // from the non-modifier keysym. See #9875 for the
2463 // broken alt-modifier effect of having this code active.
2464 #if !defined(Q_OS_MAC)
2465 // If a non-Shift Modifier is used we have a non-bound key sequence
2466 // (such as Alt+j = j). This should be omitted (#5575).
2467 // On Windows, AltModifier and ControlModifier are both
2468 // set when AltGr is pressed. Therefore, in order to not
2469 // break AltGr-bound symbols (see #5575 for details),
2470 // unbound Ctrl+Alt key sequences are allowed.
2471 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2472 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2473 && !(state & AltModifier && state & ControlModifier)
2477 if (current_view_) {
2478 current_view_->message(_("Unknown function."));
2479 current_view_->restartCaret();
2484 // Since all checks above were passed, we now really have text that
2485 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2486 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2488 LYXERR(Debug::KEY, "isText() is true, inserting.");
2489 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2491 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2492 if (current_view_) {
2493 current_view_->message(_("Unknown function."));
2494 current_view_->restartCaret();
2500 if (func.action() == LFUN_SELF_INSERT) {
2501 if (encoded_last_key != 0) {
2502 docstring const arg(1, encoded_last_key);
2503 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2504 FuncRequest::KEYBOARD));
2505 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2508 processFuncRequest(func);
2512 void GuiApplication::processFuncRequest(FuncRequest const & func)
2514 lyx::dispatch(func);
2518 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2520 addToFuncRequestQueue(func);
2521 processFuncRequestQueueAsync();
2525 void GuiApplication::processFuncRequestQueue()
2527 while (!d->func_request_queue_.empty()) {
2528 // take the item from the stack _before_ processing the
2529 // request in order to avoid race conditions from nested
2530 // or parallel requests (see #10406)
2531 FuncRequest const fr(d->func_request_queue_.front());
2532 d->func_request_queue_.pop();
2533 processFuncRequest(fr);
2538 void GuiApplication::processFuncRequestQueueAsync()
2540 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2544 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2546 d->func_request_queue_.push(func);
2550 void GuiApplication::resetGui()
2552 // Set the language defined by the user.
2556 if (!readUIFile(toqstr(lyxrc.ui_file)))
2557 // Gives some error box here.
2560 if (d->global_menubar_)
2561 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2563 QHash<int, GuiView *>::iterator it;
2564 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2567 gv->setLayoutDirection(layoutDirection());
2571 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2575 bool GuiApplication::rtlContext() const
2577 if (current_view_ && current_view_->currentBufferView()) {
2578 BufferView const * bv = current_view_->currentBufferView();
2579 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2581 return layoutDirection() == Qt::RightToLeft;
2585 void GuiApplication::createView(int view_id)
2587 createView(QString(), true, view_id);
2591 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2594 // release the keyboard which might have been grabbed by the global
2595 // menubar on Mac to catch shortcuts even without any GuiView.
2596 if (d->global_menubar_)
2597 d->global_menubar_->releaseKeyboard();
2601 while (d->views_.find(id) != d->views_.end())
2604 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2605 GuiView * view = new GuiView(id);
2606 // `view' is the new current_view_. Tell coverity that is is not 0.
2607 LATTEST(current_view_);
2609 d->views_[id] = view;
2613 view->activateWindow();
2616 if (!geometry_arg.isEmpty()) {
2617 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2621 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2622 QRegularExpressionMatch match = re.match(geometry_arg);
2623 w = match.captured(1).toInt();
2624 h = match.captured(2).toInt();
2625 x = match.captured(3).toInt();
2626 y = match.captured(4).toInt();
2627 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2628 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2630 // Set initial geometry such that we can get the frame size.
2631 view->setGeometry(x, y, w, h);
2632 int framewidth = view->geometry().x() - view->x();
2633 int titleheight = view->geometry().y() - view->y();
2634 // Negative displacements must be interpreted as distances
2635 // from the right or bottom screen borders.
2636 if (sx == '-' || sy == '-') {
2637 QRect rec = QGuiApplication::primaryScreen()->geometry();
2639 x += rec.width() - w - framewidth;
2641 y += rec.height() - h - titleheight;
2642 view->setGeometry(x, y, w, h);
2644 // Make sure that the left and top frame borders are visible.
2645 if (view->x() < 0 || view->y() < 0) {
2650 view->setGeometry(x, y, w, h);
2658 bool GuiApplication::unhide(Buffer * buf)
2662 currentView()->setBuffer(buf, false);
2667 QPixmap GuiApplication::getScaledPixmap(QString imagedir, QString name) const
2670 // Consider device/pixel ratio (HiDPI)
2672 dpr = currentView()->pixelRatio();
2673 // We render SVG directly for HiDPI scalability
2674 QPixmap pm = getPixmap(imagedir, name, "svgz,png");
2675 FileName fname = imageLibFileSearch(imagedir, name, "svgz,png");
2676 QString fpath = toqstr(fname.absFileName());
2677 if (!fpath.isEmpty() && !fpath.endsWith(".png")) {
2678 QSvgRenderer svgRenderer(fpath);
2679 if (svgRenderer.isValid()) {
2680 pm = QPixmap(pm.size() * dpr);
2681 pm.fill(Qt::transparent);
2682 QPainter painter(&pm);
2683 svgRenderer.render(&painter);
2684 pm.setDevicePixelRatio(dpr);
2691 Clipboard & GuiApplication::clipboard()
2693 return d->clipboard_;
2697 Selection & GuiApplication::selection()
2699 return d->selection_;
2703 FontLoader & GuiApplication::fontLoader()
2705 return d->font_loader_;
2709 Toolbars const & GuiApplication::toolbars() const
2711 return d->toolbars_;
2715 Toolbars & GuiApplication::toolbars()
2717 return d->toolbars_;
2721 Menus const & GuiApplication::menus() const
2727 Menus & GuiApplication::menus()
2733 bool GuiApplication::needsBackingStore() const
2735 /* Qt on macOS and Wayland does not respect the
2736 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2737 * store at each update. Therefore, we use our own backing store
2738 * in these two cases. It is also possible to force the use of the
2739 * backing store for cases like x11 with transparent WM themes.
2741 return platformName() == "cocoa" || platformName().contains("wayland");
2745 QList<int> GuiApplication::viewIds() const
2747 return d->views_.keys();
2751 ColorCache & GuiApplication::colorCache()
2753 return d->color_cache_;
2757 int GuiApplication::exec()
2759 // asynchronously handle batch commands. This event will be in
2760 // the event queue in front of other asynchronous events. Hence,
2761 // we can assume in the latter that the gui is setup already.
2762 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2764 return QApplication::exec();
2768 void GuiApplication::exit(int status)
2770 QApplication::exit(status);
2774 void GuiApplication::setGuiLanguage()
2778 // install translation file for Qt built-in dialogs
2779 QString const language_name = QString("qt_") + theLocale.name();
2780 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2781 // Short-named translator can be loaded from a long name, but not the
2782 // opposite. Therefore, long name should be used without truncation.
2783 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2784 if (!d->qt_trans_.load(language_name,
2785 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2786 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2788 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2790 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2793 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2797 switch (theLocale.language()) {
2798 case QLocale::Arabic :
2799 case QLocale::Hebrew :
2800 case QLocale::Persian :
2801 case QLocale::Urdu :
2802 setLayoutDirection(Qt::RightToLeft);
2805 setLayoutDirection(Qt::LeftToRight);
2810 void GuiApplication::execBatchCommands()
2815 if (!readUIFile(toqstr(lyxrc.ui_file)))
2816 // Gives some error box here.
2820 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2821 # if QT_VERSION < 0x060000
2822 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2824 // Create the global default menubar which is shown for the dialogs
2825 // and if no GuiView is visible.
2826 // This must be done after the session was recovered to know the "last files".
2827 d->global_menubar_ = new QMenuBar(0);
2828 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2831 lyx::execBatchCommands();
2835 QAbstractItemModel * GuiApplication::languageModel()
2837 if (d->language_model_)
2838 return d->language_model_;
2840 QStandardItemModel * lang_model = new QStandardItemModel(this);
2841 lang_model->insertColumns(0, 3);
2842 QIcon speller(guiApp ? guiApp->getScaledPixmap("images/", "dialog-show_spellchecker")
2843 : getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2844 QIcon saurus(guiApp ? guiApp->getScaledPixmap("images/", "thesaurus-entry")
2845 : getPixmap("images/", "thesaurus-entry", "svgz,png"));
2846 Languages::const_iterator it = lyx::languages.begin();
2847 Languages::const_iterator end = lyx::languages.end();
2848 for (; it != end; ++it) {
2849 int current_row = lang_model->rowCount();
2850 lang_model->insertRows(current_row, 1);
2851 QModelIndex pl_item = lang_model->index(current_row, 0);
2852 QModelIndex sp_item = lang_model->index(current_row, 1);
2853 QModelIndex th_item = lang_model->index(current_row, 2);
2854 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2855 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2856 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2857 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2858 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2859 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2860 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2861 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2862 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2863 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2865 d->language_model_ = new QSortFilterProxyModel(this);
2866 d->language_model_->setSourceModel(lang_model);
2867 d->language_model_->setSortLocaleAware(true);
2868 return d->language_model_;
2872 void GuiApplication::restoreGuiSession()
2874 if (!lyxrc.load_session)
2877 Session & session = theSession();
2878 LastOpenedSection::LastOpened const & lastopened =
2879 session.lastOpened().getfiles();
2881 validateCurrentView();
2883 FileName active_file;
2884 // do not add to the lastfile list since these files are restored from
2885 // last session, and should be already there (regular files), or should
2886 // not be added at all (help files).
2887 for (auto const & last : lastopened) {
2888 FileName const & file_name = last.file_name;
2889 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2890 && current_view_->documentBufferView() != nullptr)) {
2891 string const & fname = file_name.absFileName();
2892 createView(support::checksum(fname));
2894 current_view_->loadDocument(file_name, false);
2897 active_file = file_name;
2900 // Restore last active buffer
2901 Buffer * buffer = theBufferList().getBuffer(active_file);
2902 if (buffer && current_view_)
2903 current_view_->setBuffer(buffer);
2905 // clear this list to save a few bytes of RAM
2906 session.lastOpened().clear();
2910 QString const GuiApplication::romanFontName()
2913 font.setStyleHint(QFont::Serif);
2914 font.setFamily("serif");
2916 return QFontInfo(font).family();
2920 QString const GuiApplication::sansFontName()
2923 font.setStyleHint(QFont::SansSerif);
2924 font.setFamily("sans");
2926 return QFontInfo(font).family();
2930 QString const GuiApplication::typewriterFontName()
2932 return QFontInfo(typewriterSystemFont()).family();
2937 // We cannot use QFont::fixedPitch() because it doesn't
2938 // return the fact but only if it is requested.
2939 static bool isFixedPitch(const QFont & font) {
2940 const QFontInfo fi(font);
2941 return fi.fixedPitch();
2946 QFont const GuiApplication::typewriterSystemFont()
2948 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2949 if (!isFixedPitch(font)) {
2950 // try to enforce a real monospaced font
2951 font.setStyleHint(QFont::Monospace);
2952 if (!isFixedPitch(font)) {
2953 font.setStyleHint(QFont::TypeWriter);
2954 if (!isFixedPitch(font)) font.setFamily("courier");
2958 // On a Mac the result is too small and it's not practical to
2959 // rely on Qtconfig utility to change the system settings of Qt.
2960 font.setPointSize(12);
2966 void GuiApplication::handleRegularEvents()
2968 ForkedCallsController::handleCompletedProcesses();
2972 bool GuiApplication::event(QEvent * e)
2975 case QEvent::FileOpen: {
2976 // Open a file; this happens only on Mac OS X for now.
2978 // We do this asynchronously because on startup the batch
2979 // commands are not executed here yet and the gui is not ready
2981 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2982 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2983 processFuncRequestAsync(fr);
2987 case QEvent::ApplicationPaletteChange: {
2988 // runtime switch from/to dark mode
2990 return QApplication::event(e);
2993 return QApplication::event(e);
2998 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3001 return QApplication::notify(receiver, event);
3003 catch (ExceptionMessage const & e) {
3005 case ErrorException:
3007 setQuitOnLastWindowClosed(false);
3009 Alert::error(e.title_, e.details_);
3011 // Properly crash in debug mode in order to get a useful backtrace.
3014 // In release mode, try to exit gracefully.
3016 // FIXME: GCC 7 thinks we can fall through here. Can we?
3018 case BufferException: {
3019 if (!current_view_ || !current_view_->documentBufferView())
3021 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3022 docstring details = e.details_ + '\n';
3023 details += buf->emergencyWrite();
3024 theBufferList().release(buf);
3025 details += "\n" + _("The current document was closed.");
3026 Alert::error(e.title_, details);
3029 case WarningException:
3030 Alert::warning(e.title_, e.details_);
3034 catch (exception const & e) {
3035 docstring s = _("LyX has caught an exception, it will now "
3036 "attempt to save all unsaved documents and exit."
3038 s += from_ascii(e.what());
3039 Alert::error(_("Software exception Detected"), s);
3043 docstring s = _("LyX has caught some really weird exception, it will "
3044 "now attempt to save all unsaved documents and exit.");
3045 Alert::error(_("Software exception Detected"), s);
3052 bool GuiApplication::isInDarkMode()
3054 return colorCache().isDarkMode();
3058 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3060 QColor const & qcol = d->color_cache_.get(col);
3061 if (!qcol.isValid()) {
3067 rgbcol.r = qcol.red();
3068 rgbcol.g = qcol.green();
3069 rgbcol.b = qcol.blue();
3074 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3076 QColor const qcol(lcolor.getX11HexName(col).c_str());
3077 if (!qcol.isValid()) {
3083 rgbcol.r = qcol.red();
3084 rgbcol.g = qcol.green();
3085 rgbcol.b = qcol.blue();
3090 string const GuiApplication::hexName(ColorCode col)
3092 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3096 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3098 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3099 d->socket_notifiers_[fd] = sn;
3100 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3104 void GuiApplication::socketDataReceived(int fd)
3106 d->socket_notifiers_[fd]->func_();
3110 void GuiApplication::unregisterSocketCallback(int fd)
3112 d->socket_notifiers_.take(fd)->setEnabled(false);
3116 void GuiApplication::commitData(QSessionManager & sm)
3118 /** The implementation is required to avoid an application exit
3119 ** when session state save is triggered by session manager.
3120 ** The default implementation sends a close event to all
3121 ** visible top level widgets when session management allows
3123 ** We are changing that to check the state of each buffer in all
3124 ** views and ask the users what to do if buffers are dirty.
3125 ** Furthermore, we save the session state.
3126 ** We do NOT close the views here since the user still can cancel
3127 ** the logout process (see #9277); also, this would hide LyX from
3128 ** an OSes own session handling (application restoration).
3130 #ifdef QT_NO_SESSIONMANAGER
3132 #warning Qt is compiled without session manager
3134 #pragma message("warning: Qt is compiled without session manager")
3138 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3146 void GuiApplication::unregisterView(GuiView * gv)
3148 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3149 d->views_.remove(gv->id());
3150 if (current_view_ == gv)
3151 current_view_ = nullptr;
3156 bool GuiApplication::closeAllViews()
3158 if (d->views_.empty())
3161 // When a view/window was closed before without quitting LyX, there
3162 // are already entries in the lastOpened list.
3163 theSession().lastOpened().clear();
3165 QList<GuiView *> const views = d->views_.values();
3166 for (GuiView * view : views) {
3167 if (!view->closeScheduled())
3176 bool GuiApplication::prepareAllViewsForLogout()
3178 if (d->views_.empty())
3181 QList<GuiView *> const views = d->views_.values();
3182 for (GuiView * view : views) {
3183 if (!view->prepareAllBuffersForLogout())
3191 GuiView & GuiApplication::view(int id) const
3193 LAPPERR(d->views_.contains(id));
3194 return *d->views_.value(id);
3198 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3200 QList<GuiView *> const views = d->views_.values();
3201 for (GuiView * view : views)
3202 view->hideDialog(name, inset);
3206 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3208 Buffer const * buf = nullptr;
3209 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3210 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3211 if (Buffer const * ptr = (*it)->updateInset(inset))
3218 bool GuiApplication::searchMenu(FuncRequest const & func,
3219 docstring_list & names) const
3221 BufferView * bv = nullptr;
3223 bv = current_view_->currentBufferView();
3224 return d->menus_.searchMenu(func, names, bv);
3228 bool GuiApplication::hasBufferView() const
3230 return (current_view_ && current_view_->currentBufferView());
3234 // Ensure that a file is read only once (prevents include loops)
3235 static QStringList uifiles;
3236 // store which ui files define Toolbars
3237 static QStringList toolbar_uifiles;
3240 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3251 LexerKeyword uitags[] = {
3252 { "format", ui_format },
3253 { "include", ui_include },
3254 { "menuset", ui_menuset },
3255 { "toolbars", ui_toolbars },
3256 { "toolbarset", ui_toolbarset }
3260 lex.setFile(ui_path);
3262 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3266 if (lyxerr.debugging(Debug::PARSER))
3267 lex.printTable(lyxerr);
3270 // format before introduction of format tag
3271 unsigned int format = 0;
3272 while (lex.isOK()) {
3273 int const status = lex.lex();
3275 // we have to do this check here, outside the switch,
3276 // because otherwise we would start reading include files,
3277 // e.g., if the first tag we hit was an include tag.
3278 if (status == ui_format)
3280 format = lex.getInteger();
3284 // this will trigger unless the first tag we hit is a format
3285 // tag, with the right format.
3286 if (format != LFUN_FORMAT)
3287 return FormatMismatch;
3290 case Lexer::LEX_FEOF:
3295 QString const file = toqstr(lex.getString());
3296 bool const success = readUIFile(file, true);
3298 LYXERR0("Failed to read included file: " << fromqstr(file));
3305 d->menus_.read(lex);
3309 d->toolbars_.readToolbars(lex);
3313 d->toolbars_.readToolbarSettings(lex);
3314 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3318 if (!rtrim(lex.getString()).empty())
3319 lex.printError("LyX::ReadUIFile: "
3320 "Unknown menu tag: `$$Token'");
3322 LYXERR0("Error with status: " << status);
3328 return (error ? ReadError : ReadOK);
3332 bool GuiApplication::readUIFile(QString const & name, bool include)
3334 LYXERR(Debug::INIT, "About to read " << name << "...");
3338 ui_path = libFileSearch("ui", name, "inc");
3339 if (ui_path.empty())
3340 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3342 ui_path = libFileSearch("ui", name, "ui");
3345 if (ui_path.empty()) {
3346 static const QString defaultUIFile = "default";
3347 LYXERR(Debug::INIT, "Could not find " << name);
3349 Alert::warning(_("Could not find UI definition file"),
3350 bformat(_("Error while reading the included file\n%1$s\n"
3351 "Please check your installation."), qstring_to_ucs4(name)));
3354 if (name == defaultUIFile) {
3355 LYXERR(Debug::INIT, "Could not find default UI file!!");
3356 Alert::warning(_("Could not find default UI file"),
3357 _("LyX could not find the default UI file!\n"
3358 "Please check your installation."));
3361 Alert::warning(_("Could not find UI definition file"),
3362 bformat(_("Error while reading the configuration file\n%1$s\n"
3363 "Falling back to default.\n"
3364 "Please look under Tools>Preferences>User Interface and\n"
3365 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3366 return readUIFile(defaultUIFile, false);
3369 QString const uifile = toqstr(ui_path.absFileName());
3370 if (uifiles.contains(uifile)) {
3372 // We are reading again the top uifile so reset the safeguard:
3375 d->toolbars_.reset();
3377 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3378 << "Is this an include loop?");
3382 uifiles.push_back(uifile);
3384 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3386 ReturnValues retval = readUIFile(ui_path);
3388 if (retval == FormatMismatch) {
3389 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3390 TempFile tmp("convertXXXXXX.ui");
3391 FileName const tempfile = tmp.name();
3392 bool const success = prefs2prefs(ui_path, tempfile, true);
3394 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3395 " to format " << LFUN_FORMAT << ".");
3397 retval = readUIFile(tempfile);
3401 if (retval != ReadOK) {
3402 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3410 settings.beginGroup("ui_files");
3411 bool touched = false;
3412 for (int i = 0; i != uifiles.size(); ++i) {
3413 QFileInfo fi(uifiles[i]);
3414 QDateTime const date_value = fi.lastModified();
3415 QString const name_key = QString::number(i);
3416 // if an ui file which defines Toolbars has changed,
3417 // we have to reset the settings
3418 if (toolbar_uifiles.contains(uifiles[i])
3419 && (!settings.contains(name_key)
3420 || settings.value(name_key).toString() != uifiles[i]
3421 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3423 settings.setValue(name_key, uifiles[i]);
3424 settings.setValue(name_key + "/date", date_value);
3427 settings.endGroup();
3429 settings.remove("views");
3435 void GuiApplication::onLastWindowClosed()
3437 if (d->global_menubar_)
3438 d->global_menubar_->grabKeyboard();
3442 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3444 std::string name = "unknown";
3446 case Qt::ApplicationSuspended:
3447 name = "ApplicationSuspended";
3449 case Qt::ApplicationHidden:
3450 name = "ApplicationHidden";
3452 case Qt::ApplicationInactive:
3453 name = "ApplicationInactive";
3455 case Qt::ApplicationActive:
3456 name = "ApplicationActive";
3457 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3458 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3459 if (d->views_.empty() && d->last_state_ == state) {
3460 LYXERR(Debug::GUI, "Open new window...");
3465 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3466 d->last_state_ = state;
3470 void GuiApplication::startLongOperation() {
3471 d->key_checker_.start();
3475 bool GuiApplication::longOperationCancelled() {
3476 return d->key_checker_.pressed();
3480 void GuiApplication::stopLongOperation() {
3481 d->key_checker_.stop();
3485 bool GuiApplication::longOperationStarted() {
3486 return d->key_checker_.started();
3490 ////////////////////////////////////////////////////////////////////////
3492 // X11 specific stuff goes here...
3494 #if defined(QPA_XCB)
3495 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3496 void * message, QINTPTR *)
3498 if (!current_view_ || eventType != "xcb_generic_event_t")
3501 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3503 switch (ev->response_type) {
3504 case XCB_SELECTION_REQUEST: {
3505 xcb_selection_request_event_t * srev =
3506 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3507 if (srev->selection != XCB_ATOM_PRIMARY)
3509 LYXERR(Debug::SELECTION, "X requested selection.");
3510 BufferView * bv = current_view_->currentBufferView();
3512 docstring const sel = bv->requestSelection();
3514 d->selection_.put(sel);
3515 #ifdef HAVE_QT5_X11_EXTRAS
3516 // Refresh the selection request timestamp.
3517 // We have to do this by ourselves as Qt seems
3518 // not doing that, maybe because of our
3519 // "persistent selection" implementation
3520 // (see comments in GuiSelection.cpp).
3521 // It is expected that every X11 event is
3522 // 32 bytes long, even if not all 32 bytes are
3524 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3525 struct alignas(32) padded_event
3526 : xcb_selection_notify_event_t {};
3527 padded_event nev = {};
3528 nev.response_type = XCB_SELECTION_NOTIFY;
3529 nev.requestor = srev->requestor;
3530 nev.selection = srev->selection;
3531 nev.target = srev->target;
3532 nev.property = XCB_NONE;
3533 nev.time = XCB_CURRENT_TIME;
3534 xcb_connection_t * con = QX11Info::connection();
3535 xcb_send_event(con, 0, srev->requestor,
3536 XCB_EVENT_MASK_NO_EVENT,
3537 reinterpret_cast<char const *>(&nev));
3545 case XCB_SELECTION_CLEAR: {
3546 xcb_selection_clear_event_t * scev =
3547 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3548 if (scev->selection != XCB_ATOM_PRIMARY)
3550 LYXERR(Debug::SELECTION, "Lost selection.");
3551 BufferView * bv = current_view_->currentBufferView();
3553 bv->clearSelection();
3561 } // namespace frontend
3564 void hideDialogs(std::string const & name, Inset * inset)
3567 frontend::guiApp->hideDialogs(name, inset);
3571 ////////////////////////////////////////////////////////////////////
3575 ////////////////////////////////////////////////////////////////////
3577 frontend::FontLoader & theFontLoader()
3579 LAPPERR(frontend::guiApp);
3580 return frontend::guiApp->fontLoader();
3584 frontend::FontMetrics const & theFontMetrics(Font const & f)
3586 return theFontMetrics(f.fontInfo());
3590 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3592 LAPPERR(frontend::guiApp);
3593 return frontend::guiApp->fontLoader().metrics(f);
3597 ////////////////////////////////////////////////////////////////////
3601 ////////////////////////////////////////////////////////////////////
3603 frontend::Clipboard & theClipboard()
3605 LAPPERR(frontend::guiApp);
3606 return frontend::guiApp->clipboard();
3610 frontend::Selection & theSelection()
3612 LAPPERR(frontend::guiApp);
3613 return frontend::guiApp->selection();
3619 #include "moc_GuiApplication.cpp"