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));
528 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
533 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
535 if (!f.argument().empty()) {
536 // if there are arguments, first search an icon which name is the full thing
537 QString name = lfunname + ' ' + toqstr(f.argument());
538 name.replace(' ', '_');
539 name.replace(';', '_');
540 name.replace('\\', "backslash");
541 // avoid duplication for these
542 name.replace("dialog-toggle", "dialog-show");
545 // then special default icon for some lfuns
546 switch (f.action()) {
547 case LFUN_MATH_INSERT:
548 names << "math/" + findImg(toqstr(f.argument()).mid(1));
550 case LFUN_MATH_DELIM:
551 case LFUN_MATH_BIGDELIM:
552 names << "math/" + findImg(toqstr(f.argument()));
555 names << "commands/" + toqstr(f.argument());
557 case LFUN_COMMAND_ALTERNATIVES: {
558 // use the first of the alternative commands
560 docstring dummy = split(f.argument(), firstcom, ';');
561 QString name1 = toqstr(firstcom);
562 name1.replace(' ', '_');
563 name1.replace(';', '_');
564 name1.replace('\\', "backslash");
573 // next thing to try is function name alone
576 // and finally maybe the unknown icon
580 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
581 // The folders where icons are searched for
582 QStringList imagedirs;
583 imagedirs << "images/ipa/" << "images/";
584 // This is used to search for rtl version of icons which have the +rtl suffix.
585 QStringList suffixes;
588 suffixes << QString();
590 for (QString const & imagedir : imagedirs)
591 for (QString const & name : names)
592 for (QString const & suffix : suffixes) {
593 QString id = imagedir;
594 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
595 if (fname.exists()) {
596 docstring const fpath = fname.absoluteFilePath();
597 res.filepath = toqstr(fname.absFileName());
598 // these icons are subject to inversion in dark mode
599 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
600 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
601 res.swap = rtl && suffix.isEmpty();
606 LYXERR(Debug::GUI, "Cannot find icon for command \""
607 << lyxaction.getActionName(f.action())
608 << '(' << to_utf8(f.argument()) << ")\"");
614 QPixmap prepareForDarkMode(QPixmap pixmap)
616 QPalette palette = QPalette();
617 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
618 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
620 // guess whether we are in dark mode
621 if (text_color.black() > bg_color.black())
622 // not in dark mode, do nothing
625 // create a layer with black text turned to QPalette::WindowText
626 QPixmap black_overlay(pixmap.size());
627 black_overlay.fill(text_color);
628 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
630 // create a layer with blue text turned to lighter blue
631 QPixmap blue_overlay(pixmap.size());
632 QColor math_blue(0, 0, 255);
633 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
634 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
636 // create a layer with ("latex") red text turned to lighter red
637 QPixmap red_overlay(pixmap.size());
638 QColor math_red(128, 0, 0);
639 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
640 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
642 // put layers on top of existing pixmap
643 QPainter painter(&pixmap);
644 painter.drawPixmap(pixmap.rect(), black_overlay);
645 painter.drawPixmap(pixmap.rect(), blue_overlay);
646 painter.drawPixmap(pixmap.rect(), red_overlay);
652 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
654 QString imagedir = path;
655 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
656 QString fpath = toqstr(fname.absFileName());
657 QPixmap pixmap = QPixmap();
659 if (pixmap.load(fpath)) {
660 if (fpath.contains("math") || fpath.contains("ipa")
661 || fpath.contains("bullets"))
662 return prepareForDarkMode(pixmap);
666 bool const list = ext.contains(",");
667 LYXERR(Debug::GUI, "Cannot load pixmap \""
668 << path << "/" << name << "." << (list ? "{" : "") << ext
669 << (list ? "}" : "") << "\".");
675 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
677 #if (QT_VERSION >= 0x040600)
678 if (lyxrc.use_system_theme_icons) {
679 // use the icons from system theme that are available
680 QString action = toqstr(lyxaction.getActionName(f.action()));
681 if (!f.argument().empty())
682 action += " " + toqstr(f.argument());
683 QString const theme_icon = themeIconName(action);
684 if (QIcon::hasThemeIcon(theme_icon)) {
685 QIcon const thmicn = QIcon::fromTheme(theme_icon);
686 if (!thmicn.isNull())
692 IconInfo icondata = iconInfo(f, unknown, rtl);
693 if (icondata.filepath.isEmpty())
696 //LYXERR(Debug::GUI, "Found icon: " << icon);
697 QPixmap pixmap = QPixmap();
698 if (!pixmap.load(icondata.filepath)) {
699 LYXERR0("Cannot load icon " << icondata.filepath << ".");
704 pixmap = prepareForDarkMode(pixmap);
707 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
709 return QIcon(pixmap);
713 ////////////////////////////////////////////////////////////////////////
715 // LyX server support code.
717 ////////////////////////////////////////////////////////////////////////
719 class SocketNotifier : public QSocketNotifier
722 /// connect a connection notification from the LyXServerSocket
723 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
724 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
728 /// The callback function
729 Application::SocketCallback func_;
733 class GuiTranslator : public QTranslator
736 GuiTranslator(QObject * parent = nullptr)
737 : QTranslator(parent)
740 QString translate(const char * /* context */,
741 const char *sourceText,
742 #if QT_VERSION >= 0x050000
743 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
745 const char * /*comment*/ = 0) const override
748 // Here we declare the strings that need to be translated from Qt own GUI
749 // This is needed to include these strings to po files
753 _("Restore Defaults");
756 // Already in po: "Cancel", "&Cancel"
757 _("Apply"); // Already in po: "&Apply"
758 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
761 docstring s = getGuiMessages().getIfFound(sourceText);
762 // This test should eventually be removed when translations are updated
764 LYXERR(Debug::LOCALE, "Missing translation for `"
765 << string(sourceText) << "'");
771 ////////////////////////////////////////////////////////////////////////
773 // Mac specific stuff goes here...
775 ////////////////////////////////////////////////////////////////////////
777 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
778 // QMacPasteboardMimeGraphics can only be compiled on Mac.
780 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
783 QMacPasteboardMimeGraphics()
784 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
787 QString convertorName() { return "Graphics"; }
789 QString flavorFor(QString const & mime)
791 LYXERR(Debug::ACTION, "flavorFor " << mime);
792 if (mime == pdfMimeType())
793 return QLatin1String("com.adobe.pdf");
797 QString mimeFor(QString flav)
799 LYXERR(Debug::ACTION, "mimeFor " << flav);
800 if (flav == QLatin1String("com.adobe.pdf"))
801 return pdfMimeType();
805 bool canConvert(QString const & mime, QString flav)
807 return mimeFor(flav) == mime;
810 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
814 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
818 QList<QByteArray> convertFromMime(QString const & /*mime*/,
819 QVariant data, QString /*flav*/)
821 QList<QByteArray> ret;
822 ret.append(data.toByteArray());
828 ///////////////////////////////////////////////////////////////
830 // You can find more platform specific stuff at the end of this file...
832 ///////////////////////////////////////////////////////////////
834 ////////////////////////////////////////////////////////////////////////
835 // Windows specific stuff goes here...
837 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
838 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
839 // QWindowsMimeMetafile can only be compiled on Windows.
841 static FORMATETC cfFromMime(QString const & mimetype)
844 if (mimetype == emfMimeType()) {
845 formatetc.cfFormat = CF_ENHMETAFILE;
846 formatetc.tymed = TYMED_ENHMF;
847 } else if (mimetype == wmfMimeType()) {
848 formatetc.cfFormat = CF_METAFILEPICT;
849 formatetc.tymed = TYMED_MFPICT;
852 formatetc.dwAspect = DVASPECT_CONTENT;
853 formatetc.lindex = -1;
858 class QWindowsMimeMetafile : public QWINDOWSMIME {
860 QWindowsMimeMetafile() {}
862 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
863 QMimeData const * /*mimedata*/) const override
868 bool canConvertToMime(QString const & mimetype,
869 IDataObject * pDataObj) const override
871 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
873 FORMATETC formatetc = cfFromMime(mimetype);
874 return pDataObj->QueryGetData(&formatetc) == S_OK;
877 bool convertFromMime(FORMATETC const & /*formatetc*/,
878 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
883 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
884 QVARIANTTYPE /*preferredType*/) const override
887 if (!canConvertToMime(mimetype, pDataObj))
890 FORMATETC formatetc = cfFromMime(mimetype);
892 if (pDataObj->GetData(&formatetc, &s) != S_OK)
896 if (s.tymed == TYMED_ENHMF) {
897 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
898 data.resize(dataSize);
899 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
900 (LPBYTE)data.data());
901 } else if (s.tymed == TYMED_MFPICT) {
902 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
903 data.resize(dataSize);
904 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
905 (LPBYTE)data.data());
908 ReleaseStgMedium(&s);
914 QVector<FORMATETC> formatsForMime(QString const & mimetype,
915 QMimeData const * /*mimedata*/) const override
917 QVector<FORMATETC> formats;
918 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
919 formats += cfFromMime(mimetype);
923 QString mimeForFormat(FORMATETC const & formatetc) const override
925 switch (formatetc.cfFormat) {
927 return emfMimeType();
928 case CF_METAFILEPICT:
929 return wmfMimeType();
939 /// Allows to check whether ESC was pressed during a long operation
940 class KeyChecker : public QObject {
945 KeyChecker() : pressed_(false), started_(false) {}
948 QCoreApplication::instance()->installEventFilter(this);
953 QCoreApplication::instance()->removeEventFilter(this);
957 QCoreApplication::processEvents();
960 bool started() const {
963 bool eventFilter(QObject *obj, QEvent *event) override {
964 LYXERR(Debug::ACTION, "Event Type: " << event->type());
965 switch (event->type()) {
969 case QEvent::UpdateRequest:
970 case QEvent::CursorChange:
971 case QEvent::ActionChanged:
972 case QEvent::EnabledChange:
973 case QEvent::SockAct:
976 case QEvent::ToolTipChange:
977 case QEvent::LayoutRequest:
978 case QEvent::MetaCall:
979 return QObject::eventFilter(obj, event);
981 // FIXME Blocking all these events is a bad idea.
982 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
983 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
991 ////////////////////////////////////////////////////////////////////////
992 // GuiApplication::Private definition and implementation.
993 ////////////////////////////////////////////////////////////////////////
995 struct GuiApplication::Private
997 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
998 global_menubar_(nullptr)
999 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1000 , last_state_(Qt::ApplicationInactive)
1003 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1004 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1005 /// WMF Mime handler for Windows clipboard.
1006 wmf_mime_ = new QWindowsMimeMetafile;
1007 #if (QT_VERSION >= 0x060000)
1008 win_app_ = dynamic_cast<QWindowsApplication *>
1009 (QGuiApplicationPrivate::platformIntegration());
1010 win_app_->registerMime(wmf_mime_);
1014 initKeySequences(&theTopLevelKeymap());
1017 #if (QT_VERSION >= 0x060000)
1018 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1021 win_app_->unregisterMime(wmf_mime_);
1026 void initKeySequences(KeyMap * kb)
1028 keyseq = KeySequence(kb, kb);
1029 cancel_meta_seq = KeySequence(kb, kb);
1033 QSortFilterProxyModel * language_model_;
1035 GuiClipboard clipboard_;
1037 GuiSelection selection_;
1039 FontLoader font_loader_;
1041 ColorCache color_cache_;
1042 /// the built-in Qt translation mechanism
1043 QTranslator qt_trans_;
1044 /// LyX gettext-based translation for Qt elements
1045 GuiTranslator gui_trans_;
1047 QHash<int, SocketNotifier *> socket_notifiers_;
1051 /// The global instance
1054 /// this timer is used for any regular events one wants to
1055 /// perform. at present it is used to check if forked processes
1057 QTimer general_timer_;
1059 /// delayed FuncRequests
1060 std::queue<FuncRequest> func_request_queue_;
1065 KeySequence cancel_meta_seq;
1067 KeyModifier meta_fake_bit;
1069 /// The result of last dispatch action
1070 DispatchResult dispatch_result_;
1072 /// Multiple views container.
1074 * Warning: This must not be a smart pointer as the destruction of the
1075 * object is handled by Qt when the view is closed
1076 * \sa Qt::WA_DeleteOnClose attribute.
1078 QHash<int, GuiView *> views_;
1080 /// Only used on mac.
1081 QMenuBar * global_menubar_;
1082 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1083 /// Holds previous application state on Mac
1084 Qt::ApplicationState last_state_;
1087 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1088 /// Linkback mime handler for MacOSX.
1089 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1092 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1093 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1094 /// WMF Mime handler for Windows clipboard.
1095 QWindowsMimeMetafile * wmf_mime_;
1096 #if (QT_VERSION >= 0x060000)
1097 QWindowsApplication * win_app_;
1102 /// Allows to check whether ESC was pressed during a long operation
1103 KeyChecker key_checker_;
1107 GuiApplication * guiApp;
1109 GuiApplication::~GuiApplication()
1112 closeAllLinkBackLinks();
1118 GuiApplication::GuiApplication(int & argc, char ** argv)
1119 : QApplication(argc, argv), current_view_(nullptr),
1120 d(new GuiApplication::Private)
1122 QString app_name = "LyX";
1123 QCoreApplication::setOrganizationName(app_name);
1124 QCoreApplication::setOrganizationDomain("lyx.org");
1125 QCoreApplication::setApplicationName(lyx_package);
1126 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1127 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1130 #if QT_VERSION >= 0x050700
1131 setDesktopFileName(lyx_package);
1134 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1135 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1137 qsrand(QDateTime::currentDateTime().toTime_t());
1140 // Install LyX translator for missing Qt translations
1141 installTranslator(&d->gui_trans_);
1142 // Install Qt native translator for GUI elements.
1143 installTranslator(&d->qt_trans_);
1146 // Enable reception of XCB events.
1147 installNativeEventFilter(this);
1150 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1151 // lyxrc setting for this in order to let the application stay resident.
1152 // But then we need some kind of dock icon, at least on Windows.
1154 if (lyxrc.quit_on_last_window_closed)
1155 setQuitOnLastWindowClosed(false);
1158 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1159 // seems to be the default case for applications like LyX.
1160 setQuitOnLastWindowClosed(false);
1163 appleCleanupEditMenu();
1164 appleCleanupViewMenu();
1165 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1166 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1167 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1171 #if defined(Q_WS_X11) || defined(QPA_XCB)
1172 // doubleClickInterval() is 400 ms on X11 which is just too long.
1173 // On Windows and Mac OS X, the operating system's value is used.
1174 // On Microsoft Windows, calling this function sets the double
1175 // click interval for all applications. So we don't!
1176 QApplication::setDoubleClickInterval(300);
1179 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1181 // needs to be done before reading lyxrc
1183 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1187 // Initialize RC Fonts
1188 if (lyxrc.roman_font_name.empty())
1189 lyxrc.roman_font_name = fromqstr(romanFontName());
1191 if (lyxrc.sans_font_name.empty())
1192 lyxrc.sans_font_name = fromqstr(sansFontName());
1194 if (lyxrc.typewriter_font_name.empty())
1195 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1197 #if (QT_VERSION >= 0x050000)
1198 // Qt4 does this in event(), see below.
1199 // Track change of keyboard
1200 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1203 d->general_timer_.setInterval(500);
1204 connect(&d->general_timer_, SIGNAL(timeout()),
1205 this, SLOT(handleRegularEvents()));
1206 d->general_timer_.start();
1208 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1209 // This is clearly not enough in a time where we use threads for
1210 // document preview and/or export. 20 should be OK.
1211 QThreadPool::globalInstance()->setMaxThreadCount(20);
1213 // make sure tooltips are formatted
1214 installEventFilter(new ToolTipFormatter(this));
1218 GuiApplication * theGuiApp()
1220 return dynamic_cast<GuiApplication *>(theApp());
1224 #if QT_VERSION < 0x050000
1225 // Emulate platformName() for Qt4
1227 // FIXME: when ditching this method, remove all tests
1228 // platformName() == "qt4x11"
1230 QString GuiApplication::platformName() const
1232 # if defined(Q_WS_X11)
1233 // Note that this one does not really exist
1235 # elif defined(Q_OS_MAC)
1237 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1240 LYXERR0("Unknown platform!");
1247 double GuiApplication::pixelRatio() const
1249 #if QT_VERSION >= 0x050000
1250 return qt_scale_factor * devicePixelRatio();
1257 void GuiApplication::clearSession()
1264 docstring Application::iconName(FuncRequest const & f, bool unknown)
1266 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1270 docstring Application::mathIcon(docstring const & c)
1272 return qstring_to_ucs4(findImg(toqstr(c)));
1276 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1280 BufferView * bv = nullptr;
1281 BufferView * doc_bv = nullptr;
1283 if (cmd.action() == LFUN_NOACTION) {
1284 status.message(from_utf8(N_("Nothing to do")));
1285 status.setEnabled(false);
1288 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1289 status.setUnknown(true);
1290 status.message(from_utf8(N_("Unknown action")));
1291 status.setEnabled(false);
1294 // Does the GuiApplication know something?
1295 else if (getStatus(cmd, status)) { }
1297 // If we do not have a GuiView, then other functions are disabled
1298 else if (!current_view_)
1299 status.setEnabled(false);
1301 // Does the GuiView know something?
1302 else if (current_view_->getStatus(cmd, status)) { }
1304 // In LyX/Mac, when a dialog is open, the menus of the
1305 // application can still be accessed without giving focus to
1306 // the main window. In this case, we want to disable the menu
1307 // entries that are buffer or view-related.
1308 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1310 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1311 status.setEnabled(false);
1314 // If we do not have a BufferView, then other functions are disabled
1315 else if (!(bv = current_view_->currentBufferView()))
1316 status.setEnabled(false);
1318 // Does the current BufferView know something?
1319 else if (bv->getStatus(cmd, status)) { }
1321 // Does the current Buffer know something?
1322 else if (bv->buffer().getStatus(cmd, status)) { }
1324 // If we do not have a document BufferView, different from the
1325 // current BufferView, then other functions are disabled
1326 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1327 status.setEnabled(false);
1329 // Does the document Buffer know something?
1330 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1333 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1334 status.message(from_utf8(N_("Command not handled")));
1335 status.setEnabled(false);
1338 // the default error message if we disable the command
1339 if (!status.enabled() && status.message().empty())
1340 status.message(from_utf8(N_("Command disabled")));
1346 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1348 // I would really like to avoid having this switch and rather try to
1349 // encode this in the function itself.
1350 // -- And I'd rather let an inset decide which LFUNs it is willing
1351 // to handle (Andre')
1353 switch (cmd.action()) {
1355 // This could be used for the no-GUI version. The GUI version is handled in
1356 // GuiView::getStatus(). See above.
1358 case LFUN_BUFFER_WRITE:
1359 case LFUN_BUFFER_WRITE_AS:
1360 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1361 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1362 enable = b && (b->isUnnamed() || !b->isClean());
1367 case LFUN_BOOKMARK_GOTO: {
1368 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1369 enable = theSession().bookmarks().isValid(num);
1373 case LFUN_BOOKMARK_CLEAR:
1374 enable = theSession().bookmarks().hasValid();
1377 // this one is difficult to get right. As a half-baked
1378 // solution, we consider only the first action of the sequence
1379 case LFUN_COMMAND_SEQUENCE: {
1380 // argument contains ';'-terminated commands
1381 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1382 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1383 func.setOrigin(cmd.origin());
1384 flag = getStatus(func);
1388 // we want to check if at least one of these is enabled
1389 case LFUN_COMMAND_ALTERNATIVES: {
1390 // argument contains ';'-terminated commands
1391 string arg = to_utf8(cmd.argument());
1392 while (!arg.empty()) {
1394 arg = split(arg, first, ';');
1395 FuncRequest func(lyxaction.lookupFunc(first));
1396 func.setOrigin(cmd.origin());
1397 flag = getStatus(func);
1398 // if this one is enabled, the whole thing is
1407 string name = to_utf8(cmd.argument());
1408 if (theTopLevelCmdDef().lock(name, func)) {
1409 func.setOrigin(cmd.origin());
1410 flag = getStatus(func);
1411 theTopLevelCmdDef().release(name);
1413 // catch recursion or unknown command
1414 // definition. all operations until the
1415 // recursion or unknown command definition
1416 // occurs are performed, so set the state to
1423 case LFUN_IF_RELATIVES: {
1424 string const lfun = to_utf8(cmd.argument());
1425 BufferView const * bv =
1426 current_view_ ? current_view_->currentBufferView() : nullptr;
1427 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1431 FuncRequest func(lyxaction.lookupFunc(lfun));
1432 func.setOrigin(cmd.origin());
1433 flag = getStatus(func);
1437 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1439 case LFUN_PREFERENCES_SAVE:
1440 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1441 // these are handled in our dispatch()
1444 case LFUN_DEBUG_LEVEL_SET: {
1445 string bad = Debug::badValue(to_utf8(cmd.argument()));
1446 enable = bad.empty();
1448 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1452 case LFUN_WINDOW_CLOSE:
1453 enable = !d->views_.empty();
1456 case LFUN_BUFFER_NEW:
1457 case LFUN_BUFFER_NEW_TEMPLATE:
1458 case LFUN_FILE_OPEN:
1459 case LFUN_LYXFILES_OPEN:
1460 case LFUN_HELP_OPEN:
1461 case LFUN_SCREEN_FONT_UPDATE:
1462 case LFUN_SET_COLOR:
1463 case LFUN_WINDOW_NEW:
1465 case LFUN_LYXRC_APPLY:
1466 case LFUN_COMMAND_PREFIX:
1468 case LFUN_META_PREFIX:
1469 case LFUN_RECONFIGURE:
1470 case LFUN_SERVER_GET_FILENAME:
1471 case LFUN_SERVER_NOTIFY:
1475 case LFUN_BUFFER_FORALL: {
1476 if (theBufferList().empty()) {
1477 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1478 flag.setEnabled(false);
1482 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1483 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1484 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1485 flag.setEnabled(false);
1490 case LFUN_DIALOG_SHOW: {
1491 string const name = cmd.getArg(0);
1492 return name == "aboutlyx"
1493 || name == "lyxfiles"
1495 || name == "texinfo"
1496 || name == "progress"
1497 || name == "compare";
1505 flag.setEnabled(false);
1509 /// make a post-dispatch status message
1510 static docstring makeDispatchMessage(docstring const & msg,
1511 FuncRequest const & cmd)
1513 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1514 || cmd.origin() == FuncRequest::TOOLBAR
1515 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1517 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1518 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1522 docstring dispatch_msg = msg;
1523 if (!dispatch_msg.empty())
1524 dispatch_msg += ' ';
1526 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1528 bool argsadded = false;
1530 if (!cmd.argument().empty()) {
1531 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1532 comname += ' ' + cmd.argument();
1536 docstring const shortcuts = theTopLevelKeymap().
1537 printBindings(cmd, KeySequence::ForGui);
1539 if (!shortcuts.empty())
1540 comname += ": " + shortcuts;
1541 else if (!argsadded && !cmd.argument().empty())
1542 comname += ' ' + cmd.argument();
1544 if (!comname.empty()) {
1545 comname = rtrim(comname);
1546 dispatch_msg += '(' + rtrim(comname) + ')';
1548 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1549 return dispatch_msg;
1553 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1557 Buffer * buffer = nullptr;
1558 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1559 //setCurrentView(cmd.view_origin); //does not work
1561 dr.setMessage(_("Wrong focus!"));
1562 d->dispatch_result_ = dr;
1563 return d->dispatch_result_;
1565 if (current_view_ && current_view_->currentBufferView()) {
1566 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1567 buffer = ¤t_view_->currentBufferView()->buffer();
1570 dr.screenUpdate(Update::FitCursor);
1572 // All the code is kept inside the undo group because
1573 // updateBuffer can create undo actions (see #11292)
1574 UndoGroupHelper ugh(buffer);
1576 if (dr.screenUpdate() & Update::ForceAll) {
1577 for (Buffer const * b : theBufferList())
1579 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1582 updateCurrentView(cmd, dr);
1585 d->dispatch_result_ = dr;
1586 return d->dispatch_result_;
1590 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1595 BufferView * bv = current_view_->currentBufferView();
1597 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1598 bv->cursor().clearBufferUpdate();
1599 bv->buffer().updateBuffer();
1601 // BufferView::update() updates the ViewMetricsInfo and
1602 // also initializes the position cache for all insets in
1603 // (at least partially) visible top-level paragraphs.
1604 // We will redraw the screen only if needed.
1605 bv->processUpdateFlags(dr.screenUpdate());
1607 // Do we have a selection?
1608 theSelection().haveSelection(bv->cursor().selection());
1611 current_view_->restartCaret();
1613 if (dr.needMessageUpdate()) {
1614 // Some messages may already be translated, so we cannot use _()
1615 current_view_->message(makeDispatchMessage(
1616 translateIfPossible(dr.message()), cmd));
1621 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1622 bool switchToBuffer)
1624 if (!theSession().bookmarks().isValid(idx))
1626 BookmarksSection::Bookmark const & bm =
1627 theSession().bookmarks().bookmark(idx);
1628 LASSERT(!bm.filename.empty(), return);
1629 string const file = bm.filename.absFileName();
1630 // if the file is not opened, open it.
1631 if (!theBufferList().exists(bm.filename)) {
1633 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1637 // open may fail, so we need to test it again
1638 if (!theBufferList().exists(bm.filename))
1641 // bm can be changed when saving
1642 BookmarksSection::Bookmark tmp = bm;
1644 // Special case idx == 0 used for back-from-back jump navigation
1646 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1648 // if the current buffer is not that one, switch to it.
1649 BufferView * doc_bv = current_view_ ?
1650 current_view_->documentBufferView() : nullptr;
1651 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1652 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1653 if (switchToBuffer) {
1654 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1657 doc_bv = current_view_->documentBufferView();
1662 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1663 if (!doc_bv || !doc_bv->moveToPosition(
1664 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1667 Cursor & cur = doc_bv->cursor();
1668 if (old && cur != *old)
1669 notifyCursorLeavesOrEnters(*old, cur);
1675 // Cursor jump succeeded!
1676 pit_type new_pit = cur.pit();
1677 pos_type new_pos = cur.pos();
1678 int new_id = cur.paragraph().id();
1680 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1681 // see http://www.lyx.org/trac/ticket/3092
1682 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1683 || bm.top_id != new_id) {
1684 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1685 new_pit, new_pos, new_id);
1689 // This function runs "configure" and then rereads lyx.defaults to
1690 // reconfigure the automatic settings.
1691 void GuiApplication::reconfigure(string const & option)
1693 // emit message signal.
1694 if (current_view_) {
1695 current_view_->message(_("Running configure..."));
1696 current_view_->setCursor(Qt::WaitCursor);
1699 // Run configure in user lyx directory
1700 string const lock_file = package().getConfigureLockName();
1701 int fd = fileLock(lock_file.c_str());
1702 int const ret = package().reconfigureUserLyXDir(option);
1703 // emit message signal.
1705 current_view_->message(_("Reloading configuration..."));
1706 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1707 // Re-read packages.lst
1708 LaTeXPackages::getAvailable();
1709 fileUnlock(fd, lock_file.c_str());
1712 current_view_->unsetCursor();
1715 Alert::information(_("System reconfiguration failed"),
1716 _("The system reconfiguration has failed.\n"
1717 "Default textclass is used but LyX may\n"
1718 "not be able to work properly.\n"
1719 "Please reconfigure again if needed."));
1721 Alert::information(_("System reconfigured"),
1722 _("The system has been reconfigured.\n"
1723 "You need to restart LyX to make use of any\n"
1724 "updated document class specifications."));
1727 void GuiApplication::validateCurrentView()
1729 if (!d->views_.empty() && !current_view_) {
1730 // currently at least one view exists but no view has the focus.
1731 // choose the last view to make it current.
1732 // a view without any open document is preferred.
1733 GuiView * candidate = nullptr;
1734 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1735 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1736 for (; it != end; ++it) {
1738 if (!candidate->documentBufferView())
1741 setCurrentView(candidate);
1745 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1747 string const argument = to_utf8(cmd.argument());
1748 FuncCode const action = cmd.action();
1750 LYXERR(Debug::ACTION, "cmd: " << cmd);
1752 // we have not done anything wrong yet.
1755 FuncStatus const flag = getStatus(cmd);
1756 if (!flag.enabled()) {
1757 // We cannot use this function here
1758 LYXERR(Debug::ACTION, "action "
1759 << lyxaction.getActionName(action)
1760 << " [" << action << "] is disabled at this location");
1761 dr.setMessage(flag.message());
1763 dr.dispatched(false);
1764 dr.screenUpdate(Update::None);
1765 dr.clearBufferUpdate();
1769 if (cmd.origin() == FuncRequest::LYXSERVER) {
1770 if (current_view_ && current_view_->currentBufferView())
1771 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1772 // we will also need to redraw the screen at the end
1773 dr.screenUpdate(Update::FitCursor);
1776 // Assumes that the action will be dispatched.
1777 dr.dispatched(true);
1779 switch (cmd.action()) {
1781 case LFUN_WINDOW_NEW:
1782 createView(toqstr(cmd.argument()));
1785 case LFUN_WINDOW_CLOSE:
1786 // FIXME: this is done also in GuiView::closeBuffer()!
1787 // update bookmark pit of the current buffer before window close
1788 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1789 gotoBookmark(i, false, false);
1790 // clear the last opened list, because
1791 // maybe this will end the session
1792 theSession().lastOpened().clear();
1793 // check for valid current_view_
1794 validateCurrentView();
1796 current_view_->closeScheduled();
1800 // quitting is triggered by the gui code
1801 // (leaving the event loop).
1803 current_view_->message(from_utf8(N_("Exiting.")));
1804 if (closeAllViews())
1808 case LFUN_SCREEN_FONT_UPDATE: {
1809 // handle the screen font changes.
1810 /* FIXME: this only updates the current document, whereas all
1811 * documents should see their metrics updated.
1813 d->font_loader_.update();
1814 dr.screenUpdate(Update::Force | Update::FitCursor);
1818 case LFUN_BUFFER_NEW:
1819 validateCurrentView();
1821 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1822 createView(QString(), false); // keep hidden
1823 current_view_->newDocument(to_utf8(cmd.argument()));
1824 current_view_->show();
1825 setActiveWindow(current_view_);
1827 current_view_->newDocument(to_utf8(cmd.argument()));
1831 case LFUN_BUFFER_NEW_TEMPLATE: {
1832 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1833 string const temp = cmd.getArg(1);
1834 validateCurrentView();
1836 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1838 current_view_->newDocument(file, temp, true);
1839 if (!current_view_->documentBufferView())
1840 current_view_->close();
1842 current_view_->newDocument(file, temp, true);
1847 case LFUN_FILE_OPEN: {
1848 // FIXME: normally the code below is not needed, since getStatus makes sure that
1849 // current_view_ is not null.
1850 validateCurrentView();
1851 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1852 string const fname = trim(to_utf8(cmd.argument()), "\"");
1853 bool const is_open = FileName::isAbsolute(fname)
1854 && theBufferList().getBuffer(FileName(fname));
1856 || (!lyxrc.open_buffers_in_tabs
1857 && current_view_->documentBufferView() != nullptr
1859 // We want the ui session to be saved per document and not per
1860 // window number. The filename crc is a good enough identifier.
1861 createView(support::checksum(fname));
1862 current_view_->openDocument(fname);
1863 if (!current_view_->documentBufferView())
1864 current_view_->close();
1865 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1866 current_view_->raise();
1867 current_view_->activateWindow();
1868 current_view_->showNormal();
1871 current_view_->openDocument(fname);
1872 if (cmd.origin() == FuncRequest::LYXSERVER) {
1873 current_view_->raise();
1874 current_view_->activateWindow();
1875 current_view_->showNormal();
1881 case LFUN_HELP_OPEN: {
1882 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1883 if (current_view_ == nullptr)
1885 string const arg = to_utf8(cmd.argument());
1887 current_view_->message(_("Missing argument"));
1890 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1892 fname = i18nLibFileSearch("examples", arg, "lyx");
1894 if (fname.empty()) {
1895 lyxerr << "LyX: unable to find documentation file `"
1896 << arg << "'. Bad installation?" << endl;
1899 current_view_->message(bformat(_("Opening help file %1$s..."),
1900 makeDisplayPath(fname.absFileName())));
1901 Buffer * buf = current_view_->loadDocument(fname, false);
1903 buf->setReadonly(!current_view_->develMode());
1907 case LFUN_LYXFILES_OPEN: {
1908 // This is the actual reason for this method (#12106).
1909 validateCurrentView();
1911 || (!lyxrc.open_buffers_in_tabs
1912 && current_view_->documentBufferView() != nullptr))
1914 string arg = to_utf8(cmd.argument());
1918 if (arg != "templates" && arg != "examples") {
1919 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1922 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1926 case LFUN_SET_COLOR: {
1927 string const lyx_name = cmd.getArg(0);
1928 string x11_name = cmd.getArg(1);
1929 string x11_darkname = cmd.getArg(2);
1930 if (lyx_name.empty() || x11_name.empty()) {
1932 current_view_->message(
1933 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1938 // FIXME: The graphics cache no longer has a changeDisplay method.
1939 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1940 bool const graphicsbg_changed =
1941 lyx_name == graphicsbg && x11_name != graphicsbg;
1942 if (graphicsbg_changed)
1943 graphics::GCache::get().changeDisplay(true);
1946 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1947 x11_darkname = x11_name;
1950 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1952 current_view_->message(
1953 bformat(_("Set-color \"%1$s\" failed "
1954 "- color is undefined or "
1955 "may not be redefined"),
1956 from_utf8(lyx_name)));
1959 // Make sure we don't keep old colors in cache.
1960 d->color_cache_.clear();
1961 // Update the current view
1962 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1966 case LFUN_LYXRC_APPLY: {
1967 // reset active key sequences, since the bindings
1968 // are updated (bug 6064)
1970 LyXRC const lyxrc_orig = lyxrc;
1972 istringstream ss(to_utf8(cmd.argument()));
1973 bool const success = lyxrc.read(ss);
1976 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1977 << "Unable to read lyxrc data"
1982 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1984 // If the request comes from the minibuffer, then we can't reset
1985 // the GUI, since that would destroy the minibuffer itself and
1986 // cause a crash, since we are currently in one of the methods of
1987 // GuiCommandBuffer. See bug #8540.
1988 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1991 // FIXME Unfortunately, that leaves a bug here, since we cannot
1992 // reset the GUI in this case. If the changes to lyxrc affected the
1993 // UI, then, nothing would happen. This seems fairly unlikely, but
1994 // it definitely is a bug.
1996 dr.forceBufferUpdate();
2000 case LFUN_COMMAND_PREFIX:
2001 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2006 d->meta_fake_bit = NoModifier;
2007 GuiView * gv = currentView();
2008 if (gv && gv->currentBufferView())
2009 // cancel any selection
2010 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2011 dr.setMessage(from_ascii(N_("Cancel")));
2014 case LFUN_META_PREFIX:
2015 d->meta_fake_bit = AltModifier;
2016 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2019 // --- Menus -----------------------------------------------
2020 case LFUN_RECONFIGURE:
2021 // argument is any additional parameter to the configure.py command
2022 reconfigure(to_utf8(cmd.argument()));
2025 // --- lyxserver commands ----------------------------
2026 case LFUN_SERVER_GET_FILENAME: {
2027 if (current_view_ && current_view_->documentBufferView()) {
2028 docstring const fname = from_utf8(
2029 current_view_->documentBufferView()->buffer().absFileName());
2030 dr.setMessage(fname);
2031 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2033 dr.setMessage(docstring());
2034 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2039 case LFUN_SERVER_NOTIFY: {
2040 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2041 dr.setMessage(dispatch_buffer);
2042 theServer().notifyClient(to_utf8(dispatch_buffer));
2046 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2047 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2053 string rest = split(argument, countstr, ' ');
2054 int const count = convert<int>(countstr);
2055 // an arbitrary number to limit number of iterations
2056 int const max_iter = 10000;
2057 if (count > max_iter) {
2058 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2061 for (int i = 0; i < count; ++i) {
2062 FuncRequest lfun = lyxaction.lookupFunc(rest);
2063 lfun.allowAsync(false);
2070 case LFUN_COMMAND_SEQUENCE: {
2071 // argument contains ';'-terminated commands
2072 string arg = argument;
2073 // FIXME: this LFUN should also work without any view.
2074 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2075 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2076 // This handles undo groups automagically
2077 UndoGroupHelper ugh(buffer);
2078 while (!arg.empty()) {
2080 arg = split(arg, first, ';');
2081 FuncRequest func(lyxaction.lookupFunc(first));
2082 func.allowAsync(false);
2083 func.setOrigin(cmd.origin());
2089 case LFUN_BUFFER_FORALL: {
2090 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2091 funcToRun.allowAsync(false);
2093 map<Buffer *, GuiView *> views_lVisible;
2094 map<GuiView *, Buffer *> activeBuffers;
2096 QList<GuiView *> allViews = d->views_.values();
2098 // this for does not modify any buffer. It just collects info on local
2099 // visibility of buffers and on which buffer is active in each view.
2100 Buffer * const last = theBufferList().last();
2101 for(GuiView * view : allViews) {
2102 // all of the buffers might be locally hidden. That is, there is no
2104 if (!view || !view->currentBufferView())
2105 activeBuffers[view] = nullptr;
2107 activeBuffers[view] = &view->currentBufferView()->buffer();
2109 // find out if each is locally visible or locally hidden.
2110 // we don't use a for loop as the buffer list cycles.
2111 Buffer * b = theBufferList().first();
2113 bool const locallyVisible = view && view->workArea(*b);
2114 if (locallyVisible) {
2115 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2116 // only need to overwrite/add if we don't already know a buffer is globally
2117 // visible or we do know but we would prefer to dispatch LFUN from the
2118 // current view because of cursor position issues.
2119 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2120 views_lVisible[b] = view;
2124 b = theBufferList().next(b);
2128 GuiView * const homeView = currentView();
2129 Buffer * b = theBufferList().first();
2130 Buffer * nextBuf = nullptr;
2131 int numProcessed = 0;
2134 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2136 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2138 // first change to a view where b is locally visible, preferably current_view_.
2139 GuiView * const vLv = views_lVisible[b];
2141 lyx::dispatch(funcToRun);
2149 // put things back to how they were (if possible).
2150 for (GuiView * view : allViews) {
2151 Buffer * originalBuf = activeBuffers[view];
2152 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2153 if (theBufferList().isLoaded(originalBuf))
2154 view->setBuffer(originalBuf);
2156 homeView->setFocus();
2158 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2162 case LFUN_COMMAND_ALTERNATIVES: {
2163 // argument contains ';'-terminated commands
2164 string arg = argument;
2165 while (!arg.empty()) {
2167 arg = split(arg, first, ';');
2168 FuncRequest func(lyxaction.lookupFunc(first));
2169 func.setOrigin(cmd.origin());
2170 FuncStatus const stat = getStatus(func);
2171 if (stat.enabled()) {
2181 if (theTopLevelCmdDef().lock(argument, func)) {
2182 func.setOrigin(cmd.origin());
2184 theTopLevelCmdDef().release(argument);
2186 if (func.action() == LFUN_UNKNOWN_ACTION) {
2187 // unknown command definition
2188 lyxerr << "Warning: unknown command definition `"
2192 // recursion detected
2193 lyxerr << "Warning: Recursion in the command definition `"
2194 << argument << "' detected"
2201 case LFUN_IF_RELATIVES: {
2202 string const lfun = to_utf8(cmd.argument());
2203 FuncRequest func(lyxaction.lookupFunc(lfun));
2204 func.setOrigin(cmd.origin());
2205 FuncStatus const stat = getStatus(func);
2206 if (stat.enabled()) {
2213 case LFUN_PREFERENCES_SAVE:
2214 lyxrc.write(support::makeAbsPath("preferences",
2215 package().user_support().absFileName()), false);
2218 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2219 string const fname = addName(addPath(package().user_support().absFileName(),
2220 "templates/"), "defaults.lyx");
2221 Buffer defaults(fname);
2223 istringstream ss(argument);
2228 // We need to make sure that, after we recreat the DocumentClass,
2229 // which we do in readHeader, we apply it to the document itself.
2230 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2231 int const unknown_tokens = defaults.readHeader(lex);
2232 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2233 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2234 cap::switchBetweenClasses(olddc, newdc, theinset);
2236 if (unknown_tokens != 0) {
2237 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2238 << unknown_tokens << " unknown token"
2239 << (unknown_tokens == 1 ? "" : "s")
2243 if (defaults.writeFile(FileName(defaults.absFileName())))
2244 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2245 makeDisplayPath(fname)));
2248 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2253 case LFUN_BOOKMARK_GOTO:
2254 // go to bookmark, open unopened file and switch to buffer if necessary
2255 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2256 dr.screenUpdate(Update::Force | Update::FitCursor);
2259 case LFUN_BOOKMARK_CLEAR:
2260 theSession().bookmarks().clear();
2261 dr.screenUpdate(Update::Force);
2264 case LFUN_DEBUG_LEVEL_SET:
2265 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2268 case LFUN_DIALOG_SHOW: {
2269 string const name = cmd.getArg(0);
2271 if ( name == "aboutlyx"
2273 || name == "texinfo"
2274 || name == "progress"
2275 || name == "compare")
2277 // work around: on Mac OS the application
2278 // is not terminated when closing the last view.
2279 // Create a new one to be able to dispatch the
2280 // LFUN_DIALOG_SHOW to this view.
2281 if (current_view_ == nullptr)
2287 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2290 current_view_->dispatch(cmd, dr);
2294 if (current_view_ && current_view_->isFullScreen()) {
2295 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2296 current_view_->menuBar()->hide();
2299 if (cmd.origin() == FuncRequest::LYXSERVER)
2300 updateCurrentView(cmd, dr);
2304 docstring GuiApplication::viewStatusMessage()
2306 // When meta-fake key is pressed, show the key sequence so far + "M-".
2307 if (d->meta_fake_bit != NoModifier)
2308 return d->keyseq.print(KeySequence::ForGui) + "M-";
2310 // Else, when a non-complete key sequence is pressed,
2311 // show the available options.
2312 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2313 return d->keyseq.printOptions(true);
2319 string GuiApplication::inputLanguageCode() const
2321 #if (QT_VERSION < 0x050000)
2322 QLocale loc = keyboardInputLocale();
2324 QLocale loc = inputMethod()->locale();
2326 //LYXERR0("input lang = " << fromqstr(loc.name()));
2327 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2331 void GuiApplication::onLocaleChanged()
2333 //LYXERR0("Change language to " << inputLanguage()->lang());
2334 if (currentView() && currentView()->currentBufferView())
2335 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2339 void GuiApplication::onPaletteChanged()
2341 colorCache().setPalette(palette());
2345 void GuiApplication::handleKeyFunc(FuncCode action)
2349 if (d->keyseq.length())
2351 GuiView * gv = currentView();
2352 LASSERT(gv && gv->currentBufferView(), return);
2353 BufferView * bv = gv->currentBufferView();
2354 bv->getIntl().getTransManager().deadkey(
2355 c, get_accent(action).accent, bv->cursor().innerText(),
2357 // Need to clear, in case the minibuffer calls these
2360 // copied verbatim from do_accent_char
2361 bv->cursor().resetAnchor();
2365 //Keep this in sync with GuiApplication::processKeySym below
2366 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2367 KeyModifier state) const
2369 // Do nothing if we have nothing
2370 if (!keysym.isOK() || keysym.isModifier())
2372 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2374 FuncRequest func = seq.addkey(keysym, state);
2375 // When not cancel or meta-fake, do the normal lookup.
2376 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2378 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2380 // Maybe user can only reach the key via holding down shift.
2381 // Let's see. But only if shift is the only modifier
2382 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2383 // If addkey looked up a command and did not find further commands then
2384 // seq has been reset at this point
2385 func = seq.addkey(keysym, NoModifier);
2387 LYXERR(Debug::KEY, " Key (queried) [action="
2388 << lyxaction.getActionName(func.action()) << "]["
2389 << seq.print(KeySequence::Portable) << ']');
2390 return func.action() != LFUN_UNKNOWN_ACTION;
2394 //Keep this in sync with GuiApplication::queryKeySym above
2395 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2397 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2399 // Do nothing if we have nothing (JMarc)
2400 if (!keysym.isOK() || keysym.isModifier()) {
2402 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2404 current_view_->restartCaret();
2408 char_type encoded_last_key = keysym.getUCSEncoded();
2410 // Do a one-deep top-level lookup for
2411 // cancel and meta-fake keys. RVDK_PATCH_5
2412 d->cancel_meta_seq.reset();
2414 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2415 LYXERR(Debug::KEY, "action first set to ["
2416 << lyxaction.getActionName(func.action()) << ']');
2418 // When not cancel or meta-fake, do the normal lookup.
2419 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2420 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2421 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2422 // remove Caps Lock and Mod2 as a modifiers
2423 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2424 LYXERR(Debug::KEY, "action now set to ["
2425 << lyxaction.getActionName(func.action()) << ']');
2428 // Don't remove this unless you know what you are doing.
2429 d->meta_fake_bit = NoModifier;
2431 // Can this happen now ?
2432 if (func.action() == LFUN_NOACTION)
2433 func = FuncRequest(LFUN_COMMAND_PREFIX);
2435 LYXERR(Debug::KEY, " Key [action="
2436 << lyxaction.getActionName(func.action()) << "]["
2437 << d->keyseq.print(KeySequence::Portable) << ']');
2439 // already here we know if it any point in going further
2440 // why not return already here if action == -1 and
2441 // num_bytes == 0? (Lgb)
2443 if (d->keyseq.length() > 1 && current_view_)
2444 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2447 // Maybe user can only reach the key via holding down shift.
2448 // Let's see. But only if shift is the only modifier
2449 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2450 LYXERR(Debug::KEY, "Trying without shift");
2451 // If addkey looked up a command and did not find further commands then
2452 // seq has been reset at this point
2453 func = d->keyseq.addkey(keysym, NoModifier);
2454 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2457 if (func.action() == LFUN_UNKNOWN_ACTION) {
2458 // We didn't match any of the key sequences.
2459 // See if it's normal insertable text not already
2460 // covered by a binding
2461 if (keysym.isText() && d->keyseq.length() == 1) {
2462 // Non-printable characters (such as ASCII control characters)
2463 // must not be inserted (#5704)
2464 if (!isPrintable(encoded_last_key)) {
2465 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2467 current_view_->restartCaret();
2470 // The following modifier check is not needed on Mac.
2471 // The keysym is either not text or it is different
2472 // from the non-modifier keysym. See #9875 for the
2473 // broken alt-modifier effect of having this code active.
2474 #if !defined(Q_OS_MAC)
2475 // If a non-Shift Modifier is used we have a non-bound key sequence
2476 // (such as Alt+j = j). This should be omitted (#5575).
2477 // On Windows, AltModifier and ControlModifier are both
2478 // set when AltGr is pressed. Therefore, in order to not
2479 // break AltGr-bound symbols (see #5575 for details),
2480 // unbound Ctrl+Alt key sequences are allowed.
2481 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2482 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2483 && !(state & AltModifier && state & ControlModifier)
2487 if (current_view_) {
2488 current_view_->message(_("Unknown function."));
2489 current_view_->restartCaret();
2494 // Since all checks above were passed, we now really have text that
2495 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2496 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2498 LYXERR(Debug::KEY, "isText() is true, inserting.");
2499 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2501 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2502 if (current_view_) {
2503 current_view_->message(_("Unknown function."));
2504 current_view_->restartCaret();
2510 if (func.action() == LFUN_SELF_INSERT) {
2511 if (encoded_last_key != 0) {
2512 docstring const arg(1, encoded_last_key);
2513 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2514 FuncRequest::KEYBOARD));
2515 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2518 processFuncRequest(func);
2522 void GuiApplication::processFuncRequest(FuncRequest const & func)
2524 lyx::dispatch(func);
2528 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2530 addToFuncRequestQueue(func);
2531 processFuncRequestQueueAsync();
2535 void GuiApplication::processFuncRequestQueue()
2537 while (!d->func_request_queue_.empty()) {
2538 // take the item from the stack _before_ processing the
2539 // request in order to avoid race conditions from nested
2540 // or parallel requests (see #10406)
2541 FuncRequest const fr(d->func_request_queue_.front());
2542 d->func_request_queue_.pop();
2543 processFuncRequest(fr);
2548 void GuiApplication::processFuncRequestQueueAsync()
2550 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2554 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2556 d->func_request_queue_.push(func);
2560 void GuiApplication::resetGui()
2562 // Set the language defined by the user.
2566 if (!readUIFile(toqstr(lyxrc.ui_file)))
2567 // Gives some error box here.
2570 if (d->global_menubar_)
2571 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2573 QHash<int, GuiView *>::iterator it;
2574 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2577 gv->setLayoutDirection(layoutDirection());
2581 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2585 bool GuiApplication::rtlContext() const
2587 if (current_view_ && current_view_->currentBufferView()) {
2588 BufferView const * bv = current_view_->currentBufferView();
2589 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2591 return layoutDirection() == Qt::RightToLeft;
2595 void GuiApplication::createView(int view_id)
2597 createView(QString(), true, view_id);
2601 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2604 // release the keyboard which might have been grabbed by the global
2605 // menubar on Mac to catch shortcuts even without any GuiView.
2606 if (d->global_menubar_)
2607 d->global_menubar_->releaseKeyboard();
2611 while (d->views_.find(id) != d->views_.end())
2614 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2615 GuiView * view = new GuiView(id);
2616 // `view' is the new current_view_. Tell coverity that is is not 0.
2617 LATTEST(current_view_);
2619 d->views_[id] = view;
2623 setActiveWindow(view);
2626 if (!geometry_arg.isEmpty()) {
2627 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2631 #if QT_VERSION < 0x060000
2632 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2633 re.indexIn(geometry_arg);
2634 w = re.cap(1).toInt();
2635 h = re.cap(2).toInt();
2636 x = re.cap(3).toInt();
2637 y = re.cap(4).toInt();
2638 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2639 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2641 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2642 QRegularExpressionMatch match = re.match(geometry_arg);
2643 w = match.captured(1).toInt();
2644 h = match.captured(2).toInt();
2645 x = match.captured(3).toInt();
2646 y = match.captured(4).toInt();
2647 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2648 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2650 // Set initial geometry such that we can get the frame size.
2651 view->setGeometry(x, y, w, h);
2652 int framewidth = view->geometry().x() - view->x();
2653 int titleheight = view->geometry().y() - view->y();
2654 // Negative displacements must be interpreted as distances
2655 // from the right or bottom screen borders.
2656 if (sx == '-' || sy == '-') {
2657 #if QT_VERSION < 0x060000
2658 QRect rec = QApplication::desktop()->screenGeometry();
2660 QRect rec = QGuiApplication::primaryScreen()->geometry();
2663 x += rec.width() - w - framewidth;
2665 y += rec.height() - h - titleheight;
2666 view->setGeometry(x, y, w, h);
2668 // Make sure that the left and top frame borders are visible.
2669 if (view->x() < 0 || view->y() < 0) {
2674 view->setGeometry(x, y, w, h);
2682 bool GuiApplication::unhide(Buffer * buf)
2686 currentView()->setBuffer(buf, false);
2691 Clipboard & GuiApplication::clipboard()
2693 return d->clipboard_;
2697 Selection & GuiApplication::selection()
2699 return d->selection_;
2703 FontLoader & GuiApplication::fontLoader()
2705 return d->font_loader_;
2709 Toolbars const & GuiApplication::toolbars() const
2711 return d->toolbars_;
2715 Toolbars & GuiApplication::toolbars()
2717 return d->toolbars_;
2721 Menus const & GuiApplication::menus() const
2727 Menus & GuiApplication::menus()
2733 bool GuiApplication::needsBackingStore() const
2735 /* Qt on macOS and Wayland does not respect the
2736 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2737 * store at each update. Therefore, we use our own backing store
2738 * in these two cases. It is also possible to force the use of the
2739 * backing store for cases like x11 with transparent WM themes.
2741 return platformName() == "cocoa" || platformName().contains("wayland");
2745 QList<int> GuiApplication::viewIds() const
2747 return d->views_.keys();
2751 ColorCache & GuiApplication::colorCache()
2753 return d->color_cache_;
2757 int GuiApplication::exec()
2759 // asynchronously handle batch commands. This event will be in
2760 // the event queue in front of other asynchronous events. Hence,
2761 // we can assume in the latter that the gui is setup already.
2762 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2764 return QApplication::exec();
2768 void GuiApplication::exit(int status)
2770 QApplication::exit(status);
2774 void GuiApplication::setGuiLanguage()
2778 // install translation file for Qt built-in dialogs
2779 QString const language_name = QString("qt_") + theLocale.name();
2780 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2781 // Short-named translator can be loaded from a long name, but not the
2782 // opposite. Therefore, long name should be used without truncation.
2783 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2784 if (!d->qt_trans_.load(language_name,
2785 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2786 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2788 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2790 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2793 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2797 switch (theLocale.language()) {
2798 case QLocale::Arabic :
2799 case QLocale::Hebrew :
2800 case QLocale::Persian :
2801 case QLocale::Urdu :
2802 setLayoutDirection(Qt::RightToLeft);
2805 setLayoutDirection(Qt::LeftToRight);
2810 void GuiApplication::execBatchCommands()
2815 if (!readUIFile(toqstr(lyxrc.ui_file)))
2816 // Gives some error box here.
2820 #if QT_VERSION > 0x040600
2821 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2823 #if QT_VERSION >= 0x050000 && QT_VERSION < 0x060000
2824 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2826 // Create the global default menubar which is shown for the dialogs
2827 // and if no GuiView is visible.
2828 // This must be done after the session was recovered to know the "last files".
2829 d->global_menubar_ = new QMenuBar(0);
2830 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2833 lyx::execBatchCommands();
2837 QAbstractItemModel * GuiApplication::languageModel()
2839 if (d->language_model_)
2840 return d->language_model_;
2842 QStandardItemModel * lang_model = new QStandardItemModel(this);
2843 lang_model->insertColumns(0, 3);
2844 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2845 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2846 Languages::const_iterator it = lyx::languages.begin();
2847 Languages::const_iterator end = lyx::languages.end();
2848 for (; it != end; ++it) {
2849 int current_row = lang_model->rowCount();
2850 lang_model->insertRows(current_row, 1);
2851 QModelIndex pl_item = lang_model->index(current_row, 0);
2852 QModelIndex sp_item = lang_model->index(current_row, 1);
2853 QModelIndex th_item = lang_model->index(current_row, 2);
2854 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2855 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2856 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2857 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2858 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2859 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2860 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2861 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2862 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2863 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2865 d->language_model_ = new QSortFilterProxyModel(this);
2866 d->language_model_->setSourceModel(lang_model);
2867 d->language_model_->setSortLocaleAware(true);
2868 return d->language_model_;
2872 void GuiApplication::restoreGuiSession()
2874 if (!lyxrc.load_session)
2877 Session & session = theSession();
2878 LastOpenedSection::LastOpened const & lastopened =
2879 session.lastOpened().getfiles();
2881 validateCurrentView();
2883 FileName active_file;
2884 // do not add to the lastfile list since these files are restored from
2885 // last session, and should be already there (regular files), or should
2886 // not be added at all (help files).
2887 for (auto const & last : lastopened) {
2888 FileName const & file_name = last.file_name;
2889 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2890 && current_view_->documentBufferView() != nullptr)) {
2891 string const & fname = file_name.absFileName();
2892 createView(support::checksum(fname));
2894 current_view_->loadDocument(file_name, false);
2897 active_file = file_name;
2900 // Restore last active buffer
2901 Buffer * buffer = theBufferList().getBuffer(active_file);
2902 if (buffer && current_view_)
2903 current_view_->setBuffer(buffer);
2905 // clear this list to save a few bytes of RAM
2906 session.lastOpened().clear();
2910 QString const GuiApplication::romanFontName()
2913 font.setStyleHint(QFont::Serif);
2914 font.setFamily("serif");
2916 return QFontInfo(font).family();
2920 QString const GuiApplication::sansFontName()
2923 font.setStyleHint(QFont::SansSerif);
2924 font.setFamily("sans");
2926 return QFontInfo(font).family();
2930 QString const GuiApplication::typewriterFontName()
2932 return QFontInfo(typewriterSystemFont()).family();
2937 // We cannot use QFont::fixedPitch() because it doesn't
2938 // return the fact but only if it is requested.
2939 static bool isFixedPitch(const QFont & font) {
2940 const QFontInfo fi(font);
2941 return fi.fixedPitch();
2946 QFont const GuiApplication::typewriterSystemFont()
2948 #if QT_VERSION >= 0x050200
2949 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2951 QFont font("monospace");
2953 if (!isFixedPitch(font)) {
2954 // try to enforce a real monospaced font
2955 font.setStyleHint(QFont::Monospace);
2956 if (!isFixedPitch(font)) {
2957 font.setStyleHint(QFont::TypeWriter);
2958 if (!isFixedPitch(font)) font.setFamily("courier");
2962 // On a Mac the result is too small and it's not practical to
2963 // rely on Qtconfig utility to change the system settings of Qt.
2964 font.setPointSize(12);
2970 void GuiApplication::handleRegularEvents()
2972 ForkedCallsController::handleCompletedProcesses();
2976 bool GuiApplication::event(QEvent * e)
2979 case QEvent::FileOpen: {
2980 // Open a file; this happens only on Mac OS X for now.
2982 // We do this asynchronously because on startup the batch
2983 // commands are not executed here yet and the gui is not ready
2985 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2986 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2987 processFuncRequestAsync(fr);
2991 #if (QT_VERSION < 0x050000)
2992 // Qt5 uses a signal for that, see above.
2993 case QEvent::KeyboardLayoutChange:
2994 //LYXERR0("keyboard change");
2995 if (currentView() && currentView()->currentBufferView())
2996 currentView()->currentBufferView()->cursor().setLanguageFromInput();
3000 case QEvent::ApplicationPaletteChange: {
3001 // runtime switch from/to dark mode
3003 return QApplication::event(e);
3006 return QApplication::event(e);
3011 bool GuiApplication::notify(QObject * receiver, QEvent * event)
3014 return QApplication::notify(receiver, event);
3016 catch (ExceptionMessage const & e) {
3018 case ErrorException:
3020 setQuitOnLastWindowClosed(false);
3022 Alert::error(e.title_, e.details_);
3024 // Properly crash in debug mode in order to get a useful backtrace.
3027 // In release mode, try to exit gracefully.
3029 // FIXME: GCC 7 thinks we can fall through here. Can we?
3031 case BufferException: {
3032 if (!current_view_ || !current_view_->documentBufferView())
3034 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3035 docstring details = e.details_ + '\n';
3036 details += buf->emergencyWrite();
3037 theBufferList().release(buf);
3038 details += "\n" + _("The current document was closed.");
3039 Alert::error(e.title_, details);
3042 case WarningException:
3043 Alert::warning(e.title_, e.details_);
3047 catch (exception const & e) {
3048 docstring s = _("LyX has caught an exception, it will now "
3049 "attempt to save all unsaved documents and exit."
3051 s += from_ascii(e.what());
3052 Alert::error(_("Software exception Detected"), s);
3056 docstring s = _("LyX has caught some really weird exception, it will "
3057 "now attempt to save all unsaved documents and exit.");
3058 Alert::error(_("Software exception Detected"), s);
3065 bool GuiApplication::isInDarkMode()
3067 return colorCache().isDarkMode();
3071 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3073 QColor const & qcol = d->color_cache_.get(col);
3074 if (!qcol.isValid()) {
3080 rgbcol.r = qcol.red();
3081 rgbcol.g = qcol.green();
3082 rgbcol.b = qcol.blue();
3087 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3089 QColor const qcol(lcolor.getX11HexName(col).c_str());
3090 if (!qcol.isValid()) {
3096 rgbcol.r = qcol.red();
3097 rgbcol.g = qcol.green();
3098 rgbcol.b = qcol.blue();
3103 string const GuiApplication::hexName(ColorCode col)
3105 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3109 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3111 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3112 d->socket_notifiers_[fd] = sn;
3113 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3117 void GuiApplication::socketDataReceived(int fd)
3119 d->socket_notifiers_[fd]->func_();
3123 void GuiApplication::unregisterSocketCallback(int fd)
3125 d->socket_notifiers_.take(fd)->setEnabled(false);
3129 void GuiApplication::commitData(QSessionManager & sm)
3131 /** The implementation is required to avoid an application exit
3132 ** when session state save is triggered by session manager.
3133 ** The default implementation sends a close event to all
3134 ** visible top level widgets when session management allows
3136 ** We are changing that to check the state of each buffer in all
3137 ** views and ask the users what to do if buffers are dirty.
3138 ** Furthermore, we save the session state.
3139 ** We do NOT close the views here since the user still can cancel
3140 ** the logout process (see #9277); also, this would hide LyX from
3141 ** an OSes own session handling (application restoration).
3143 #ifdef QT_NO_SESSIONMANAGER
3145 #warning Qt is compiled without session manager
3147 #pragma message("warning: Qt is compiled without session manager")
3151 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3159 void GuiApplication::unregisterView(GuiView * gv)
3161 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3162 d->views_.remove(gv->id());
3163 if (current_view_ == gv)
3164 current_view_ = nullptr;
3169 bool GuiApplication::closeAllViews()
3171 if (d->views_.empty())
3174 // When a view/window was closed before without quitting LyX, there
3175 // are already entries in the lastOpened list.
3176 theSession().lastOpened().clear();
3178 QList<GuiView *> const views = d->views_.values();
3179 for (GuiView * view : views) {
3180 if (!view->closeScheduled())
3189 bool GuiApplication::prepareAllViewsForLogout()
3191 if (d->views_.empty())
3194 QList<GuiView *> const views = d->views_.values();
3195 for (GuiView * view : views) {
3196 if (!view->prepareAllBuffersForLogout())
3204 GuiView & GuiApplication::view(int id) const
3206 LAPPERR(d->views_.contains(id));
3207 return *d->views_.value(id);
3211 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3213 QList<GuiView *> const views = d->views_.values();
3214 for (GuiView * view : views)
3215 view->hideDialog(name, inset);
3219 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3221 Buffer const * buf = nullptr;
3222 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3223 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3224 if (Buffer const * ptr = (*it)->updateInset(inset))
3231 bool GuiApplication::searchMenu(FuncRequest const & func,
3232 docstring_list & names) const
3234 BufferView * bv = nullptr;
3236 bv = current_view_->currentBufferView();
3237 return d->menus_.searchMenu(func, names, bv);
3241 bool GuiApplication::hasBufferView() const
3243 return (current_view_ && current_view_->currentBufferView());
3247 // Ensure that a file is read only once (prevents include loops)
3248 static QStringList uifiles;
3249 // store which ui files define Toolbars
3250 static QStringList toolbar_uifiles;
3253 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3264 LexerKeyword uitags[] = {
3265 { "format", ui_format },
3266 { "include", ui_include },
3267 { "menuset", ui_menuset },
3268 { "toolbars", ui_toolbars },
3269 { "toolbarset", ui_toolbarset }
3273 lex.setFile(ui_path);
3275 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3279 if (lyxerr.debugging(Debug::PARSER))
3280 lex.printTable(lyxerr);
3283 // format before introduction of format tag
3284 unsigned int format = 0;
3285 while (lex.isOK()) {
3286 int const status = lex.lex();
3288 // we have to do this check here, outside the switch,
3289 // because otherwise we would start reading include files,
3290 // e.g., if the first tag we hit was an include tag.
3291 if (status == ui_format)
3293 format = lex.getInteger();
3297 // this will trigger unless the first tag we hit is a format
3298 // tag, with the right format.
3299 if (format != LFUN_FORMAT)
3300 return FormatMismatch;
3303 case Lexer::LEX_FEOF:
3308 QString const file = toqstr(lex.getString());
3309 bool const success = readUIFile(file, true);
3311 LYXERR0("Failed to read included file: " << fromqstr(file));
3318 d->menus_.read(lex);
3322 d->toolbars_.readToolbars(lex);
3326 d->toolbars_.readToolbarSettings(lex);
3327 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3331 if (!rtrim(lex.getString()).empty())
3332 lex.printError("LyX::ReadUIFile: "
3333 "Unknown menu tag: `$$Token'");
3335 LYXERR0("Error with status: " << status);
3341 return (error ? ReadError : ReadOK);
3345 bool GuiApplication::readUIFile(QString const & name, bool include)
3347 LYXERR(Debug::INIT, "About to read " << name << "...");
3351 ui_path = libFileSearch("ui", name, "inc");
3352 if (ui_path.empty())
3353 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3355 ui_path = libFileSearch("ui", name, "ui");
3358 if (ui_path.empty()) {
3359 static const QString defaultUIFile = "default";
3360 LYXERR(Debug::INIT, "Could not find " << name);
3362 Alert::warning(_("Could not find UI definition file"),
3363 bformat(_("Error while reading the included file\n%1$s\n"
3364 "Please check your installation."), qstring_to_ucs4(name)));
3367 if (name == defaultUIFile) {
3368 LYXERR(Debug::INIT, "Could not find default UI file!!");
3369 Alert::warning(_("Could not find default UI file"),
3370 _("LyX could not find the default UI file!\n"
3371 "Please check your installation."));
3374 Alert::warning(_("Could not find UI definition file"),
3375 bformat(_("Error while reading the configuration file\n%1$s\n"
3376 "Falling back to default.\n"
3377 "Please look under Tools>Preferences>User Interface and\n"
3378 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3379 return readUIFile(defaultUIFile, false);
3382 QString const uifile = toqstr(ui_path.absFileName());
3383 if (uifiles.contains(uifile)) {
3385 // We are reading again the top uifile so reset the safeguard:
3388 d->toolbars_.reset();
3390 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3391 << "Is this an include loop?");
3395 uifiles.push_back(uifile);
3397 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3399 ReturnValues retval = readUIFile(ui_path);
3401 if (retval == FormatMismatch) {
3402 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3403 TempFile tmp("convertXXXXXX.ui");
3404 FileName const tempfile = tmp.name();
3405 bool const success = prefs2prefs(ui_path, tempfile, true);
3407 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3408 " to format " << LFUN_FORMAT << ".");
3410 retval = readUIFile(tempfile);
3414 if (retval != ReadOK) {
3415 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3423 settings.beginGroup("ui_files");
3424 bool touched = false;
3425 for (int i = 0; i != uifiles.size(); ++i) {
3426 QFileInfo fi(uifiles[i]);
3427 QDateTime const date_value = fi.lastModified();
3428 QString const name_key = QString::number(i);
3429 // if an ui file which defines Toolbars has changed,
3430 // we have to reset the settings
3431 if (toolbar_uifiles.contains(uifiles[i])
3432 && (!settings.contains(name_key)
3433 || settings.value(name_key).toString() != uifiles[i]
3434 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3436 settings.setValue(name_key, uifiles[i]);
3437 settings.setValue(name_key + "/date", date_value);
3440 settings.endGroup();
3442 settings.remove("views");
3448 void GuiApplication::onLastWindowClosed()
3450 if (d->global_menubar_)
3451 d->global_menubar_->grabKeyboard();
3455 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3456 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3458 std::string name = "unknown";
3460 case Qt::ApplicationSuspended:
3461 name = "ApplicationSuspended";
3463 case Qt::ApplicationHidden:
3464 name = "ApplicationHidden";
3466 case Qt::ApplicationInactive:
3467 name = "ApplicationInactive";
3469 case Qt::ApplicationActive:
3470 name = "ApplicationActive";
3471 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3472 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3473 if (d->views_.empty() && d->last_state_ == state) {
3474 LYXERR(Debug::GUI, "Open new window...");
3479 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3480 d->last_state_ = state;
3485 void GuiApplication::startLongOperation() {
3486 d->key_checker_.start();
3490 bool GuiApplication::longOperationCancelled() {
3491 return d->key_checker_.pressed();
3495 void GuiApplication::stopLongOperation() {
3496 d->key_checker_.stop();
3500 bool GuiApplication::longOperationStarted() {
3501 return d->key_checker_.started();
3505 ////////////////////////////////////////////////////////////////////////
3507 // X11 specific stuff goes here...
3510 bool GuiApplication::x11EventFilter(XEvent * xev)
3515 switch (xev->type) {
3516 case SelectionRequest: {
3517 if (xev->xselectionrequest.selection != XA_PRIMARY)
3519 LYXERR(Debug::SELECTION, "X requested selection.");
3520 BufferView * bv = current_view_->currentBufferView();
3522 docstring const sel = bv->requestSelection();
3524 d->selection_.put(sel);
3525 // Refresh the selection request timestamp.
3526 // We have to do this by ourselves as Qt seems
3527 // not doing that, maybe because of our
3528 // "persistent selection" implementation
3529 // (see comments in GuiSelection.cpp).
3530 XSelectionEvent nev;
3531 nev.type = SelectionNotify;
3532 nev.display = xev->xselectionrequest.display;
3533 nev.requestor = xev->xselectionrequest.requestor;
3534 nev.selection = xev->xselectionrequest.selection;
3535 nev.target = xev->xselectionrequest.target;
3536 nev.property = 0L; // None
3537 nev.time = CurrentTime;
3538 XSendEvent(QX11Info::display(),
3539 nev.requestor, False, 0,
3540 reinterpret_cast<XEvent *>(&nev));
3546 case SelectionClear: {
3547 if (xev->xselectionclear.selection != XA_PRIMARY)
3549 LYXERR(Debug::SELECTION, "Lost selection.");
3550 BufferView * bv = current_view_->currentBufferView();
3552 bv->clearSelection();
3558 #elif defined(QPA_XCB)
3559 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3560 void * message, long *)
3562 if (!current_view_ || eventType != "xcb_generic_event_t")
3565 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3567 switch (ev->response_type) {
3568 case XCB_SELECTION_REQUEST: {
3569 xcb_selection_request_event_t * srev =
3570 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3571 if (srev->selection != XCB_ATOM_PRIMARY)
3573 LYXERR(Debug::SELECTION, "X requested selection.");
3574 BufferView * bv = current_view_->currentBufferView();
3576 docstring const sel = bv->requestSelection();
3578 d->selection_.put(sel);
3579 #ifdef HAVE_QT5_X11_EXTRAS
3580 // Refresh the selection request timestamp.
3581 // We have to do this by ourselves as Qt seems
3582 // not doing that, maybe because of our
3583 // "persistent selection" implementation
3584 // (see comments in GuiSelection.cpp).
3585 // It is expected that every X11 event is
3586 // 32 bytes long, even if not all 32 bytes are
3588 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3589 struct alignas(32) padded_event
3590 : xcb_selection_notify_event_t {};
3591 padded_event nev = {};
3592 nev.response_type = XCB_SELECTION_NOTIFY;
3593 nev.requestor = srev->requestor;
3594 nev.selection = srev->selection;
3595 nev.target = srev->target;
3596 nev.property = XCB_NONE;
3597 nev.time = XCB_CURRENT_TIME;
3598 xcb_connection_t * con = QX11Info::connection();
3599 xcb_send_event(con, 0, srev->requestor,
3600 XCB_EVENT_MASK_NO_EVENT,
3601 reinterpret_cast<char const *>(&nev));
3609 case XCB_SELECTION_CLEAR: {
3610 xcb_selection_clear_event_t * scev =
3611 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3612 if (scev->selection != XCB_ATOM_PRIMARY)
3614 LYXERR(Debug::SELECTION, "Lost selection.");
3615 BufferView * bv = current_view_->currentBufferView();
3617 bv->clearSelection();
3625 } // namespace frontend
3628 void hideDialogs(std::string const & name, Inset * inset)
3631 frontend::guiApp->hideDialogs(name, inset);
3635 ////////////////////////////////////////////////////////////////////
3639 ////////////////////////////////////////////////////////////////////
3641 frontend::FontLoader & theFontLoader()
3643 LAPPERR(frontend::guiApp);
3644 return frontend::guiApp->fontLoader();
3648 frontend::FontMetrics const & theFontMetrics(Font const & f)
3650 return theFontMetrics(f.fontInfo());
3654 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3656 LAPPERR(frontend::guiApp);
3657 return frontend::guiApp->fontLoader().metrics(f);
3661 ////////////////////////////////////////////////////////////////////
3665 ////////////////////////////////////////////////////////////////////
3667 frontend::Clipboard & theClipboard()
3669 LAPPERR(frontend::guiApp);
3670 return frontend::guiApp->clipboard();
3674 frontend::Selection & theSelection()
3676 LAPPERR(frontend::guiApp);
3677 return frontend::guiApp->selection();
3683 #include "moc_GuiApplication.cpp"