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);
558 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
563 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
565 if (!f.argument().empty()) {
566 // if there are arguments, first search an icon which name is the full thing
567 QString name = lfunname + ' ' + toqstr(f.argument());
568 name.replace(' ', '_');
569 name.replace(';', '_');
570 name.replace('\\', "backslash");
572 QString alias = getAlias(name);
576 // then special default icon for some lfuns
577 switch (f.action()) {
578 case LFUN_MATH_INSERT:
579 names << "math/" + findImg(toqstr(f.argument()).mid(1));
581 case LFUN_MATH_DELIM:
582 case LFUN_MATH_BIGDELIM:
583 names << "math/" + findImg(toqstr(f.argument()));
586 names << "commands/" + toqstr(f.argument());
588 case LFUN_COMMAND_ALTERNATIVES: {
589 // use the first of the alternative commands
591 docstring dummy = split(f.argument(), firstcom, ';');
592 QString name1 = toqstr(firstcom);
593 name1.replace(' ', '_');
594 name1.replace(';', '_');
595 name1.replace('\\', "backslash");
604 // next thing to try is function name alone
606 QString alias = getAlias(lfunname);
607 if (alias != lfunname)
610 // and finally maybe the unknown icon
614 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
615 // The folders where icons are searched for
616 QStringList imagedirs;
617 imagedirs << "images/ipa/" << "images/";
618 // This is used to search for rtl version of icons which have the +rtl suffix.
619 QStringList suffixes;
622 suffixes << QString();
624 for (QString const & imagedir : imagedirs)
625 for (QString const & name : names)
626 for (QString const & suffix : suffixes) {
627 QString id = imagedir;
628 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
629 if (fname.exists()) {
630 docstring const fpath = fname.absoluteFilePath();
631 res.filepath = toqstr(fname.absFileName());
632 // these icons are subject to inversion in dark mode
633 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
634 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
635 res.swap = rtl && suffix.isEmpty();
640 LYXERR(Debug::GUI, "Cannot find icon for command \""
641 << lyxaction.getActionName(f.action())
642 << '(' << to_utf8(f.argument()) << ")\"");
648 QPixmap prepareForDarkMode(QPixmap pixmap)
650 QPalette palette = QPalette();
651 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
652 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
654 // guess whether we are in dark mode
655 if (text_color.black() > bg_color.black())
656 // not in dark mode, do nothing
659 // create a layer with black text turned to QPalette::WindowText
660 QPixmap black_overlay(pixmap.size());
661 black_overlay.fill(text_color);
662 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
664 // create a layer with blue text turned to lighter blue
665 QPixmap blue_overlay(pixmap.size());
666 QColor math_blue(0, 0, 255);
667 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
668 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
670 // create a layer with ("latex") red text turned to lighter red
671 QPixmap red_overlay(pixmap.size());
672 QColor math_red(128, 0, 0);
673 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
674 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
676 // put layers on top of existing pixmap
677 QPainter painter(&pixmap);
678 painter.drawPixmap(pixmap.rect(), black_overlay);
679 painter.drawPixmap(pixmap.rect(), blue_overlay);
680 painter.drawPixmap(pixmap.rect(), red_overlay);
686 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
688 QString imagedir = path;
689 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
690 QString fpath = toqstr(fname.absFileName());
691 QPixmap pixmap = QPixmap();
693 if (pixmap.load(fpath)) {
694 if (fpath.contains("math") || fpath.contains("ipa")
695 || fpath.contains("bullets"))
696 return prepareForDarkMode(pixmap);
700 bool const list = ext.contains(",");
701 LYXERR(Debug::GUI, "Cannot load pixmap \""
702 << path << "/" << name << "." << (list ? "{" : "") << ext
703 << (list ? "}" : "") << "\".");
709 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
711 #if (QT_VERSION >= 0x040600)
712 if (lyxrc.use_system_theme_icons) {
713 // use the icons from system theme that are available
714 QString action = toqstr(lyxaction.getActionName(f.action()));
715 if (!f.argument().empty())
716 action += " " + toqstr(f.argument());
717 QString const theme_icon = themeIconName(action);
718 if (QIcon::hasThemeIcon(theme_icon)) {
719 QIcon const thmicn = QIcon::fromTheme(theme_icon);
720 if (!thmicn.isNull())
726 IconInfo icondata = iconInfo(f, unknown, rtl);
727 if (icondata.filepath.isEmpty())
730 //LYXERR(Debug::GUI, "Found icon: " << icon);
731 QPixmap pixmap = QPixmap();
732 if (!pixmap.load(icondata.filepath)) {
733 LYXERR0("Cannot load icon " << icondata.filepath << ".");
738 pixmap = prepareForDarkMode(pixmap);
741 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
743 return QIcon(pixmap);
747 ////////////////////////////////////////////////////////////////////////
749 // LyX server support code.
751 ////////////////////////////////////////////////////////////////////////
753 class SocketNotifier : public QSocketNotifier
756 /// connect a connection notification from the LyXServerSocket
757 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
758 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
762 /// The callback function
763 Application::SocketCallback func_;
767 class GuiTranslator : public QTranslator
770 GuiTranslator(QObject * parent = nullptr)
771 : QTranslator(parent)
774 QString translate(const char * /* context */,
775 const char *sourceText,
776 #if QT_VERSION >= 0x050000
777 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
779 const char * /*comment*/ = 0) const override
782 // Here we declare the strings that need to be translated from Qt own GUI
783 // This is needed to include these strings to po files
787 _("Restore Defaults");
790 // Already in po: "Cancel", "&Cancel"
791 _("Apply"); // Already in po: "&Apply"
792 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
795 docstring s = getGuiMessages().getIfFound(sourceText);
796 // This test should eventually be removed when translations are updated
798 LYXERR(Debug::LOCALE, "Missing translation for `"
799 << string(sourceText) << "'");
805 ////////////////////////////////////////////////////////////////////////
807 // Mac specific stuff goes here...
809 ////////////////////////////////////////////////////////////////////////
811 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
812 // QMacPasteboardMimeGraphics can only be compiled on Mac.
814 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
817 QMacPasteboardMimeGraphics()
818 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
821 QString convertorName() { return "Graphics"; }
823 QString flavorFor(QString const & mime)
825 LYXERR(Debug::ACTION, "flavorFor " << mime);
826 if (mime == pdfMimeType())
827 return QLatin1String("com.adobe.pdf");
831 QString mimeFor(QString flav)
833 LYXERR(Debug::ACTION, "mimeFor " << flav);
834 if (flav == QLatin1String("com.adobe.pdf"))
835 return pdfMimeType();
839 bool canConvert(QString const & mime, QString flav)
841 return mimeFor(flav) == mime;
844 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
848 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
852 QList<QByteArray> convertFromMime(QString const & /*mime*/,
853 QVariant data, QString /*flav*/)
855 QList<QByteArray> ret;
856 ret.append(data.toByteArray());
862 ///////////////////////////////////////////////////////////////
864 // You can find more platform specific stuff at the end of this file...
866 ///////////////////////////////////////////////////////////////
868 ////////////////////////////////////////////////////////////////////////
869 // Windows specific stuff goes here...
871 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
872 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
873 // QWindowsMimeMetafile can only be compiled on Windows.
875 static FORMATETC cfFromMime(QString const & mimetype)
878 if (mimetype == emfMimeType()) {
879 formatetc.cfFormat = CF_ENHMETAFILE;
880 formatetc.tymed = TYMED_ENHMF;
881 } else if (mimetype == wmfMimeType()) {
882 formatetc.cfFormat = CF_METAFILEPICT;
883 formatetc.tymed = TYMED_MFPICT;
886 formatetc.dwAspect = DVASPECT_CONTENT;
887 formatetc.lindex = -1;
892 class QWindowsMimeMetafile : public QWINDOWSMIME {
894 QWindowsMimeMetafile() {}
896 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
897 QMimeData const * /*mimedata*/) const override
902 bool canConvertToMime(QString const & mimetype,
903 IDataObject * pDataObj) const override
905 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
907 FORMATETC formatetc = cfFromMime(mimetype);
908 return pDataObj->QueryGetData(&formatetc) == S_OK;
911 bool convertFromMime(FORMATETC const & /*formatetc*/,
912 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
917 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
918 QVARIANTTYPE /*preferredType*/) const override
921 if (!canConvertToMime(mimetype, pDataObj))
924 FORMATETC formatetc = cfFromMime(mimetype);
926 if (pDataObj->GetData(&formatetc, &s) != S_OK)
930 if (s.tymed == TYMED_ENHMF) {
931 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
932 data.resize(dataSize);
933 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
934 (LPBYTE)data.data());
935 } else if (s.tymed == TYMED_MFPICT) {
936 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
937 data.resize(dataSize);
938 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
939 (LPBYTE)data.data());
942 ReleaseStgMedium(&s);
948 QVector<FORMATETC> formatsForMime(QString const & mimetype,
949 QMimeData const * /*mimedata*/) const override
951 QVector<FORMATETC> formats;
952 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
953 formats += cfFromMime(mimetype);
957 QString mimeForFormat(FORMATETC const & formatetc) const override
959 switch (formatetc.cfFormat) {
961 return emfMimeType();
962 case CF_METAFILEPICT:
963 return wmfMimeType();
973 /// Allows to check whether ESC was pressed during a long operation
974 class KeyChecker : public QObject {
979 KeyChecker() : pressed_(false), started_(false) {}
982 QCoreApplication::instance()->installEventFilter(this);
987 QCoreApplication::instance()->removeEventFilter(this);
991 QCoreApplication::processEvents();
994 bool started() const {
997 bool eventFilter(QObject *obj, QEvent *event) override {
998 LYXERR(Debug::ACTION, "Event Type: " << event->type());
999 switch (event->type()) {
1002 case QEvent::Resize:
1003 case QEvent::UpdateRequest:
1004 case QEvent::CursorChange:
1005 case QEvent::ActionChanged:
1006 case QEvent::EnabledChange:
1007 case QEvent::SockAct:
1010 case QEvent::ToolTipChange:
1011 case QEvent::LayoutRequest:
1012 case QEvent::MetaCall:
1013 return QObject::eventFilter(obj, event);
1015 // FIXME Blocking all these events is a bad idea.
1016 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1017 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1025 ////////////////////////////////////////////////////////////////////////
1026 // GuiApplication::Private definition and implementation.
1027 ////////////////////////////////////////////////////////////////////////
1029 struct GuiApplication::Private
1031 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1032 global_menubar_(nullptr)
1033 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1034 , last_state_(Qt::ApplicationInactive)
1037 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1038 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1039 /// WMF Mime handler for Windows clipboard.
1040 wmf_mime_ = new QWindowsMimeMetafile;
1041 #if (QT_VERSION >= 0x060000)
1042 win_app_ = dynamic_cast<QWindowsApplication *>
1043 (QGuiApplicationPrivate::platformIntegration());
1044 win_app_->registerMime(wmf_mime_);
1048 initKeySequences(&theTopLevelKeymap());
1051 #if (QT_VERSION >= 0x060000)
1052 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1055 win_app_->unregisterMime(wmf_mime_);
1060 void initKeySequences(KeyMap * kb)
1062 keyseq = KeySequence(kb, kb);
1063 cancel_meta_seq = KeySequence(kb, kb);
1067 QSortFilterProxyModel * language_model_;
1069 GuiClipboard clipboard_;
1071 GuiSelection selection_;
1073 FontLoader font_loader_;
1075 ColorCache color_cache_;
1076 /// the built-in Qt translation mechanism
1077 QTranslator qt_trans_;
1078 /// LyX gettext-based translation for Qt elements
1079 GuiTranslator gui_trans_;
1081 QHash<int, SocketNotifier *> socket_notifiers_;
1085 /// The global instance
1088 /// this timer is used for any regular events one wants to
1089 /// perform. at present it is used to check if forked processes
1091 QTimer general_timer_;
1093 /// delayed FuncRequests
1094 std::queue<FuncRequest> func_request_queue_;
1099 KeySequence cancel_meta_seq;
1101 KeyModifier meta_fake_bit;
1103 /// The result of last dispatch action
1104 DispatchResult dispatch_result_;
1106 /// Multiple views container.
1108 * Warning: This must not be a smart pointer as the destruction of the
1109 * object is handled by Qt when the view is closed
1110 * \sa Qt::WA_DeleteOnClose attribute.
1112 QHash<int, GuiView *> views_;
1114 /// Only used on mac.
1115 QMenuBar * global_menubar_;
1116 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1117 /// Holds previous application state on Mac
1118 Qt::ApplicationState last_state_;
1121 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1122 /// Linkback mime handler for MacOSX.
1123 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1126 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1127 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1128 /// WMF Mime handler for Windows clipboard.
1129 QWindowsMimeMetafile * wmf_mime_;
1130 #if (QT_VERSION >= 0x060000)
1131 QWindowsApplication * win_app_;
1136 /// Allows to check whether ESC was pressed during a long operation
1137 KeyChecker key_checker_;
1141 GuiApplication * guiApp;
1143 GuiApplication::~GuiApplication()
1146 closeAllLinkBackLinks();
1152 GuiApplication::GuiApplication(int & argc, char ** argv)
1153 : QApplication(argc, argv), current_view_(nullptr),
1154 d(new GuiApplication::Private)
1156 QString app_name = "LyX";
1157 QCoreApplication::setOrganizationName(app_name);
1158 QCoreApplication::setOrganizationDomain("lyx.org");
1159 QCoreApplication::setApplicationName(lyx_package);
1160 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1161 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1164 #if QT_VERSION >= 0x050700
1165 setDesktopFileName(lyx_package);
1168 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1169 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1171 qsrand(QDateTime::currentDateTime().toTime_t());
1174 // Install LyX translator for missing Qt translations
1175 installTranslator(&d->gui_trans_);
1176 // Install Qt native translator for GUI elements.
1177 installTranslator(&d->qt_trans_);
1180 // Enable reception of XCB events.
1181 installNativeEventFilter(this);
1184 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1185 // lyxrc setting for this in order to let the application stay resident.
1186 // But then we need some kind of dock icon, at least on Windows.
1188 if (lyxrc.quit_on_last_window_closed)
1189 setQuitOnLastWindowClosed(false);
1192 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1193 // seems to be the default case for applications like LyX.
1194 setQuitOnLastWindowClosed(false);
1197 appleCleanupEditMenu();
1198 appleCleanupViewMenu();
1199 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1200 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1201 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1205 #if defined(Q_WS_X11) || defined(QPA_XCB)
1206 // doubleClickInterval() is 400 ms on X11 which is just too long.
1207 // On Windows and Mac OS X, the operating system's value is used.
1208 // On Microsoft Windows, calling this function sets the double
1209 // click interval for all applications. So we don't!
1210 QApplication::setDoubleClickInterval(300);
1213 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1215 // needs to be done before reading lyxrc
1217 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1221 // Initialize RC Fonts
1222 if (lyxrc.roman_font_name.empty())
1223 lyxrc.roman_font_name = fromqstr(romanFontName());
1225 if (lyxrc.sans_font_name.empty())
1226 lyxrc.sans_font_name = fromqstr(sansFontName());
1228 if (lyxrc.typewriter_font_name.empty())
1229 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1231 #if (QT_VERSION >= 0x050000)
1232 // Qt4 does this in event(), see below.
1233 // Track change of keyboard
1234 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1237 d->general_timer_.setInterval(500);
1238 connect(&d->general_timer_, SIGNAL(timeout()),
1239 this, SLOT(handleRegularEvents()));
1240 d->general_timer_.start();
1242 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1243 // This is clearly not enough in a time where we use threads for
1244 // document preview and/or export. 20 should be OK.
1245 QThreadPool::globalInstance()->setMaxThreadCount(20);
1247 // make sure tooltips are formatted
1248 installEventFilter(new ToolTipFormatter(this));
1252 GuiApplication * theGuiApp()
1254 return dynamic_cast<GuiApplication *>(theApp());
1258 #if QT_VERSION < 0x050000
1259 // Emulate platformName() for Qt4
1261 // FIXME: when ditching this method, remove all tests
1262 // platformName() == "qt4x11"
1264 QString GuiApplication::platformName() const
1266 # if defined(Q_WS_X11)
1267 // Note that this one does not really exist
1269 # elif defined(Q_OS_MAC)
1271 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1274 LYXERR0("Unknown platform!");
1281 double GuiApplication::pixelRatio() const
1283 #if QT_VERSION >= 0x050000
1284 return qt_scale_factor * devicePixelRatio();
1291 void GuiApplication::clearSession()
1298 docstring Application::iconName(FuncRequest const & f, bool unknown)
1300 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1304 docstring Application::mathIcon(docstring const & c)
1306 return qstring_to_ucs4(findImg(toqstr(c)));
1310 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1314 BufferView * bv = nullptr;
1315 BufferView * doc_bv = nullptr;
1317 if (cmd.action() == LFUN_NOACTION) {
1318 status.message(from_utf8(N_("Nothing to do")));
1319 status.setEnabled(false);
1322 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1323 status.setUnknown(true);
1324 status.message(from_utf8(N_("Unknown action")));
1325 status.setEnabled(false);
1328 // Does the GuiApplication know something?
1329 else if (getStatus(cmd, status)) { }
1331 // If we do not have a GuiView, then other functions are disabled
1332 else if (!current_view_)
1333 status.setEnabled(false);
1335 // Does the GuiView know something?
1336 else if (current_view_->getStatus(cmd, status)) { }
1338 // In LyX/Mac, when a dialog is open, the menus of the
1339 // application can still be accessed without giving focus to
1340 // the main window. In this case, we want to disable the menu
1341 // entries that are buffer or view-related.
1342 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1344 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1345 status.setEnabled(false);
1348 // If we do not have a BufferView, then other functions are disabled
1349 else if (!(bv = current_view_->currentBufferView()))
1350 status.setEnabled(false);
1352 // Does the current BufferView know something?
1353 else if (bv->getStatus(cmd, status)) { }
1355 // Does the current Buffer know something?
1356 else if (bv->buffer().getStatus(cmd, status)) { }
1358 // If we do not have a document BufferView, different from the
1359 // current BufferView, then other functions are disabled
1360 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1361 status.setEnabled(false);
1363 // Does the document Buffer know something?
1364 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1367 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1368 status.message(from_utf8(N_("Command not handled")));
1369 status.setEnabled(false);
1372 // the default error message if we disable the command
1373 if (!status.enabled() && status.message().empty())
1374 status.message(from_utf8(N_("Command disabled")));
1380 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1382 // I would really like to avoid having this switch and rather try to
1383 // encode this in the function itself.
1384 // -- And I'd rather let an inset decide which LFUNs it is willing
1385 // to handle (Andre')
1387 switch (cmd.action()) {
1389 // This could be used for the no-GUI version. The GUI version is handled in
1390 // GuiView::getStatus(). See above.
1392 case LFUN_BUFFER_WRITE:
1393 case LFUN_BUFFER_WRITE_AS:
1394 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1395 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1396 enable = b && (b->isUnnamed() || !b->isClean());
1401 case LFUN_BOOKMARK_GOTO: {
1402 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1403 enable = theSession().bookmarks().isValid(num);
1407 case LFUN_BOOKMARK_CLEAR:
1408 enable = theSession().bookmarks().hasValid();
1411 // this one is difficult to get right. As a half-baked
1412 // solution, we consider only the first action of the sequence
1413 case LFUN_COMMAND_SEQUENCE: {
1414 // argument contains ';'-terminated commands
1415 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1416 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1417 func.setOrigin(cmd.origin());
1418 flag = getStatus(func);
1422 // we want to check if at least one of these is enabled
1423 case LFUN_COMMAND_ALTERNATIVES: {
1424 // argument contains ';'-terminated commands
1425 string arg = to_utf8(cmd.argument());
1426 while (!arg.empty()) {
1428 arg = split(arg, first, ';');
1429 FuncRequest func(lyxaction.lookupFunc(first));
1430 func.setOrigin(cmd.origin());
1431 flag = getStatus(func);
1432 // if this one is enabled, the whole thing is
1441 string name = to_utf8(cmd.argument());
1442 if (theTopLevelCmdDef().lock(name, func)) {
1443 func.setOrigin(cmd.origin());
1444 flag = getStatus(func);
1445 theTopLevelCmdDef().release(name);
1447 // catch recursion or unknown command
1448 // definition. all operations until the
1449 // recursion or unknown command definition
1450 // occurs are performed, so set the state to
1457 case LFUN_IF_RELATIVES: {
1458 string const lfun = to_utf8(cmd.argument());
1459 BufferView const * bv =
1460 current_view_ ? current_view_->currentBufferView() : nullptr;
1461 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1465 FuncRequest func(lyxaction.lookupFunc(lfun));
1466 func.setOrigin(cmd.origin());
1467 flag = getStatus(func);
1471 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1473 case LFUN_PREFERENCES_SAVE:
1474 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1475 // these are handled in our dispatch()
1478 case LFUN_DEBUG_LEVEL_SET: {
1479 string bad = Debug::badValue(to_utf8(cmd.argument()));
1480 enable = bad.empty();
1482 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1486 case LFUN_WINDOW_CLOSE:
1487 enable = !d->views_.empty();
1490 case LFUN_BUFFER_NEW:
1491 case LFUN_BUFFER_NEW_TEMPLATE:
1492 case LFUN_FILE_OPEN:
1493 case LFUN_LYXFILES_OPEN:
1494 case LFUN_HELP_OPEN:
1495 case LFUN_SCREEN_FONT_UPDATE:
1496 case LFUN_SET_COLOR:
1497 case LFUN_WINDOW_NEW:
1499 case LFUN_LYXRC_APPLY:
1500 case LFUN_COMMAND_PREFIX:
1502 case LFUN_META_PREFIX:
1503 case LFUN_RECONFIGURE:
1504 case LFUN_SERVER_GET_FILENAME:
1505 case LFUN_SERVER_NOTIFY:
1509 case LFUN_BUFFER_FORALL: {
1510 if (theBufferList().empty()) {
1511 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1512 flag.setEnabled(false);
1516 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1517 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1518 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1519 flag.setEnabled(false);
1524 case LFUN_DIALOG_SHOW: {
1525 string const name = cmd.getArg(0);
1526 return name == "aboutlyx"
1527 || name == "lyxfiles"
1529 || name == "texinfo"
1530 || name == "progress"
1531 || name == "compare";
1539 flag.setEnabled(false);
1543 /// make a post-dispatch status message
1544 static docstring makeDispatchMessage(docstring const & msg,
1545 FuncRequest const & cmd)
1547 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1548 || cmd.origin() == FuncRequest::TOOLBAR
1549 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1551 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1552 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1556 docstring dispatch_msg = msg;
1557 if (!dispatch_msg.empty())
1558 dispatch_msg += ' ';
1560 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1562 bool argsadded = false;
1564 if (!cmd.argument().empty()) {
1565 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1566 comname += ' ' + cmd.argument();
1570 docstring const shortcuts = theTopLevelKeymap().
1571 printBindings(cmd, KeySequence::ForGui);
1573 if (!shortcuts.empty())
1574 comname += ": " + shortcuts;
1575 else if (!argsadded && !cmd.argument().empty())
1576 comname += ' ' + cmd.argument();
1578 if (!comname.empty()) {
1579 comname = rtrim(comname);
1580 dispatch_msg += '(' + rtrim(comname) + ')';
1582 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1583 return dispatch_msg;
1587 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1591 Buffer * buffer = nullptr;
1592 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1593 //setCurrentView(cmd.view_origin); //does not work
1595 dr.setMessage(_("Wrong focus!"));
1596 d->dispatch_result_ = dr;
1597 return d->dispatch_result_;
1599 if (current_view_ && current_view_->currentBufferView()) {
1600 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1601 buffer = ¤t_view_->currentBufferView()->buffer();
1604 dr.screenUpdate(Update::FitCursor);
1606 // All the code is kept inside the undo group because
1607 // updateBuffer can create undo actions (see #11292)
1608 UndoGroupHelper ugh(buffer);
1610 if (dr.screenUpdate() & Update::ForceAll) {
1611 for (Buffer const * b : theBufferList())
1613 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1616 updateCurrentView(cmd, dr);
1619 d->dispatch_result_ = dr;
1620 return d->dispatch_result_;
1624 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1629 BufferView * bv = current_view_->currentBufferView();
1631 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1632 bv->cursor().clearBufferUpdate();
1633 bv->buffer().updateBuffer();
1635 // BufferView::update() updates the ViewMetricsInfo and
1636 // also initializes the position cache for all insets in
1637 // (at least partially) visible top-level paragraphs.
1638 // We will redraw the screen only if needed.
1639 bv->processUpdateFlags(dr.screenUpdate());
1641 // Do we have a selection?
1642 theSelection().haveSelection(bv->cursor().selection());
1645 current_view_->restartCaret();
1647 if (dr.needMessageUpdate()) {
1648 // Some messages may already be translated, so we cannot use _()
1649 current_view_->message(makeDispatchMessage(
1650 translateIfPossible(dr.message()), cmd));
1655 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1656 bool switchToBuffer)
1658 if (!theSession().bookmarks().isValid(idx))
1660 BookmarksSection::Bookmark const & bm =
1661 theSession().bookmarks().bookmark(idx);
1662 LASSERT(!bm.filename.empty(), return);
1663 string const file = bm.filename.absFileName();
1664 // if the file is not opened, open it.
1665 if (!theBufferList().exists(bm.filename)) {
1667 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1671 // open may fail, so we need to test it again
1672 if (!theBufferList().exists(bm.filename))
1675 // bm can be changed when saving
1676 BookmarksSection::Bookmark tmp = bm;
1678 // Special case idx == 0 used for back-from-back jump navigation
1680 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1682 // if the current buffer is not that one, switch to it.
1683 BufferView * doc_bv = current_view_ ?
1684 current_view_->documentBufferView() : nullptr;
1685 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1686 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1687 if (switchToBuffer) {
1688 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1691 doc_bv = current_view_->documentBufferView();
1696 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1697 if (!doc_bv || !doc_bv->moveToPosition(
1698 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1701 Cursor & cur = doc_bv->cursor();
1702 if (old && cur != *old)
1703 notifyCursorLeavesOrEnters(*old, cur);
1709 // Cursor jump succeeded!
1710 pit_type new_pit = cur.pit();
1711 pos_type new_pos = cur.pos();
1712 int new_id = cur.paragraph().id();
1714 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1715 // see http://www.lyx.org/trac/ticket/3092
1716 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1717 || bm.top_id != new_id) {
1718 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1719 new_pit, new_pos, new_id);
1723 // This function runs "configure" and then rereads lyx.defaults to
1724 // reconfigure the automatic settings.
1725 void GuiApplication::reconfigure(string const & option)
1727 // emit message signal.
1728 if (current_view_) {
1729 current_view_->message(_("Running configure..."));
1730 current_view_->setCursor(Qt::WaitCursor);
1733 // Run configure in user lyx directory
1734 string const lock_file = package().getConfigureLockName();
1735 int fd = fileLock(lock_file.c_str());
1736 int const ret = package().reconfigureUserLyXDir(option);
1737 // emit message signal.
1739 current_view_->message(_("Reloading configuration..."));
1740 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1741 // Re-read packages.lst
1742 LaTeXPackages::getAvailable();
1743 fileUnlock(fd, lock_file.c_str());
1746 current_view_->unsetCursor();
1749 Alert::information(_("System reconfiguration failed"),
1750 _("The system reconfiguration has failed.\n"
1751 "Default textclass is used but LyX may\n"
1752 "not be able to work properly.\n"
1753 "Please reconfigure again if needed."));
1755 Alert::information(_("System reconfigured"),
1756 _("The system has been reconfigured.\n"
1757 "You need to restart LyX to make use of any\n"
1758 "updated document class specifications."));
1761 void GuiApplication::validateCurrentView()
1763 if (!d->views_.empty() && !current_view_) {
1764 // currently at least one view exists but no view has the focus.
1765 // choose the last view to make it current.
1766 // a view without any open document is preferred.
1767 GuiView * candidate = nullptr;
1768 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1769 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1770 for (; it != end; ++it) {
1772 if (!candidate->documentBufferView())
1775 setCurrentView(candidate);
1779 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1781 string const argument = to_utf8(cmd.argument());
1782 FuncCode const action = cmd.action();
1784 LYXERR(Debug::ACTION, "cmd: " << cmd);
1786 // we have not done anything wrong yet.
1789 FuncStatus const flag = getStatus(cmd);
1790 if (!flag.enabled()) {
1791 // We cannot use this function here
1792 LYXERR(Debug::ACTION, "action "
1793 << lyxaction.getActionName(action)
1794 << " [" << action << "] is disabled at this location");
1795 dr.setMessage(flag.message());
1797 dr.dispatched(false);
1798 dr.screenUpdate(Update::None);
1799 dr.clearBufferUpdate();
1803 if (cmd.origin() == FuncRequest::LYXSERVER) {
1804 if (current_view_ && current_view_->currentBufferView())
1805 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1806 // we will also need to redraw the screen at the end
1807 dr.screenUpdate(Update::FitCursor);
1810 // Assumes that the action will be dispatched.
1811 dr.dispatched(true);
1813 switch (cmd.action()) {
1815 case LFUN_WINDOW_NEW:
1816 createView(toqstr(cmd.argument()));
1819 case LFUN_WINDOW_CLOSE:
1820 // FIXME: this is done also in GuiView::closeBuffer()!
1821 // update bookmark pit of the current buffer before window close
1822 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1823 gotoBookmark(i, false, false);
1824 // clear the last opened list, because
1825 // maybe this will end the session
1826 theSession().lastOpened().clear();
1827 // check for valid current_view_
1828 validateCurrentView();
1830 current_view_->closeScheduled();
1834 // quitting is triggered by the gui code
1835 // (leaving the event loop).
1837 current_view_->message(from_utf8(N_("Exiting.")));
1838 if (closeAllViews())
1842 case LFUN_SCREEN_FONT_UPDATE: {
1843 // handle the screen font changes.
1844 /* FIXME: this only updates the current document, whereas all
1845 * documents should see their metrics updated.
1847 d->font_loader_.update();
1848 dr.screenUpdate(Update::Force | Update::FitCursor);
1852 case LFUN_BUFFER_NEW:
1853 validateCurrentView();
1855 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1856 createView(QString(), false); // keep hidden
1857 current_view_->newDocument(to_utf8(cmd.argument()));
1858 current_view_->show();
1859 setActiveWindow(current_view_);
1861 current_view_->newDocument(to_utf8(cmd.argument()));
1865 case LFUN_BUFFER_NEW_TEMPLATE: {
1866 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1867 string const temp = cmd.getArg(1);
1868 validateCurrentView();
1870 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1872 current_view_->newDocument(file, temp, true);
1873 if (!current_view_->documentBufferView())
1874 current_view_->close();
1876 current_view_->newDocument(file, temp, true);
1881 case LFUN_FILE_OPEN: {
1882 // FIXME: normally the code below is not needed, since getStatus makes sure that
1883 // current_view_ is not null.
1884 validateCurrentView();
1885 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1886 string const fname = trim(to_utf8(cmd.argument()), "\"");
1887 bool const is_open = FileName::isAbsolute(fname)
1888 && theBufferList().getBuffer(FileName(fname));
1890 || (!lyxrc.open_buffers_in_tabs
1891 && current_view_->documentBufferView() != nullptr
1893 // We want the ui session to be saved per document and not per
1894 // window number. The filename crc is a good enough identifier.
1895 createView(support::checksum(fname));
1896 current_view_->openDocument(fname);
1897 if (!current_view_->documentBufferView())
1898 current_view_->close();
1899 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1900 current_view_->raise();
1901 current_view_->activateWindow();
1902 current_view_->showNormal();
1905 current_view_->openDocument(fname);
1906 if (cmd.origin() == FuncRequest::LYXSERVER) {
1907 current_view_->raise();
1908 current_view_->activateWindow();
1909 current_view_->showNormal();
1915 case LFUN_HELP_OPEN: {
1916 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1917 if (current_view_ == nullptr)
1919 string const arg = to_utf8(cmd.argument());
1921 current_view_->message(_("Missing argument"));
1924 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1926 fname = i18nLibFileSearch("examples", arg, "lyx");
1928 if (fname.empty()) {
1929 lyxerr << "LyX: unable to find documentation file `"
1930 << arg << "'. Bad installation?" << endl;
1933 current_view_->message(bformat(_("Opening help file %1$s..."),
1934 makeDisplayPath(fname.absFileName())));
1935 Buffer * buf = current_view_->loadDocument(fname, false);
1937 buf->setReadonly(!current_view_->develMode());
1941 case LFUN_LYXFILES_OPEN: {
1942 // This is the actual reason for this method (#12106).
1943 validateCurrentView();
1945 || (!lyxrc.open_buffers_in_tabs
1946 && current_view_->documentBufferView() != nullptr))
1948 string arg = to_utf8(cmd.argument());
1952 if (arg != "templates" && arg != "examples") {
1953 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1956 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1960 case LFUN_SET_COLOR: {
1961 string const lyx_name = cmd.getArg(0);
1962 string x11_name = cmd.getArg(1);
1963 string x11_darkname = cmd.getArg(2);
1964 if (lyx_name.empty() || x11_name.empty()) {
1966 current_view_->message(
1967 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1972 // FIXME: The graphics cache no longer has a changeDisplay method.
1973 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1974 bool const graphicsbg_changed =
1975 lyx_name == graphicsbg && x11_name != graphicsbg;
1976 if (graphicsbg_changed)
1977 graphics::GCache::get().changeDisplay(true);
1980 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1981 x11_darkname = x11_name;
1984 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1986 current_view_->message(
1987 bformat(_("Set-color \"%1$s\" failed "
1988 "- color is undefined or "
1989 "may not be redefined"),
1990 from_utf8(lyx_name)));
1993 // Make sure we don't keep old colors in cache.
1994 d->color_cache_.clear();
1995 // Update the current view
1996 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2000 case LFUN_LYXRC_APPLY: {
2001 // reset active key sequences, since the bindings
2002 // are updated (bug 6064)
2004 LyXRC const lyxrc_orig = lyxrc;
2006 istringstream ss(to_utf8(cmd.argument()));
2007 bool const success = lyxrc.read(ss);
2010 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
2011 << "Unable to read lyxrc data"
2016 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
2018 // If the request comes from the minibuffer, then we can't reset
2019 // the GUI, since that would destroy the minibuffer itself and
2020 // cause a crash, since we are currently in one of the methods of
2021 // GuiCommandBuffer. See bug #8540.
2022 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
2025 // FIXME Unfortunately, that leaves a bug here, since we cannot
2026 // reset the GUI in this case. If the changes to lyxrc affected the
2027 // UI, then, nothing would happen. This seems fairly unlikely, but
2028 // it definitely is a bug.
2030 dr.forceBufferUpdate();
2034 case LFUN_COMMAND_PREFIX:
2035 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2040 d->meta_fake_bit = NoModifier;
2041 GuiView * gv = currentView();
2042 if (gv && gv->currentBufferView())
2043 // cancel any selection
2044 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2045 dr.setMessage(from_ascii(N_("Cancel")));
2048 case LFUN_META_PREFIX:
2049 d->meta_fake_bit = AltModifier;
2050 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2053 // --- Menus -----------------------------------------------
2054 case LFUN_RECONFIGURE:
2055 // argument is any additional parameter to the configure.py command
2056 reconfigure(to_utf8(cmd.argument()));
2059 // --- lyxserver commands ----------------------------
2060 case LFUN_SERVER_GET_FILENAME: {
2061 if (current_view_ && current_view_->documentBufferView()) {
2062 docstring const fname = from_utf8(
2063 current_view_->documentBufferView()->buffer().absFileName());
2064 dr.setMessage(fname);
2065 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2067 dr.setMessage(docstring());
2068 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2073 case LFUN_SERVER_NOTIFY: {
2074 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2075 dr.setMessage(dispatch_buffer);
2076 theServer().notifyClient(to_utf8(dispatch_buffer));
2080 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2081 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2087 string rest = split(argument, countstr, ' ');
2088 int const count = convert<int>(countstr);
2089 // an arbitrary number to limit number of iterations
2090 int const max_iter = 10000;
2091 if (count > max_iter) {
2092 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2095 for (int i = 0; i < count; ++i) {
2096 FuncRequest lfun = lyxaction.lookupFunc(rest);
2097 lfun.allowAsync(false);
2104 case LFUN_COMMAND_SEQUENCE: {
2105 // argument contains ';'-terminated commands
2106 string arg = argument;
2107 // FIXME: this LFUN should also work without any view.
2108 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2109 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2110 // This handles undo groups automagically
2111 UndoGroupHelper ugh(buffer);
2112 while (!arg.empty()) {
2114 arg = split(arg, first, ';');
2115 FuncRequest func(lyxaction.lookupFunc(first));
2116 func.allowAsync(false);
2117 func.setOrigin(cmd.origin());
2123 case LFUN_BUFFER_FORALL: {
2124 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2125 funcToRun.allowAsync(false);
2127 map<Buffer *, GuiView *> views_lVisible;
2128 map<GuiView *, Buffer *> activeBuffers;
2130 QList<GuiView *> allViews = d->views_.values();
2132 // this for does not modify any buffer. It just collects info on local
2133 // visibility of buffers and on which buffer is active in each view.
2134 Buffer * const last = theBufferList().last();
2135 for(GuiView * view : allViews) {
2136 // all of the buffers might be locally hidden. That is, there is no
2138 if (!view || !view->currentBufferView())
2139 activeBuffers[view] = nullptr;
2141 activeBuffers[view] = &view->currentBufferView()->buffer();
2143 // find out if each is locally visible or locally hidden.
2144 // we don't use a for loop as the buffer list cycles.
2145 Buffer * b = theBufferList().first();
2147 bool const locallyVisible = view && view->workArea(*b);
2148 if (locallyVisible) {
2149 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2150 // only need to overwrite/add if we don't already know a buffer is globally
2151 // visible or we do know but we would prefer to dispatch LFUN from the
2152 // current view because of cursor position issues.
2153 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2154 views_lVisible[b] = view;
2158 b = theBufferList().next(b);
2162 GuiView * const homeView = currentView();
2163 Buffer * b = theBufferList().first();
2164 Buffer * nextBuf = nullptr;
2165 int numProcessed = 0;
2168 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2170 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2172 // first change to a view where b is locally visible, preferably current_view_.
2173 GuiView * const vLv = views_lVisible[b];
2175 lyx::dispatch(funcToRun);
2183 // put things back to how they were (if possible).
2184 for (GuiView * view : allViews) {
2185 Buffer * originalBuf = activeBuffers[view];
2186 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2187 if (theBufferList().isLoaded(originalBuf))
2188 view->setBuffer(originalBuf);
2190 homeView->setFocus();
2192 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2196 case LFUN_COMMAND_ALTERNATIVES: {
2197 // argument contains ';'-terminated commands
2198 string arg = argument;
2199 while (!arg.empty()) {
2201 arg = split(arg, first, ';');
2202 FuncRequest func(lyxaction.lookupFunc(first));
2203 func.setOrigin(cmd.origin());
2204 FuncStatus const stat = getStatus(func);
2205 if (stat.enabled()) {
2215 if (theTopLevelCmdDef().lock(argument, func)) {
2216 func.setOrigin(cmd.origin());
2218 theTopLevelCmdDef().release(argument);
2220 if (func.action() == LFUN_UNKNOWN_ACTION) {
2221 // unknown command definition
2222 lyxerr << "Warning: unknown command definition `"
2226 // recursion detected
2227 lyxerr << "Warning: Recursion in the command definition `"
2228 << argument << "' detected"
2235 case LFUN_IF_RELATIVES: {
2236 string const lfun = to_utf8(cmd.argument());
2237 FuncRequest func(lyxaction.lookupFunc(lfun));
2238 func.setOrigin(cmd.origin());
2239 FuncStatus const stat = getStatus(func);
2240 if (stat.enabled()) {
2247 case LFUN_PREFERENCES_SAVE:
2248 lyxrc.write(support::makeAbsPath("preferences",
2249 package().user_support().absFileName()), false);
2252 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2253 string const fname = addName(addPath(package().user_support().absFileName(),
2254 "templates/"), "defaults.lyx");
2255 Buffer defaults(fname);
2257 istringstream ss(argument);
2262 // We need to make sure that, after we recreat the DocumentClass,
2263 // which we do in readHeader, we apply it to the document itself.
2264 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2265 int const unknown_tokens = defaults.readHeader(lex);
2266 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2267 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2268 cap::switchBetweenClasses(olddc, newdc, theinset);
2270 if (unknown_tokens != 0) {
2271 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2272 << unknown_tokens << " unknown token"
2273 << (unknown_tokens == 1 ? "" : "s")
2277 if (defaults.writeFile(FileName(defaults.absFileName())))
2278 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2279 makeDisplayPath(fname)));
2282 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2287 case LFUN_BOOKMARK_GOTO:
2288 // go to bookmark, open unopened file and switch to buffer if necessary
2289 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2290 dr.screenUpdate(Update::Force | Update::FitCursor);
2293 case LFUN_BOOKMARK_CLEAR:
2294 theSession().bookmarks().clear();
2295 dr.screenUpdate(Update::Force);
2298 case LFUN_DEBUG_LEVEL_SET:
2299 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2302 case LFUN_DIALOG_SHOW: {
2303 string const name = cmd.getArg(0);
2305 if ( name == "aboutlyx"
2307 || name == "texinfo"
2308 || name == "progress"
2309 || name == "compare")
2311 // work around: on Mac OS the application
2312 // is not terminated when closing the last view.
2313 // Create a new one to be able to dispatch the
2314 // LFUN_DIALOG_SHOW to this view.
2315 if (current_view_ == nullptr)
2321 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2324 current_view_->dispatch(cmd, dr);
2328 if (current_view_ && current_view_->isFullScreen()) {
2329 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2330 current_view_->menuBar()->hide();
2333 if (cmd.origin() == FuncRequest::LYXSERVER)
2334 updateCurrentView(cmd, dr);
2338 docstring GuiApplication::viewStatusMessage()
2340 // When meta-fake key is pressed, show the key sequence so far + "M-".
2341 if (d->meta_fake_bit != NoModifier)
2342 return d->keyseq.print(KeySequence::ForGui) + "M-";
2344 // Else, when a non-complete key sequence is pressed,
2345 // show the available options.
2346 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2347 return d->keyseq.printOptions(true);
2353 string GuiApplication::inputLanguageCode() const
2355 #if (QT_VERSION < 0x050000)
2356 QLocale loc = keyboardInputLocale();
2358 QLocale loc = inputMethod()->locale();
2360 //LYXERR0("input lang = " << fromqstr(loc.name()));
2361 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2365 void GuiApplication::onLocaleChanged()
2367 //LYXERR0("Change language to " << inputLanguage()->lang());
2368 if (currentView() && currentView()->currentBufferView())
2369 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2373 void GuiApplication::onPaletteChanged()
2375 colorCache().setPalette(palette());
2379 void GuiApplication::handleKeyFunc(FuncCode action)
2383 if (d->keyseq.length())
2385 GuiView * gv = currentView();
2386 LASSERT(gv && gv->currentBufferView(), return);
2387 BufferView * bv = gv->currentBufferView();
2388 bv->getIntl().getTransManager().deadkey(
2389 c, get_accent(action).accent, bv->cursor().innerText(),
2391 // Need to clear, in case the minibuffer calls these
2394 // copied verbatim from do_accent_char
2395 bv->cursor().resetAnchor();
2399 //Keep this in sync with GuiApplication::processKeySym below
2400 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2401 KeyModifier state) const
2403 // Do nothing if we have nothing
2404 if (!keysym.isOK() || keysym.isModifier())
2406 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2408 FuncRequest func = seq.addkey(keysym, state);
2409 // When not cancel or meta-fake, do the normal lookup.
2410 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2412 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2414 // Maybe user can only reach the key via holding down shift.
2415 // Let's see. But only if shift is the only modifier
2416 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2417 // If addkey looked up a command and did not find further commands then
2418 // seq has been reset at this point
2419 func = seq.addkey(keysym, NoModifier);
2421 LYXERR(Debug::KEY, " Key (queried) [action="
2422 << lyxaction.getActionName(func.action()) << "]["
2423 << seq.print(KeySequence::Portable) << ']');
2424 return func.action() != LFUN_UNKNOWN_ACTION;
2428 //Keep this in sync with GuiApplication::queryKeySym above
2429 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2431 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2433 // Do nothing if we have nothing (JMarc)
2434 if (!keysym.isOK() || keysym.isModifier()) {
2436 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2438 current_view_->restartCaret();
2442 char_type encoded_last_key = keysym.getUCSEncoded();
2444 // Do a one-deep top-level lookup for
2445 // cancel and meta-fake keys. RVDK_PATCH_5
2446 d->cancel_meta_seq.reset();
2448 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2449 LYXERR(Debug::KEY, "action first set to ["
2450 << lyxaction.getActionName(func.action()) << ']');
2452 // When not cancel or meta-fake, do the normal lookup.
2453 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2454 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2455 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2456 // remove Caps Lock and Mod2 as a modifiers
2457 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2458 LYXERR(Debug::KEY, "action now set to ["
2459 << lyxaction.getActionName(func.action()) << ']');
2462 // Don't remove this unless you know what you are doing.
2463 d->meta_fake_bit = NoModifier;
2465 // Can this happen now ?
2466 if (func.action() == LFUN_NOACTION)
2467 func = FuncRequest(LFUN_COMMAND_PREFIX);
2469 LYXERR(Debug::KEY, " Key [action="
2470 << lyxaction.getActionName(func.action()) << "]["
2471 << d->keyseq.print(KeySequence::Portable) << ']');
2473 // already here we know if it any point in going further
2474 // why not return already here if action == -1 and
2475 // num_bytes == 0? (Lgb)
2477 if (d->keyseq.length() > 1 && current_view_)
2478 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2481 // Maybe user can only reach the key via holding down shift.
2482 // Let's see. But only if shift is the only modifier
2483 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2484 LYXERR(Debug::KEY, "Trying without shift");
2485 // If addkey looked up a command and did not find further commands then
2486 // seq has been reset at this point
2487 func = d->keyseq.addkey(keysym, NoModifier);
2488 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2491 if (func.action() == LFUN_UNKNOWN_ACTION) {
2492 // We didn't match any of the key sequences.
2493 // See if it's normal insertable text not already
2494 // covered by a binding
2495 if (keysym.isText() && d->keyseq.length() == 1) {
2496 // Non-printable characters (such as ASCII control characters)
2497 // must not be inserted (#5704)
2498 if (!isPrintable(encoded_last_key)) {
2499 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2501 current_view_->restartCaret();
2504 // The following modifier check is not needed on Mac.
2505 // The keysym is either not text or it is different
2506 // from the non-modifier keysym. See #9875 for the
2507 // broken alt-modifier effect of having this code active.
2508 #if !defined(Q_OS_MAC)
2509 // If a non-Shift Modifier is used we have a non-bound key sequence
2510 // (such as Alt+j = j). This should be omitted (#5575).
2511 // On Windows, AltModifier and ControlModifier are both
2512 // set when AltGr is pressed. Therefore, in order to not
2513 // break AltGr-bound symbols (see #5575 for details),
2514 // unbound Ctrl+Alt key sequences are allowed.
2515 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2516 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2517 && !(state & AltModifier && state & ControlModifier)
2521 if (current_view_) {
2522 current_view_->message(_("Unknown function."));
2523 current_view_->restartCaret();
2528 // Since all checks above were passed, we now really have text that
2529 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2530 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2532 LYXERR(Debug::KEY, "isText() is true, inserting.");
2533 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2535 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2536 if (current_view_) {
2537 current_view_->message(_("Unknown function."));
2538 current_view_->restartCaret();
2544 if (func.action() == LFUN_SELF_INSERT) {
2545 if (encoded_last_key != 0) {
2546 docstring const arg(1, encoded_last_key);
2547 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2548 FuncRequest::KEYBOARD));
2549 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2552 processFuncRequest(func);
2556 void GuiApplication::processFuncRequest(FuncRequest const & func)
2558 lyx::dispatch(func);
2562 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2564 addToFuncRequestQueue(func);
2565 processFuncRequestQueueAsync();
2569 void GuiApplication::processFuncRequestQueue()
2571 while (!d->func_request_queue_.empty()) {
2572 // take the item from the stack _before_ processing the
2573 // request in order to avoid race conditions from nested
2574 // or parallel requests (see #10406)
2575 FuncRequest const fr(d->func_request_queue_.front());
2576 d->func_request_queue_.pop();
2577 processFuncRequest(fr);
2582 void GuiApplication::processFuncRequestQueueAsync()
2584 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2588 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2590 d->func_request_queue_.push(func);
2594 void GuiApplication::resetGui()
2596 // Set the language defined by the user.
2600 if (!readUIFile(toqstr(lyxrc.ui_file)))
2601 // Gives some error box here.
2604 if (d->global_menubar_)
2605 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2607 QHash<int, GuiView *>::iterator it;
2608 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2611 gv->setLayoutDirection(layoutDirection());
2615 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2619 bool GuiApplication::rtlContext() const
2621 if (current_view_ && current_view_->currentBufferView()) {
2622 BufferView const * bv = current_view_->currentBufferView();
2623 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2625 return layoutDirection() == Qt::RightToLeft;
2629 void GuiApplication::createView(int view_id)
2631 createView(QString(), true, view_id);
2635 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2638 // release the keyboard which might have been grabbed by the global
2639 // menubar on Mac to catch shortcuts even without any GuiView.
2640 if (d->global_menubar_)
2641 d->global_menubar_->releaseKeyboard();
2645 while (d->views_.find(id) != d->views_.end())
2648 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2649 GuiView * view = new GuiView(id);
2650 // `view' is the new current_view_. Tell coverity that is is not 0.
2651 LATTEST(current_view_);
2653 d->views_[id] = view;
2657 setActiveWindow(view);
2660 if (!geometry_arg.isEmpty()) {
2661 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2665 #if QT_VERSION < 0x060000
2666 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2667 re.indexIn(geometry_arg);
2668 w = re.cap(1).toInt();
2669 h = re.cap(2).toInt();
2670 x = re.cap(3).toInt();
2671 y = re.cap(4).toInt();
2672 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2673 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2675 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2676 QRegularExpressionMatch match = re.match(geometry_arg);
2677 w = match.captured(1).toInt();
2678 h = match.captured(2).toInt();
2679 x = match.captured(3).toInt();
2680 y = match.captured(4).toInt();
2681 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2682 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2684 // Set initial geometry such that we can get the frame size.
2685 view->setGeometry(x, y, w, h);
2686 int framewidth = view->geometry().x() - view->x();
2687 int titleheight = view->geometry().y() - view->y();
2688 // Negative displacements must be interpreted as distances
2689 // from the right or bottom screen borders.
2690 if (sx == '-' || sy == '-') {
2691 #if QT_VERSION < 0x060000
2692 QRect rec = QApplication::desktop()->screenGeometry();
2694 QRect rec = QGuiApplication::primaryScreen()->geometry();
2697 x += rec.width() - w - framewidth;
2699 y += rec.height() - h - titleheight;
2700 view->setGeometry(x, y, w, h);
2702 // Make sure that the left and top frame borders are visible.
2703 if (view->x() < 0 || view->y() < 0) {
2708 view->setGeometry(x, y, w, h);
2716 bool GuiApplication::unhide(Buffer * buf)
2720 currentView()->setBuffer(buf, false);
2725 Clipboard & GuiApplication::clipboard()
2727 return d->clipboard_;
2731 Selection & GuiApplication::selection()
2733 return d->selection_;
2737 FontLoader & GuiApplication::fontLoader()
2739 return d->font_loader_;
2743 Toolbars const & GuiApplication::toolbars() const
2745 return d->toolbars_;
2749 Toolbars & GuiApplication::toolbars()
2751 return d->toolbars_;
2755 Menus const & GuiApplication::menus() const
2761 Menus & GuiApplication::menus()
2767 bool GuiApplication::needsBackingStore() const
2769 /* Qt on macOS and Wayland does not respect the
2770 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2771 * store at each update. Therefore, we use our own backing store
2772 * in these two cases. It is also possible to force the use of the
2773 * backing store for cases like x11 with transparent WM themes.
2775 return platformName() == "cocoa" || platformName().contains("wayland");
2779 QList<int> GuiApplication::viewIds() const
2781 return d->views_.keys();
2785 ColorCache & GuiApplication::colorCache()
2787 return d->color_cache_;
2791 int GuiApplication::exec()
2793 // asynchronously handle batch commands. This event will be in
2794 // the event queue in front of other asynchronous events. Hence,
2795 // we can assume in the latter that the gui is setup already.
2796 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2798 return QApplication::exec();
2802 void GuiApplication::exit(int status)
2804 QApplication::exit(status);
2808 void GuiApplication::setGuiLanguage()
2812 // install translation file for Qt built-in dialogs
2813 QString const language_name = QString("qt_") + theLocale.name();
2814 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2815 // Short-named translator can be loaded from a long name, but not the
2816 // opposite. Therefore, long name should be used without truncation.
2817 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2818 if (!d->qt_trans_.load(language_name,
2819 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2820 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2822 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2824 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2827 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2831 switch (theLocale.language()) {
2832 case QLocale::Arabic :
2833 case QLocale::Hebrew :
2834 case QLocale::Persian :
2835 case QLocale::Urdu :
2836 setLayoutDirection(Qt::RightToLeft);
2839 setLayoutDirection(Qt::LeftToRight);
2844 void GuiApplication::execBatchCommands()
2849 if (!readUIFile(toqstr(lyxrc.ui_file)))
2850 // Gives some error box here.
2854 #if QT_VERSION > 0x040600
2855 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2857 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2858 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2860 // Create the global default menubar which is shown for the dialogs
2861 // and if no GuiView is visible.
2862 // This must be done after the session was recovered to know the "last files".
2863 d->global_menubar_ = new QMenuBar(0);
2864 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2867 lyx::execBatchCommands();
2871 QAbstractItemModel * GuiApplication::languageModel()
2873 if (d->language_model_)
2874 return d->language_model_;
2876 QStandardItemModel * lang_model = new QStandardItemModel(this);
2877 lang_model->insertColumns(0, 3);
2878 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2879 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2880 Languages::const_iterator it = lyx::languages.begin();
2881 Languages::const_iterator end = lyx::languages.end();
2882 for (; it != end; ++it) {
2883 int current_row = lang_model->rowCount();
2884 lang_model->insertRows(current_row, 1);
2885 QModelIndex pl_item = lang_model->index(current_row, 0);
2886 QModelIndex sp_item = lang_model->index(current_row, 1);
2887 QModelIndex th_item = lang_model->index(current_row, 2);
2888 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2889 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2890 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2891 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2892 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2893 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2894 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2895 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2896 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2897 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2899 d->language_model_ = new QSortFilterProxyModel(this);
2900 d->language_model_->setSourceModel(lang_model);
2901 d->language_model_->setSortLocaleAware(true);
2902 return d->language_model_;
2906 void GuiApplication::restoreGuiSession()
2908 if (!lyxrc.load_session)
2911 Session & session = theSession();
2912 LastOpenedSection::LastOpened const & lastopened =
2913 session.lastOpened().getfiles();
2915 validateCurrentView();
2917 FileName active_file;
2918 // do not add to the lastfile list since these files are restored from
2919 // last session, and should be already there (regular files), or should
2920 // not be added at all (help files).
2921 for (auto const & last : lastopened) {
2922 FileName const & file_name = last.file_name;
2923 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2924 && current_view_->documentBufferView() != nullptr)) {
2925 string const & fname = file_name.absFileName();
2926 createView(support::checksum(fname));
2928 current_view_->loadDocument(file_name, false);
2931 active_file = file_name;
2934 // Restore last active buffer
2935 Buffer * buffer = theBufferList().getBuffer(active_file);
2936 if (buffer && current_view_)
2937 current_view_->setBuffer(buffer);
2939 // clear this list to save a few bytes of RAM
2940 session.lastOpened().clear();
2944 QString const GuiApplication::romanFontName()
2947 font.setStyleHint(QFont::Serif);
2948 font.setFamily("serif");
2950 return QFontInfo(font).family();
2954 QString const GuiApplication::sansFontName()
2957 font.setStyleHint(QFont::SansSerif);
2958 font.setFamily("sans");
2960 return QFontInfo(font).family();
2964 QString const GuiApplication::typewriterFontName()
2966 return QFontInfo(typewriterSystemFont()).family();
2971 // We cannot use QFont::fixedPitch() because it doesn't
2972 // return the fact but only if it is requested.
2973 static bool isFixedPitch(const QFont & font) {
2974 const QFontInfo fi(font);
2975 return fi.fixedPitch();
2980 QFont const GuiApplication::typewriterSystemFont()
2982 #if QT_VERSION >= 0x050200
2983 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2985 QFont font("monospace");
2987 if (!isFixedPitch(font)) {
2988 // try to enforce a real monospaced font
2989 font.setStyleHint(QFont::Monospace);
2990 if (!isFixedPitch(font)) {
2991 font.setStyleHint(QFont::TypeWriter);
2992 if (!isFixedPitch(font)) font.setFamily("courier");
2996 // On a Mac the result is too small and it's not practical to
2997 // rely on Qtconfig utility to change the system settings of Qt.
2998 font.setPointSize(12);
3004 void GuiApplication::handleRegularEvents()
3006 ForkedCallsController::handleCompletedProcesses();
3010 bool GuiApplication::event(QEvent * e)
3013 case QEvent::FileOpen: {
3014 // Open a file; this happens only on Mac OS X for now.
3016 // We do this asynchronously because on startup the batch
3017 // commands are not executed here yet and the gui is not ready
3019 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
3020 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
3021 processFuncRequestAsync(fr);
3025 #if (QT_VERSION < 0x050000)
3026 // Qt5 uses a signal for that, see above.
3027 case QEvent::KeyboardLayoutChange:
3028 //LYXERR0("keyboard change");
3029 if (currentView() && currentView()->currentBufferView())
3030 currentView()->currentBufferView()->cursor().setLanguageFromInput();
3034 case QEvent::ApplicationPaletteChange: {
3035 // runtime switch from/to dark mode
3037 return QApplication::event(e);
3040 return QApplication::event(e);
3045 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3048 return QApplication::notify(receiver, event);
3050 catch (ExceptionMessage const & e) {
3052 case ErrorException:
3054 setQuitOnLastWindowClosed(false);
3056 Alert::error(e.title_, e.details_);
3058 // Properly crash in debug mode in order to get a useful backtrace.
3061 // In release mode, try to exit gracefully.
3063 // FIXME: GCC 7 thinks we can fall through here. Can we?
3065 case BufferException: {
3066 if (!current_view_ || !current_view_->documentBufferView())
3068 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3069 docstring details = e.details_ + '\n';
3070 details += buf->emergencyWrite();
3071 theBufferList().release(buf);
3072 details += "\n" + _("The current document was closed.");
3073 Alert::error(e.title_, details);
3076 case WarningException:
3077 Alert::warning(e.title_, e.details_);
3081 catch (exception const & e) {
3082 docstring s = _("LyX has caught an exception, it will now "
3083 "attempt to save all unsaved documents and exit."
3085 s += from_ascii(e.what());
3086 Alert::error(_("Software exception Detected"), s);
3090 docstring s = _("LyX has caught some really weird exception, it will "
3091 "now attempt to save all unsaved documents and exit.");
3092 Alert::error(_("Software exception Detected"), s);
3099 bool GuiApplication::isInDarkMode()
3101 return colorCache().isDarkMode();
3105 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3107 QColor const & qcol = d->color_cache_.get(col);
3108 if (!qcol.isValid()) {
3114 rgbcol.r = qcol.red();
3115 rgbcol.g = qcol.green();
3116 rgbcol.b = qcol.blue();
3121 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3123 QColor const qcol(lcolor.getX11HexName(col).c_str());
3124 if (!qcol.isValid()) {
3130 rgbcol.r = qcol.red();
3131 rgbcol.g = qcol.green();
3132 rgbcol.b = qcol.blue();
3137 string const GuiApplication::hexName(ColorCode col)
3139 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3143 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3145 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3146 d->socket_notifiers_[fd] = sn;
3147 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3151 void GuiApplication::socketDataReceived(int fd)
3153 d->socket_notifiers_[fd]->func_();
3157 void GuiApplication::unregisterSocketCallback(int fd)
3159 d->socket_notifiers_.take(fd)->setEnabled(false);
3163 void GuiApplication::commitData(QSessionManager & sm)
3165 /** The implementation is required to avoid an application exit
3166 ** when session state save is triggered by session manager.
3167 ** The default implementation sends a close event to all
3168 ** visible top level widgets when session management allows
3170 ** We are changing that to check the state of each buffer in all
3171 ** views and ask the users what to do if buffers are dirty.
3172 ** Furthermore, we save the session state.
3173 ** We do NOT close the views here since the user still can cancel
3174 ** the logout process (see #9277); also, this would hide LyX from
3175 ** an OSes own session handling (application restoration).
3177 #ifdef QT_NO_SESSIONMANAGER
3179 #warning Qt is compiled without session manager
3181 #pragma message("warning: Qt is compiled without session manager")
3185 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3193 void GuiApplication::unregisterView(GuiView * gv)
3195 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3196 d->views_.remove(gv->id());
3197 if (current_view_ == gv)
3198 current_view_ = nullptr;
3203 bool GuiApplication::closeAllViews()
3205 if (d->views_.empty())
3208 // When a view/window was closed before without quitting LyX, there
3209 // are already entries in the lastOpened list.
3210 theSession().lastOpened().clear();
3212 QList<GuiView *> const views = d->views_.values();
3213 for (GuiView * view : views) {
3214 if (!view->closeScheduled())
3223 bool GuiApplication::prepareAllViewsForLogout()
3225 if (d->views_.empty())
3228 QList<GuiView *> const views = d->views_.values();
3229 for (GuiView * view : views) {
3230 if (!view->prepareAllBuffersForLogout())
3238 GuiView & GuiApplication::view(int id) const
3240 LAPPERR(d->views_.contains(id));
3241 return *d->views_.value(id);
3245 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3247 QList<GuiView *> const views = d->views_.values();
3248 for (GuiView * view : views)
3249 view->hideDialog(name, inset);
3253 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3255 Buffer const * buf = nullptr;
3256 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3257 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3258 if (Buffer const * ptr = (*it)->updateInset(inset))
3265 bool GuiApplication::searchMenu(FuncRequest const & func,
3266 docstring_list & names) const
3268 BufferView * bv = nullptr;
3270 bv = current_view_->currentBufferView();
3271 return d->menus_.searchMenu(func, names, bv);
3275 bool GuiApplication::hasBufferView() const
3277 return (current_view_ && current_view_->currentBufferView());
3281 // Ensure that a file is read only once (prevents include loops)
3282 static QStringList uifiles;
3283 // store which ui files define Toolbars
3284 static QStringList toolbar_uifiles;
3287 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3298 LexerKeyword uitags[] = {
3299 { "format", ui_format },
3300 { "include", ui_include },
3301 { "menuset", ui_menuset },
3302 { "toolbars", ui_toolbars },
3303 { "toolbarset", ui_toolbarset }
3307 lex.setFile(ui_path);
3309 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3313 if (lyxerr.debugging(Debug::PARSER))
3314 lex.printTable(lyxerr);
3317 // format before introduction of format tag
3318 unsigned int format = 0;
3319 while (lex.isOK()) {
3320 int const status = lex.lex();
3322 // we have to do this check here, outside the switch,
3323 // because otherwise we would start reading include files,
3324 // e.g., if the first tag we hit was an include tag.
3325 if (status == ui_format)
3327 format = lex.getInteger();
3331 // this will trigger unless the first tag we hit is a format
3332 // tag, with the right format.
3333 if (format != LFUN_FORMAT)
3334 return FormatMismatch;
3337 case Lexer::LEX_FEOF:
3342 QString const file = toqstr(lex.getString());
3343 bool const success = readUIFile(file, true);
3345 LYXERR0("Failed to read included file: " << fromqstr(file));
3352 d->menus_.read(lex);
3356 d->toolbars_.readToolbars(lex);
3360 d->toolbars_.readToolbarSettings(lex);
3361 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3365 if (!rtrim(lex.getString()).empty())
3366 lex.printError("LyX::ReadUIFile: "
3367 "Unknown menu tag: `$$Token'");
3369 LYXERR0("Error with status: " << status);
3375 return (error ? ReadError : ReadOK);
3379 bool GuiApplication::readUIFile(QString const & name, bool include)
3381 LYXERR(Debug::INIT, "About to read " << name << "...");
3385 ui_path = libFileSearch("ui", name, "inc");
3386 if (ui_path.empty())
3387 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3389 ui_path = libFileSearch("ui", name, "ui");
3392 if (ui_path.empty()) {
3393 static const QString defaultUIFile = "default";
3394 LYXERR(Debug::INIT, "Could not find " << name);
3396 Alert::warning(_("Could not find UI definition file"),
3397 bformat(_("Error while reading the included file\n%1$s\n"
3398 "Please check your installation."), qstring_to_ucs4(name)));
3401 if (name == defaultUIFile) {
3402 LYXERR(Debug::INIT, "Could not find default UI file!!");
3403 Alert::warning(_("Could not find default UI file"),
3404 _("LyX could not find the default UI file!\n"
3405 "Please check your installation."));
3408 Alert::warning(_("Could not find UI definition file"),
3409 bformat(_("Error while reading the configuration file\n%1$s\n"
3410 "Falling back to default.\n"
3411 "Please look under Tools>Preferences>User Interface and\n"
3412 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3413 return readUIFile(defaultUIFile, false);
3416 QString const uifile = toqstr(ui_path.absFileName());
3417 if (uifiles.contains(uifile)) {
3419 // We are reading again the top uifile so reset the safeguard:
3422 d->toolbars_.reset();
3424 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3425 << "Is this an include loop?");
3429 uifiles.push_back(uifile);
3431 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3433 ReturnValues retval = readUIFile(ui_path);
3435 if (retval == FormatMismatch) {
3436 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3437 TempFile tmp("convertXXXXXX.ui");
3438 FileName const tempfile = tmp.name();
3439 bool const success = prefs2prefs(ui_path, tempfile, true);
3441 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3442 " to format " << LFUN_FORMAT << ".");
3444 retval = readUIFile(tempfile);
3448 if (retval != ReadOK) {
3449 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3457 settings.beginGroup("ui_files");
3458 bool touched = false;
3459 for (int i = 0; i != uifiles.size(); ++i) {
3460 QFileInfo fi(uifiles[i]);
3461 QDateTime const date_value = fi.lastModified();
3462 QString const name_key = QString::number(i);
3463 // if an ui file which defines Toolbars has changed,
3464 // we have to reset the settings
3465 if (toolbar_uifiles.contains(uifiles[i])
3466 && (!settings.contains(name_key)
3467 || settings.value(name_key).toString() != uifiles[i]
3468 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3470 settings.setValue(name_key, uifiles[i]);
3471 settings.setValue(name_key + "/date", date_value);
3474 settings.endGroup();
3476 settings.remove("views");
3482 void GuiApplication::onLastWindowClosed()
3484 if (d->global_menubar_)
3485 d->global_menubar_->grabKeyboard();
3489 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3490 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3492 std::string name = "unknown";
3494 case Qt::ApplicationSuspended:
3495 name = "ApplicationSuspended";
3497 case Qt::ApplicationHidden:
3498 name = "ApplicationHidden";
3500 case Qt::ApplicationInactive:
3501 name = "ApplicationInactive";
3503 case Qt::ApplicationActive:
3504 name = "ApplicationActive";
3505 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3506 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3507 if (d->views_.empty() && d->last_state_ == state) {
3508 LYXERR(Debug::GUI, "Open new window...");
3513 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3514 d->last_state_ = state;
3519 void GuiApplication::startLongOperation() {
3520 d->key_checker_.start();
3524 bool GuiApplication::longOperationCancelled() {
3525 return d->key_checker_.pressed();
3529 void GuiApplication::stopLongOperation() {
3530 d->key_checker_.stop();
3534 bool GuiApplication::longOperationStarted() {
3535 return d->key_checker_.started();
3539 ////////////////////////////////////////////////////////////////////////
3541 // X11 specific stuff goes here...
3544 bool GuiApplication::x11EventFilter(XEvent * xev)
3549 switch (xev->type) {
3550 case SelectionRequest: {
3551 if (xev->xselectionrequest.selection != XA_PRIMARY)
3553 LYXERR(Debug::SELECTION, "X requested selection.");
3554 BufferView * bv = current_view_->currentBufferView();
3556 docstring const sel = bv->requestSelection();
3558 d->selection_.put(sel);
3559 // Refresh the selection request timestamp.
3560 // We have to do this by ourselves as Qt seems
3561 // not doing that, maybe because of our
3562 // "persistent selection" implementation
3563 // (see comments in GuiSelection.cpp).
3564 XSelectionEvent nev;
3565 nev.type = SelectionNotify;
3566 nev.display = xev->xselectionrequest.display;
3567 nev.requestor = xev->xselectionrequest.requestor;
3568 nev.selection = xev->xselectionrequest.selection;
3569 nev.target = xev->xselectionrequest.target;
3570 nev.property = 0L; // None
3571 nev.time = CurrentTime;
3572 XSendEvent(QX11Info::display(),
3573 nev.requestor, False, 0,
3574 reinterpret_cast<XEvent *>(&nev));
3580 case SelectionClear: {
3581 if (xev->xselectionclear.selection != XA_PRIMARY)
3583 LYXERR(Debug::SELECTION, "Lost selection.");
3584 BufferView * bv = current_view_->currentBufferView();
3586 bv->clearSelection();
3592 #elif defined(QPA_XCB)
3593 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3594 void * message, long *)
3596 if (!current_view_ || eventType != "xcb_generic_event_t")
3599 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3601 switch (ev->response_type) {
3602 case XCB_SELECTION_REQUEST: {
3603 xcb_selection_request_event_t * srev =
3604 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3605 if (srev->selection != XCB_ATOM_PRIMARY)
3607 LYXERR(Debug::SELECTION, "X requested selection.");
3608 BufferView * bv = current_view_->currentBufferView();
3610 docstring const sel = bv->requestSelection();
3612 d->selection_.put(sel);
3613 #ifdef HAVE_QT5_X11_EXTRAS
3614 // Refresh the selection request timestamp.
3615 // We have to do this by ourselves as Qt seems
3616 // not doing that, maybe because of our
3617 // "persistent selection" implementation
3618 // (see comments in GuiSelection.cpp).
3619 // It is expected that every X11 event is
3620 // 32 bytes long, even if not all 32 bytes are
3622 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3623 struct alignas(32) padded_event
3624 : xcb_selection_notify_event_t {};
3625 padded_event nev = {};
3626 nev.response_type = XCB_SELECTION_NOTIFY;
3627 nev.requestor = srev->requestor;
3628 nev.selection = srev->selection;
3629 nev.target = srev->target;
3630 nev.property = XCB_NONE;
3631 nev.time = XCB_CURRENT_TIME;
3632 xcb_connection_t * con = QX11Info::connection();
3633 xcb_send_event(con, 0, srev->requestor,
3634 XCB_EVENT_MASK_NO_EVENT,
3635 reinterpret_cast<char const *>(&nev));
3643 case XCB_SELECTION_CLEAR: {
3644 xcb_selection_clear_event_t * scev =
3645 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3646 if (scev->selection != XCB_ATOM_PRIMARY)
3648 LYXERR(Debug::SELECTION, "Lost selection.");
3649 BufferView * bv = current_view_->currentBufferView();
3651 bv->clearSelection();
3659 } // namespace frontend
3662 void hideDialogs(std::string const & name, Inset * inset)
3665 frontend::guiApp->hideDialogs(name, inset);
3669 ////////////////////////////////////////////////////////////////////
3673 ////////////////////////////////////////////////////////////////////
3675 frontend::FontLoader & theFontLoader()
3677 LAPPERR(frontend::guiApp);
3678 return frontend::guiApp->fontLoader();
3682 frontend::FontMetrics const & theFontMetrics(Font const & f)
3684 return theFontMetrics(f.fontInfo());
3688 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3690 LAPPERR(frontend::guiApp);
3691 return frontend::guiApp->fontLoader().metrics(f);
3695 ////////////////////////////////////////////////////////////////////
3699 ////////////////////////////////////////////////////////////////////
3701 frontend::Clipboard & theClipboard()
3703 LAPPERR(frontend::guiApp);
3704 return frontend::guiApp->clipboard();
3708 frontend::Selection & theSelection()
3710 LAPPERR(frontend::guiApp);
3711 return frontend::guiApp->selection();
3717 #include "moc_GuiApplication.cpp"