2 * \file GuiApplication.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Abdelrazak Younes
10 * Full author contact details are available in file CREDITS.
15 #include "GuiApplication.h"
17 #include "ToolTipFormatter.h"
18 #include "ColorCache.h"
19 #include "GuiClipboard.h"
20 #include "GuiSelection.h"
23 #include "qt_helpers.h"
26 #include "frontends/alert.h"
27 #include "frontends/Application.h"
28 #include "frontends/FontLoader.h"
29 #include "frontends/FontMetrics.h"
32 #include "BufferList.h"
33 #include "BufferParams.h"
34 #include "BufferView.h"
37 #include "Converter.h"
39 #include "CutAndPaste.h"
40 #include "ErrorList.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
44 #include "GuiWorkArea.h"
48 #include "LaTeXPackages.h"
51 #include "LyXAction.h"
53 #include "Paragraph.h"
56 #include "SpellChecker.h"
57 #include "Thesaurus.h"
60 #include "insets/InsetText.h"
62 #include "support/checksum.h"
63 #include "support/convert.h"
64 #include "support/debug.h"
65 #include "support/ExceptionMessage.h"
66 #include "support/environment.h"
67 #include "support/FileName.h"
68 #include "support/filetools.h"
69 #include "support/ForkedCalls.h"
70 #include "support/gettext.h"
71 #include "support/lassert.h"
72 #include "support/lstrings.h"
73 #include "support/lyxalgo.h" // sorted
74 #include "support/textutils.h"
75 #include "support/Messages.h"
76 #include "support/os.h"
77 #include "support/Package.h"
78 #include "support/TempFile.h"
81 #include "support/AppleScript.h"
82 #include "support/AppleSupport.h"
83 #include "support/linkback/LinkBackProxy.h"
92 #if QT_VERSION < 0x060000
93 #include <QDesktopWidget>
96 #include <QFileOpenEvent>
98 #include <QFontDatabase>
101 #include <QImageReader>
104 #include <QLibraryInfo>
111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
112 #include <QRandomGenerator>
115 #include <QSessionManager>
117 #include <QSocketNotifier>
118 #include <QSortFilterProxyModel>
119 #include <QStandardItemModel>
121 #include <QTranslator>
122 #include <QThreadPool>
126 #include <X11/Xatom.h>
127 #include <X11/Xlib.h>
131 #elif defined(QPA_XCB)
133 #ifdef HAVE_QT5_X11_EXTRAS
134 #include <QtX11Extras/QX11Info>
138 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
139 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
140 #if (QT_VERSION < 0x050000)
141 #include <QWindowsMime>
142 #define QWINDOWSMIME QWindowsMime
143 #define QVARIANTTYPE QVariant::Type
144 #elif (QT_VERSION >= 0x060000)
145 #include <QtGui/private/qguiapplication_p.h>
146 #include <QtGui/private/qwindowsmime_p.h>
147 #include <QtGui/qpa/qplatformintegration.h>
148 #define QWINDOWSMIME QWindowsMime
149 #define QVARIANTTYPE QMetaType
150 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
151 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
154 #define QWINDOWSMIME QWinMime
155 #define QVARIANTTYPE QVariant::Type
164 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
165 #include <QMacPasteboardMime>
173 using namespace lyx::support;
178 frontend::Application * createApplication(int & argc, char * argv[])
180 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
181 // prune -geometry argument(s) by shifting
182 // the following ones 2 places down.
183 for (int i = 0 ; i < argc ; ++i) {
184 if (strcmp(argv[i], "-geometry") == 0) {
185 int const remove = (i+1) < argc ? 2 : 1;
187 for (int j = i; j < argc; ++j)
188 argv[j] = argv[j + remove];
194 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
195 // On Windows, allow bringing the LyX window to top
196 AllowSetForegroundWindow(ASFW_ANY);
200 #if defined(Q_OS_MAC)
201 int const cursor_time_on = NSTextInsertionPointBlinkPeriodOn();
202 int const cursor_time_off = NSTextInsertionPointBlinkPeriodOff();
203 if (cursor_time_on > 0 && cursor_time_off > 0) {
204 QApplication::setCursorFlashTime(cursor_time_on + cursor_time_off);
205 } else if (cursor_time_on <= 0 && cursor_time_off > 0) {
206 // Off is set and On is undefined of zero
207 QApplication::setCursorFlashTime(0);
208 } else if (cursor_time_off <= 0 && cursor_time_on > 0) {
209 // On is set and Off is undefined of zero
210 QApplication::setCursorFlashTime(0);
214 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
215 // macOS does it by itself.
216 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
217 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
218 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
219 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
220 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
221 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
224 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
225 // HighDPI scale factor policy must be set before QGuiApplication is created
226 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
227 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
231 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
232 // I'd rather do that in the constructor, but I do not think that
233 // the palette is accessible there.
234 guiApp->colorCache().setPalette(guiApp->palette());
243 if (lyxrc.gui_language == "auto") {
244 theLocale = QLocale::system();
245 code = fromqstr(theLocale.name());
247 Language const * l = languages.getLanguage(lyxrc.gui_language);
248 code = l ? l->code() : "C";
249 theLocale = QLocale(toqstr(code));
251 // Qt tries to outsmart us and transforms en_US to C.
252 Messages::guiLanguage((code == "C") ? "en_US" : code);
253 QLocale::setDefault(theLocale);
254 setlocale(LC_NUMERIC, "C");
261 /// Return the list of loadable formats.
262 vector<string> loadableImageFormats()
266 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
268 LYXERR(Debug::GRAPHICS,
269 "\nThe image loader can load the following directly:\n");
271 if (qt_formats.empty())
272 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
274 bool jpeg_found = false;
275 bool jpg_found = false;
276 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
278 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
280 string ext = ascii_lowercase((const char *) *it);
288 else if (ext == "jpg") {
293 else if (lyxrc.use_converter_cache &&
294 (ext == "svg" || ext == "svgz") &&
295 theConverters().isReachable("svg", "png"))
296 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
297 // the SVG as in the output. However we require that the converter
298 // cache is enabled since this is expensive. We also require that
299 // an explicit svg->png converter is defined, since the default
300 // converter could produce bad quality as well. This assumes that
301 // png can always be loaded.
310 ////////////////////////////////////////////////////////////////////////
312 // Icon loading support code
314 ////////////////////////////////////////////////////////////////////////
324 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
326 return lhs.key < rhs.key;
332 CompareKey(QString const & name) : name_(name) {}
333 bool operator()(ImgMap const & other) const { return other.key == name_; }
339 // this must be sorted alphabetically
340 // Upper case comes before lower case
341 // Please don't change the formatting, this list is parsed by
342 // development/tools/generate_symbols_images.py.
343 ImgMap sorted_img_map[] = {
344 { "Arrownot", "arrownot2"},
345 { "Arrowvert", "arrowvert2"},
346 { "Bowtie", "bowtie2" },
348 { "Bumpeq", "bumpeq2" },
349 { "CIRCLE", "circle3" },
351 { "CheckedBox", "checkedbox2" },
352 { "Circle", "circle2" },
353 { "Colonapprox", "colonapprox2" },
354 { "Coloneq", "coloneq2" },
355 { "Coloneqq", "coloneqq2" },
356 { "Colonsim", "colonsim2" },
358 { "DOWNarrow", "downarrow3" },
359 { "Delta", "delta2" },
360 { "Diamond", "diamond2" },
361 { "Doteq", "doteq2" },
362 { "Downarrow", "downarrow2" },
363 { "Eqcolon", "eqcolon2" },
364 { "Eqqcolon", "eqqcolon2" },
365 { "Gamma", "gamma2" },
367 { "LEFTCIRCLE", "leftcircle3" },
368 { "LEFTarrow", "leftarrow3" },
369 { "LEFTcircle", "leftcircle4" },
371 { "Lambda", "lambda2" },
373 { "Leftarrow", "leftarrow2" },
374 { "Leftcircle", "leftcircle2" },
375 { "Leftrightarrow", "leftrightarrow2" },
376 { "Longarrownot", "longarrownot2"},
377 { "Longleftarrow", "longleftarrow2" },
378 { "Longleftrightarrow", "longleftrightarrow2" },
379 { "Longmapsfrom", "longmapsfrom2"},
380 { "Longmapsto", "longmapsto2"},
381 { "Longrightarrow", "longrightarrow2" },
382 { "Mapsfrom", "mapsfrom2"},
383 { "Mapsfromchar", "mapsfromchar2"},
384 { "Mapsto", "mapsto2"},
385 { "Mapstochar", "mapstochar2"},
386 { "Omega", "omega2" },
391 { "RIGHTCIRCLE", "rightcircle3" },
392 { "RIGHTarrow", "rightarrow3" },
393 { "RIGHTcircle", "rightcircle4" },
395 { "Rightarrow", "rightarrow2" },
396 { "Rightcircle", "rightcircle2" },
397 { "Sigma", "sigma2" },
398 { "Square", "square2" },
399 { "Subset", "subset2" },
400 { "Supset", "supset2" },
401 { "Theta", "theta2" },
402 { "Thorn", "thorn2" },
403 { "UParrow", "uparrow3" },
404 { "Uparrow", "uparrow2" },
405 { "Updownarrow", "updownarrow2" },
406 { "Upsilon", "upsilon2" },
407 { "Vdash", "vdash3" },
412 { "lVert", "vert2" },
414 { "nLeftarrow", "nleftarrow2" },
415 { "nLeftrightarrow", "nleftrightarrow2" },
416 { "nRightarrow", "nrightarrow2" },
417 { "nVDash", "nvdash3" },
418 { "nVdash", "nvdash4" },
419 { "nvDash", "nvdash2" },
420 { "rVert", "vert2" },
422 { "textrm \\AA", "textrm_AA"},
423 { "textrm \\O", "textrm_O"},
424 { "vDash", "vdash2" },
425 { "varDelta", "vardelta2" },
426 { "varGamma", "vargamma2" },
427 { "varLambda", "varlambda2" },
428 { "varOmega", "varomega2" },
429 { "varPhi", "varphi2" },
430 { "varPi", "varpi2" },
431 { "varPsi", "varpsi2" },
432 { "varSigma", "varsigma2" },
433 { "varTheta", "vartheta2" },
434 { "varUpsilon", "varupsilon2" },
435 { "varXi", "varxi2" }
439 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
441 // This list specifies which system's theme icon is related to which lyx
442 // command. It was based on:
443 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
444 // this must be sorted alphabetically
445 // Upper case comes before lower case
446 ImgMap sorted_theme_icon_map[] = {
447 { "bookmark-goto 0", "go-jump" },
448 { "buffer-new", "document-new" },
449 { "buffer-write", "document-save" },
450 { "buffer-write-as", "document-save-as" },
451 { "buffer-zoom-in", "zoom-in" },
452 { "buffer-zoom-out", "zoom-out" },
453 { "copy", "edit-copy" },
454 { "cut", "edit-cut" },
455 { "depth-decrement", "format-indent-less" },
456 { "depth-increment", "format-indent-more" },
457 { "dialog-show spellchecker", "tools-check-spelling" },
458 { "dialog-show-new-inset graphics", "insert-image" },
459 { "dialog-toggle findreplaceadv", "edit-find-replace" },
460 { "file-open", "document-open" },
461 { "font-bold", "format-text-bold" },
462 { "font-ital", "format-text-italic" },
463 { "font-strikeout", "format-text-strikethrough" },
464 { "font-underline", "format-text-underline" },
465 { "lyx-quit", "application-exit" },
466 { "paste", "edit-paste" },
467 { "redo", "edit-redo" },
468 { "undo", "edit-undo" },
469 { "window-close", "window-close" },
470 { "window-new", "window-new" }
473 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
476 QString findImg(QString const & name)
478 ImgMap const * const begin = sorted_img_map;
479 ImgMap const * const end = begin + nr_sorted_img_map;
480 LATTEST(sorted(begin, end));
482 ImgMap const * const it = find_if(begin, end, CompareKey(name));
486 img_name = it->value;
489 img_name.replace('_', "underscore");
490 img_name.replace(' ', '_');
492 // This way we can have "math-delim { }" on the toolbar.
493 img_name.replace('(', "lparen");
494 img_name.replace(')', "rparen");
495 img_name.replace('[', "lbracket");
496 img_name.replace(']', "rbracket");
497 img_name.replace('{', "lbrace");
498 img_name.replace('}', "rbrace");
499 img_name.replace('|', "bars");
500 img_name.replace(',', "thinspace");
501 img_name.replace(':', "mediumspace");
502 img_name.replace(';', "thickspace");
503 img_name.replace('!', "negthinspace");
506 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
507 << "Looking for math icon called \"" << img_name << '"');
514 QString themeIconName(QString const & action)
516 ImgMap const * const begin = sorted_theme_icon_map;
517 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
518 LASSERT(sorted(begin, end), /**/);
520 ImgMap const * const it = find_if(begin, end, CompareKey(action));
530 QString getAlias(QString name) {
531 static bool has_aliases = false;
532 static vector <pair<QString,QString>> aliases;
533 // Initialize aliases list (once).
535 FileName alfile = libFileSearch("images", "icon.aliases");
536 if (alfile.exists()) {
543 aliases.push_back({toqstr(from), toqstr(to)});
548 // check for the following aliases
549 for (auto alias : aliases) {
550 if (name.contains(alias.first))
551 name.replace(alias.first, alias.second);
559 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
564 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
566 if (!f.argument().empty()) {
567 // if there are arguments, first search an icon which name is the full thing
568 QString name = lfunname + ' ' + toqstr(f.argument());
569 name.replace(' ', '_');
570 name.replace(';', '_');
571 name.replace('\\', "backslash");
573 QString alias = getAlias(name);
577 // then special default icon for some lfuns
578 switch (f.action()) {
579 case LFUN_MATH_INSERT:
580 names << "math/" + findImg(toqstr(f.argument()).mid(1));
582 case LFUN_MATH_DELIM:
583 case LFUN_MATH_BIGDELIM:
584 names << "math/" + findImg(toqstr(f.argument()));
587 names << "commands/" + toqstr(f.argument());
589 case LFUN_COMMAND_ALTERNATIVES: {
590 // use the first of the alternative commands
592 docstring dummy = split(f.argument(), firstcom, ';');
593 QString name1 = toqstr(firstcom);
594 name1.replace(' ', '_');
595 name1.replace(';', '_');
596 name1.replace('\\', "backslash");
605 // next thing to try is function name alone
607 QString alias = getAlias(lfunname);
608 if (alias != lfunname)
611 // and finally maybe the unknown icon
615 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
616 // The folders where icons are searched for
617 QStringList imagedirs;
618 imagedirs << "images/ipa/" << "images/";
619 // This is used to search for rtl version of icons which have the +rtl suffix.
620 QStringList suffixes;
623 suffixes << QString();
625 for (QString const & imagedir : imagedirs)
626 for (QString const & name : names)
627 for (QString const & suffix : suffixes) {
628 QString id = imagedir;
629 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
630 if (fname.exists()) {
631 docstring const fpath = fname.absoluteFilePath();
632 res.filepath = toqstr(fname.absFileName());
633 // these icons are subject to inversion in dark mode
634 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
635 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
636 res.swap = rtl && suffix.isEmpty();
641 LYXERR(Debug::GUI, "Cannot find icon for command \""
642 << lyxaction.getActionName(f.action())
643 << '(' << to_utf8(f.argument()) << ")\"");
649 QPixmap prepareForDarkMode(QPixmap pixmap)
651 QPalette palette = QPalette();
652 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
653 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
655 // guess whether we are in dark mode
656 if (text_color.black() > bg_color.black())
657 // not in dark mode, do nothing
660 // create a layer with black text turned to QPalette::WindowText
661 QPixmap black_overlay(pixmap.size());
662 black_overlay.fill(text_color);
663 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
665 // create a layer with blue text turned to lighter blue
666 QPixmap blue_overlay(pixmap.size());
667 QColor math_blue(0, 0, 255);
668 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
669 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
671 // create a layer with ("latex") red text turned to lighter red
672 QPixmap red_overlay(pixmap.size());
673 QColor math_red(128, 0, 0);
674 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
675 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
677 // put layers on top of existing pixmap
678 QPainter painter(&pixmap);
679 painter.drawPixmap(pixmap.rect(), black_overlay);
680 painter.drawPixmap(pixmap.rect(), blue_overlay);
681 painter.drawPixmap(pixmap.rect(), red_overlay);
687 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
689 QString imagedir = path;
690 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
691 QString fpath = toqstr(fname.absFileName());
692 QPixmap pixmap = QPixmap();
694 if (pixmap.load(fpath)) {
695 if (fpath.contains("math") || fpath.contains("ipa")
696 || fpath.contains("bullets"))
697 return prepareForDarkMode(pixmap);
701 bool const list = ext.contains(",");
702 LYXERR(Debug::GUI, "Cannot load pixmap \""
703 << path << "/" << name << "." << (list ? "{" : "") << ext
704 << (list ? "}" : "") << "\".");
710 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
712 #if (QT_VERSION >= 0x040600)
713 if (lyxrc.use_system_theme_icons) {
714 // use the icons from system theme that are available
715 QString action = toqstr(lyxaction.getActionName(f.action()));
716 if (!f.argument().empty())
717 action += " " + toqstr(f.argument());
718 QString const theme_icon = themeIconName(action);
719 if (QIcon::hasThemeIcon(theme_icon)) {
720 QIcon const thmicn = QIcon::fromTheme(theme_icon);
721 if (!thmicn.isNull())
727 IconInfo icondata = iconInfo(f, unknown, rtl);
728 if (icondata.filepath.isEmpty())
731 //LYXERR(Debug::GUI, "Found icon: " << icon);
732 QPixmap pixmap = QPixmap();
733 if (!pixmap.load(icondata.filepath)) {
734 LYXERR0("Cannot load icon " << icondata.filepath << ".");
739 pixmap = prepareForDarkMode(pixmap);
742 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
744 return QIcon(pixmap);
748 ////////////////////////////////////////////////////////////////////////
750 // LyX server support code.
752 ////////////////////////////////////////////////////////////////////////
754 class SocketNotifier : public QSocketNotifier
757 /// connect a connection notification from the LyXServerSocket
758 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
759 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
763 /// The callback function
764 Application::SocketCallback func_;
768 class GuiTranslator : public QTranslator
771 GuiTranslator(QObject * parent = nullptr)
772 : QTranslator(parent)
775 QString translate(const char * /* context */,
776 const char *sourceText,
777 #if QT_VERSION >= 0x050000
778 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
780 const char * /*comment*/ = 0) const override
783 // Here we declare the strings that need to be translated from Qt own GUI
784 // This is needed to include these strings to po files
788 _("Restore Defaults");
791 // Already in po: "Cancel", "&Cancel"
792 _("Apply"); // Already in po: "&Apply"
793 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
796 docstring s = getGuiMessages().getIfFound(sourceText);
797 // This test should eventually be removed when translations are updated
799 LYXERR(Debug::LOCALE, "Missing translation for `"
800 << string(sourceText) << "'");
806 ////////////////////////////////////////////////////////////////////////
808 // Mac specific stuff goes here...
810 ////////////////////////////////////////////////////////////////////////
812 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
813 // QMacPasteboardMimeGraphics can only be compiled on Mac.
815 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
818 QMacPasteboardMimeGraphics()
819 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
822 QString convertorName() { return "Graphics"; }
824 QString flavorFor(QString const & mime)
826 LYXERR(Debug::ACTION, "flavorFor " << mime);
827 if (mime == pdfMimeType())
828 return QLatin1String("com.adobe.pdf");
832 QString mimeFor(QString flav)
834 LYXERR(Debug::ACTION, "mimeFor " << flav);
835 if (flav == QLatin1String("com.adobe.pdf"))
836 return pdfMimeType();
840 bool canConvert(QString const & mime, QString flav)
842 return mimeFor(flav) == mime;
845 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
849 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
853 QList<QByteArray> convertFromMime(QString const & /*mime*/,
854 QVariant data, QString /*flav*/)
856 QList<QByteArray> ret;
857 ret.append(data.toByteArray());
863 ///////////////////////////////////////////////////////////////
865 // You can find more platform specific stuff at the end of this file...
867 ///////////////////////////////////////////////////////////////
869 ////////////////////////////////////////////////////////////////////////
870 // Windows specific stuff goes here...
872 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
873 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
874 // QWindowsMimeMetafile can only be compiled on Windows.
876 static FORMATETC cfFromMime(QString const & mimetype)
879 if (mimetype == emfMimeType()) {
880 formatetc.cfFormat = CF_ENHMETAFILE;
881 formatetc.tymed = TYMED_ENHMF;
882 } else if (mimetype == wmfMimeType()) {
883 formatetc.cfFormat = CF_METAFILEPICT;
884 formatetc.tymed = TYMED_MFPICT;
887 formatetc.dwAspect = DVASPECT_CONTENT;
888 formatetc.lindex = -1;
893 class QWindowsMimeMetafile : public QWINDOWSMIME {
895 QWindowsMimeMetafile() {}
897 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
898 QMimeData const * /*mimedata*/) const override
903 bool canConvertToMime(QString const & mimetype,
904 IDataObject * pDataObj) const override
906 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
908 FORMATETC formatetc = cfFromMime(mimetype);
909 return pDataObj->QueryGetData(&formatetc) == S_OK;
912 bool convertFromMime(FORMATETC const & /*formatetc*/,
913 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
918 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
919 QVARIANTTYPE /*preferredType*/) const override
922 if (!canConvertToMime(mimetype, pDataObj))
925 FORMATETC formatetc = cfFromMime(mimetype);
927 if (pDataObj->GetData(&formatetc, &s) != S_OK)
931 if (s.tymed == TYMED_ENHMF) {
932 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
933 data.resize(dataSize);
934 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
935 (LPBYTE)data.data());
936 } else if (s.tymed == TYMED_MFPICT) {
937 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
938 data.resize(dataSize);
939 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
940 (LPBYTE)data.data());
943 ReleaseStgMedium(&s);
949 QVector<FORMATETC> formatsForMime(QString const & mimetype,
950 QMimeData const * /*mimedata*/) const override
952 QVector<FORMATETC> formats;
953 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
954 formats += cfFromMime(mimetype);
958 QString mimeForFormat(FORMATETC const & formatetc) const override
960 switch (formatetc.cfFormat) {
962 return emfMimeType();
963 case CF_METAFILEPICT:
964 return wmfMimeType();
974 /// Allows to check whether ESC was pressed during a long operation
975 class KeyChecker : public QObject {
980 KeyChecker() : pressed_(false), started_(false) {}
983 QCoreApplication::instance()->installEventFilter(this);
988 QCoreApplication::instance()->removeEventFilter(this);
992 QCoreApplication::processEvents();
995 bool started() const {
998 bool eventFilter(QObject *obj, QEvent *event) override {
999 LYXERR(Debug::ACTION, "Event Type: " << event->type());
1000 switch (event->type()) {
1003 case QEvent::Resize:
1004 case QEvent::UpdateRequest:
1005 case QEvent::CursorChange:
1006 case QEvent::ActionChanged:
1007 case QEvent::EnabledChange:
1008 case QEvent::SockAct:
1011 case QEvent::ToolTipChange:
1012 case QEvent::LayoutRequest:
1013 case QEvent::MetaCall:
1014 return QObject::eventFilter(obj, event);
1016 // FIXME Blocking all these events is a bad idea.
1017 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1018 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1026 ////////////////////////////////////////////////////////////////////////
1027 // GuiApplication::Private definition and implementation.
1028 ////////////////////////////////////////////////////////////////////////
1030 struct GuiApplication::Private
1032 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1033 global_menubar_(nullptr)
1034 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1035 , last_state_(Qt::ApplicationInactive)
1038 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1039 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1040 /// WMF Mime handler for Windows clipboard.
1041 wmf_mime_ = new QWindowsMimeMetafile;
1042 #if (QT_VERSION >= 0x060000)
1043 win_app_ = dynamic_cast<QWindowsApplication *>
1044 (QGuiApplicationPrivate::platformIntegration());
1045 win_app_->registerMime(wmf_mime_);
1049 initKeySequences(&theTopLevelKeymap());
1052 #if (QT_VERSION >= 0x060000)
1053 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1056 win_app_->unregisterMime(wmf_mime_);
1061 void initKeySequences(KeyMap * kb)
1063 keyseq = KeySequence(kb, kb);
1064 cancel_meta_seq = KeySequence(kb, kb);
1068 QSortFilterProxyModel * language_model_;
1070 GuiClipboard clipboard_;
1072 GuiSelection selection_;
1074 FontLoader font_loader_;
1076 ColorCache color_cache_;
1077 /// the built-in Qt translation mechanism
1078 QTranslator qt_trans_;
1079 /// LyX gettext-based translation for Qt elements
1080 GuiTranslator gui_trans_;
1082 QHash<int, SocketNotifier *> socket_notifiers_;
1086 /// The global instance
1089 /// this timer is used for any regular events one wants to
1090 /// perform. at present it is used to check if forked processes
1092 QTimer general_timer_;
1094 /// delayed FuncRequests
1095 std::queue<FuncRequest> func_request_queue_;
1100 KeySequence cancel_meta_seq;
1102 KeyModifier meta_fake_bit;
1104 /// The result of last dispatch action
1105 DispatchResult dispatch_result_;
1107 /// Multiple views container.
1109 * Warning: This must not be a smart pointer as the destruction of the
1110 * object is handled by Qt when the view is closed
1111 * \sa Qt::WA_DeleteOnClose attribute.
1113 QHash<int, GuiView *> views_;
1115 /// Only used on mac.
1116 QMenuBar * global_menubar_;
1117 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1118 /// Holds previous application state on Mac
1119 Qt::ApplicationState last_state_;
1122 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1123 /// Linkback mime handler for MacOSX.
1124 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1127 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1128 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1129 /// WMF Mime handler for Windows clipboard.
1130 QWindowsMimeMetafile * wmf_mime_;
1131 #if (QT_VERSION >= 0x060000)
1132 QWindowsApplication * win_app_;
1137 /// Allows to check whether ESC was pressed during a long operation
1138 KeyChecker key_checker_;
1142 GuiApplication * guiApp;
1144 GuiApplication::~GuiApplication()
1147 closeAllLinkBackLinks();
1153 GuiApplication::GuiApplication(int & argc, char ** argv)
1154 : QApplication(argc, argv), current_view_(nullptr),
1155 d(new GuiApplication::Private)
1157 QString app_name = "LyX";
1158 QCoreApplication::setOrganizationName(app_name);
1159 QCoreApplication::setOrganizationDomain("lyx.org");
1160 QCoreApplication::setApplicationName(lyx_package);
1161 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1162 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1165 #if QT_VERSION >= 0x050700
1166 setDesktopFileName(lyx_package);
1169 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1170 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1172 qsrand(QDateTime::currentDateTime().toTime_t());
1175 // Install LyX translator for missing Qt translations
1176 installTranslator(&d->gui_trans_);
1177 // Install Qt native translator for GUI elements.
1178 installTranslator(&d->qt_trans_);
1181 // Enable reception of XCB events.
1182 installNativeEventFilter(this);
1185 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1186 // lyxrc setting for this in order to let the application stay resident.
1187 // But then we need some kind of dock icon, at least on Windows.
1189 if (lyxrc.quit_on_last_window_closed)
1190 setQuitOnLastWindowClosed(false);
1193 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1194 // seems to be the default case for applications like LyX.
1195 setQuitOnLastWindowClosed(false);
1198 appleCleanupEditMenu();
1199 appleCleanupViewMenu();
1200 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1201 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1202 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1206 #if defined(Q_WS_X11) || defined(QPA_XCB)
1207 // doubleClickInterval() is 400 ms on X11 which is just too long.
1208 // On Windows and Mac OS X, the operating system's value is used.
1209 // On Microsoft Windows, calling this function sets the double
1210 // click interval for all applications. So we don't!
1211 QApplication::setDoubleClickInterval(300);
1214 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1216 // needs to be done before reading lyxrc
1218 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1222 // Initialize RC Fonts
1223 if (lyxrc.roman_font_name.empty())
1224 lyxrc.roman_font_name = fromqstr(romanFontName());
1226 if (lyxrc.sans_font_name.empty())
1227 lyxrc.sans_font_name = fromqstr(sansFontName());
1229 if (lyxrc.typewriter_font_name.empty())
1230 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1232 #if (QT_VERSION >= 0x050000)
1233 // Qt4 does this in event(), see below.
1234 // Track change of keyboard
1235 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1238 d->general_timer_.setInterval(500);
1239 connect(&d->general_timer_, SIGNAL(timeout()),
1240 this, SLOT(handleRegularEvents()));
1241 d->general_timer_.start();
1243 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1244 // This is clearly not enough in a time where we use threads for
1245 // document preview and/or export. 20 should be OK.
1246 QThreadPool::globalInstance()->setMaxThreadCount(20);
1248 // make sure tooltips are formatted
1249 installEventFilter(new ToolTipFormatter(this));
1253 GuiApplication * theGuiApp()
1255 return dynamic_cast<GuiApplication *>(theApp());
1259 #if QT_VERSION < 0x050000
1260 // Emulate platformName() for Qt4
1262 // FIXME: when ditching this method, remove all tests
1263 // platformName() == "qt4x11"
1265 QString GuiApplication::platformName() const
1267 # if defined(Q_WS_X11)
1268 // Note that this one does not really exist
1270 # elif defined(Q_OS_MAC)
1272 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1275 LYXERR0("Unknown platform!");
1282 double GuiApplication::pixelRatio() const
1284 #if QT_VERSION >= 0x050000
1285 return qt_scale_factor * devicePixelRatio();
1292 void GuiApplication::clearSession()
1299 docstring Application::iconName(FuncRequest const & f, bool unknown)
1301 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1305 docstring Application::mathIcon(docstring const & c)
1307 return qstring_to_ucs4(findImg(toqstr(c)));
1311 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1315 BufferView * bv = nullptr;
1316 BufferView * doc_bv = nullptr;
1318 if (cmd.action() == LFUN_NOACTION) {
1319 status.message(from_utf8(N_("Nothing to do")));
1320 status.setEnabled(false);
1323 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1324 status.setUnknown(true);
1325 status.message(from_utf8(N_("Unknown action")));
1326 status.setEnabled(false);
1329 // Does the GuiApplication know something?
1330 else if (getStatus(cmd, status)) { }
1332 // If we do not have a GuiView, then other functions are disabled
1333 else if (!current_view_)
1334 status.setEnabled(false);
1336 // Does the GuiView know something?
1337 else if (current_view_->getStatus(cmd, status)) { }
1339 // In LyX/Mac, when a dialog is open, the menus of the
1340 // application can still be accessed without giving focus to
1341 // the main window. In this case, we want to disable the menu
1342 // entries that are buffer or view-related.
1343 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1345 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1346 status.setEnabled(false);
1349 // If we do not have a BufferView, then other functions are disabled
1350 else if (!(bv = current_view_->currentBufferView()))
1351 status.setEnabled(false);
1353 // Does the current BufferView know something?
1354 else if (bv->getStatus(cmd, status)) { }
1356 // Does the current Buffer know something?
1357 else if (bv->buffer().getStatus(cmd, status)) { }
1359 // If we do not have a document BufferView, different from the
1360 // current BufferView, then other functions are disabled
1361 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1362 status.setEnabled(false);
1364 // Does the document Buffer know something?
1365 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1368 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1369 status.message(from_utf8(N_("Command not handled")));
1370 status.setEnabled(false);
1373 // the default error message if we disable the command
1374 if (!status.enabled() && status.message().empty())
1375 status.message(from_utf8(N_("Command disabled")));
1381 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1383 // I would really like to avoid having this switch and rather try to
1384 // encode this in the function itself.
1385 // -- And I'd rather let an inset decide which LFUNs it is willing
1386 // to handle (Andre')
1388 switch (cmd.action()) {
1390 // This could be used for the no-GUI version. The GUI version is handled in
1391 // GuiView::getStatus(). See above.
1393 case LFUN_BUFFER_WRITE:
1394 case LFUN_BUFFER_WRITE_AS:
1395 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1396 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1397 enable = b && (b->isUnnamed() || !b->isClean());
1402 case LFUN_BOOKMARK_GOTO: {
1403 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1404 enable = theSession().bookmarks().isValid(num);
1408 case LFUN_BOOKMARK_CLEAR:
1409 enable = theSession().bookmarks().hasValid();
1412 // this one is difficult to get right. As a half-baked
1413 // solution, we consider only the first action of the sequence
1414 case LFUN_COMMAND_SEQUENCE: {
1415 // argument contains ';'-terminated commands
1416 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1417 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1418 func.setOrigin(cmd.origin());
1419 flag = getStatus(func);
1423 // we want to check if at least one of these is enabled
1424 case LFUN_COMMAND_ALTERNATIVES: {
1425 // argument contains ';'-terminated commands
1426 string arg = to_utf8(cmd.argument());
1427 while (!arg.empty()) {
1429 arg = split(arg, first, ';');
1430 FuncRequest func(lyxaction.lookupFunc(first));
1431 func.setOrigin(cmd.origin());
1432 flag = getStatus(func);
1433 // if this one is enabled, the whole thing is
1442 string name = to_utf8(cmd.argument());
1443 if (theTopLevelCmdDef().lock(name, func)) {
1444 func.setOrigin(cmd.origin());
1445 flag = getStatus(func);
1446 theTopLevelCmdDef().release(name);
1448 // catch recursion or unknown command
1449 // definition. all operations until the
1450 // recursion or unknown command definition
1451 // occurs are performed, so set the state to
1458 case LFUN_IF_RELATIVES: {
1459 string const lfun = to_utf8(cmd.argument());
1460 BufferView const * bv =
1461 current_view_ ? current_view_->currentBufferView() : nullptr;
1462 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1466 FuncRequest func(lyxaction.lookupFunc(lfun));
1467 func.setOrigin(cmd.origin());
1468 flag = getStatus(func);
1472 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1474 case LFUN_PREFERENCES_SAVE:
1475 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1476 // these are handled in our dispatch()
1479 case LFUN_DEBUG_LEVEL_SET: {
1480 string bad = Debug::badValue(to_utf8(cmd.argument()));
1481 enable = bad.empty();
1483 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1487 case LFUN_WINDOW_CLOSE:
1488 enable = !d->views_.empty();
1491 case LFUN_BUFFER_NEW:
1492 case LFUN_BUFFER_NEW_TEMPLATE:
1493 case LFUN_FILE_OPEN:
1494 case LFUN_LYXFILES_OPEN:
1495 case LFUN_HELP_OPEN:
1496 case LFUN_SCREEN_FONT_UPDATE:
1497 case LFUN_SET_COLOR:
1498 case LFUN_WINDOW_NEW:
1500 case LFUN_LYXRC_APPLY:
1501 case LFUN_COMMAND_PREFIX:
1503 case LFUN_META_PREFIX:
1504 case LFUN_RECONFIGURE:
1505 case LFUN_SERVER_GET_FILENAME:
1506 case LFUN_SERVER_NOTIFY:
1510 case LFUN_BUFFER_FORALL: {
1511 if (theBufferList().empty()) {
1512 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1513 flag.setEnabled(false);
1517 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1518 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1519 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1520 flag.setEnabled(false);
1525 case LFUN_DIALOG_SHOW: {
1526 string const name = cmd.getArg(0);
1527 return name == "aboutlyx"
1528 || name == "lyxfiles"
1530 || name == "texinfo"
1531 || name == "progress"
1532 || name == "compare";
1540 flag.setEnabled(false);
1544 /// make a post-dispatch status message
1545 static docstring makeDispatchMessage(docstring const & msg,
1546 FuncRequest const & cmd)
1548 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1549 || cmd.origin() == FuncRequest::TOOLBAR
1550 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1552 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1553 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1557 docstring dispatch_msg = msg;
1558 if (!dispatch_msg.empty())
1559 dispatch_msg += ' ';
1561 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1563 bool argsadded = false;
1565 if (!cmd.argument().empty()) {
1566 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1567 comname += ' ' + cmd.argument();
1571 docstring const shortcuts = theTopLevelKeymap().
1572 printBindings(cmd, KeySequence::ForGui);
1574 if (!shortcuts.empty())
1575 comname += ": " + shortcuts;
1576 else if (!argsadded && !cmd.argument().empty())
1577 comname += ' ' + cmd.argument();
1579 if (!comname.empty()) {
1580 comname = rtrim(comname);
1581 dispatch_msg += '(' + rtrim(comname) + ')';
1583 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1584 return dispatch_msg;
1588 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1592 Buffer * buffer = nullptr;
1593 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1594 //setCurrentView(cmd.view_origin); //does not work
1596 dr.setMessage(_("Wrong focus!"));
1597 d->dispatch_result_ = dr;
1598 return d->dispatch_result_;
1600 if (current_view_ && current_view_->currentBufferView()) {
1601 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1602 buffer = ¤t_view_->currentBufferView()->buffer();
1605 dr.screenUpdate(Update::FitCursor);
1607 // All the code is kept inside the undo group because
1608 // updateBuffer can create undo actions (see #11292)
1609 UndoGroupHelper ugh(buffer);
1611 if (dr.screenUpdate() & Update::ForceAll) {
1612 for (Buffer const * b : theBufferList())
1614 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1617 updateCurrentView(cmd, dr);
1620 d->dispatch_result_ = dr;
1621 return d->dispatch_result_;
1625 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1630 BufferView * bv = current_view_->currentBufferView();
1632 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1633 bv->cursor().clearBufferUpdate();
1634 bv->buffer().updateBuffer();
1636 // BufferView::update() updates the ViewMetricsInfo and
1637 // also initializes the position cache for all insets in
1638 // (at least partially) visible top-level paragraphs.
1639 // We will redraw the screen only if needed.
1640 bv->processUpdateFlags(dr.screenUpdate());
1642 // Do we have a selection?
1643 theSelection().haveSelection(bv->cursor().selection());
1646 current_view_->restartCaret();
1648 if (dr.needMessageUpdate()) {
1649 // Some messages may already be translated, so we cannot use _()
1650 current_view_->message(makeDispatchMessage(
1651 translateIfPossible(dr.message()), cmd));
1656 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1657 bool switchToBuffer)
1659 if (!theSession().bookmarks().isValid(idx))
1661 BookmarksSection::Bookmark const & bm =
1662 theSession().bookmarks().bookmark(idx);
1663 LASSERT(!bm.filename.empty(), return);
1664 string const file = bm.filename.absFileName();
1665 // if the file is not opened, open it.
1666 if (!theBufferList().exists(bm.filename)) {
1668 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1672 // open may fail, so we need to test it again
1673 if (!theBufferList().exists(bm.filename))
1676 // bm can be changed when saving
1677 BookmarksSection::Bookmark tmp = bm;
1679 // Special case idx == 0 used for back-from-back jump navigation
1681 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1683 // if the current buffer is not that one, switch to it.
1684 BufferView * doc_bv = current_view_ ?
1685 current_view_->documentBufferView() : nullptr;
1686 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1687 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1688 if (switchToBuffer) {
1689 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1692 doc_bv = current_view_->documentBufferView();
1697 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1698 if (!doc_bv || !doc_bv->moveToPosition(
1699 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1702 Cursor & cur = doc_bv->cursor();
1703 if (old && cur != *old)
1704 notifyCursorLeavesOrEnters(*old, cur);
1710 // Cursor jump succeeded!
1711 pit_type new_pit = cur.pit();
1712 pos_type new_pos = cur.pos();
1713 int new_id = cur.paragraph().id();
1715 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1716 // see http://www.lyx.org/trac/ticket/3092
1717 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1718 || bm.top_id != new_id) {
1719 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1720 new_pit, new_pos, new_id);
1724 // This function runs "configure" and then rereads lyx.defaults to
1725 // reconfigure the automatic settings.
1726 void GuiApplication::reconfigure(string const & option)
1728 // emit message signal.
1729 if (current_view_) {
1730 current_view_->message(_("Running configure..."));
1731 current_view_->setCursor(Qt::WaitCursor);
1734 // Run configure in user lyx directory
1735 string const lock_file = package().getConfigureLockName();
1736 int fd = fileLock(lock_file.c_str());
1737 int const ret = package().reconfigureUserLyXDir(option);
1738 // emit message signal.
1740 current_view_->message(_("Reloading configuration..."));
1741 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1742 // Re-read packages.lst
1743 LaTeXPackages::getAvailable();
1744 fileUnlock(fd, lock_file.c_str());
1747 current_view_->unsetCursor();
1750 Alert::information(_("System reconfiguration failed"),
1751 _("The system reconfiguration has failed.\n"
1752 "Default textclass is used but LyX may\n"
1753 "not be able to work properly.\n"
1754 "Please reconfigure again if needed."));
1756 Alert::information(_("System reconfigured"),
1757 _("The system has been reconfigured.\n"
1758 "You need to restart LyX to make use of any\n"
1759 "updated document class specifications."));
1762 void GuiApplication::validateCurrentView()
1764 if (!d->views_.empty() && !current_view_) {
1765 // currently at least one view exists but no view has the focus.
1766 // choose the last view to make it current.
1767 // a view without any open document is preferred.
1768 GuiView * candidate = nullptr;
1769 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1770 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1771 for (; it != end; ++it) {
1773 if (!candidate->documentBufferView())
1776 setCurrentView(candidate);
1780 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1782 string const argument = to_utf8(cmd.argument());
1783 FuncCode const action = cmd.action();
1785 LYXERR(Debug::ACTION, "cmd: " << cmd);
1787 // we have not done anything wrong yet.
1790 FuncStatus const flag = getStatus(cmd);
1791 if (!flag.enabled()) {
1792 // We cannot use this function here
1793 LYXERR(Debug::ACTION, "action "
1794 << lyxaction.getActionName(action)
1795 << " [" << action << "] is disabled at this location");
1796 dr.setMessage(flag.message());
1798 dr.dispatched(false);
1799 dr.screenUpdate(Update::None);
1800 dr.clearBufferUpdate();
1804 if (cmd.origin() == FuncRequest::LYXSERVER) {
1805 if (current_view_ && current_view_->currentBufferView())
1806 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1807 // we will also need to redraw the screen at the end
1808 dr.screenUpdate(Update::FitCursor);
1811 // Assumes that the action will be dispatched.
1812 dr.dispatched(true);
1814 switch (cmd.action()) {
1816 case LFUN_WINDOW_NEW:
1817 createView(toqstr(cmd.argument()));
1820 case LFUN_WINDOW_CLOSE:
1821 // FIXME: this is done also in GuiView::closeBuffer()!
1822 // update bookmark pit of the current buffer before window close
1823 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1824 gotoBookmark(i, false, false);
1825 // clear the last opened list, because
1826 // maybe this will end the session
1827 theSession().lastOpened().clear();
1828 // check for valid current_view_
1829 validateCurrentView();
1831 current_view_->closeScheduled();
1835 // quitting is triggered by the gui code
1836 // (leaving the event loop).
1838 current_view_->message(from_utf8(N_("Exiting.")));
1839 if (closeAllViews())
1843 case LFUN_SCREEN_FONT_UPDATE: {
1844 // handle the screen font changes.
1845 /* FIXME: this only updates the current document, whereas all
1846 * documents should see their metrics updated.
1848 d->font_loader_.update();
1849 dr.screenUpdate(Update::Force | Update::FitCursor);
1853 case LFUN_BUFFER_NEW:
1854 validateCurrentView();
1856 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1857 createView(QString(), false); // keep hidden
1858 current_view_->newDocument(to_utf8(cmd.argument()));
1859 current_view_->show();
1860 setActiveWindow(current_view_);
1862 current_view_->newDocument(to_utf8(cmd.argument()));
1866 case LFUN_BUFFER_NEW_TEMPLATE: {
1867 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1868 string const temp = cmd.getArg(1);
1869 validateCurrentView();
1871 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1873 current_view_->newDocument(file, temp, true);
1874 if (!current_view_->documentBufferView())
1875 current_view_->close();
1877 current_view_->newDocument(file, temp, true);
1882 case LFUN_FILE_OPEN: {
1883 // FIXME: normally the code below is not needed, since getStatus makes sure that
1884 // current_view_ is not null.
1885 validateCurrentView();
1886 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1887 string const fname = trim(to_utf8(cmd.argument()), "\"");
1888 bool const is_open = FileName::isAbsolute(fname)
1889 && theBufferList().getBuffer(FileName(fname));
1891 || (!lyxrc.open_buffers_in_tabs
1892 && current_view_->documentBufferView() != nullptr
1894 // We want the ui session to be saved per document and not per
1895 // window number. The filename crc is a good enough identifier.
1896 createView(support::checksum(fname));
1897 current_view_->openDocument(fname);
1898 if (!current_view_->documentBufferView())
1899 current_view_->close();
1900 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1901 current_view_->raise();
1902 current_view_->activateWindow();
1903 current_view_->showNormal();
1906 current_view_->openDocument(fname);
1907 if (cmd.origin() == FuncRequest::LYXSERVER) {
1908 current_view_->raise();
1909 current_view_->activateWindow();
1910 current_view_->showNormal();
1916 case LFUN_HELP_OPEN: {
1917 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1918 if (current_view_ == nullptr)
1920 string const arg = to_utf8(cmd.argument());
1922 current_view_->message(_("Missing argument"));
1925 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1927 fname = i18nLibFileSearch("examples", arg, "lyx");
1929 if (fname.empty()) {
1930 lyxerr << "LyX: unable to find documentation file `"
1931 << arg << "'. Bad installation?" << endl;
1934 current_view_->message(bformat(_("Opening help file %1$s..."),
1935 makeDisplayPath(fname.absFileName())));
1936 Buffer * buf = current_view_->loadDocument(fname, false);
1938 buf->setReadonly(!current_view_->develMode());
1942 case LFUN_LYXFILES_OPEN: {
1943 // This is the actual reason for this method (#12106).
1944 validateCurrentView();
1946 || (!lyxrc.open_buffers_in_tabs
1947 && current_view_->documentBufferView() != nullptr))
1949 string arg = to_utf8(cmd.argument());
1953 if (arg != "templates" && arg != "examples") {
1954 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1957 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1961 case LFUN_SET_COLOR: {
1962 string const lyx_name = cmd.getArg(0);
1963 string x11_name = cmd.getArg(1);
1964 string x11_darkname = cmd.getArg(2);
1965 if (lyx_name.empty() || x11_name.empty()) {
1967 current_view_->message(
1968 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1973 // FIXME: The graphics cache no longer has a changeDisplay method.
1974 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1975 bool const graphicsbg_changed =
1976 lyx_name == graphicsbg && x11_name != graphicsbg;
1977 if (graphicsbg_changed)
1978 graphics::GCache::get().changeDisplay(true);
1981 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1982 x11_darkname = x11_name;
1985 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1987 current_view_->message(
1988 bformat(_("Set-color \"%1$s\" failed "
1989 "- color is undefined or "
1990 "may not be redefined"),
1991 from_utf8(lyx_name)));
1994 // Make sure we don't keep old colors in cache.
1995 d->color_cache_.clear();
1996 // Update the current view
1997 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2001 case LFUN_LYXRC_APPLY: {
2002 // reset active key sequences, since the bindings
2003 // are updated (bug 6064)
2005 LyXRC const lyxrc_orig = lyxrc;
2007 istringstream ss(to_utf8(cmd.argument()));
2008 bool const success = lyxrc.read(ss);
2011 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
2012 << "Unable to read lyxrc data"
2017 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
2019 // If the request comes from the minibuffer, then we can't reset
2020 // the GUI, since that would destroy the minibuffer itself and
2021 // cause a crash, since we are currently in one of the methods of
2022 // GuiCommandBuffer. See bug #8540.
2023 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
2026 // FIXME Unfortunately, that leaves a bug here, since we cannot
2027 // reset the GUI in this case. If the changes to lyxrc affected the
2028 // UI, then, nothing would happen. This seems fairly unlikely, but
2029 // it definitely is a bug.
2031 dr.forceBufferUpdate();
2035 case LFUN_COMMAND_PREFIX:
2036 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2041 d->meta_fake_bit = NoModifier;
2042 GuiView * gv = currentView();
2043 if (gv && gv->currentBufferView())
2044 // cancel any selection
2045 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2046 dr.setMessage(from_ascii(N_("Cancel")));
2049 case LFUN_META_PREFIX:
2050 d->meta_fake_bit = AltModifier;
2051 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2054 // --- Menus -----------------------------------------------
2055 case LFUN_RECONFIGURE:
2056 // argument is any additional parameter to the configure.py command
2057 reconfigure(to_utf8(cmd.argument()));
2060 // --- lyxserver commands ----------------------------
2061 case LFUN_SERVER_GET_FILENAME: {
2062 if (current_view_ && current_view_->documentBufferView()) {
2063 docstring const fname = from_utf8(
2064 current_view_->documentBufferView()->buffer().absFileName());
2065 dr.setMessage(fname);
2066 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2068 dr.setMessage(docstring());
2069 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2074 case LFUN_SERVER_NOTIFY: {
2075 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2076 dr.setMessage(dispatch_buffer);
2077 theServer().notifyClient(to_utf8(dispatch_buffer));
2081 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2082 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2088 string rest = split(argument, countstr, ' ');
2089 int const count = convert<int>(countstr);
2090 // an arbitrary number to limit number of iterations
2091 int const max_iter = 10000;
2092 if (count > max_iter) {
2093 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2096 for (int i = 0; i < count; ++i) {
2097 FuncRequest lfun = lyxaction.lookupFunc(rest);
2098 lfun.allowAsync(false);
2105 case LFUN_COMMAND_SEQUENCE: {
2106 // argument contains ';'-terminated commands
2107 string arg = argument;
2108 // FIXME: this LFUN should also work without any view.
2109 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2110 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2111 // This handles undo groups automagically
2112 UndoGroupHelper ugh(buffer);
2113 while (!arg.empty()) {
2115 arg = split(arg, first, ';');
2116 FuncRequest func(lyxaction.lookupFunc(first));
2117 func.allowAsync(false);
2118 func.setOrigin(cmd.origin());
2124 case LFUN_BUFFER_FORALL: {
2125 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2126 funcToRun.allowAsync(false);
2128 map<Buffer *, GuiView *> views_lVisible;
2129 map<GuiView *, Buffer *> activeBuffers;
2131 QList<GuiView *> allViews = d->views_.values();
2133 // this for does not modify any buffer. It just collects info on local
2134 // visibility of buffers and on which buffer is active in each view.
2135 Buffer * const last = theBufferList().last();
2136 for(GuiView * view : allViews) {
2137 // all of the buffers might be locally hidden. That is, there is no
2139 if (!view || !view->currentBufferView())
2140 activeBuffers[view] = nullptr;
2142 activeBuffers[view] = &view->currentBufferView()->buffer();
2144 // find out if each is locally visible or locally hidden.
2145 // we don't use a for loop as the buffer list cycles.
2146 Buffer * b = theBufferList().first();
2148 bool const locallyVisible = view && view->workArea(*b);
2149 if (locallyVisible) {
2150 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2151 // only need to overwrite/add if we don't already know a buffer is globally
2152 // visible or we do know but we would prefer to dispatch LFUN from the
2153 // current view because of cursor position issues.
2154 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2155 views_lVisible[b] = view;
2159 b = theBufferList().next(b);
2163 GuiView * const homeView = currentView();
2164 Buffer * b = theBufferList().first();
2165 Buffer * nextBuf = nullptr;
2166 int numProcessed = 0;
2169 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2171 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2173 // first change to a view where b is locally visible, preferably current_view_.
2174 GuiView * const vLv = views_lVisible[b];
2176 lyx::dispatch(funcToRun);
2184 // put things back to how they were (if possible).
2185 for (GuiView * view : allViews) {
2186 Buffer * originalBuf = activeBuffers[view];
2187 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2188 if (theBufferList().isLoaded(originalBuf))
2189 view->setBuffer(originalBuf);
2191 homeView->setFocus();
2193 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2197 case LFUN_COMMAND_ALTERNATIVES: {
2198 // argument contains ';'-terminated commands
2199 string arg = argument;
2200 while (!arg.empty()) {
2202 arg = split(arg, first, ';');
2203 FuncRequest func(lyxaction.lookupFunc(first));
2204 func.setOrigin(cmd.origin());
2205 FuncStatus const stat = getStatus(func);
2206 if (stat.enabled()) {
2216 if (theTopLevelCmdDef().lock(argument, func)) {
2217 func.setOrigin(cmd.origin());
2219 theTopLevelCmdDef().release(argument);
2221 if (func.action() == LFUN_UNKNOWN_ACTION) {
2222 // unknown command definition
2223 lyxerr << "Warning: unknown command definition `"
2227 // recursion detected
2228 lyxerr << "Warning: Recursion in the command definition `"
2229 << argument << "' detected"
2236 case LFUN_IF_RELATIVES: {
2237 string const lfun = to_utf8(cmd.argument());
2238 FuncRequest func(lyxaction.lookupFunc(lfun));
2239 func.setOrigin(cmd.origin());
2240 FuncStatus const stat = getStatus(func);
2241 if (stat.enabled()) {
2248 case LFUN_PREFERENCES_SAVE:
2249 lyxrc.write(support::makeAbsPath("preferences",
2250 package().user_support().absFileName()), false);
2253 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2254 string const fname = addName(addPath(package().user_support().absFileName(),
2255 "templates/"), "defaults.lyx");
2256 Buffer defaults(fname);
2258 istringstream ss(argument);
2263 // We need to make sure that, after we recreat the DocumentClass,
2264 // which we do in readHeader, we apply it to the document itself.
2265 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2266 int const unknown_tokens = defaults.readHeader(lex);
2267 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2268 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2269 cap::switchBetweenClasses(olddc, newdc, theinset);
2271 if (unknown_tokens != 0) {
2272 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2273 << unknown_tokens << " unknown token"
2274 << (unknown_tokens == 1 ? "" : "s")
2278 if (defaults.writeFile(FileName(defaults.absFileName())))
2279 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2280 makeDisplayPath(fname)));
2283 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2288 case LFUN_BOOKMARK_GOTO:
2289 // go to bookmark, open unopened file and switch to buffer if necessary
2290 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2291 dr.screenUpdate(Update::Force | Update::FitCursor);
2294 case LFUN_BOOKMARK_CLEAR:
2295 theSession().bookmarks().clear();
2296 dr.screenUpdate(Update::Force);
2299 case LFUN_DEBUG_LEVEL_SET:
2300 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2303 case LFUN_DIALOG_SHOW: {
2304 string const name = cmd.getArg(0);
2306 if ( name == "aboutlyx"
2308 || name == "texinfo"
2309 || name == "progress"
2310 || name == "compare")
2312 // work around: on Mac OS the application
2313 // is not terminated when closing the last view.
2314 // Create a new one to be able to dispatch the
2315 // LFUN_DIALOG_SHOW to this view.
2316 if (current_view_ == nullptr)
2322 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2325 current_view_->dispatch(cmd, dr);
2329 if (current_view_ && current_view_->isFullScreen()) {
2330 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2331 current_view_->menuBar()->hide();
2334 if (cmd.origin() == FuncRequest::LYXSERVER)
2335 updateCurrentView(cmd, dr);
2339 docstring GuiApplication::viewStatusMessage()
2341 // When meta-fake key is pressed, show the key sequence so far + "M-".
2342 if (d->meta_fake_bit != NoModifier)
2343 return d->keyseq.print(KeySequence::ForGui) + "M-";
2345 // Else, when a non-complete key sequence is pressed,
2346 // show the available options.
2347 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2348 return d->keyseq.printOptions(true);
2354 string GuiApplication::inputLanguageCode() const
2356 #if (QT_VERSION < 0x050000)
2357 QLocale loc = keyboardInputLocale();
2359 QLocale loc = inputMethod()->locale();
2361 //LYXERR0("input lang = " << fromqstr(loc.name()));
2362 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2366 void GuiApplication::onLocaleChanged()
2368 //LYXERR0("Change language to " << inputLanguage()->lang());
2369 if (currentView() && currentView()->currentBufferView())
2370 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2374 void GuiApplication::onPaletteChanged()
2376 colorCache().setPalette(palette());
2380 void GuiApplication::handleKeyFunc(FuncCode action)
2384 if (d->keyseq.length())
2386 GuiView * gv = currentView();
2387 LASSERT(gv && gv->currentBufferView(), return);
2388 BufferView * bv = gv->currentBufferView();
2389 bv->getIntl().getTransManager().deadkey(
2390 c, get_accent(action).accent, bv->cursor().innerText(),
2392 // Need to clear, in case the minibuffer calls these
2395 // copied verbatim from do_accent_char
2396 bv->cursor().resetAnchor();
2400 //Keep this in sync with GuiApplication::processKeySym below
2401 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2402 KeyModifier state) const
2404 // Do nothing if we have nothing
2405 if (!keysym.isOK() || keysym.isModifier())
2407 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2409 FuncRequest func = seq.addkey(keysym, state);
2410 // When not cancel or meta-fake, do the normal lookup.
2411 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2413 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2415 // Maybe user can only reach the key via holding down shift.
2416 // Let's see. But only if shift is the only modifier
2417 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2418 // If addkey looked up a command and did not find further commands then
2419 // seq has been reset at this point
2420 func = seq.addkey(keysym, NoModifier);
2422 LYXERR(Debug::KEY, " Key (queried) [action="
2423 << lyxaction.getActionName(func.action()) << "]["
2424 << seq.print(KeySequence::Portable) << ']');
2425 return func.action() != LFUN_UNKNOWN_ACTION;
2429 //Keep this in sync with GuiApplication::queryKeySym above
2430 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2432 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2434 // Do nothing if we have nothing (JMarc)
2435 if (!keysym.isOK() || keysym.isModifier()) {
2437 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2439 current_view_->restartCaret();
2443 char_type encoded_last_key = keysym.getUCSEncoded();
2445 // Do a one-deep top-level lookup for
2446 // cancel and meta-fake keys. RVDK_PATCH_5
2447 d->cancel_meta_seq.reset();
2449 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2450 LYXERR(Debug::KEY, "action first set to ["
2451 << lyxaction.getActionName(func.action()) << ']');
2453 // When not cancel or meta-fake, do the normal lookup.
2454 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2455 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2456 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2457 // remove Caps Lock and Mod2 as a modifiers
2458 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2459 LYXERR(Debug::KEY, "action now set to ["
2460 << lyxaction.getActionName(func.action()) << ']');
2463 // Don't remove this unless you know what you are doing.
2464 d->meta_fake_bit = NoModifier;
2466 // Can this happen now ?
2467 if (func.action() == LFUN_NOACTION)
2468 func = FuncRequest(LFUN_COMMAND_PREFIX);
2470 LYXERR(Debug::KEY, " Key [action="
2471 << lyxaction.getActionName(func.action()) << "]["
2472 << d->keyseq.print(KeySequence::Portable) << ']');
2474 // already here we know if it any point in going further
2475 // why not return already here if action == -1 and
2476 // num_bytes == 0? (Lgb)
2478 if (d->keyseq.length() > 1 && current_view_)
2479 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2482 // Maybe user can only reach the key via holding down shift.
2483 // Let's see. But only if shift is the only modifier
2484 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2485 LYXERR(Debug::KEY, "Trying without shift");
2486 // If addkey looked up a command and did not find further commands then
2487 // seq has been reset at this point
2488 func = d->keyseq.addkey(keysym, NoModifier);
2489 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2492 if (func.action() == LFUN_UNKNOWN_ACTION) {
2493 // We didn't match any of the key sequences.
2494 // See if it's normal insertable text not already
2495 // covered by a binding
2496 if (keysym.isText() && d->keyseq.length() == 1) {
2497 // Non-printable characters (such as ASCII control characters)
2498 // must not be inserted (#5704)
2499 if (!isPrintable(encoded_last_key)) {
2500 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2502 current_view_->restartCaret();
2505 // The following modifier check is not needed on Mac.
2506 // The keysym is either not text or it is different
2507 // from the non-modifier keysym. See #9875 for the
2508 // broken alt-modifier effect of having this code active.
2509 #if !defined(Q_OS_MAC)
2510 // If a non-Shift Modifier is used we have a non-bound key sequence
2511 // (such as Alt+j = j). This should be omitted (#5575).
2512 // On Windows, AltModifier and ControlModifier are both
2513 // set when AltGr is pressed. Therefore, in order to not
2514 // break AltGr-bound symbols (see #5575 for details),
2515 // unbound Ctrl+Alt key sequences are allowed.
2516 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2517 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2518 && !(state & AltModifier && state & ControlModifier)
2522 if (current_view_) {
2523 current_view_->message(_("Unknown function."));
2524 current_view_->restartCaret();
2529 // Since all checks above were passed, we now really have text that
2530 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2531 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2533 LYXERR(Debug::KEY, "isText() is true, inserting.");
2534 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2536 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2537 if (current_view_) {
2538 current_view_->message(_("Unknown function."));
2539 current_view_->restartCaret();
2545 if (func.action() == LFUN_SELF_INSERT) {
2546 if (encoded_last_key != 0) {
2547 docstring const arg(1, encoded_last_key);
2548 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2549 FuncRequest::KEYBOARD));
2550 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2553 processFuncRequest(func);
2557 void GuiApplication::processFuncRequest(FuncRequest const & func)
2559 lyx::dispatch(func);
2563 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2565 addToFuncRequestQueue(func);
2566 processFuncRequestQueueAsync();
2570 void GuiApplication::processFuncRequestQueue()
2572 while (!d->func_request_queue_.empty()) {
2573 // take the item from the stack _before_ processing the
2574 // request in order to avoid race conditions from nested
2575 // or parallel requests (see #10406)
2576 FuncRequest const fr(d->func_request_queue_.front());
2577 d->func_request_queue_.pop();
2578 processFuncRequest(fr);
2583 void GuiApplication::processFuncRequestQueueAsync()
2585 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2589 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2591 d->func_request_queue_.push(func);
2595 void GuiApplication::resetGui()
2597 // Set the language defined by the user.
2601 if (!readUIFile(toqstr(lyxrc.ui_file)))
2602 // Gives some error box here.
2605 if (d->global_menubar_)
2606 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2608 QHash<int, GuiView *>::iterator it;
2609 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2612 gv->setLayoutDirection(layoutDirection());
2616 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2620 bool GuiApplication::rtlContext() const
2622 if (current_view_ && current_view_->currentBufferView()) {
2623 BufferView const * bv = current_view_->currentBufferView();
2624 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2626 return layoutDirection() == Qt::RightToLeft;
2630 void GuiApplication::createView(int view_id)
2632 createView(QString(), true, view_id);
2636 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2639 // release the keyboard which might have been grabbed by the global
2640 // menubar on Mac to catch shortcuts even without any GuiView.
2641 if (d->global_menubar_)
2642 d->global_menubar_->releaseKeyboard();
2646 while (d->views_.find(id) != d->views_.end())
2649 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2650 GuiView * view = new GuiView(id);
2651 // `view' is the new current_view_. Tell coverity that is is not 0.
2652 LATTEST(current_view_);
2654 d->views_[id] = view;
2658 setActiveWindow(view);
2661 if (!geometry_arg.isEmpty()) {
2662 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2666 #if QT_VERSION < 0x060000
2667 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2668 re.indexIn(geometry_arg);
2669 w = re.cap(1).toInt();
2670 h = re.cap(2).toInt();
2671 x = re.cap(3).toInt();
2672 y = re.cap(4).toInt();
2673 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2674 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2676 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2677 QRegularExpressionMatch match = re.match(geometry_arg);
2678 w = match.captured(1).toInt();
2679 h = match.captured(2).toInt();
2680 x = match.captured(3).toInt();
2681 y = match.captured(4).toInt();
2682 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2683 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2685 // Set initial geometry such that we can get the frame size.
2686 view->setGeometry(x, y, w, h);
2687 int framewidth = view->geometry().x() - view->x();
2688 int titleheight = view->geometry().y() - view->y();
2689 // Negative displacements must be interpreted as distances
2690 // from the right or bottom screen borders.
2691 if (sx == '-' || sy == '-') {
2692 #if QT_VERSION < 0x060000
2693 QRect rec = QApplication::desktop()->screenGeometry();
2695 QRect rec = QGuiApplication::primaryScreen()->geometry();
2698 x += rec.width() - w - framewidth;
2700 y += rec.height() - h - titleheight;
2701 view->setGeometry(x, y, w, h);
2703 // Make sure that the left and top frame borders are visible.
2704 if (view->x() < 0 || view->y() < 0) {
2709 view->setGeometry(x, y, w, h);
2717 bool GuiApplication::unhide(Buffer * buf)
2721 currentView()->setBuffer(buf, false);
2726 Clipboard & GuiApplication::clipboard()
2728 return d->clipboard_;
2732 Selection & GuiApplication::selection()
2734 return d->selection_;
2738 FontLoader & GuiApplication::fontLoader()
2740 return d->font_loader_;
2744 Toolbars const & GuiApplication::toolbars() const
2746 return d->toolbars_;
2750 Toolbars & GuiApplication::toolbars()
2752 return d->toolbars_;
2756 Menus const & GuiApplication::menus() const
2762 Menus & GuiApplication::menus()
2768 bool GuiApplication::needsBackingStore() const
2770 /* Qt on macOS and Wayland does not respect the
2771 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2772 * store at each update. Therefore, we use our own backing store
2773 * in these two cases. It is also possible to force the use of the
2774 * backing store for cases like x11 with transparent WM themes.
2776 return platformName() == "cocoa" || platformName().contains("wayland");
2780 QList<int> GuiApplication::viewIds() const
2782 return d->views_.keys();
2786 ColorCache & GuiApplication::colorCache()
2788 return d->color_cache_;
2792 int GuiApplication::exec()
2794 // asynchronously handle batch commands. This event will be in
2795 // the event queue in front of other asynchronous events. Hence,
2796 // we can assume in the latter that the gui is setup already.
2797 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2799 return QApplication::exec();
2803 void GuiApplication::exit(int status)
2805 QApplication::exit(status);
2809 void GuiApplication::setGuiLanguage()
2813 // install translation file for Qt built-in dialogs
2814 QString const language_name = QString("qt_") + theLocale.name();
2815 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2816 // Short-named translator can be loaded from a long name, but not the
2817 // opposite. Therefore, long name should be used without truncation.
2818 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2819 if (!d->qt_trans_.load(language_name,
2820 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2821 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2823 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2825 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2828 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2832 switch (theLocale.language()) {
2833 case QLocale::Arabic :
2834 case QLocale::Hebrew :
2835 case QLocale::Persian :
2836 case QLocale::Urdu :
2837 setLayoutDirection(Qt::RightToLeft);
2840 setLayoutDirection(Qt::LeftToRight);
2845 void GuiApplication::execBatchCommands()
2850 if (!readUIFile(toqstr(lyxrc.ui_file)))
2851 // Gives some error box here.
2855 #if QT_VERSION > 0x040600
2856 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2858 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2859 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2861 // Create the global default menubar which is shown for the dialogs
2862 // and if no GuiView is visible.
2863 // This must be done after the session was recovered to know the "last files".
2864 d->global_menubar_ = new QMenuBar(0);
2865 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2868 lyx::execBatchCommands();
2872 QAbstractItemModel * GuiApplication::languageModel()
2874 if (d->language_model_)
2875 return d->language_model_;
2877 QStandardItemModel * lang_model = new QStandardItemModel(this);
2878 lang_model->insertColumns(0, 3);
2879 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2880 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2881 Languages::const_iterator it = lyx::languages.begin();
2882 Languages::const_iterator end = lyx::languages.end();
2883 for (; it != end; ++it) {
2884 int current_row = lang_model->rowCount();
2885 lang_model->insertRows(current_row, 1);
2886 QModelIndex pl_item = lang_model->index(current_row, 0);
2887 QModelIndex sp_item = lang_model->index(current_row, 1);
2888 QModelIndex th_item = lang_model->index(current_row, 2);
2889 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2890 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2891 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2892 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2893 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2894 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2895 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2896 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2897 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2898 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2900 d->language_model_ = new QSortFilterProxyModel(this);
2901 d->language_model_->setSourceModel(lang_model);
2902 d->language_model_->setSortLocaleAware(true);
2903 return d->language_model_;
2907 void GuiApplication::restoreGuiSession()
2909 if (!lyxrc.load_session)
2912 Session & session = theSession();
2913 LastOpenedSection::LastOpened const & lastopened =
2914 session.lastOpened().getfiles();
2916 validateCurrentView();
2918 FileName active_file;
2919 // do not add to the lastfile list since these files are restored from
2920 // last session, and should be already there (regular files), or should
2921 // not be added at all (help files).
2922 for (auto const & last : lastopened) {
2923 FileName const & file_name = last.file_name;
2924 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2925 && current_view_->documentBufferView() != nullptr)) {
2926 string const & fname = file_name.absFileName();
2927 createView(support::checksum(fname));
2929 current_view_->loadDocument(file_name, false);
2932 active_file = file_name;
2935 // Restore last active buffer
2936 Buffer * buffer = theBufferList().getBuffer(active_file);
2937 if (buffer && current_view_)
2938 current_view_->setBuffer(buffer);
2940 // clear this list to save a few bytes of RAM
2941 session.lastOpened().clear();
2945 QString const GuiApplication::romanFontName()
2948 font.setStyleHint(QFont::Serif);
2949 font.setFamily("serif");
2951 return QFontInfo(font).family();
2955 QString const GuiApplication::sansFontName()
2958 font.setStyleHint(QFont::SansSerif);
2959 font.setFamily("sans");
2961 return QFontInfo(font).family();
2965 QString const GuiApplication::typewriterFontName()
2967 return QFontInfo(typewriterSystemFont()).family();
2972 // We cannot use QFont::fixedPitch() because it doesn't
2973 // return the fact but only if it is requested.
2974 static bool isFixedPitch(const QFont & font) {
2975 const QFontInfo fi(font);
2976 return fi.fixedPitch();
2981 QFont const GuiApplication::typewriterSystemFont()
2983 #if QT_VERSION >= 0x050200
2984 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2986 QFont font("monospace");
2988 if (!isFixedPitch(font)) {
2989 // try to enforce a real monospaced font
2990 font.setStyleHint(QFont::Monospace);
2991 if (!isFixedPitch(font)) {
2992 font.setStyleHint(QFont::TypeWriter);
2993 if (!isFixedPitch(font)) font.setFamily("courier");
2997 // On a Mac the result is too small and it's not practical to
2998 // rely on Qtconfig utility to change the system settings of Qt.
2999 font.setPointSize(12);
3005 void GuiApplication::handleRegularEvents()
3007 ForkedCallsController::handleCompletedProcesses();
3011 bool GuiApplication::event(QEvent * e)
3014 case QEvent::FileOpen: {
3015 // Open a file; this happens only on Mac OS X for now.
3017 // We do this asynchronously because on startup the batch
3018 // commands are not executed here yet and the gui is not ready
3020 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
3021 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
3022 processFuncRequestAsync(fr);
3026 #if (QT_VERSION < 0x050000)
3027 // Qt5 uses a signal for that, see above.
3028 case QEvent::KeyboardLayoutChange:
3029 //LYXERR0("keyboard change");
3030 if (currentView() && currentView()->currentBufferView())
3031 currentView()->currentBufferView()->cursor().setLanguageFromInput();
3035 case QEvent::ApplicationPaletteChange: {
3036 // runtime switch from/to dark mode
3038 return QApplication::event(e);
3041 return QApplication::event(e);
3046 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3049 return QApplication::notify(receiver, event);
3051 catch (ExceptionMessage const & e) {
3053 case ErrorException:
3055 setQuitOnLastWindowClosed(false);
3057 Alert::error(e.title_, e.details_);
3059 // Properly crash in debug mode in order to get a useful backtrace.
3062 // In release mode, try to exit gracefully.
3064 // FIXME: GCC 7 thinks we can fall through here. Can we?
3066 case BufferException: {
3067 if (!current_view_ || !current_view_->documentBufferView())
3069 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3070 docstring details = e.details_ + '\n';
3071 details += buf->emergencyWrite();
3072 theBufferList().release(buf);
3073 details += "\n" + _("The current document was closed.");
3074 Alert::error(e.title_, details);
3077 case WarningException:
3078 Alert::warning(e.title_, e.details_);
3082 catch (exception const & e) {
3083 docstring s = _("LyX has caught an exception, it will now "
3084 "attempt to save all unsaved documents and exit."
3086 s += from_ascii(e.what());
3087 Alert::error(_("Software exception Detected"), s);
3091 docstring s = _("LyX has caught some really weird exception, it will "
3092 "now attempt to save all unsaved documents and exit.");
3093 Alert::error(_("Software exception Detected"), s);
3100 bool GuiApplication::isInDarkMode()
3102 return colorCache().isDarkMode();
3106 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3108 QColor const & qcol = d->color_cache_.get(col);
3109 if (!qcol.isValid()) {
3115 rgbcol.r = qcol.red();
3116 rgbcol.g = qcol.green();
3117 rgbcol.b = qcol.blue();
3122 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3124 QColor const qcol(lcolor.getX11HexName(col).c_str());
3125 if (!qcol.isValid()) {
3131 rgbcol.r = qcol.red();
3132 rgbcol.g = qcol.green();
3133 rgbcol.b = qcol.blue();
3138 string const GuiApplication::hexName(ColorCode col)
3140 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3144 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3146 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3147 d->socket_notifiers_[fd] = sn;
3148 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3152 void GuiApplication::socketDataReceived(int fd)
3154 d->socket_notifiers_[fd]->func_();
3158 void GuiApplication::unregisterSocketCallback(int fd)
3160 d->socket_notifiers_.take(fd)->setEnabled(false);
3164 void GuiApplication::commitData(QSessionManager & sm)
3166 /** The implementation is required to avoid an application exit
3167 ** when session state save is triggered by session manager.
3168 ** The default implementation sends a close event to all
3169 ** visible top level widgets when session management allows
3171 ** We are changing that to check the state of each buffer in all
3172 ** views and ask the users what to do if buffers are dirty.
3173 ** Furthermore, we save the session state.
3174 ** We do NOT close the views here since the user still can cancel
3175 ** the logout process (see #9277); also, this would hide LyX from
3176 ** an OSes own session handling (application restoration).
3178 #ifdef QT_NO_SESSIONMANAGER
3180 #warning Qt is compiled without session manager
3182 #pragma message("warning: Qt is compiled without session manager")
3186 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3194 void GuiApplication::unregisterView(GuiView * gv)
3196 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3197 d->views_.remove(gv->id());
3198 if (current_view_ == gv)
3199 current_view_ = nullptr;
3204 bool GuiApplication::closeAllViews()
3206 if (d->views_.empty())
3209 // When a view/window was closed before without quitting LyX, there
3210 // are already entries in the lastOpened list.
3211 theSession().lastOpened().clear();
3213 QList<GuiView *> const views = d->views_.values();
3214 for (GuiView * view : views) {
3215 if (!view->closeScheduled())
3224 bool GuiApplication::prepareAllViewsForLogout()
3226 if (d->views_.empty())
3229 QList<GuiView *> const views = d->views_.values();
3230 for (GuiView * view : views) {
3231 if (!view->prepareAllBuffersForLogout())
3239 GuiView & GuiApplication::view(int id) const
3241 LAPPERR(d->views_.contains(id));
3242 return *d->views_.value(id);
3246 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3248 QList<GuiView *> const views = d->views_.values();
3249 for (GuiView * view : views)
3250 view->hideDialog(name, inset);
3254 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3256 Buffer const * buf = nullptr;
3257 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3258 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3259 if (Buffer const * ptr = (*it)->updateInset(inset))
3266 bool GuiApplication::searchMenu(FuncRequest const & func,
3267 docstring_list & names) const
3269 BufferView * bv = nullptr;
3271 bv = current_view_->currentBufferView();
3272 return d->menus_.searchMenu(func, names, bv);
3276 bool GuiApplication::hasBufferView() const
3278 return (current_view_ && current_view_->currentBufferView());
3282 // Ensure that a file is read only once (prevents include loops)
3283 static QStringList uifiles;
3284 // store which ui files define Toolbars
3285 static QStringList toolbar_uifiles;
3288 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3299 LexerKeyword uitags[] = {
3300 { "format", ui_format },
3301 { "include", ui_include },
3302 { "menuset", ui_menuset },
3303 { "toolbars", ui_toolbars },
3304 { "toolbarset", ui_toolbarset }
3308 lex.setFile(ui_path);
3310 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3314 if (lyxerr.debugging(Debug::PARSER))
3315 lex.printTable(lyxerr);
3318 // format before introduction of format tag
3319 unsigned int format = 0;
3320 while (lex.isOK()) {
3321 int const status = lex.lex();
3323 // we have to do this check here, outside the switch,
3324 // because otherwise we would start reading include files,
3325 // e.g., if the first tag we hit was an include tag.
3326 if (status == ui_format)
3328 format = lex.getInteger();
3332 // this will trigger unless the first tag we hit is a format
3333 // tag, with the right format.
3334 if (format != LFUN_FORMAT)
3335 return FormatMismatch;
3338 case Lexer::LEX_FEOF:
3343 QString const file = toqstr(lex.getString());
3344 bool const success = readUIFile(file, true);
3346 LYXERR0("Failed to read included file: " << fromqstr(file));
3353 d->menus_.read(lex);
3357 d->toolbars_.readToolbars(lex);
3361 d->toolbars_.readToolbarSettings(lex);
3362 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3366 if (!rtrim(lex.getString()).empty())
3367 lex.printError("LyX::ReadUIFile: "
3368 "Unknown menu tag: `$$Token'");
3370 LYXERR0("Error with status: " << status);
3376 return (error ? ReadError : ReadOK);
3380 bool GuiApplication::readUIFile(QString const & name, bool include)
3382 LYXERR(Debug::INIT, "About to read " << name << "...");
3386 ui_path = libFileSearch("ui", name, "inc");
3387 if (ui_path.empty())
3388 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3390 ui_path = libFileSearch("ui", name, "ui");
3393 if (ui_path.empty()) {
3394 static const QString defaultUIFile = "default";
3395 LYXERR(Debug::INIT, "Could not find " << name);
3397 Alert::warning(_("Could not find UI definition file"),
3398 bformat(_("Error while reading the included file\n%1$s\n"
3399 "Please check your installation."), qstring_to_ucs4(name)));
3402 if (name == defaultUIFile) {
3403 LYXERR(Debug::INIT, "Could not find default UI file!!");
3404 Alert::warning(_("Could not find default UI file"),
3405 _("LyX could not find the default UI file!\n"
3406 "Please check your installation."));
3409 Alert::warning(_("Could not find UI definition file"),
3410 bformat(_("Error while reading the configuration file\n%1$s\n"
3411 "Falling back to default.\n"
3412 "Please look under Tools>Preferences>User Interface and\n"
3413 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3414 return readUIFile(defaultUIFile, false);
3417 QString const uifile = toqstr(ui_path.absFileName());
3418 if (uifiles.contains(uifile)) {
3420 // We are reading again the top uifile so reset the safeguard:
3423 d->toolbars_.reset();
3425 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3426 << "Is this an include loop?");
3430 uifiles.push_back(uifile);
3432 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3434 ReturnValues retval = readUIFile(ui_path);
3436 if (retval == FormatMismatch) {
3437 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3438 TempFile tmp("convertXXXXXX.ui");
3439 FileName const tempfile = tmp.name();
3440 bool const success = prefs2prefs(ui_path, tempfile, true);
3442 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3443 " to format " << LFUN_FORMAT << ".");
3445 retval = readUIFile(tempfile);
3449 if (retval != ReadOK) {
3450 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3458 settings.beginGroup("ui_files");
3459 bool touched = false;
3460 for (int i = 0; i != uifiles.size(); ++i) {
3461 QFileInfo fi(uifiles[i]);
3462 QDateTime const date_value = fi.lastModified();
3463 QString const name_key = QString::number(i);
3464 // if an ui file which defines Toolbars has changed,
3465 // we have to reset the settings
3466 if (toolbar_uifiles.contains(uifiles[i])
3467 && (!settings.contains(name_key)
3468 || settings.value(name_key).toString() != uifiles[i]
3469 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3471 settings.setValue(name_key, uifiles[i]);
3472 settings.setValue(name_key + "/date", date_value);
3475 settings.endGroup();
3477 settings.remove("views");
3483 void GuiApplication::onLastWindowClosed()
3485 if (d->global_menubar_)
3486 d->global_menubar_->grabKeyboard();
3490 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3491 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3493 std::string name = "unknown";
3495 case Qt::ApplicationSuspended:
3496 name = "ApplicationSuspended";
3498 case Qt::ApplicationHidden:
3499 name = "ApplicationHidden";
3501 case Qt::ApplicationInactive:
3502 name = "ApplicationInactive";
3504 case Qt::ApplicationActive:
3505 name = "ApplicationActive";
3506 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3507 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3508 if (d->views_.empty() && d->last_state_ == state) {
3509 LYXERR(Debug::GUI, "Open new window...");
3514 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3515 d->last_state_ = state;
3520 void GuiApplication::startLongOperation() {
3521 d->key_checker_.start();
3525 bool GuiApplication::longOperationCancelled() {
3526 return d->key_checker_.pressed();
3530 void GuiApplication::stopLongOperation() {
3531 d->key_checker_.stop();
3535 bool GuiApplication::longOperationStarted() {
3536 return d->key_checker_.started();
3540 ////////////////////////////////////////////////////////////////////////
3542 // X11 specific stuff goes here...
3545 bool GuiApplication::x11EventFilter(XEvent * xev)
3550 switch (xev->type) {
3551 case SelectionRequest: {
3552 if (xev->xselectionrequest.selection != XA_PRIMARY)
3554 LYXERR(Debug::SELECTION, "X requested selection.");
3555 BufferView * bv = current_view_->currentBufferView();
3557 docstring const sel = bv->requestSelection();
3559 d->selection_.put(sel);
3560 // Refresh the selection request timestamp.
3561 // We have to do this by ourselves as Qt seems
3562 // not doing that, maybe because of our
3563 // "persistent selection" implementation
3564 // (see comments in GuiSelection.cpp).
3565 XSelectionEvent nev;
3566 nev.type = SelectionNotify;
3567 nev.display = xev->xselectionrequest.display;
3568 nev.requestor = xev->xselectionrequest.requestor;
3569 nev.selection = xev->xselectionrequest.selection;
3570 nev.target = xev->xselectionrequest.target;
3571 nev.property = 0L; // None
3572 nev.time = CurrentTime;
3573 XSendEvent(QX11Info::display(),
3574 nev.requestor, False, 0,
3575 reinterpret_cast<XEvent *>(&nev));
3581 case SelectionClear: {
3582 if (xev->xselectionclear.selection != XA_PRIMARY)
3584 LYXERR(Debug::SELECTION, "Lost selection.");
3585 BufferView * bv = current_view_->currentBufferView();
3587 bv->clearSelection();
3593 #elif defined(QPA_XCB)
3594 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3595 void * message, long *)
3597 if (!current_view_ || eventType != "xcb_generic_event_t")
3600 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3602 switch (ev->response_type) {
3603 case XCB_SELECTION_REQUEST: {
3604 xcb_selection_request_event_t * srev =
3605 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3606 if (srev->selection != XCB_ATOM_PRIMARY)
3608 LYXERR(Debug::SELECTION, "X requested selection.");
3609 BufferView * bv = current_view_->currentBufferView();
3611 docstring const sel = bv->requestSelection();
3613 d->selection_.put(sel);
3614 #ifdef HAVE_QT5_X11_EXTRAS
3615 // Refresh the selection request timestamp.
3616 // We have to do this by ourselves as Qt seems
3617 // not doing that, maybe because of our
3618 // "persistent selection" implementation
3619 // (see comments in GuiSelection.cpp).
3620 // It is expected that every X11 event is
3621 // 32 bytes long, even if not all 32 bytes are
3623 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3624 struct alignas(32) padded_event
3625 : xcb_selection_notify_event_t {};
3626 padded_event nev = {};
3627 nev.response_type = XCB_SELECTION_NOTIFY;
3628 nev.requestor = srev->requestor;
3629 nev.selection = srev->selection;
3630 nev.target = srev->target;
3631 nev.property = XCB_NONE;
3632 nev.time = XCB_CURRENT_TIME;
3633 xcb_connection_t * con = QX11Info::connection();
3634 xcb_send_event(con, 0, srev->requestor,
3635 XCB_EVENT_MASK_NO_EVENT,
3636 reinterpret_cast<char const *>(&nev));
3644 case XCB_SELECTION_CLEAR: {
3645 xcb_selection_clear_event_t * scev =
3646 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3647 if (scev->selection != XCB_ATOM_PRIMARY)
3649 LYXERR(Debug::SELECTION, "Lost selection.");
3650 BufferView * bv = current_view_->currentBufferView();
3652 bv->clearSelection();
3660 } // namespace frontend
3663 void hideDialogs(std::string const & name, Inset * inset)
3666 frontend::guiApp->hideDialogs(name, inset);
3670 ////////////////////////////////////////////////////////////////////
3674 ////////////////////////////////////////////////////////////////////
3676 frontend::FontLoader & theFontLoader()
3678 LAPPERR(frontend::guiApp);
3679 return frontend::guiApp->fontLoader();
3683 frontend::FontMetrics const & theFontMetrics(Font const & f)
3685 return theFontMetrics(f.fontInfo());
3689 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3691 LAPPERR(frontend::guiApp);
3692 return frontend::guiApp->fontLoader().metrics(f);
3696 ////////////////////////////////////////////////////////////////////
3700 ////////////////////////////////////////////////////////////////////
3702 frontend::Clipboard & theClipboard()
3704 LAPPERR(frontend::guiApp);
3705 return frontend::guiApp->clipboard();
3709 frontend::Selection & theSelection()
3711 LAPPERR(frontend::guiApp);
3712 return frontend::guiApp->selection();
3718 #include "moc_GuiApplication.cpp"