2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
23 #include "qt_helpers.h"
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
37 #include "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/environment.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/ForkedCalls.h"
70 #include "support/gettext.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/lyxalgo.h" // sorted
74 #include "support/textutils.h"
75 #include "support/Messages.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/TempFile.h"
81 #include "support/AppleScript.h"
82 #include "support/AppleSupport.h"
83 #include "support/linkback/LinkBackProxy.h"
93 #include <QFileOpenEvent>
95 #include <QFontDatabase>
98 #include <QImageReader>
101 #include <QLibraryInfo>
108 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
109 #include <QRandomGenerator>
112 #include <QSessionManager>
114 #include <QSocketNotifier>
115 #include <QSortFilterProxyModel>
116 #include <QStandardItemModel>
117 #include <QSvgRenderer>
119 #include <QTranslator>
120 #include <QThreadPool>
125 #ifdef HAVE_QT5_X11_EXTRAS
126 #include <QtX11Extras/QX11Info>
130 #if (QT_VERSION >= 0x050400)
131 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
132 #if (QT_VERSION >= 0x060000)
133 #if (QT_VERSION >= 0x060500)
134 #include <QtGui/QWindowsMimeConverter>
135 #define QWINDOWSMIME QWindowsMimeConverter
136 #define QVARIANTTYPE QMetaType
138 #include <QtGui/private/qguiapplication_p.h>
139 #include <QtGui/private/qwindowsmime_p.h>
140 #include <QtGui/qpa/qplatformintegration.h>
141 #define QWINDOWSMIME QWindowsMime
142 #define QVARIANTTYPE QMetaType
143 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
144 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
148 #define QWINDOWSMIME QWinMime
149 #define QVARIANTTYPE QVariant::Type
158 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
159 #include <QMacPasteboardMime>
167 using namespace lyx::support;
172 frontend::Application * createApplication(int & argc, char * argv[])
174 #if !defined(QPA_XCB)
175 // prune -geometry argument(s) by shifting
176 // the following ones 2 places down.
177 for (int i = 0 ; i < argc ; ++i) {
178 if (strcmp(argv[i], "-geometry") == 0) {
179 int const remove = (i+1) < argc ? 2 : 1;
181 for (int j = i; j < argc; ++j)
182 argv[j] = argv[j + remove];
188 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
189 // On Windows, allow bringing the LyX window to top
190 AllowSetForegroundWindow(ASFW_ANY);
194 #if defined(Q_OS_MAC)
195 int const cursor_time_on = NSTextInsertionPointBlinkPeriodOn();
196 int const cursor_time_off = NSTextInsertionPointBlinkPeriodOff();
197 if (cursor_time_on > 0 && cursor_time_off > 0) {
198 QApplication::setCursorFlashTime(cursor_time_on + cursor_time_off);
199 } else if (cursor_time_on <= 0 && cursor_time_off > 0) {
200 // Off is set and On is undefined of zero
201 QApplication::setCursorFlashTime(0);
202 } else if (cursor_time_off <= 0 && cursor_time_on > 0) {
203 // On is set and Off is undefined of zero
204 QApplication::setCursorFlashTime(0);
208 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
209 // macOS does it by itself.
210 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
211 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
212 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
213 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
214 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
215 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
218 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
219 // HighDPI scale factor policy must be set before QGuiApplication is created
220 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
221 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
225 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
226 // I'd rather do that in the constructor, but I do not think that
227 // the palette is accessible there.
228 guiApp->colorCache().setPalette(guiApp->palette());
237 if (lyxrc.gui_language == "auto") {
238 theLocale = QLocale::system();
239 code = fromqstr(theLocale.name());
241 Language const * l = languages.getLanguage(lyxrc.gui_language);
242 code = l ? l->code() : "C";
243 theLocale = QLocale(toqstr(code));
245 // Qt tries to outsmart us and transforms en_US to C.
246 Messages::guiLanguage((code == "C") ? "en_US" : code);
247 QLocale::setDefault(theLocale);
248 setlocale(LC_NUMERIC, "C");
255 /// Return the list of loadable formats.
256 vector<string> loadableImageFormats()
260 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
262 LYXERR(Debug::GRAPHICS,
263 "\nThe image loader can load the following directly:\n");
265 if (qt_formats.empty())
266 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
268 bool jpeg_found = false;
269 bool jpg_found = false;
270 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
272 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
274 string ext = ascii_lowercase((const char *) *it);
282 else if (ext == "jpg") {
287 else if (lyxrc.use_converter_cache &&
288 (ext == "svg" || ext == "svgz") &&
289 theConverters().isReachable("svg", "png"))
290 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
291 // the SVG as in the output. However we require that the converter
292 // cache is enabled since this is expensive. We also require that
293 // an explicit svg->png converter is defined, since the default
294 // converter could produce bad quality as well. This assumes that
295 // png can always be loaded.
304 ////////////////////////////////////////////////////////////////////////
306 // Icon loading support code
308 ////////////////////////////////////////////////////////////////////////
318 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
320 return lhs.key < rhs.key;
326 CompareKey(QString const & name) : name_(name) {}
327 bool operator()(ImgMap const & other) const { return other.key == name_; }
333 // this must be sorted alphabetically
334 // Upper case comes before lower case
335 // Please don't change the formatting, this list is parsed by
336 // development/tools/generate_symbols_images.py.
337 ImgMap sorted_img_map[] = {
338 { "Arrownot", "arrownot2"},
339 { "Arrowvert", "arrowvert2"},
340 { "Bowtie", "bowtie2" },
342 { "Bumpeq", "bumpeq2" },
343 { "CIRCLE", "circle3" },
345 { "CheckedBox", "checkedbox2" },
346 { "Circle", "circle2" },
347 { "Colonapprox", "colonapprox2" },
348 { "Coloneq", "coloneq2" },
349 { "Coloneqq", "coloneqq2" },
350 { "Colonsim", "colonsim2" },
352 { "DOWNarrow", "downarrow3" },
353 { "Delta", "delta2" },
354 { "Diamond", "diamond2" },
355 { "Doteq", "doteq2" },
356 { "Downarrow", "downarrow2" },
357 { "Eqcolon", "eqcolon2" },
358 { "Eqqcolon", "eqqcolon2" },
359 { "Gamma", "gamma2" },
361 { "LEFTCIRCLE", "leftcircle3" },
362 { "LEFTarrow", "leftarrow3" },
363 { "LEFTcircle", "leftcircle4" },
365 { "Lambda", "lambda2" },
367 { "Leftarrow", "leftarrow2" },
368 { "Leftcircle", "leftcircle2" },
369 { "Leftrightarrow", "leftrightarrow2" },
370 { "Longarrownot", "longarrownot2"},
371 { "Longleftarrow", "longleftarrow2" },
372 { "Longleftrightarrow", "longleftrightarrow2" },
373 { "Longmapsfrom", "longmapsfrom2"},
374 { "Longmapsto", "longmapsto2"},
375 { "Longrightarrow", "longrightarrow2" },
376 { "Mapsfrom", "mapsfrom2"},
377 { "Mapsfromchar", "mapsfromchar2"},
378 { "Mapsto", "mapsto2"},
379 { "Mapstochar", "mapstochar2"},
380 { "Omega", "omega2" },
385 { "RIGHTCIRCLE", "rightcircle3" },
386 { "RIGHTarrow", "rightarrow3" },
387 { "RIGHTcircle", "rightcircle4" },
389 { "Rightarrow", "rightarrow2" },
390 { "Rightcircle", "rightcircle2" },
391 { "Sigma", "sigma2" },
392 { "Square", "square2" },
393 { "Subset", "subset2" },
394 { "Supset", "supset2" },
395 { "Theta", "theta2" },
396 { "Thorn", "thorn2" },
397 { "UParrow", "uparrow3" },
398 { "Uparrow", "uparrow2" },
399 { "Updownarrow", "updownarrow2" },
400 { "Upsilon", "upsilon2" },
401 { "Vdash", "vdash3" },
406 { "lVert", "vert2" },
408 { "nLeftarrow", "nleftarrow2" },
409 { "nLeftrightarrow", "nleftrightarrow2" },
410 { "nRightarrow", "nrightarrow2" },
411 { "nVDash", "nvdash3" },
412 { "nVdash", "nvdash4" },
413 { "nvDash", "nvdash2" },
414 { "rVert", "vert2" },
416 { "textrm \\AA", "textrm_AA"},
417 { "textrm \\O", "textrm_O"},
418 { "vDash", "vdash2" },
419 { "varDelta", "vardelta2" },
420 { "varGamma", "vargamma2" },
421 { "varLambda", "varlambda2" },
422 { "varOmega", "varomega2" },
423 { "varPhi", "varphi2" },
424 { "varPi", "varpi2" },
425 { "varPsi", "varpsi2" },
426 { "varSigma", "varsigma2" },
427 { "varTheta", "vartheta2" },
428 { "varUpsilon", "varupsilon2" },
429 { "varXi", "varxi2" }
433 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
435 // This list specifies which system's theme icon is related to which lyx
436 // command. It was based on:
437 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
438 // this must be sorted alphabetically
439 // Upper case comes before lower case
440 ImgMap sorted_theme_icon_map[] = {
441 { "bookmark-goto 0", "go-jump" },
442 { "buffer-new", "document-new" },
443 { "buffer-write", "document-save" },
444 { "buffer-write-as", "document-save-as" },
445 { "buffer-zoom-in", "zoom-in" },
446 { "buffer-zoom-out", "zoom-out" },
447 { "copy", "edit-copy" },
448 { "cut", "edit-cut" },
449 { "depth-decrement", "format-indent-less" },
450 { "depth-increment", "format-indent-more" },
451 { "dialog-show spellchecker", "tools-check-spelling" },
452 { "dialog-show-new-inset graphics", "insert-image" },
453 { "dialog-toggle findreplaceadv", "edit-find-replace" },
454 { "file-open", "document-open" },
455 { "font-bold", "format-text-bold" },
456 { "font-ital", "format-text-italic" },
457 { "font-strikeout", "format-text-strikethrough" },
458 { "font-underline", "format-text-underline" },
459 { "lyx-quit", "application-exit" },
460 { "paste", "edit-paste" },
461 { "redo", "edit-redo" },
462 { "undo", "edit-undo" },
463 { "window-close", "window-close" },
464 { "window-new", "window-new" }
467 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
470 QString findImg(QString const & name)
472 ImgMap const * const begin = sorted_img_map;
473 ImgMap const * const end = begin + nr_sorted_img_map;
474 LATTEST(sorted(begin, end));
476 ImgMap const * const it = find_if(begin, end, CompareKey(name));
480 img_name = it->value;
483 img_name.replace('_', "underscore");
484 img_name.replace(' ', '_');
486 // This way we can have "math-delim { }" on the toolbar.
487 img_name.replace('(', "lparen");
488 img_name.replace(')', "rparen");
489 img_name.replace('[', "lbracket");
490 img_name.replace(']', "rbracket");
491 img_name.replace('{', "lbrace");
492 img_name.replace('}', "rbrace");
493 img_name.replace('|', "bars");
494 img_name.replace(',', "thinspace");
495 img_name.replace(':', "mediumspace");
496 img_name.replace(';', "thickspace");
497 img_name.replace('!', "negthinspace");
500 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
501 << "Looking for math icon called \"" << img_name << '"');
508 QString themeIconName(QString const & action)
510 ImgMap const * const begin = sorted_theme_icon_map;
511 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
512 LASSERT(sorted(begin, end), /**/);
514 ImgMap const * const it = find_if(begin, end, CompareKey(action));
524 /* Get aliases for icon name. This allows to avoid duplication of
525 * icons when new versions of functions are introduced for the
526 * toolbar. A good example is the introduction of layout-toggle in
528 * The file is parsed by Lexer. Each line is of the form
529 * <original substring> <replacement substring>
531 * The return value is another icon file name that can be queried.
533 // FIXME: consider using regular expressions.
534 QString getAlias(QString name) {
535 static bool has_aliases = false;
536 static vector <pair<QString,QString>> aliases;
537 // Initialize aliases list (once).
539 FileName alfile = libFileSearch("images", "icon.aliases");
540 if (alfile.exists()) {
547 aliases.push_back({toqstr(from), toqstr(to)});
552 // check for the following aliases
553 for (auto const & alias : aliases) {
554 if (name.contains(alias.first))
555 name.replace(alias.first, alias.second);
563 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
568 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
570 if (!f.argument().empty()) {
571 // if there are arguments, first search an icon which name is the full thing
572 QString name = lfunname + ' ' + toqstr(f.argument());
573 name.replace(' ', '_');
574 name.replace(';', '_');
575 name.replace('\\', "backslash");
577 QString alias = getAlias(name);
581 // then special default icon for some lfuns
582 switch (f.action()) {
583 case LFUN_MATH_INSERT:
584 names << "math/" + findImg(toqstr(f.argument()).mid(1));
586 case LFUN_MATH_DELIM:
587 case LFUN_MATH_BIGDELIM:
588 names << "math/" + findImg(toqstr(f.argument()));
591 names << "commands/" + toqstr(f.argument());
593 case LFUN_COMMAND_ALTERNATIVES: {
594 // use the first of the alternative commands
596 docstring dummy = split(f.argument(), firstcom, ';');
597 QString name1 = toqstr(firstcom);
598 name1.replace(' ', '_');
599 name1.replace(';', '_');
600 name1.replace('\\', "backslash");
609 // next thing to try is function name alone
611 QString alias = getAlias(lfunname);
612 if (alias != lfunname)
615 // and finally maybe the unknown icon
619 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
620 // The folders where icons are searched for
621 QStringList imagedirs;
622 imagedirs << "images/ipa/" << "images/";
623 // This is used to search for rtl version of icons which have the +rtl suffix.
624 QStringList suffixes;
627 suffixes << QString();
629 for (QString const & imagedir : imagedirs)
630 for (QString const & name : names)
631 for (QString const & suffix : suffixes) {
632 QString id = imagedir;
633 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
634 if (fname.exists()) {
635 docstring const fpath = fname.absoluteFilePath();
636 res.filepath = toqstr(fname.absFileName());
637 // these icons are subject to inversion in dark mode
638 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
639 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
640 res.swap = rtl && suffix.isEmpty();
645 LYXERR(Debug::GUI, "Cannot find icon for command \""
646 << lyxaction.getActionName(f.action())
647 << '(' << to_utf8(f.argument()) << ")\"");
653 QPixmap prepareForDarkMode(QPixmap pixmap)
655 QPalette palette = QPalette();
656 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
657 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
659 // guess whether we are in dark mode
660 if (text_color.black() > bg_color.black())
661 // not in dark mode, do nothing
664 // create a layer with black text turned to QPalette::WindowText
665 QPixmap black_overlay(pixmap.size());
666 black_overlay.fill(text_color);
667 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
669 // create a layer with blue text turned to lighter blue
670 QPixmap blue_overlay(pixmap.size());
671 QColor math_blue(0, 0, 255);
672 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
673 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
675 // create a layer with ("latex") red text turned to lighter red
676 QPixmap red_overlay(pixmap.size());
677 QColor math_red(128, 0, 0);
678 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
679 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
681 // put layers on top of existing pixmap
682 QPainter painter(&pixmap);
683 painter.drawPixmap(pixmap.rect(), black_overlay);
684 painter.drawPixmap(pixmap.rect(), blue_overlay);
685 painter.drawPixmap(pixmap.rect(), red_overlay);
691 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
693 QString imagedir = path;
694 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
695 QString fpath = toqstr(fname.absFileName());
696 QPixmap pixmap = QPixmap();
698 if (pixmap.load(fpath)) {
699 if (fpath.contains("math") || fpath.contains("ipa")
700 || fpath.contains("bullets"))
701 return prepareForDarkMode(pixmap);
705 bool const list = ext.contains(",");
706 LYXERR(Debug::GUI, "Cannot load pixmap \""
707 << path << "/" << name << "." << (list ? "{" : "") << ext
708 << (list ? "}" : "") << "\".");
714 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
716 if (lyxrc.use_system_theme_icons) {
717 // use the icons from system theme that are available
718 QString action = toqstr(lyxaction.getActionName(f.action()));
719 if (!f.argument().empty())
720 action += " " + toqstr(f.argument());
721 QString const theme_icon = themeIconName(action);
722 if (QIcon::hasThemeIcon(theme_icon)) {
723 QIcon const thmicn = QIcon::fromTheme(theme_icon);
724 if (!thmicn.isNull())
729 IconInfo icondata = iconInfo(f, unknown, rtl);
730 if (icondata.filepath.isEmpty())
733 //LYXERR(Debug::GUI, "Found icon: " << icon);
734 QPixmap pixmap = QPixmap();
735 if (!pixmap.load(icondata.filepath)) {
736 LYXERR0("Cannot load icon " << icondata.filepath << ".");
741 pixmap = prepareForDarkMode(pixmap);
744 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
746 return QIcon(pixmap);
750 ////////////////////////////////////////////////////////////////////////
752 // LyX server support code.
754 ////////////////////////////////////////////////////////////////////////
756 class SocketNotifier : public QSocketNotifier
759 /// connect a connection notification from the LyXServerSocket
760 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
761 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
765 /// The callback function
766 Application::SocketCallback func_;
770 class GuiTranslator : public QTranslator
773 GuiTranslator(QObject * parent = nullptr)
774 : QTranslator(parent)
777 QString translate(const char * /* context */,
778 const char *sourceText,
779 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
781 // Here we declare the strings that need to be translated from Qt own GUI
782 // This is needed to include these strings to po files
786 _("Restore Defaults");
789 // Already in po: "Cancel", "&Cancel"
790 _("Apply"); // Already in po: "&Apply"
791 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
794 docstring s = getGuiMessages().getIfFound(sourceText);
795 // This test should eventually be removed when translations are updated
797 LYXERR(Debug::LOCALE, "Missing translation for `"
798 << string(sourceText) << "'");
804 ////////////////////////////////////////////////////////////////////////
806 // Mac specific stuff goes here...
808 ////////////////////////////////////////////////////////////////////////
810 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
811 // QMacPasteboardMimeGraphics can only be compiled on Mac.
813 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
816 QMacPasteboardMimeGraphics()
817 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
820 QString convertorName() { return "Graphics"; }
822 QString flavorFor(QString const & mime)
824 LYXERR(Debug::ACTION, "flavorFor " << mime);
825 if (mime == pdfMimeType())
826 return QLatin1String("com.adobe.pdf");
830 QString mimeFor(QString flav)
832 LYXERR(Debug::ACTION, "mimeFor " << flav);
833 if (flav == QLatin1String("com.adobe.pdf"))
834 return pdfMimeType();
838 bool canConvert(QString const & mime, QString flav)
840 return mimeFor(flav) == mime;
843 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
847 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
851 QList<QByteArray> convertFromMime(QString const & /*mime*/,
852 QVariant data, QString /*flav*/)
854 QList<QByteArray> ret;
855 ret.append(data.toByteArray());
861 ///////////////////////////////////////////////////////////////
863 // You can find more platform specific stuff at the end of this file...
865 ///////////////////////////////////////////////////////////////
867 ////////////////////////////////////////////////////////////////////////
868 // Windows specific stuff goes here...
870 #if (QT_VERSION >= 0x050400)
871 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
872 // QWindowsMimeMetafile can only be compiled on Windows.
874 static FORMATETC cfFromMime(QString const & mimetype)
877 if (mimetype == emfMimeType()) {
878 formatetc.cfFormat = CF_ENHMETAFILE;
879 formatetc.tymed = TYMED_ENHMF;
880 } else if (mimetype == wmfMimeType()) {
881 formatetc.cfFormat = CF_METAFILEPICT;
882 formatetc.tymed = TYMED_MFPICT;
885 formatetc.dwAspect = DVASPECT_CONTENT;
886 formatetc.lindex = -1;
891 class QWindowsMimeMetafile : public QWINDOWSMIME {
893 QWindowsMimeMetafile() {}
895 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
896 QMimeData const * /*mimedata*/) const override
901 bool canConvertToMime(QString const & mimetype,
902 IDataObject * pDataObj) const override
904 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
906 FORMATETC formatetc = cfFromMime(mimetype);
907 return pDataObj->QueryGetData(&formatetc) == S_OK;
910 bool convertFromMime(FORMATETC const & /*formatetc*/,
911 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
916 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
917 QVARIANTTYPE /*preferredType*/) const override
920 if (!canConvertToMime(mimetype, pDataObj))
923 FORMATETC formatetc = cfFromMime(mimetype);
925 if (pDataObj->GetData(&formatetc, &s) != S_OK)
929 if (s.tymed == TYMED_ENHMF) {
930 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
931 data.resize(dataSize);
932 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
933 (LPBYTE)data.data());
934 } else if (s.tymed == TYMED_MFPICT) {
935 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
936 data.resize(dataSize);
937 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
938 (LPBYTE)data.data());
941 ReleaseStgMedium(&s);
947 QVector<FORMATETC> formatsForMime(QString const & mimetype,
948 QMimeData const * /*mimedata*/) const override
950 QVector<FORMATETC> formats;
951 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
952 formats += cfFromMime(mimetype);
956 QString mimeForFormat(FORMATETC const & formatetc) const override
958 switch (formatetc.cfFormat) {
960 return emfMimeType();
961 case CF_METAFILEPICT:
962 return wmfMimeType();
972 /// Allows to check whether ESC was pressed during a long operation
973 class KeyChecker : public QObject {
978 KeyChecker() : pressed_(false), started_(false) {}
981 QCoreApplication::instance()->installEventFilter(this);
986 QCoreApplication::instance()->removeEventFilter(this);
990 QCoreApplication::processEvents();
993 bool started() const {
996 bool eventFilter(QObject *obj, QEvent *event) override {
997 LYXERR(Debug::ACTION, "Event Type: " << event->type());
998 switch (event->type()) {
1001 case QEvent::Resize:
1002 case QEvent::UpdateRequest:
1003 case QEvent::CursorChange:
1004 case QEvent::ActionChanged:
1005 case QEvent::EnabledChange:
1006 case QEvent::SockAct:
1009 case QEvent::ToolTipChange:
1010 case QEvent::LayoutRequest:
1011 case QEvent::MetaCall:
1012 return QObject::eventFilter(obj, event);
1014 // FIXME Blocking all these events is a bad idea.
1015 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1016 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1024 ////////////////////////////////////////////////////////////////////////
1025 // GuiApplication::Private definition and implementation.
1026 ////////////////////////////////////////////////////////////////////////
1028 struct GuiApplication::Private
1030 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1031 global_menubar_(nullptr), last_state_(Qt::ApplicationInactive)
1033 #if (QT_VERSION >= 0x050400)
1034 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1035 /// WMF Mime handler for Windows clipboard.
1036 wmf_mime_ = new QWindowsMimeMetafile;
1037 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1038 win_app_ = dynamic_cast<QWindowsApplication *>
1039 (QGuiApplicationPrivate::platformIntegration());
1040 win_app_->registerMime(wmf_mime_);
1044 initKeySequences(&theTopLevelKeymap());
1047 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1048 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1051 win_app_->unregisterMime(wmf_mime_);
1056 void initKeySequences(KeyMap * kb)
1058 keyseq = KeySequence(kb, kb);
1059 cancel_meta_seq = KeySequence(kb, kb);
1063 QSortFilterProxyModel * language_model_;
1065 GuiClipboard clipboard_;
1067 GuiSelection selection_;
1069 FontLoader font_loader_;
1071 ColorCache color_cache_;
1072 /// the built-in Qt translation mechanism
1073 QTranslator qt_trans_;
1074 /// LyX gettext-based translation for Qt elements
1075 GuiTranslator gui_trans_;
1077 QHash<int, SocketNotifier *> socket_notifiers_;
1081 /// The global instance
1084 /// this timer is used for any regular events one wants to
1085 /// perform. at present it is used to check if forked processes
1087 QTimer general_timer_;
1089 /// delayed FuncRequests
1090 std::queue<FuncRequest> func_request_queue_;
1095 KeySequence cancel_meta_seq;
1097 KeyModifier meta_fake_bit;
1099 /// The result of last dispatch action
1100 DispatchResult dispatch_result_;
1102 /// Multiple views container.
1104 * Warning: This must not be a smart pointer as the destruction of the
1105 * object is handled by Qt when the view is closed
1106 * \sa Qt::WA_DeleteOnClose attribute.
1108 QHash<int, GuiView *> views_;
1110 /// Only used on mac.
1111 QMenuBar * global_menubar_;
1112 /// Holds previous application state on Mac
1113 Qt::ApplicationState last_state_;
1115 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1116 /// Linkback mime handler for MacOSX.
1117 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1120 #if (QT_VERSION >= 0x050400)
1121 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1122 /// WMF Mime handler for Windows clipboard.
1123 QWindowsMimeMetafile * wmf_mime_;
1124 #if (QT_VERSION >= 0x060000 && QT_VERSION < 0x060500)
1125 QWindowsApplication * win_app_;
1130 /// Allows to check whether ESC was pressed during a long operation
1131 KeyChecker key_checker_;
1135 GuiApplication * guiApp;
1137 GuiApplication::~GuiApplication()
1140 closeAllLinkBackLinks();
1146 GuiApplication::GuiApplication(int & argc, char ** argv)
1147 : QApplication(argc, argv), current_view_(nullptr),
1148 d(new GuiApplication::Private)
1150 QString app_name = "LyX";
1151 QCoreApplication::setOrganizationName(app_name);
1152 QCoreApplication::setOrganizationDomain("lyx.org");
1153 QCoreApplication::setApplicationName(lyx_package);
1154 #if QT_VERSION < 0x060000
1155 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1158 #if QT_VERSION >= 0x050700
1159 setDesktopFileName(lyx_package);
1162 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1163 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1165 qsrand(QDateTime::currentDateTime().toTime_t());
1168 // Install LyX translator for missing Qt translations
1169 installTranslator(&d->gui_trans_);
1170 // Install Qt native translator for GUI elements.
1171 installTranslator(&d->qt_trans_);
1174 // Enable reception of XCB events.
1175 installNativeEventFilter(this);
1178 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1179 // lyxrc setting for this in order to let the application stay resident.
1180 // But then we need some kind of dock icon, at least on Windows.
1182 if (lyxrc.quit_on_last_window_closed)
1183 setQuitOnLastWindowClosed(false);
1186 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1187 // seems to be the default case for applications like LyX.
1188 setQuitOnLastWindowClosed(false);
1191 appleCleanupEditMenu();
1192 appleCleanupViewMenu();
1193 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1194 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1197 #if defined(QPA_XCB)
1198 // doubleClickInterval() is 400 ms on X11 which is just too long.
1199 // On Windows and Mac OS X, the operating system's value is used.
1200 // On Microsoft Windows, calling this function sets the double
1201 // click interval for all applications. So we don't!
1202 QApplication::setDoubleClickInterval(300);
1205 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1207 // needs to be done before reading lyxrc
1209 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1213 // Initialize RC Fonts
1214 if (lyxrc.roman_font_name.empty())
1215 lyxrc.roman_font_name = fromqstr(romanFontName());
1217 if (lyxrc.sans_font_name.empty())
1218 lyxrc.sans_font_name = fromqstr(sansFontName());
1220 if (lyxrc.typewriter_font_name.empty())
1221 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1223 // Track change of keyboard
1224 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1226 d->general_timer_.setInterval(500);
1227 connect(&d->general_timer_, SIGNAL(timeout()),
1228 this, SLOT(handleRegularEvents()));
1229 d->general_timer_.start();
1231 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1232 // This is clearly not enough in a time where we use threads for
1233 // document preview and/or export. 20 should be OK.
1234 QThreadPool::globalInstance()->setMaxThreadCount(20);
1236 // make sure tooltips are formatted
1237 installEventFilter(new ToolTipFormatter(this));
1241 GuiApplication * theGuiApp()
1243 return dynamic_cast<GuiApplication *>(theApp());
1247 double GuiApplication::pixelRatio() const
1249 return qt_scale_factor * devicePixelRatio();
1253 void GuiApplication::clearSession()
1260 docstring Application::iconName(FuncRequest const & f, bool unknown)
1262 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1266 docstring Application::mathIcon(docstring const & c)
1268 return qstring_to_ucs4(findImg(toqstr(c)));
1272 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1276 BufferView * bv = nullptr;
1277 BufferView * doc_bv = nullptr;
1279 if (cmd.action() == LFUN_NOACTION) {
1280 status.message(from_utf8(N_("Nothing to do")));
1281 status.setEnabled(false);
1284 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1285 status.setUnknown(true);
1286 status.message(from_utf8(N_("Unknown action")));
1287 status.setEnabled(false);
1290 // Does the GuiApplication know something?
1291 else if (getStatus(cmd, status)) { }
1293 // If we do not have a GuiView, then other functions are disabled
1294 else if (!current_view_)
1295 status.setEnabled(false);
1297 // Does the GuiView know something?
1298 else if (current_view_->getStatus(cmd, status)) { }
1300 // In LyX/Mac, when a dialog is open, the menus of the
1301 // application can still be accessed without giving focus to
1302 // the main window. In this case, we want to disable the menu
1303 // entries that are buffer or view-related.
1304 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1306 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1307 status.setEnabled(false);
1310 // If we do not have a BufferView, then other functions are disabled
1311 else if (!(bv = current_view_->currentBufferView()))
1312 status.setEnabled(false);
1314 // Does the current BufferView know something?
1315 else if (bv->getStatus(cmd, status)) { }
1317 // Does the current Buffer know something?
1318 else if (bv->buffer().getStatus(cmd, status)) { }
1320 // If we do not have a document BufferView, different from the
1321 // current BufferView, then other functions are disabled
1322 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1323 status.setEnabled(false);
1325 // Does the document Buffer know something?
1326 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1329 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1330 status.message(from_utf8(N_("Command not handled")));
1331 status.setEnabled(false);
1334 // the default error message if we disable the command
1335 if (!status.enabled() && status.message().empty())
1336 status.message(from_utf8(N_("Command disabled")));
1342 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1344 // I would really like to avoid having this switch and rather try to
1345 // encode this in the function itself.
1346 // -- And I'd rather let an inset decide which LFUNs it is willing
1347 // to handle (Andre')
1349 switch (cmd.action()) {
1351 // This could be used for the no-GUI version. The GUI version is handled in
1352 // GuiView::getStatus(). See above.
1354 case LFUN_BUFFER_WRITE:
1355 case LFUN_BUFFER_WRITE_AS:
1356 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1357 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1358 enable = b && (b->isUnnamed() || !b->isClean());
1363 case LFUN_BOOKMARK_GOTO: {
1364 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1365 enable = theSession().bookmarks().isValid(num);
1369 case LFUN_BOOKMARK_CLEAR:
1370 enable = theSession().bookmarks().hasValid();
1373 // this one is difficult to get right. As a half-baked
1374 // solution, we consider only the first action of the sequence
1375 case LFUN_COMMAND_SEQUENCE: {
1376 // argument contains ';'-terminated commands
1377 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1378 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1379 func.setOrigin(cmd.origin());
1380 flag = getStatus(func);
1384 // we want to check if at least one of these is enabled
1385 case LFUN_COMMAND_ALTERNATIVES: {
1386 // argument contains ';'-terminated commands
1387 string arg = to_utf8(cmd.argument());
1388 while (!arg.empty()) {
1390 arg = split(arg, first, ';');
1391 FuncRequest func(lyxaction.lookupFunc(first));
1392 func.setOrigin(cmd.origin());
1393 flag = getStatus(func);
1394 // if this one is enabled, the whole thing is
1403 string name = to_utf8(cmd.argument());
1404 if (theTopLevelCmdDef().lock(name, func)) {
1405 func.setOrigin(cmd.origin());
1406 flag = getStatus(func);
1407 theTopLevelCmdDef().release(name);
1409 // catch recursion or unknown command
1410 // definition. all operations until the
1411 // recursion or unknown command definition
1412 // occurs are performed, so set the state to
1419 case LFUN_IF_RELATIVES: {
1420 string const lfun = to_utf8(cmd.argument());
1421 BufferView const * bv =
1422 current_view_ ? current_view_->currentBufferView() : nullptr;
1423 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1427 FuncRequest func(lyxaction.lookupFunc(lfun));
1428 func.setOrigin(cmd.origin());
1429 flag = getStatus(func);
1433 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1435 case LFUN_PREFERENCES_SAVE:
1436 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1437 // these are handled in our dispatch()
1440 case LFUN_DEBUG_LEVEL_SET: {
1441 string bad = Debug::badValue(to_utf8(cmd.argument()));
1442 enable = bad.empty();
1444 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1448 case LFUN_WINDOW_CLOSE:
1449 enable = !d->views_.empty();
1452 case LFUN_BUFFER_NEW:
1453 case LFUN_BUFFER_NEW_TEMPLATE:
1454 case LFUN_FILE_OPEN:
1455 case LFUN_LYXFILES_OPEN:
1456 case LFUN_HELP_OPEN:
1457 case LFUN_SCREEN_FONT_UPDATE:
1458 case LFUN_SET_COLOR:
1459 case LFUN_WINDOW_NEW:
1461 case LFUN_LYXRC_APPLY:
1462 case LFUN_COMMAND_PREFIX:
1464 case LFUN_META_PREFIX:
1465 case LFUN_RECONFIGURE:
1466 case LFUN_SERVER_GET_FILENAME:
1467 case LFUN_SERVER_NOTIFY:
1471 case LFUN_BUFFER_FORALL: {
1472 if (theBufferList().empty()) {
1473 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1474 flag.setEnabled(false);
1478 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1479 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1480 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1481 flag.setEnabled(false);
1486 case LFUN_DIALOG_SHOW: {
1487 string const name = cmd.getArg(0);
1488 return name == "aboutlyx"
1489 || name == "lyxfiles"
1491 || name == "texinfo"
1492 || name == "progress"
1493 || name == "compare";
1501 flag.setEnabled(false);
1505 /// make a post-dispatch status message
1506 static docstring makeDispatchMessage(docstring const & msg,
1507 FuncRequest const & cmd)
1509 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1510 || cmd.origin() == FuncRequest::TOOLBAR
1511 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1513 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1514 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1518 docstring dispatch_msg = msg;
1519 if (!dispatch_msg.empty())
1520 dispatch_msg += ' ';
1522 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1524 bool argsadded = false;
1526 if (!cmd.argument().empty()) {
1527 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1528 comname += ' ' + cmd.argument();
1532 docstring const shortcuts = theTopLevelKeymap().
1533 printBindings(cmd, KeySequence::ForGui);
1535 if (!shortcuts.empty())
1536 comname += ": " + shortcuts;
1537 else if (!argsadded && !cmd.argument().empty())
1538 comname += ' ' + cmd.argument();
1540 if (!comname.empty()) {
1541 comname = rtrim(comname);
1542 dispatch_msg += '(' + rtrim(comname) + ')';
1544 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1545 return dispatch_msg;
1549 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1553 Buffer * buffer = nullptr;
1554 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1555 //setCurrentView(cmd.view_origin); //does not work
1557 dr.setMessage(_("Wrong focus!"));
1558 d->dispatch_result_ = dr;
1559 return d->dispatch_result_;
1561 if (current_view_ && current_view_->currentBufferView()) {
1562 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1563 buffer = ¤t_view_->currentBufferView()->buffer();
1566 dr.screenUpdate(Update::FitCursor);
1568 // All the code is kept inside the undo group because
1569 // updateBuffer can create undo actions (see #11292)
1570 UndoGroupHelper ugh(buffer);
1572 if (dr.screenUpdate() & Update::ForceAll) {
1573 for (Buffer const * b : theBufferList())
1575 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1578 updateCurrentView(cmd, dr);
1581 d->dispatch_result_ = dr;
1582 return d->dispatch_result_;
1586 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1591 BufferView * bv = current_view_->currentBufferView();
1593 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1594 bv->cursor().clearBufferUpdate();
1595 bv->buffer().updateBuffer();
1597 // BufferView::update() updates the ViewMetricsInfo and
1598 // also initializes the position cache for all insets in
1599 // (at least partially) visible top-level paragraphs.
1600 // We will redraw the screen only if needed.
1601 bv->processUpdateFlags(dr.screenUpdate());
1603 // Do we have a selection?
1604 theSelection().haveSelection(bv->cursor().selection());
1607 current_view_->restartCaret();
1609 if (dr.needMessageUpdate()) {
1610 // Some messages may already be translated, so we cannot use _()
1611 current_view_->message(makeDispatchMessage(
1612 translateIfPossible(dr.message()), cmd));
1617 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1618 bool switchToBuffer)
1620 if (!theSession().bookmarks().isValid(idx))
1622 BookmarksSection::Bookmark const & bm =
1623 theSession().bookmarks().bookmark(idx);
1624 LASSERT(!bm.filename.empty(), return);
1625 string const file = bm.filename.absFileName();
1626 // if the file is not opened, open it.
1627 if (!theBufferList().exists(bm.filename)) {
1629 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1633 // open may fail, so we need to test it again
1634 if (!theBufferList().exists(bm.filename))
1637 // bm can be changed when saving
1638 BookmarksSection::Bookmark tmp = bm;
1640 // Special case idx == 0 used for back-from-back jump navigation
1642 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1644 // if the current buffer is not that one, switch to it.
1645 BufferView * doc_bv = current_view_ ?
1646 current_view_->documentBufferView() : nullptr;
1647 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1648 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1649 if (switchToBuffer) {
1650 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1653 doc_bv = current_view_->documentBufferView();
1658 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1659 if (!doc_bv || !doc_bv->moveToPosition(
1660 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1663 Cursor & cur = doc_bv->cursor();
1664 if (old && cur != *old)
1665 notifyCursorLeavesOrEnters(*old, cur);
1671 // Cursor jump succeeded!
1672 pit_type new_pit = cur.pit();
1673 pos_type new_pos = cur.pos();
1674 int new_id = cur.paragraph().id();
1676 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1677 // see http://www.lyx.org/trac/ticket/3092
1678 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1679 || bm.top_id != new_id) {
1680 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1681 new_pit, new_pos, new_id);
1685 // This function runs "configure" and then rereads lyx.defaults to
1686 // reconfigure the automatic settings.
1687 void GuiApplication::reconfigure(string const & option)
1689 // emit message signal.
1690 if (current_view_) {
1691 current_view_->message(_("Running configure..."));
1692 current_view_->setCursor(Qt::WaitCursor);
1695 // Run configure in user lyx directory
1696 string const lock_file = package().getConfigureLockName();
1697 int fd = fileLock(lock_file.c_str());
1698 int const ret = package().reconfigureUserLyXDir(option);
1699 // emit message signal.
1701 current_view_->message(_("Reloading configuration..."));
1702 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1703 // Re-read packages.lst
1704 LaTeXPackages::getAvailable();
1705 fileUnlock(fd, lock_file.c_str());
1708 current_view_->unsetCursor();
1711 Alert::information(_("System reconfiguration failed"),
1712 _("The system reconfiguration has failed.\n"
1713 "Default textclass is used but LyX may\n"
1714 "not be able to work properly.\n"
1715 "Please reconfigure again if needed."));
1717 Alert::information(_("System reconfigured"),
1718 _("The system has been reconfigured.\n"
1719 "You need to restart LyX to make use of any\n"
1720 "updated document class specifications."));
1723 void GuiApplication::validateCurrentView()
1725 if (!d->views_.empty() && !current_view_) {
1726 // currently at least one view exists but no view has the focus.
1727 // choose the last view to make it current.
1728 // a view without any open document is preferred.
1729 GuiView * candidate = nullptr;
1730 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1731 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1732 for (; it != end; ++it) {
1734 if (!candidate->documentBufferView())
1737 setCurrentView(candidate);
1741 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1743 string const argument = to_utf8(cmd.argument());
1744 FuncCode const action = cmd.action();
1746 LYXERR(Debug::ACTION, "cmd: " << cmd);
1748 // we have not done anything wrong yet.
1751 FuncStatus const flag = getStatus(cmd);
1752 if (!flag.enabled()) {
1753 // We cannot use this function here
1754 LYXERR(Debug::ACTION, "action "
1755 << lyxaction.getActionName(action)
1756 << " [" << action << "] is disabled at this location");
1757 dr.setMessage(flag.message());
1759 dr.dispatched(false);
1760 dr.screenUpdate(Update::None);
1761 dr.clearBufferUpdate();
1765 if (cmd.origin() == FuncRequest::LYXSERVER) {
1766 if (current_view_ && current_view_->currentBufferView())
1767 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1768 // we will also need to redraw the screen at the end
1769 dr.screenUpdate(Update::FitCursor);
1772 // Assumes that the action will be dispatched.
1773 dr.dispatched(true);
1775 switch (cmd.action()) {
1777 case LFUN_WINDOW_NEW:
1778 createView(toqstr(cmd.argument()));
1781 case LFUN_WINDOW_CLOSE:
1782 // FIXME: this is done also in GuiView::closeBuffer()!
1783 // update bookmark pit of the current buffer before window close
1784 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1785 gotoBookmark(i, false, false);
1786 // clear the last opened list, because
1787 // maybe this will end the session
1788 theSession().lastOpened().clear();
1789 // check for valid current_view_
1790 validateCurrentView();
1792 current_view_->closeScheduled();
1796 // quitting is triggered by the gui code
1797 // (leaving the event loop).
1799 current_view_->message(from_utf8(N_("Exiting.")));
1800 if (closeAllViews())
1804 case LFUN_SCREEN_FONT_UPDATE: {
1805 // handle the screen font changes.
1806 /* FIXME: this only updates the current document, whereas all
1807 * documents should see their metrics updated.
1809 d->font_loader_.update();
1810 dr.screenUpdate(Update::Force | Update::FitCursor);
1814 case LFUN_BUFFER_NEW:
1815 validateCurrentView();
1817 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1818 createView(QString(), false); // keep hidden
1819 current_view_->newDocument(to_utf8(cmd.argument()));
1820 current_view_->show();
1821 current_view_->activateWindow();
1823 current_view_->newDocument(to_utf8(cmd.argument()));
1827 case LFUN_BUFFER_NEW_TEMPLATE: {
1828 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1829 string const temp = cmd.getArg(1);
1830 validateCurrentView();
1832 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1834 current_view_->newDocument(file, temp, true);
1835 if (!current_view_->documentBufferView())
1836 current_view_->close();
1838 current_view_->newDocument(file, temp, true);
1843 case LFUN_FILE_OPEN: {
1844 // FIXME: normally the code below is not needed, since getStatus makes sure that
1845 // current_view_ is not null.
1846 validateCurrentView();
1847 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1848 string const fname = trim(to_utf8(cmd.argument()), "\"");
1849 bool const is_open = FileName::isAbsolute(fname)
1850 && theBufferList().getBuffer(FileName(fname));
1852 || (!lyxrc.open_buffers_in_tabs
1853 && current_view_->documentBufferView() != nullptr
1855 // We want the ui session to be saved per document and not per
1856 // window number. The filename crc is a good enough identifier.
1857 createView(support::checksum(fname));
1858 current_view_->openDocuments(fname, cmd.origin());
1859 if (!current_view_->documentBufferView())
1860 current_view_->close();
1861 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1862 current_view_->raise();
1863 current_view_->activateWindow();
1864 current_view_->showNormal();
1867 current_view_->openDocuments(fname, cmd.origin());
1868 if (cmd.origin() == FuncRequest::LYXSERVER) {
1869 current_view_->raise();
1870 current_view_->activateWindow();
1871 current_view_->showNormal();
1877 case LFUN_HELP_OPEN: {
1878 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1879 if (current_view_ == nullptr)
1881 string const arg = to_utf8(cmd.argument());
1883 current_view_->message(_("Missing argument"));
1886 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1888 fname = i18nLibFileSearch("examples", arg, "lyx");
1890 if (fname.empty()) {
1891 lyxerr << "LyX: unable to find documentation file `"
1892 << arg << "'. Bad installation?" << endl;
1895 current_view_->message(bformat(_("Opening help file %1$s..."),
1896 makeDisplayPath(fname.absFileName())));
1897 Buffer * buf = current_view_->loadDocument(fname, false);
1899 buf->setReadonly(!current_view_->develMode());
1903 case LFUN_LYXFILES_OPEN: {
1904 string arg = to_utf8(cmd.argument());
1908 if (arg != "templates" && arg != "examples") {
1909 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1912 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1916 case LFUN_SET_COLOR: {
1917 string const lyx_name = cmd.getArg(0);
1918 string x11_name = cmd.getArg(1);
1919 string x11_darkname = cmd.getArg(2);
1920 if (lyx_name.empty() || x11_name.empty()) {
1922 current_view_->message(
1923 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1928 // FIXME: The graphics cache no longer has a changeDisplay method.
1929 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1930 bool const graphicsbg_changed =
1931 lyx_name == graphicsbg && x11_name != graphicsbg;
1932 if (graphicsbg_changed)
1933 graphics::GCache::get().changeDisplay(true);
1936 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1937 x11_darkname = x11_name;
1940 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1942 current_view_->message(
1943 bformat(_("Set-color \"%1$s\" failed "
1944 "- color is undefined or "
1945 "may not be redefined"),
1946 from_utf8(lyx_name)));
1949 // Make sure we don't keep old colors in cache.
1950 d->color_cache_.clear();
1951 // Update the current view
1952 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1956 case LFUN_LYXRC_APPLY: {
1957 // reset active key sequences, since the bindings
1958 // are updated (bug 6064)
1960 LyXRC const lyxrc_orig = lyxrc;
1962 istringstream ss(to_utf8(cmd.argument()));
1963 bool const success = lyxrc.read(ss);
1966 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1967 << "Unable to read lyxrc data"
1972 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1974 // If the request comes from the minibuffer, then we can't reset
1975 // the GUI, since that would destroy the minibuffer itself and
1976 // cause a crash, since we are currently in one of the methods of
1977 // GuiCommandBuffer. See bug #8540.
1978 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1981 // FIXME Unfortunately, that leaves a bug here, since we cannot
1982 // reset the GUI in this case. If the changes to lyxrc affected the
1983 // UI, then, nothing would happen. This seems fairly unlikely, but
1984 // it definitely is a bug.
1986 dr.forceBufferUpdate();
1990 case LFUN_COMMAND_PREFIX:
1991 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1996 d->meta_fake_bit = NoModifier;
1997 GuiView * gv = currentView();
1998 if (gv && gv->currentBufferView())
1999 // cancel any selection
2000 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2001 dr.setMessage(from_ascii(N_("Cancel")));
2004 case LFUN_META_PREFIX:
2005 d->meta_fake_bit = AltModifier;
2006 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2009 // --- Menus -----------------------------------------------
2010 case LFUN_RECONFIGURE:
2011 // argument is any additional parameter to the configure.py command
2012 reconfigure(to_utf8(cmd.argument()));
2015 // --- lyxserver commands ----------------------------
2016 case LFUN_SERVER_GET_FILENAME: {
2017 if (current_view_ && current_view_->documentBufferView()) {
2018 docstring const fname = from_utf8(
2019 current_view_->documentBufferView()->buffer().absFileName());
2020 dr.setMessage(fname);
2021 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2023 dr.setMessage(docstring());
2024 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2029 case LFUN_SERVER_NOTIFY: {
2030 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2031 dr.setMessage(dispatch_buffer);
2032 theServer().notifyClient(to_utf8(dispatch_buffer));
2036 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2037 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2043 string rest = split(argument, countstr, ' ');
2044 int const count = convert<int>(countstr);
2045 // an arbitrary number to limit number of iterations
2046 int const max_iter = 10000;
2047 if (count > max_iter) {
2048 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2051 for (int i = 0; i < count; ++i) {
2052 FuncRequest lfun = lyxaction.lookupFunc(rest);
2053 lfun.allowAsync(false);
2060 case LFUN_COMMAND_SEQUENCE: {
2061 // argument contains ';'-terminated commands
2062 string arg = argument;
2063 // FIXME: this LFUN should also work without any view.
2064 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2065 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2066 // This handles undo groups automagically
2067 UndoGroupHelper ugh(buffer);
2068 while (!arg.empty()) {
2070 arg = split(arg, first, ';');
2071 FuncRequest func(lyxaction.lookupFunc(first));
2072 func.allowAsync(false);
2073 func.setOrigin(cmd.origin());
2079 case LFUN_BUFFER_FORALL: {
2080 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2081 funcToRun.allowAsync(false);
2083 map<Buffer *, GuiView *> views_lVisible;
2084 map<GuiView *, Buffer *> activeBuffers;
2086 QList<GuiView *> allViews = d->views_.values();
2088 // this for does not modify any buffer. It just collects info on local
2089 // visibility of buffers and on which buffer is active in each view.
2090 Buffer * const last = theBufferList().last();
2091 for(GuiView * view : allViews) {
2092 // all of the buffers might be locally hidden. That is, there is no
2094 if (!view || !view->currentBufferView())
2095 activeBuffers[view] = nullptr;
2097 activeBuffers[view] = &view->currentBufferView()->buffer();
2099 // find out if each is locally visible or locally hidden.
2100 // we don't use a for loop as the buffer list cycles.
2101 Buffer * b = theBufferList().first();
2103 bool const locallyVisible = view && view->workArea(*b);
2104 if (locallyVisible) {
2105 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2106 // only need to overwrite/add if we don't already know a buffer is globally
2107 // visible or we do know but we would prefer to dispatch LFUN from the
2108 // current view because of cursor position issues.
2109 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2110 views_lVisible[b] = view;
2114 b = theBufferList().next(b);
2118 GuiView * const homeView = currentView();
2119 Buffer * b = theBufferList().first();
2120 Buffer * nextBuf = nullptr;
2121 int numProcessed = 0;
2124 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2126 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2128 // first change to a view where b is locally visible, preferably current_view_.
2129 GuiView * const vLv = views_lVisible[b];
2131 lyx::dispatch(funcToRun);
2139 // put things back to how they were (if possible).
2140 for (GuiView * view : allViews) {
2141 Buffer * originalBuf = activeBuffers[view];
2142 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2143 if (theBufferList().isLoaded(originalBuf))
2144 view->setBuffer(originalBuf);
2146 homeView->setFocus();
2148 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2152 case LFUN_COMMAND_ALTERNATIVES: {
2153 // argument contains ';'-terminated commands
2154 string arg = argument;
2155 while (!arg.empty()) {
2157 arg = split(arg, first, ';');
2158 FuncRequest func(lyxaction.lookupFunc(first));
2159 func.setOrigin(cmd.origin());
2160 FuncStatus const stat = getStatus(func);
2161 if (stat.enabled()) {
2171 if (theTopLevelCmdDef().lock(argument, func)) {
2172 func.setOrigin(cmd.origin());
2174 theTopLevelCmdDef().release(argument);
2176 if (func.action() == LFUN_UNKNOWN_ACTION) {
2177 // unknown command definition
2178 lyxerr << "Warning: unknown command definition `"
2182 // recursion detected
2183 lyxerr << "Warning: Recursion in the command definition `"
2184 << argument << "' detected"
2191 case LFUN_IF_RELATIVES: {
2192 string const lfun = to_utf8(cmd.argument());
2193 FuncRequest func(lyxaction.lookupFunc(lfun));
2194 func.setOrigin(cmd.origin());
2195 FuncStatus const stat = getStatus(func);
2196 if (stat.enabled()) {
2203 case LFUN_PREFERENCES_SAVE:
2204 lyxrc.write(support::makeAbsPath("preferences",
2205 package().user_support().absFileName()), false);
2208 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2209 string const fname = addName(addPath(package().user_support().absFileName(),
2210 "templates/"), "defaults.lyx");
2211 Buffer defaults(fname);
2213 istringstream ss(argument);
2218 // We need to make sure that, after we recreat the DocumentClass,
2219 // which we do in readHeader, we apply it to the document itself.
2220 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2221 int const unknown_tokens = defaults.readHeader(lex);
2222 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2223 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2224 cap::switchBetweenClasses(olddc, newdc, theinset);
2226 if (unknown_tokens != 0) {
2227 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2228 << unknown_tokens << " unknown token"
2229 << (unknown_tokens == 1 ? "" : "s")
2233 if (defaults.writeFile(FileName(defaults.absFileName())))
2234 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2235 makeDisplayPath(fname)));
2238 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2243 case LFUN_BOOKMARK_GOTO:
2244 // go to bookmark, open unopened file and switch to buffer if necessary
2245 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2246 dr.screenUpdate(Update::Force | Update::FitCursor);
2249 case LFUN_BOOKMARK_CLEAR:
2250 theSession().bookmarks().clear();
2251 dr.screenUpdate(Update::Force);
2254 case LFUN_DEBUG_LEVEL_SET:
2255 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2258 case LFUN_DIALOG_SHOW: {
2259 string const name = cmd.getArg(0);
2260 // Workaround: on Mac OS the application
2261 // is not terminated when closing the last view.
2262 // With the following dialogs which should still
2263 // be usable, create a new one to be able
2264 // to dispatch LFUN_DIALOG_SHOW to this view.
2265 if (name == "aboutlyx" || name == "compare"
2266 || name == "lyxfiles" || name == "prefs"
2267 || name == "progress" || name == "texinfo")
2269 if (current_view_ == nullptr)
2275 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2278 current_view_->dispatch(cmd, dr);
2282 if (current_view_ && current_view_->isFullScreen()) {
2283 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2284 current_view_->menuBar()->hide();
2287 if (cmd.origin() == FuncRequest::LYXSERVER)
2288 updateCurrentView(cmd, dr);
2292 docstring GuiApplication::viewStatusMessage()
2294 // When meta-fake key is pressed, show the key sequence so far + "M-".
2295 if (d->meta_fake_bit != NoModifier)
2296 return d->keyseq.print(KeySequence::ForGui) + "M-";
2298 // Else, when a non-complete key sequence is pressed,
2299 // show the available options.
2300 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2301 return d->keyseq.printOptions(true);
2307 string GuiApplication::inputLanguageCode() const
2309 QLocale loc = inputMethod()->locale();
2310 //LYXERR0("input lang = " << fromqstr(loc.name()));
2311 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2315 void GuiApplication::onLocaleChanged()
2317 //LYXERR0("Change language to " << inputLanguage()->lang());
2318 if (currentView() && currentView()->currentBufferView())
2319 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2323 void GuiApplication::onPaletteChanged()
2325 colorCache().setPalette(palette());
2329 void GuiApplication::handleKeyFunc(FuncCode action)
2333 if (d->keyseq.length())
2335 GuiView * gv = currentView();
2336 LASSERT(gv && gv->currentBufferView(), return);
2337 BufferView * bv = gv->currentBufferView();
2338 bv->getIntl().getTransManager().deadkey(
2339 c, get_accent(action).accent, bv->cursor().innerText(),
2341 // Need to clear, in case the minibuffer calls these
2344 // copied verbatim from do_accent_char
2345 bv->cursor().resetAnchor();
2349 //Keep this in sync with GuiApplication::processKeySym below
2350 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2351 KeyModifier state) const
2353 // Do nothing if we have nothing
2354 if (!keysym.isOK() || keysym.isModifier())
2356 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2358 FuncRequest func = seq.addkey(keysym, state);
2359 // When not cancel or meta-fake, do the normal lookup.
2360 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2362 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2364 // Maybe user can only reach the key via holding down shift.
2365 // Let's see. But only if shift is the only modifier
2366 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2367 // If addkey looked up a command and did not find further commands then
2368 // seq has been reset at this point
2369 func = seq.addkey(keysym, NoModifier);
2371 LYXERR(Debug::KEY, " Key (queried) [action="
2372 << lyxaction.getActionName(func.action()) << "]["
2373 << seq.print(KeySequence::Portable) << ']');
2374 return func.action() != LFUN_UNKNOWN_ACTION;
2378 //Keep this in sync with GuiApplication::queryKeySym above
2379 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2381 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2383 // Do nothing if we have nothing (JMarc)
2384 if (!keysym.isOK() || keysym.isModifier()) {
2386 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2388 current_view_->restartCaret();
2392 char_type encoded_last_key = keysym.getUCSEncoded();
2394 // Do a one-deep top-level lookup for
2395 // cancel and meta-fake keys. RVDK_PATCH_5
2396 d->cancel_meta_seq.reset();
2398 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2399 LYXERR(Debug::KEY, "action first set to ["
2400 << lyxaction.getActionName(func.action()) << ']');
2402 // When not cancel or meta-fake, do the normal lookup.
2403 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2404 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2405 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2406 // remove Caps Lock and Mod2 as a modifiers
2407 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2408 LYXERR(Debug::KEY, "action now set to ["
2409 << lyxaction.getActionName(func.action()) << ']');
2412 // Don't remove this unless you know what you are doing.
2413 d->meta_fake_bit = NoModifier;
2415 // Can this happen now ?
2416 if (func.action() == LFUN_NOACTION)
2417 func = FuncRequest(LFUN_COMMAND_PREFIX);
2419 LYXERR(Debug::KEY, " Key [action="
2420 << lyxaction.getActionName(func.action()) << "]["
2421 << d->keyseq.print(KeySequence::Portable) << ']');
2423 // already here we know if it any point in going further
2424 // why not return already here if action == -1 and
2425 // num_bytes == 0? (Lgb)
2427 if (d->keyseq.length() > 1 && current_view_)
2428 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2431 // Maybe user can only reach the key via holding down shift.
2432 // Let's see. But only if shift is the only modifier
2433 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2434 LYXERR(Debug::KEY, "Trying without shift");
2435 // If addkey looked up a command and did not find further commands then
2436 // seq has been reset at this point
2437 func = d->keyseq.addkey(keysym, NoModifier);
2438 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2441 if (func.action() == LFUN_UNKNOWN_ACTION) {
2442 // We didn't match any of the key sequences.
2443 // See if it's normal insertable text not already
2444 // covered by a binding
2445 if (keysym.isText() && d->keyseq.length() == 1) {
2446 // Non-printable characters (such as ASCII control characters)
2447 // must not be inserted (#5704)
2448 if (!isPrintable(encoded_last_key)) {
2449 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2451 current_view_->restartCaret();
2454 // The following modifier check is not needed on Mac.
2455 // The keysym is either not text or it is different
2456 // from the non-modifier keysym. See #9875 for the
2457 // broken alt-modifier effect of having this code active.
2458 #if !defined(Q_OS_MAC)
2459 // If a non-Shift Modifier is used we have a non-bound key sequence
2460 // (such as Alt+j = j). This should be omitted (#5575).
2461 // On Windows, AltModifier and ControlModifier are both
2462 // set when AltGr is pressed. Therefore, in order to not
2463 // break AltGr-bound symbols (see #5575 for details),
2464 // unbound Ctrl+Alt key sequences are allowed.
2465 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2466 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2467 && !(state & AltModifier && state & ControlModifier)
2471 if (current_view_) {
2472 current_view_->message(_("Unknown function."));
2473 current_view_->restartCaret();
2478 // Since all checks above were passed, we now really have text that
2479 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2480 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2482 LYXERR(Debug::KEY, "isText() is true, inserting.");
2483 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2485 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2486 if (current_view_) {
2487 current_view_->message(_("Unknown function."));
2488 current_view_->restartCaret();
2494 if (func.action() == LFUN_SELF_INSERT) {
2495 if (encoded_last_key != 0) {
2496 docstring const arg(1, encoded_last_key);
2497 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2498 FuncRequest::KEYBOARD));
2499 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2502 processFuncRequest(func);
2506 void GuiApplication::processFuncRequest(FuncRequest const & func)
2508 lyx::dispatch(func);
2512 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2514 addToFuncRequestQueue(func);
2515 processFuncRequestQueueAsync();
2519 void GuiApplication::processFuncRequestQueue()
2521 while (!d->func_request_queue_.empty()) {
2522 // take the item from the stack _before_ processing the
2523 // request in order to avoid race conditions from nested
2524 // or parallel requests (see #10406)
2525 FuncRequest const fr(d->func_request_queue_.front());
2526 d->func_request_queue_.pop();
2527 processFuncRequest(fr);
2532 void GuiApplication::processFuncRequestQueueAsync()
2534 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2538 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2540 d->func_request_queue_.push(func);
2544 void GuiApplication::resetGui()
2546 // Set the language defined by the user.
2550 if (!readUIFile(toqstr(lyxrc.ui_file)))
2551 // Gives some error box here.
2554 if (d->global_menubar_)
2555 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2557 QHash<int, GuiView *>::iterator it;
2558 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2561 gv->setLayoutDirection(layoutDirection());
2565 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2569 bool GuiApplication::rtlContext() const
2571 if (current_view_ && current_view_->currentBufferView()) {
2572 BufferView const * bv = current_view_->currentBufferView();
2573 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2575 return layoutDirection() == Qt::RightToLeft;
2579 void GuiApplication::createView(int view_id)
2581 createView(QString(), true, view_id);
2585 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2588 // release the keyboard which might have been grabbed by the global
2589 // menubar on Mac to catch shortcuts even without any GuiView.
2590 if (d->global_menubar_)
2591 d->global_menubar_->releaseKeyboard();
2595 while (d->views_.find(id) != d->views_.end())
2598 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2599 GuiView * view = new GuiView(id);
2600 // `view' is the new current_view_. Tell coverity that is is not 0.
2601 LATTEST(current_view_);
2603 d->views_[id] = view;
2607 view->activateWindow();
2610 if (!geometry_arg.isEmpty()) {
2611 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2615 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2616 QRegularExpressionMatch match = re.match(geometry_arg);
2617 w = match.captured(1).toInt();
2618 h = match.captured(2).toInt();
2619 x = match.captured(3).toInt();
2620 y = match.captured(4).toInt();
2621 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2622 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2624 // Set initial geometry such that we can get the frame size.
2625 view->setGeometry(x, y, w, h);
2626 int framewidth = view->geometry().x() - view->x();
2627 int titleheight = view->geometry().y() - view->y();
2628 // Negative displacements must be interpreted as distances
2629 // from the right or bottom screen borders.
2630 if (sx == '-' || sy == '-') {
2631 QRect rec = QGuiApplication::primaryScreen()->geometry();
2633 x += rec.width() - w - framewidth;
2635 y += rec.height() - h - titleheight;
2636 view->setGeometry(x, y, w, h);
2638 // Make sure that the left and top frame borders are visible.
2639 if (view->x() < 0 || view->y() < 0) {
2644 view->setGeometry(x, y, w, h);
2652 bool GuiApplication::unhide(Buffer * buf)
2656 currentView()->setBuffer(buf, false);
2661 QPixmap GuiApplication::getScaledPixmap(QString imagedir, QString name) const
2664 // Consider device/pixel ratio (HiDPI)
2666 dpr = currentView()->devicePixelRatio();
2667 // We render SVG directly for HiDPI scalability
2668 QPixmap pm = getPixmap(imagedir, name, "svgz,png");
2669 FileName fname = imageLibFileSearch(imagedir, name, "svgz,png");
2670 QString fpath = toqstr(fname.absFileName());
2671 if (!fpath.isEmpty() && !fpath.endsWith(".png")) {
2672 QSvgRenderer svgRenderer(fpath);
2673 if (svgRenderer.isValid()) {
2674 pm = QPixmap(pm.size() * dpr);
2675 pm.fill(Qt::transparent);
2676 QPainter painter(&pm);
2677 svgRenderer.render(&painter);
2678 pm.setDevicePixelRatio(dpr);
2685 Clipboard & GuiApplication::clipboard()
2687 return d->clipboard_;
2691 Selection & GuiApplication::selection()
2693 return d->selection_;
2697 FontLoader & GuiApplication::fontLoader()
2699 return d->font_loader_;
2703 Toolbars const & GuiApplication::toolbars() const
2705 return d->toolbars_;
2709 Toolbars & GuiApplication::toolbars()
2711 return d->toolbars_;
2715 Menus const & GuiApplication::menus() const
2721 Menus & GuiApplication::menus()
2727 bool GuiApplication::needsBackingStore() const
2729 /* Qt on macOS and Wayland does not respect the
2730 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2731 * store at each update. Therefore, we use our own backing store
2732 * in these two cases. It is also possible to force the use of the
2733 * backing store for cases like x11 with transparent WM themes.
2735 return platformName() == "cocoa" || platformName().contains("wayland");
2739 QList<int> GuiApplication::viewIds() const
2741 return d->views_.keys();
2745 ColorCache & GuiApplication::colorCache()
2747 return d->color_cache_;
2751 int GuiApplication::exec()
2753 // asynchronously handle batch commands. This event will be in
2754 // the event queue in front of other asynchronous events. Hence,
2755 // we can assume in the latter that the gui is setup already.
2756 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2758 return QApplication::exec();
2762 void GuiApplication::exit(int status)
2764 QApplication::exit(status);
2768 void GuiApplication::setGuiLanguage()
2772 // install translation file for Qt built-in dialogs
2773 QString const language_name = QString("qt_") + theLocale.name();
2774 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2775 // Short-named translator can be loaded from a long name, but not the
2776 // opposite. Therefore, long name should be used without truncation.
2777 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2778 if (!d->qt_trans_.load(language_name,
2779 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2780 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2782 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2784 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2787 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2791 switch (theLocale.language()) {
2792 case QLocale::Arabic :
2793 case QLocale::Hebrew :
2794 case QLocale::Persian :
2795 case QLocale::Urdu :
2796 setLayoutDirection(Qt::RightToLeft);
2799 setLayoutDirection(Qt::LeftToRight);
2804 void GuiApplication::execBatchCommands()
2809 if (!readUIFile(toqstr(lyxrc.ui_file)))
2810 // Gives some error box here.
2814 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2815 # if QT_VERSION < 0x060000
2816 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2818 // Create the global default menubar which is shown for the dialogs
2819 // and if no GuiView is visible.
2820 // This must be done after the session was recovered to know the "last files".
2821 d->global_menubar_ = new QMenuBar(0);
2822 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2825 lyx::execBatchCommands();
2829 QAbstractItemModel * GuiApplication::languageModel()
2831 if (d->language_model_)
2832 return d->language_model_;
2834 QStandardItemModel * lang_model = new QStandardItemModel(this);
2835 lang_model->insertColumns(0, 3);
2836 QIcon speller(guiApp ? guiApp->getScaledPixmap("images/", "dialog-show_spellchecker")
2837 : getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2838 QIcon saurus(guiApp ? guiApp->getScaledPixmap("images/", "thesaurus-entry")
2839 : getPixmap("images/", "thesaurus-entry", "svgz,png"));
2840 Languages::const_iterator it = lyx::languages.begin();
2841 Languages::const_iterator end = lyx::languages.end();
2842 for (; it != end; ++it) {
2843 int current_row = lang_model->rowCount();
2844 lang_model->insertRows(current_row, 1);
2845 QModelIndex pl_item = lang_model->index(current_row, 0);
2846 QModelIndex sp_item = lang_model->index(current_row, 1);
2847 QModelIndex th_item = lang_model->index(current_row, 2);
2848 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2849 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2850 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2851 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2852 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2853 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2854 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2855 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2856 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2857 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2859 d->language_model_ = new QSortFilterProxyModel(this);
2860 d->language_model_->setSourceModel(lang_model);
2861 d->language_model_->setSortLocaleAware(true);
2862 return d->language_model_;
2866 void GuiApplication::restoreGuiSession()
2868 if (!lyxrc.load_session)
2871 Session & session = theSession();
2872 LastOpenedSection::LastOpened const & lastopened =
2873 session.lastOpened().getfiles();
2875 validateCurrentView();
2877 FileName active_file;
2878 // do not add to the lastfile list since these files are restored from
2879 // last session, and should be already there (regular files), or should
2880 // not be added at all (help files).
2881 for (auto const & last : lastopened) {
2882 FileName const & file_name = last.file_name;
2883 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2884 && current_view_->documentBufferView() != nullptr)) {
2885 string const & fname = file_name.absFileName();
2886 createView(support::checksum(fname));
2888 current_view_->loadDocument(file_name, false);
2891 active_file = file_name;
2894 // Restore last active buffer
2895 Buffer * buffer = theBufferList().getBuffer(active_file);
2896 if (buffer && current_view_)
2897 current_view_->setBuffer(buffer);
2899 // clear this list to save a few bytes of RAM
2900 session.lastOpened().clear();
2904 QString const GuiApplication::romanFontName()
2907 font.setStyleHint(QFont::Serif);
2908 font.setFamily("serif");
2910 return QFontInfo(font).family();
2914 QString const GuiApplication::sansFontName()
2917 font.setStyleHint(QFont::SansSerif);
2918 font.setFamily("sans");
2920 return QFontInfo(font).family();
2924 QString const GuiApplication::typewriterFontName()
2926 return QFontInfo(typewriterSystemFont()).family();
2931 // We cannot use QFont::fixedPitch() because it doesn't
2932 // return the fact but only if it is requested.
2933 static bool isFixedPitch(const QFont & font) {
2934 const QFontInfo fi(font);
2935 return fi.fixedPitch();
2940 QFont const GuiApplication::typewriterSystemFont()
2942 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2943 if (!isFixedPitch(font)) {
2944 // try to enforce a real monospaced font
2945 font.setStyleHint(QFont::Monospace);
2946 if (!isFixedPitch(font)) {
2947 font.setStyleHint(QFont::TypeWriter);
2948 if (!isFixedPitch(font)) font.setFamily("courier");
2952 // On a Mac the result is too small and it's not practical to
2953 // rely on Qtconfig utility to change the system settings of Qt.
2954 font.setPointSize(12);
2960 void GuiApplication::handleRegularEvents()
2962 ForkedCallsController::handleCompletedProcesses();
2966 bool GuiApplication::event(QEvent * e)
2969 case QEvent::FileOpen: {
2970 // Open a file; this happens only on Mac OS X for now.
2972 // We do this asynchronously because on startup the batch
2973 // commands are not executed here yet and the gui is not ready
2975 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2976 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2977 processFuncRequestAsync(fr);
2981 case QEvent::ApplicationPaletteChange: {
2982 // runtime switch from/to dark mode
2984 return QApplication::event(e);
2987 return QApplication::event(e);
2992 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2995 return QApplication::notify(receiver, event);
2997 catch (ExceptionMessage const & e) {
2999 case ErrorException:
3001 setQuitOnLastWindowClosed(false);
3003 Alert::error(e.title_, e.details_);
3005 // Properly crash in debug mode in order to get a useful backtrace.
3008 // In release mode, try to exit gracefully.
3010 // FIXME: GCC 7 thinks we can fall through here. Can we?
3012 case BufferException: {
3013 if (!current_view_ || !current_view_->documentBufferView())
3015 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3016 docstring details = e.details_ + '\n';
3017 details += buf->emergencyWrite();
3018 theBufferList().release(buf);
3019 details += "\n" + _("The current document was closed.");
3020 Alert::error(e.title_, details);
3023 case WarningException:
3024 Alert::warning(e.title_, e.details_);
3028 catch (exception const & e) {
3029 docstring s = _("LyX has caught an exception, it will now "
3030 "attempt to save all unsaved documents and exit."
3032 s += from_ascii(e.what());
3033 Alert::error(_("Software exception Detected"), s);
3037 docstring s = _("LyX has caught some really weird exception, it will "
3038 "now attempt to save all unsaved documents and exit.");
3039 Alert::error(_("Software exception Detected"), s);
3046 bool GuiApplication::isInDarkMode()
3048 return colorCache().isDarkMode();
3052 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3054 QColor const & qcol = d->color_cache_.get(col);
3055 if (!qcol.isValid()) {
3061 rgbcol.r = qcol.red();
3062 rgbcol.g = qcol.green();
3063 rgbcol.b = qcol.blue();
3068 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3070 QColor const qcol(lcolor.getX11HexName(col).c_str());
3071 if (!qcol.isValid()) {
3077 rgbcol.r = qcol.red();
3078 rgbcol.g = qcol.green();
3079 rgbcol.b = qcol.blue();
3084 string const GuiApplication::hexName(ColorCode col)
3086 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3090 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3092 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3093 d->socket_notifiers_[fd] = sn;
3094 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3098 void GuiApplication::socketDataReceived(int fd)
3100 d->socket_notifiers_[fd]->func_();
3104 void GuiApplication::unregisterSocketCallback(int fd)
3106 d->socket_notifiers_.take(fd)->setEnabled(false);
3110 void GuiApplication::commitData(QSessionManager & sm)
3112 /** The implementation is required to avoid an application exit
3113 ** when session state save is triggered by session manager.
3114 ** The default implementation sends a close event to all
3115 ** visible top level widgets when session management allows
3117 ** We are changing that to check the state of each buffer in all
3118 ** views and ask the users what to do if buffers are dirty.
3119 ** Furthermore, we save the session state.
3120 ** We do NOT close the views here since the user still can cancel
3121 ** the logout process (see #9277); also, this would hide LyX from
3122 ** an OSes own session handling (application restoration).
3124 #ifdef QT_NO_SESSIONMANAGER
3126 #warning Qt is compiled without session manager
3128 #pragma message("warning: Qt is compiled without session manager")
3132 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3140 void GuiApplication::unregisterView(GuiView * gv)
3142 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3143 d->views_.remove(gv->id());
3144 if (current_view_ == gv)
3145 current_view_ = nullptr;
3150 bool GuiApplication::closeAllViews()
3152 if (d->views_.empty())
3155 // When a view/window was closed before without quitting LyX, there
3156 // are already entries in the lastOpened list.
3157 theSession().lastOpened().clear();
3159 QList<GuiView *> const views = d->views_.values();
3160 for (GuiView * view : views) {
3161 if (!view->closeScheduled())
3170 bool GuiApplication::prepareAllViewsForLogout()
3172 if (d->views_.empty())
3175 QList<GuiView *> const views = d->views_.values();
3176 for (GuiView * view : views) {
3177 if (!view->prepareAllBuffersForLogout())
3185 GuiView & GuiApplication::view(int id) const
3187 LAPPERR(d->views_.contains(id));
3188 return *d->views_.value(id);
3192 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3194 QList<GuiView *> const views = d->views_.values();
3195 for (GuiView * view : views)
3196 view->hideDialog(name, inset);
3200 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3202 Buffer const * buf = nullptr;
3203 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3204 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3205 if (Buffer const * ptr = (*it)->updateInset(inset))
3212 bool GuiApplication::searchMenu(FuncRequest const & func,
3213 docstring_list & names) const
3215 BufferView * bv = nullptr;
3217 bv = current_view_->currentBufferView();
3218 return d->menus_.searchMenu(func, names, bv);
3222 bool GuiApplication::hasBufferView() const
3224 return (current_view_ && current_view_->currentBufferView());
3228 // Ensure that a file is read only once (prevents include loops)
3229 static QStringList uifiles;
3230 // store which ui files define Toolbars
3231 static QStringList toolbar_uifiles;
3234 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3245 LexerKeyword uitags[] = {
3246 { "format", ui_format },
3247 { "include", ui_include },
3248 { "menuset", ui_menuset },
3249 { "toolbars", ui_toolbars },
3250 { "toolbarset", ui_toolbarset }
3254 lex.setFile(ui_path);
3256 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3260 if (lyxerr.debugging(Debug::PARSER))
3261 lex.printTable(lyxerr);
3264 // format before introduction of format tag
3265 unsigned int format = 0;
3266 while (lex.isOK()) {
3267 int const status = lex.lex();
3269 // we have to do this check here, outside the switch,
3270 // because otherwise we would start reading include files,
3271 // e.g., if the first tag we hit was an include tag.
3272 if (status == ui_format)
3274 format = lex.getInteger();
3278 // this will trigger unless the first tag we hit is a format
3279 // tag, with the right format.
3280 if (format != LFUN_FORMAT)
3281 return FormatMismatch;
3284 case Lexer::LEX_FEOF:
3289 QString const file = toqstr(lex.getString());
3290 bool const success = readUIFile(file, true);
3292 LYXERR0("Failed to read included file: " << fromqstr(file));
3299 d->menus_.read(lex);
3303 d->toolbars_.readToolbars(lex);
3307 d->toolbars_.readToolbarSettings(lex);
3308 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3312 if (!rtrim(lex.getString()).empty())
3313 lex.printError("LyX::ReadUIFile: "
3314 "Unknown menu tag: `$$Token'");
3316 LYXERR0("Error with status: " << status);
3322 return (error ? ReadError : ReadOK);
3326 bool GuiApplication::readUIFile(QString const & name, bool include)
3328 LYXERR(Debug::INIT, "About to read " << name << "...");
3332 ui_path = libFileSearch("ui", name, "inc");
3333 if (ui_path.empty())
3334 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3336 ui_path = libFileSearch("ui", name, "ui");
3339 if (ui_path.empty()) {
3340 static const QString defaultUIFile = "default";
3341 LYXERR(Debug::INIT, "Could not find " << name);
3343 Alert::warning(_("Could not find UI definition file"),
3344 bformat(_("Error while reading the included file\n%1$s\n"
3345 "Please check your installation."), qstring_to_ucs4(name)));
3348 if (name == defaultUIFile) {
3349 LYXERR(Debug::INIT, "Could not find default UI file!!");
3350 Alert::warning(_("Could not find default UI file"),
3351 _("LyX could not find the default UI file!\n"
3352 "Please check your installation."));
3355 Alert::warning(_("Could not find UI definition file"),
3356 bformat(_("Error while reading the configuration file\n%1$s\n"
3357 "Falling back to default.\n"
3358 "Please look under Tools>Preferences>User Interface and\n"
3359 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3360 return readUIFile(defaultUIFile, false);
3363 QString const uifile = toqstr(ui_path.absFileName());
3364 if (uifiles.contains(uifile)) {
3366 // We are reading again the top uifile so reset the safeguard:
3369 d->toolbars_.reset();
3371 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3372 << "Is this an include loop?");
3376 uifiles.push_back(uifile);
3378 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3380 ReturnValues retval = readUIFile(ui_path);
3382 if (retval == FormatMismatch) {
3383 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3384 TempFile tmp("convertXXXXXX.ui");
3385 FileName const tempfile = tmp.name();
3386 bool const success = prefs2prefs(ui_path, tempfile, true);
3388 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3389 " to format " << LFUN_FORMAT << ".");
3391 retval = readUIFile(tempfile);
3395 if (retval != ReadOK) {
3396 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3404 settings.beginGroup("ui_files");
3405 bool touched = false;
3406 for (int i = 0; i != uifiles.size(); ++i) {
3407 QFileInfo fi(uifiles[i]);
3408 QDateTime const date_value = fi.lastModified();
3409 QString const name_key = QString::number(i);
3410 // if an ui file which defines Toolbars has changed,
3411 // we have to reset the settings
3412 if (toolbar_uifiles.contains(uifiles[i])
3413 && (!settings.contains(name_key)
3414 || settings.value(name_key).toString() != uifiles[i]
3415 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3417 settings.setValue(name_key, uifiles[i]);
3418 settings.setValue(name_key + "/date", date_value);
3421 settings.endGroup();
3423 settings.remove("views");
3429 void GuiApplication::onLastWindowClosed()
3431 if (d->global_menubar_)
3432 d->global_menubar_->grabKeyboard();
3436 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3438 std::string name = "unknown";
3440 case Qt::ApplicationSuspended:
3441 name = "ApplicationSuspended";
3443 case Qt::ApplicationHidden:
3444 name = "ApplicationHidden";
3446 case Qt::ApplicationInactive:
3447 name = "ApplicationInactive";
3449 case Qt::ApplicationActive:
3450 name = "ApplicationActive";
3451 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3452 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3453 if (d->views_.empty() && d->last_state_ == state) {
3454 LYXERR(Debug::GUI, "Open new window...");
3459 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3460 d->last_state_ = state;
3464 void GuiApplication::startLongOperation() {
3465 d->key_checker_.start();
3469 bool GuiApplication::longOperationCancelled() {
3470 return d->key_checker_.pressed();
3474 void GuiApplication::stopLongOperation() {
3475 d->key_checker_.stop();
3479 bool GuiApplication::longOperationStarted() {
3480 return d->key_checker_.started();
3484 ////////////////////////////////////////////////////////////////////////
3486 // X11 specific stuff goes here...
3488 #if defined(QPA_XCB)
3489 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3490 void * message, QINTPTR *)
3492 if (!current_view_ || eventType != "xcb_generic_event_t")
3495 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3497 switch (ev->response_type) {
3498 case XCB_SELECTION_REQUEST: {
3499 xcb_selection_request_event_t * srev =
3500 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3501 if (srev->selection != XCB_ATOM_PRIMARY)
3503 LYXERR(Debug::SELECTION, "X requested selection.");
3504 BufferView * bv = current_view_->currentBufferView();
3506 docstring const sel = bv->requestSelection();
3508 d->selection_.put(sel);
3509 #ifdef HAVE_QT5_X11_EXTRAS
3510 // Refresh the selection request timestamp.
3511 // We have to do this by ourselves as Qt seems
3512 // not doing that, maybe because of our
3513 // "persistent selection" implementation
3514 // (see comments in GuiSelection.cpp).
3515 // It is expected that every X11 event is
3516 // 32 bytes long, even if not all 32 bytes are
3518 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3519 struct alignas(32) padded_event
3520 : xcb_selection_notify_event_t {};
3521 padded_event nev = {};
3522 nev.response_type = XCB_SELECTION_NOTIFY;
3523 nev.requestor = srev->requestor;
3524 nev.selection = srev->selection;
3525 nev.target = srev->target;
3526 nev.property = XCB_NONE;
3527 nev.time = XCB_CURRENT_TIME;
3528 xcb_connection_t * con = QX11Info::connection();
3529 xcb_send_event(con, 0, srev->requestor,
3530 XCB_EVENT_MASK_NO_EVENT,
3531 reinterpret_cast<char const *>(&nev));
3539 case XCB_SELECTION_CLEAR: {
3540 xcb_selection_clear_event_t * scev =
3541 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3542 if (scev->selection != XCB_ATOM_PRIMARY)
3544 LYXERR(Debug::SELECTION, "Lost selection.");
3545 BufferView * bv = current_view_->currentBufferView();
3547 bv->clearSelection();
3555 } // namespace frontend
3558 void hideDialogs(std::string const & name, Inset * inset)
3561 frontend::guiApp->hideDialogs(name, inset);
3565 ////////////////////////////////////////////////////////////////////
3569 ////////////////////////////////////////////////////////////////////
3571 frontend::FontLoader & theFontLoader()
3573 LAPPERR(frontend::guiApp);
3574 return frontend::guiApp->fontLoader();
3578 frontend::FontMetrics const & theFontMetrics(Font const & f)
3580 return theFontMetrics(f.fontInfo());
3584 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3586 LAPPERR(frontend::guiApp);
3587 return frontend::guiApp->fontLoader().metrics(f);
3591 ////////////////////////////////////////////////////////////////////
3595 ////////////////////////////////////////////////////////////////////
3597 frontend::Clipboard & theClipboard()
3599 LAPPERR(frontend::guiApp);
3600 return frontend::guiApp->clipboard();
3604 frontend::Selection & theSelection()
3606 LAPPERR(frontend::guiApp);
3607 return frontend::guiApp->selection();
3613 #include "moc_GuiApplication.cpp"