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>
127 #ifdef HAVE_QT5_X11_EXTRAS
128 #include <QtX11Extras/QX11Info>
132 #if (QT_VERSION >= 0x050400)
133 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
134 #if (QT_VERSION >= 0x060000)
135 #include <QtGui/private/qguiapplication_p.h>
136 #include <QtGui/private/qwindowsmime_p.h>
137 #include <QtGui/qpa/qplatformintegration.h>
138 #define QWINDOWSMIME QWindowsMime
139 #define QVARIANTTYPE QMetaType
140 using QWindowsMime = QNativeInterface::Private::QWindowsMime;
141 using QWindowsApplication = QNativeInterface::Private::QWindowsApplication;
144 #define QWINDOWSMIME QWinMime
145 #define QVARIANTTYPE QVariant::Type
154 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
155 #include <QMacPasteboardMime>
163 using namespace lyx::support;
168 frontend::Application * createApplication(int & argc, char * argv[])
170 #if !defined(QPA_XCB)
171 // prune -geometry argument(s) by shifting
172 // the following ones 2 places down.
173 for (int i = 0 ; i < argc ; ++i) {
174 if (strcmp(argv[i], "-geometry") == 0) {
175 int const remove = (i+1) < argc ? 2 : 1;
177 for (int j = i; j < argc; ++j)
178 argv[j] = argv[j + remove];
184 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
185 // On Windows, allow bringing the LyX window to top
186 AllowSetForegroundWindow(ASFW_ANY);
190 #if defined(Q_OS_MAC)
191 int const cursor_time_on = NSTextInsertionPointBlinkPeriodOn();
192 int const cursor_time_off = NSTextInsertionPointBlinkPeriodOff();
193 if (cursor_time_on > 0 && cursor_time_off > 0) {
194 QApplication::setCursorFlashTime(cursor_time_on + cursor_time_off);
195 } else if (cursor_time_on <= 0 && cursor_time_off > 0) {
196 // Off is set and On is undefined of zero
197 QApplication::setCursorFlashTime(0);
198 } else if (cursor_time_off <= 0 && cursor_time_on > 0) {
199 // On is set and Off is undefined of zero
200 QApplication::setCursorFlashTime(0);
204 // Setup high DPI handling. This is a bit complicated, but will be default in Qt6.
205 // macOS does it by itself.
206 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) && !defined(Q_OS_MAC)
207 #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
208 // Attribute Qt::AA_EnableHighDpiScaling must be set before QCoreApplication is created
209 if (getEnv("QT_ENABLE_HIGHDPI_SCALING").empty()
210 && getEnv("QT_AUTO_SCREEN_SCALE_FACTOR").empty())
211 QApplication::setAttribute(Qt::AA_EnableHighDpiScaling, true);
214 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
215 // HighDPI scale factor policy must be set before QGuiApplication is created
216 if (getEnv("QT_SCALE_FACTOR_ROUNDING_POLICY").empty())
217 QApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
221 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
222 // I'd rather do that in the constructor, but I do not think that
223 // the palette is accessible there.
224 guiApp->colorCache().setPalette(guiApp->palette());
233 if (lyxrc.gui_language == "auto") {
234 theLocale = QLocale::system();
235 code = fromqstr(theLocale.name());
237 Language const * l = languages.getLanguage(lyxrc.gui_language);
238 code = l ? l->code() : "C";
239 theLocale = QLocale(toqstr(code));
241 // Qt tries to outsmart us and transforms en_US to C.
242 Messages::guiLanguage((code == "C") ? "en_US" : code);
243 QLocale::setDefault(theLocale);
244 setlocale(LC_NUMERIC, "C");
251 /// Return the list of loadable formats.
252 vector<string> loadableImageFormats()
256 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
258 LYXERR(Debug::GRAPHICS,
259 "\nThe image loader can load the following directly:\n");
261 if (qt_formats.empty())
262 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
264 bool jpeg_found = false;
265 bool jpg_found = false;
266 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
268 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
270 string ext = ascii_lowercase((const char *) *it);
278 else if (ext == "jpg") {
283 else if (lyxrc.use_converter_cache &&
284 (ext == "svg" || ext == "svgz") &&
285 theConverters().isReachable("svg", "png"))
286 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
287 // the SVG as in the output. However we require that the converter
288 // cache is enabled since this is expensive. We also require that
289 // an explicit svg->png converter is defined, since the default
290 // converter could produce bad quality as well. This assumes that
291 // png can always be loaded.
300 ////////////////////////////////////////////////////////////////////////
302 // Icon loading support code
304 ////////////////////////////////////////////////////////////////////////
314 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
316 return lhs.key < rhs.key;
322 CompareKey(QString const & name) : name_(name) {}
323 bool operator()(ImgMap const & other) const { return other.key == name_; }
329 // this must be sorted alphabetically
330 // Upper case comes before lower case
331 // Please don't change the formatting, this list is parsed by
332 // development/tools/generate_symbols_images.py.
333 ImgMap sorted_img_map[] = {
334 { "Arrownot", "arrownot2"},
335 { "Arrowvert", "arrowvert2"},
336 { "Bowtie", "bowtie2" },
338 { "Bumpeq", "bumpeq2" },
339 { "CIRCLE", "circle3" },
341 { "CheckedBox", "checkedbox2" },
342 { "Circle", "circle2" },
343 { "Colonapprox", "colonapprox2" },
344 { "Coloneq", "coloneq2" },
345 { "Coloneqq", "coloneqq2" },
346 { "Colonsim", "colonsim2" },
348 { "DOWNarrow", "downarrow3" },
349 { "Delta", "delta2" },
350 { "Diamond", "diamond2" },
351 { "Doteq", "doteq2" },
352 { "Downarrow", "downarrow2" },
353 { "Eqcolon", "eqcolon2" },
354 { "Eqqcolon", "eqqcolon2" },
355 { "Gamma", "gamma2" },
357 { "LEFTCIRCLE", "leftcircle3" },
358 { "LEFTarrow", "leftarrow3" },
359 { "LEFTcircle", "leftcircle4" },
361 { "Lambda", "lambda2" },
363 { "Leftarrow", "leftarrow2" },
364 { "Leftcircle", "leftcircle2" },
365 { "Leftrightarrow", "leftrightarrow2" },
366 { "Longarrownot", "longarrownot2"},
367 { "Longleftarrow", "longleftarrow2" },
368 { "Longleftrightarrow", "longleftrightarrow2" },
369 { "Longmapsfrom", "longmapsfrom2"},
370 { "Longmapsto", "longmapsto2"},
371 { "Longrightarrow", "longrightarrow2" },
372 { "Mapsfrom", "mapsfrom2"},
373 { "Mapsfromchar", "mapsfromchar2"},
374 { "Mapsto", "mapsto2"},
375 { "Mapstochar", "mapstochar2"},
376 { "Omega", "omega2" },
381 { "RIGHTCIRCLE", "rightcircle3" },
382 { "RIGHTarrow", "rightarrow3" },
383 { "RIGHTcircle", "rightcircle4" },
385 { "Rightarrow", "rightarrow2" },
386 { "Rightcircle", "rightcircle2" },
387 { "Sigma", "sigma2" },
388 { "Square", "square2" },
389 { "Subset", "subset2" },
390 { "Supset", "supset2" },
391 { "Theta", "theta2" },
392 { "Thorn", "thorn2" },
393 { "UParrow", "uparrow3" },
394 { "Uparrow", "uparrow2" },
395 { "Updownarrow", "updownarrow2" },
396 { "Upsilon", "upsilon2" },
397 { "Vdash", "vdash3" },
402 { "lVert", "vert2" },
404 { "nLeftarrow", "nleftarrow2" },
405 { "nLeftrightarrow", "nleftrightarrow2" },
406 { "nRightarrow", "nrightarrow2" },
407 { "nVDash", "nvdash3" },
408 { "nVdash", "nvdash4" },
409 { "nvDash", "nvdash2" },
410 { "rVert", "vert2" },
412 { "textrm \\AA", "textrm_AA"},
413 { "textrm \\O", "textrm_O"},
414 { "vDash", "vdash2" },
415 { "varDelta", "vardelta2" },
416 { "varGamma", "vargamma2" },
417 { "varLambda", "varlambda2" },
418 { "varOmega", "varomega2" },
419 { "varPhi", "varphi2" },
420 { "varPi", "varpi2" },
421 { "varPsi", "varpsi2" },
422 { "varSigma", "varsigma2" },
423 { "varTheta", "vartheta2" },
424 { "varUpsilon", "varupsilon2" },
425 { "varXi", "varxi2" }
429 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
431 // This list specifies which system's theme icon is related to which lyx
432 // command. It was based on:
433 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
434 // this must be sorted alphabetically
435 // Upper case comes before lower case
436 ImgMap sorted_theme_icon_map[] = {
437 { "bookmark-goto 0", "go-jump" },
438 { "buffer-new", "document-new" },
439 { "buffer-write", "document-save" },
440 { "buffer-write-as", "document-save-as" },
441 { "buffer-zoom-in", "zoom-in" },
442 { "buffer-zoom-out", "zoom-out" },
443 { "copy", "edit-copy" },
444 { "cut", "edit-cut" },
445 { "depth-decrement", "format-indent-less" },
446 { "depth-increment", "format-indent-more" },
447 { "dialog-show spellchecker", "tools-check-spelling" },
448 { "dialog-show-new-inset graphics", "insert-image" },
449 { "dialog-toggle findreplaceadv", "edit-find-replace" },
450 { "file-open", "document-open" },
451 { "font-bold", "format-text-bold" },
452 { "font-ital", "format-text-italic" },
453 { "font-strikeout", "format-text-strikethrough" },
454 { "font-underline", "format-text-underline" },
455 { "lyx-quit", "application-exit" },
456 { "paste", "edit-paste" },
457 { "redo", "edit-redo" },
458 { "undo", "edit-undo" },
459 { "window-close", "window-close" },
460 { "window-new", "window-new" }
463 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
466 QString findImg(QString const & name)
468 ImgMap const * const begin = sorted_img_map;
469 ImgMap const * const end = begin + nr_sorted_img_map;
470 LATTEST(sorted(begin, end));
472 ImgMap const * const it = find_if(begin, end, CompareKey(name));
476 img_name = it->value;
479 img_name.replace('_', "underscore");
480 img_name.replace(' ', '_');
482 // This way we can have "math-delim { }" on the toolbar.
483 img_name.replace('(', "lparen");
484 img_name.replace(')', "rparen");
485 img_name.replace('[', "lbracket");
486 img_name.replace(']', "rbracket");
487 img_name.replace('{', "lbrace");
488 img_name.replace('}', "rbrace");
489 img_name.replace('|', "bars");
490 img_name.replace(',', "thinspace");
491 img_name.replace(':', "mediumspace");
492 img_name.replace(';', "thickspace");
493 img_name.replace('!', "negthinspace");
496 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
497 << "Looking for math icon called \"" << img_name << '"');
504 QString themeIconName(QString const & action)
506 ImgMap const * const begin = sorted_theme_icon_map;
507 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
508 LASSERT(sorted(begin, end), /**/);
510 ImgMap const * const it = find_if(begin, end, CompareKey(action));
520 /* Get aliases for icon name. This allows to avoid duplication of
521 * icons when new versions of functions are introduced for the
522 * toolbar. A good example is the introduction of layout-toggle in
524 * The file is parsed by Lexer. Each line is of the form
525 * <original substring> <replacement substring>
527 * The return value is another icon file name that can be queried.
529 // FIXME: consider using regular expressions.
530 QString getAlias(QString name) {
531 static bool has_aliases = false;
532 static vector <pair<QString,QString>> aliases;
533 // Initialize aliases list (once).
535 FileName alfile = libFileSearch("images", "icon.aliases");
536 if (alfile.exists()) {
543 aliases.push_back({toqstr(from), toqstr(to)});
548 // check for the following aliases
549 for (auto const & alias : aliases) {
550 if (name.contains(alias.first))
551 name.replace(alias.first, alias.second);
559 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
564 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
566 if (!f.argument().empty()) {
567 // if there are arguments, first search an icon which name is the full thing
568 QString name = lfunname + ' ' + toqstr(f.argument());
569 name.replace(' ', '_');
570 name.replace(';', '_');
571 name.replace('\\', "backslash");
573 QString alias = getAlias(name);
577 // then special default icon for some lfuns
578 switch (f.action()) {
579 case LFUN_MATH_INSERT:
580 names << "math/" + findImg(toqstr(f.argument()).mid(1));
582 case LFUN_MATH_DELIM:
583 case LFUN_MATH_BIGDELIM:
584 names << "math/" + findImg(toqstr(f.argument()));
587 names << "commands/" + toqstr(f.argument());
589 case LFUN_COMMAND_ALTERNATIVES: {
590 // use the first of the alternative commands
592 docstring dummy = split(f.argument(), firstcom, ';');
593 QString name1 = toqstr(firstcom);
594 name1.replace(' ', '_');
595 name1.replace(';', '_');
596 name1.replace('\\', "backslash");
605 // next thing to try is function name alone
607 QString alias = getAlias(lfunname);
608 if (alias != lfunname)
611 // and finally maybe the unknown icon
615 search_mode const mode = theGuiApp() ? theGuiApp()->imageSearchMode() : support::must_exist;
616 // The folders where icons are searched for
617 QStringList imagedirs;
618 imagedirs << "images/ipa/" << "images/";
619 // This is used to search for rtl version of icons which have the +rtl suffix.
620 QStringList suffixes;
623 suffixes << QString();
625 for (QString const & imagedir : imagedirs)
626 for (QString const & name : names)
627 for (QString const & suffix : suffixes) {
628 QString id = imagedir;
629 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
630 if (fname.exists()) {
631 docstring const fpath = fname.absoluteFilePath();
632 res.filepath = toqstr(fname.absFileName());
633 // these icons are subject to inversion in dark mode
634 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
635 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
636 res.swap = rtl && suffix.isEmpty();
641 LYXERR(Debug::GUI, "Cannot find icon for command \""
642 << lyxaction.getActionName(f.action())
643 << '(' << to_utf8(f.argument()) << ")\"");
649 QPixmap prepareForDarkMode(QPixmap pixmap)
651 QPalette palette = QPalette();
652 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
653 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
655 // guess whether we are in dark mode
656 if (text_color.black() > bg_color.black())
657 // not in dark mode, do nothing
660 // create a layer with black text turned to QPalette::WindowText
661 QPixmap black_overlay(pixmap.size());
662 black_overlay.fill(text_color);
663 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
665 // create a layer with blue text turned to lighter blue
666 QPixmap blue_overlay(pixmap.size());
667 QColor math_blue(0, 0, 255);
668 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
669 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
671 // create a layer with ("latex") red text turned to lighter red
672 QPixmap red_overlay(pixmap.size());
673 QColor math_red(128, 0, 0);
674 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
675 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
677 // put layers on top of existing pixmap
678 QPainter painter(&pixmap);
679 painter.drawPixmap(pixmap.rect(), black_overlay);
680 painter.drawPixmap(pixmap.rect(), blue_overlay);
681 painter.drawPixmap(pixmap.rect(), red_overlay);
687 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
689 QString imagedir = path;
690 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
691 QString fpath = toqstr(fname.absFileName());
692 QPixmap pixmap = QPixmap();
694 if (pixmap.load(fpath)) {
695 if (fpath.contains("math") || fpath.contains("ipa")
696 || fpath.contains("bullets"))
697 return prepareForDarkMode(pixmap);
701 bool const list = ext.contains(",");
702 LYXERR(Debug::GUI, "Cannot load pixmap \""
703 << path << "/" << name << "." << (list ? "{" : "") << ext
704 << (list ? "}" : "") << "\".");
710 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
712 if (lyxrc.use_system_theme_icons) {
713 // use the icons from system theme that are available
714 QString action = toqstr(lyxaction.getActionName(f.action()));
715 if (!f.argument().empty())
716 action += " " + toqstr(f.argument());
717 QString const theme_icon = themeIconName(action);
718 if (QIcon::hasThemeIcon(theme_icon)) {
719 QIcon const thmicn = QIcon::fromTheme(theme_icon);
720 if (!thmicn.isNull())
725 IconInfo icondata = iconInfo(f, unknown, rtl);
726 if (icondata.filepath.isEmpty())
729 //LYXERR(Debug::GUI, "Found icon: " << icon);
730 QPixmap pixmap = QPixmap();
731 if (!pixmap.load(icondata.filepath)) {
732 LYXERR0("Cannot load icon " << icondata.filepath << ".");
737 pixmap = prepareForDarkMode(pixmap);
740 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
742 return QIcon(pixmap);
746 ////////////////////////////////////////////////////////////////////////
748 // LyX server support code.
750 ////////////////////////////////////////////////////////////////////////
752 class SocketNotifier : public QSocketNotifier
755 /// connect a connection notification from the LyXServerSocket
756 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
757 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
761 /// The callback function
762 Application::SocketCallback func_;
766 class GuiTranslator : public QTranslator
769 GuiTranslator(QObject * parent = nullptr)
770 : QTranslator(parent)
773 QString translate(const char * /* context */,
774 const char *sourceText,
775 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
777 // Here we declare the strings that need to be translated from Qt own GUI
778 // This is needed to include these strings to po files
782 _("Restore Defaults");
785 // Already in po: "Cancel", "&Cancel"
786 _("Apply"); // Already in po: "&Apply"
787 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
790 docstring s = getGuiMessages().getIfFound(sourceText);
791 // This test should eventually be removed when translations are updated
793 LYXERR(Debug::LOCALE, "Missing translation for `"
794 << string(sourceText) << "'");
800 ////////////////////////////////////////////////////////////////////////
802 // Mac specific stuff goes here...
804 ////////////////////////////////////////////////////////////////////////
806 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
807 // QMacPasteboardMimeGraphics can only be compiled on Mac.
809 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
812 QMacPasteboardMimeGraphics()
813 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
816 QString convertorName() { return "Graphics"; }
818 QString flavorFor(QString const & mime)
820 LYXERR(Debug::ACTION, "flavorFor " << mime);
821 if (mime == pdfMimeType())
822 return QLatin1String("com.adobe.pdf");
826 QString mimeFor(QString flav)
828 LYXERR(Debug::ACTION, "mimeFor " << flav);
829 if (flav == QLatin1String("com.adobe.pdf"))
830 return pdfMimeType();
834 bool canConvert(QString const & mime, QString flav)
836 return mimeFor(flav) == mime;
839 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
843 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
847 QList<QByteArray> convertFromMime(QString const & /*mime*/,
848 QVariant data, QString /*flav*/)
850 QList<QByteArray> ret;
851 ret.append(data.toByteArray());
857 ///////////////////////////////////////////////////////////////
859 // You can find more platform specific stuff at the end of this file...
861 ///////////////////////////////////////////////////////////////
863 ////////////////////////////////////////////////////////////////////////
864 // Windows specific stuff goes here...
866 #if (QT_VERSION >= 0x050400)
867 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
868 // QWindowsMimeMetafile can only be compiled on Windows.
870 static FORMATETC cfFromMime(QString const & mimetype)
873 if (mimetype == emfMimeType()) {
874 formatetc.cfFormat = CF_ENHMETAFILE;
875 formatetc.tymed = TYMED_ENHMF;
876 } else if (mimetype == wmfMimeType()) {
877 formatetc.cfFormat = CF_METAFILEPICT;
878 formatetc.tymed = TYMED_MFPICT;
881 formatetc.dwAspect = DVASPECT_CONTENT;
882 formatetc.lindex = -1;
887 class QWindowsMimeMetafile : public QWINDOWSMIME {
889 QWindowsMimeMetafile() {}
891 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
892 QMimeData const * /*mimedata*/) const override
897 bool canConvertToMime(QString const & mimetype,
898 IDataObject * pDataObj) const override
900 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
902 FORMATETC formatetc = cfFromMime(mimetype);
903 return pDataObj->QueryGetData(&formatetc) == S_OK;
906 bool convertFromMime(FORMATETC const & /*formatetc*/,
907 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
912 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
913 QVARIANTTYPE /*preferredType*/) const override
916 if (!canConvertToMime(mimetype, pDataObj))
919 FORMATETC formatetc = cfFromMime(mimetype);
921 if (pDataObj->GetData(&formatetc, &s) != S_OK)
925 if (s.tymed == TYMED_ENHMF) {
926 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
927 data.resize(dataSize);
928 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
929 (LPBYTE)data.data());
930 } else if (s.tymed == TYMED_MFPICT) {
931 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
932 data.resize(dataSize);
933 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
934 (LPBYTE)data.data());
937 ReleaseStgMedium(&s);
943 QVector<FORMATETC> formatsForMime(QString const & mimetype,
944 QMimeData const * /*mimedata*/) const override
946 QVector<FORMATETC> formats;
947 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
948 formats += cfFromMime(mimetype);
952 QString mimeForFormat(FORMATETC const & formatetc) const override
954 switch (formatetc.cfFormat) {
956 return emfMimeType();
957 case CF_METAFILEPICT:
958 return wmfMimeType();
968 /// Allows to check whether ESC was pressed during a long operation
969 class KeyChecker : public QObject {
974 KeyChecker() : pressed_(false), started_(false) {}
977 QCoreApplication::instance()->installEventFilter(this);
982 QCoreApplication::instance()->removeEventFilter(this);
986 QCoreApplication::processEvents();
989 bool started() const {
992 bool eventFilter(QObject *obj, QEvent *event) override {
993 LYXERR(Debug::ACTION, "Event Type: " << event->type());
994 switch (event->type()) {
998 case QEvent::UpdateRequest:
999 case QEvent::CursorChange:
1000 case QEvent::ActionChanged:
1001 case QEvent::EnabledChange:
1002 case QEvent::SockAct:
1005 case QEvent::ToolTipChange:
1006 case QEvent::LayoutRequest:
1007 case QEvent::MetaCall:
1008 return QObject::eventFilter(obj, event);
1010 // FIXME Blocking all these events is a bad idea.
1011 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
1012 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
1020 ////////////////////////////////////////////////////////////////////////
1021 // GuiApplication::Private definition and implementation.
1022 ////////////////////////////////////////////////////////////////////////
1024 struct GuiApplication::Private
1026 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
1027 global_menubar_(nullptr)
1028 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1029 , last_state_(Qt::ApplicationInactive)
1032 #if (QT_VERSION >= 0x050400)
1033 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1034 /// WMF Mime handler for Windows clipboard.
1035 wmf_mime_ = new QWindowsMimeMetafile;
1036 #if (QT_VERSION >= 0x060000)
1037 win_app_ = dynamic_cast<QWindowsApplication *>
1038 (QGuiApplicationPrivate::platformIntegration());
1039 win_app_->registerMime(wmf_mime_);
1043 initKeySequences(&theTopLevelKeymap());
1046 #if (QT_VERSION >= 0x060000)
1047 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1050 win_app_->unregisterMime(wmf_mime_);
1055 void initKeySequences(KeyMap * kb)
1057 keyseq = KeySequence(kb, kb);
1058 cancel_meta_seq = KeySequence(kb, kb);
1062 QSortFilterProxyModel * language_model_;
1064 GuiClipboard clipboard_;
1066 GuiSelection selection_;
1068 FontLoader font_loader_;
1070 ColorCache color_cache_;
1071 /// the built-in Qt translation mechanism
1072 QTranslator qt_trans_;
1073 /// LyX gettext-based translation for Qt elements
1074 GuiTranslator gui_trans_;
1076 QHash<int, SocketNotifier *> socket_notifiers_;
1080 /// The global instance
1083 /// this timer is used for any regular events one wants to
1084 /// perform. at present it is used to check if forked processes
1086 QTimer general_timer_;
1088 /// delayed FuncRequests
1089 std::queue<FuncRequest> func_request_queue_;
1094 KeySequence cancel_meta_seq;
1096 KeyModifier meta_fake_bit;
1098 /// The result of last dispatch action
1099 DispatchResult dispatch_result_;
1101 /// Multiple views container.
1103 * Warning: This must not be a smart pointer as the destruction of the
1104 * object is handled by Qt when the view is closed
1105 * \sa Qt::WA_DeleteOnClose attribute.
1107 QHash<int, GuiView *> views_;
1109 /// Only used on mac.
1110 QMenuBar * global_menubar_;
1111 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1112 /// Holds previous application state on Mac
1113 Qt::ApplicationState last_state_;
1116 #if defined(Q_OS_MAC) && (QT_VERSION < 0x060000)
1117 /// Linkback mime handler for MacOSX.
1118 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1121 #if (QT_VERSION >= 0x050400)
1122 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1123 /// WMF Mime handler for Windows clipboard.
1124 QWindowsMimeMetafile * wmf_mime_;
1125 #if (QT_VERSION >= 0x060000)
1126 QWindowsApplication * win_app_;
1131 /// Allows to check whether ESC was pressed during a long operation
1132 KeyChecker key_checker_;
1136 GuiApplication * guiApp;
1138 GuiApplication::~GuiApplication()
1141 closeAllLinkBackLinks();
1147 GuiApplication::GuiApplication(int & argc, char ** argv)
1148 : QApplication(argc, argv), current_view_(nullptr),
1149 d(new GuiApplication::Private)
1151 QString app_name = "LyX";
1152 QCoreApplication::setOrganizationName(app_name);
1153 QCoreApplication::setOrganizationDomain("lyx.org");
1154 QCoreApplication::setApplicationName(lyx_package);
1155 #if QT_VERSION >= 0x050100 && QT_VERSION < 0x060000
1156 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1159 #if QT_VERSION >= 0x050700
1160 setDesktopFileName(lyx_package);
1163 #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
1164 QRandomGenerator(QDateTime::currentDateTime().toSecsSinceEpoch());
1166 qsrand(QDateTime::currentDateTime().toTime_t());
1169 // Install LyX translator for missing Qt translations
1170 installTranslator(&d->gui_trans_);
1171 // Install Qt native translator for GUI elements.
1172 installTranslator(&d->qt_trans_);
1175 // Enable reception of XCB events.
1176 installNativeEventFilter(this);
1179 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1180 // lyxrc setting for this in order to let the application stay resident.
1181 // But then we need some kind of dock icon, at least on Windows.
1183 if (lyxrc.quit_on_last_window_closed)
1184 setQuitOnLastWindowClosed(false);
1187 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1188 // seems to be the default case for applications like LyX.
1189 setQuitOnLastWindowClosed(false);
1192 appleCleanupEditMenu();
1193 appleCleanupViewMenu();
1194 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
1195 connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)),
1196 this, SLOT(onApplicationStateChanged(Qt::ApplicationState)));
1200 #if defined(QPA_XCB)
1201 // doubleClickInterval() is 400 ms on X11 which is just too long.
1202 // On Windows and Mac OS X, the operating system's value is used.
1203 // On Microsoft Windows, calling this function sets the double
1204 // click interval for all applications. So we don't!
1205 QApplication::setDoubleClickInterval(300);
1208 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1210 // needs to be done before reading lyxrc
1212 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1216 // Initialize RC Fonts
1217 if (lyxrc.roman_font_name.empty())
1218 lyxrc.roman_font_name = fromqstr(romanFontName());
1220 if (lyxrc.sans_font_name.empty())
1221 lyxrc.sans_font_name = fromqstr(sansFontName());
1223 if (lyxrc.typewriter_font_name.empty())
1224 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1226 // Track change of keyboard
1227 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1229 d->general_timer_.setInterval(500);
1230 connect(&d->general_timer_, SIGNAL(timeout()),
1231 this, SLOT(handleRegularEvents()));
1232 d->general_timer_.start();
1234 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1235 // This is clearly not enough in a time where we use threads for
1236 // document preview and/or export. 20 should be OK.
1237 QThreadPool::globalInstance()->setMaxThreadCount(20);
1239 // make sure tooltips are formatted
1240 installEventFilter(new ToolTipFormatter(this));
1244 GuiApplication * theGuiApp()
1246 return dynamic_cast<GuiApplication *>(theApp());
1250 double GuiApplication::pixelRatio() const
1252 return qt_scale_factor * devicePixelRatio();
1256 void GuiApplication::clearSession()
1263 docstring Application::iconName(FuncRequest const & f, bool unknown)
1265 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1269 docstring Application::mathIcon(docstring const & c)
1271 return qstring_to_ucs4(findImg(toqstr(c)));
1275 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1279 BufferView * bv = nullptr;
1280 BufferView * doc_bv = nullptr;
1282 if (cmd.action() == LFUN_NOACTION) {
1283 status.message(from_utf8(N_("Nothing to do")));
1284 status.setEnabled(false);
1287 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1288 status.setUnknown(true);
1289 status.message(from_utf8(N_("Unknown action")));
1290 status.setEnabled(false);
1293 // Does the GuiApplication know something?
1294 else if (getStatus(cmd, status)) { }
1296 // If we do not have a GuiView, then other functions are disabled
1297 else if (!current_view_)
1298 status.setEnabled(false);
1300 // Does the GuiView know something?
1301 else if (current_view_->getStatus(cmd, status)) { }
1303 // In LyX/Mac, when a dialog is open, the menus of the
1304 // application can still be accessed without giving focus to
1305 // the main window. In this case, we want to disable the menu
1306 // entries that are buffer or view-related.
1307 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1309 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1310 status.setEnabled(false);
1313 // If we do not have a BufferView, then other functions are disabled
1314 else if (!(bv = current_view_->currentBufferView()))
1315 status.setEnabled(false);
1317 // Does the current BufferView know something?
1318 else if (bv->getStatus(cmd, status)) { }
1320 // Does the current Buffer know something?
1321 else if (bv->buffer().getStatus(cmd, status)) { }
1323 // If we do not have a document BufferView, different from the
1324 // current BufferView, then other functions are disabled
1325 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1326 status.setEnabled(false);
1328 // Does the document Buffer know something?
1329 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1332 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1333 status.message(from_utf8(N_("Command not handled")));
1334 status.setEnabled(false);
1337 // the default error message if we disable the command
1338 if (!status.enabled() && status.message().empty())
1339 status.message(from_utf8(N_("Command disabled")));
1345 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1347 // I would really like to avoid having this switch and rather try to
1348 // encode this in the function itself.
1349 // -- And I'd rather let an inset decide which LFUNs it is willing
1350 // to handle (Andre')
1352 switch (cmd.action()) {
1354 // This could be used for the no-GUI version. The GUI version is handled in
1355 // GuiView::getStatus(). See above.
1357 case LFUN_BUFFER_WRITE:
1358 case LFUN_BUFFER_WRITE_AS:
1359 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1360 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1361 enable = b && (b->isUnnamed() || !b->isClean());
1366 case LFUN_BOOKMARK_GOTO: {
1367 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1368 enable = theSession().bookmarks().isValid(num);
1372 case LFUN_BOOKMARK_CLEAR:
1373 enable = theSession().bookmarks().hasValid();
1376 // this one is difficult to get right. As a half-baked
1377 // solution, we consider only the first action of the sequence
1378 case LFUN_COMMAND_SEQUENCE: {
1379 // argument contains ';'-terminated commands
1380 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1381 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1382 func.setOrigin(cmd.origin());
1383 flag = getStatus(func);
1387 // we want to check if at least one of these is enabled
1388 case LFUN_COMMAND_ALTERNATIVES: {
1389 // argument contains ';'-terminated commands
1390 string arg = to_utf8(cmd.argument());
1391 while (!arg.empty()) {
1393 arg = split(arg, first, ';');
1394 FuncRequest func(lyxaction.lookupFunc(first));
1395 func.setOrigin(cmd.origin());
1396 flag = getStatus(func);
1397 // if this one is enabled, the whole thing is
1406 string name = to_utf8(cmd.argument());
1407 if (theTopLevelCmdDef().lock(name, func)) {
1408 func.setOrigin(cmd.origin());
1409 flag = getStatus(func);
1410 theTopLevelCmdDef().release(name);
1412 // catch recursion or unknown command
1413 // definition. all operations until the
1414 // recursion or unknown command definition
1415 // occurs are performed, so set the state to
1422 case LFUN_IF_RELATIVES: {
1423 string const lfun = to_utf8(cmd.argument());
1424 BufferView const * bv =
1425 current_view_ ? current_view_->currentBufferView() : nullptr;
1426 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1430 FuncRequest func(lyxaction.lookupFunc(lfun));
1431 func.setOrigin(cmd.origin());
1432 flag = getStatus(func);
1436 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1438 case LFUN_PREFERENCES_SAVE:
1439 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1440 // these are handled in our dispatch()
1443 case LFUN_DEBUG_LEVEL_SET: {
1444 string bad = Debug::badValue(to_utf8(cmd.argument()));
1445 enable = bad.empty();
1447 flag.message(bformat(_("Bad debug value `%1$s'."), from_utf8(bad)));
1451 case LFUN_WINDOW_CLOSE:
1452 enable = !d->views_.empty();
1455 case LFUN_BUFFER_NEW:
1456 case LFUN_BUFFER_NEW_TEMPLATE:
1457 case LFUN_FILE_OPEN:
1458 case LFUN_LYXFILES_OPEN:
1459 case LFUN_HELP_OPEN:
1460 case LFUN_SCREEN_FONT_UPDATE:
1461 case LFUN_SET_COLOR:
1462 case LFUN_WINDOW_NEW:
1464 case LFUN_LYXRC_APPLY:
1465 case LFUN_COMMAND_PREFIX:
1467 case LFUN_META_PREFIX:
1468 case LFUN_RECONFIGURE:
1469 case LFUN_SERVER_GET_FILENAME:
1470 case LFUN_SERVER_NOTIFY:
1474 case LFUN_BUFFER_FORALL: {
1475 if (theBufferList().empty()) {
1476 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1477 flag.setEnabled(false);
1481 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1482 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1483 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1484 flag.setEnabled(false);
1489 case LFUN_DIALOG_SHOW: {
1490 string const name = cmd.getArg(0);
1491 return name == "aboutlyx"
1492 || name == "lyxfiles"
1494 || name == "texinfo"
1495 || name == "progress"
1496 || name == "compare";
1504 flag.setEnabled(false);
1508 /// make a post-dispatch status message
1509 static docstring makeDispatchMessage(docstring const & msg,
1510 FuncRequest const & cmd)
1512 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1513 || cmd.origin() == FuncRequest::TOOLBAR
1514 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1516 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1517 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1521 docstring dispatch_msg = msg;
1522 if (!dispatch_msg.empty())
1523 dispatch_msg += ' ';
1525 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1527 bool argsadded = false;
1529 if (!cmd.argument().empty()) {
1530 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1531 comname += ' ' + cmd.argument();
1535 docstring const shortcuts = theTopLevelKeymap().
1536 printBindings(cmd, KeySequence::ForGui);
1538 if (!shortcuts.empty())
1539 comname += ": " + shortcuts;
1540 else if (!argsadded && !cmd.argument().empty())
1541 comname += ' ' + cmd.argument();
1543 if (!comname.empty()) {
1544 comname = rtrim(comname);
1545 dispatch_msg += '(' + rtrim(comname) + ')';
1547 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1548 return dispatch_msg;
1552 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1556 Buffer * buffer = nullptr;
1557 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1558 //setCurrentView(cmd.view_origin); //does not work
1560 dr.setMessage(_("Wrong focus!"));
1561 d->dispatch_result_ = dr;
1562 return d->dispatch_result_;
1564 if (current_view_ && current_view_->currentBufferView()) {
1565 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1566 buffer = ¤t_view_->currentBufferView()->buffer();
1569 dr.screenUpdate(Update::FitCursor);
1571 // All the code is kept inside the undo group because
1572 // updateBuffer can create undo actions (see #11292)
1573 UndoGroupHelper ugh(buffer);
1575 if (dr.screenUpdate() & Update::ForceAll) {
1576 for (Buffer const * b : theBufferList())
1578 dr.screenUpdate(dr.screenUpdate() & ~Update::ForceAll);
1581 updateCurrentView(cmd, dr);
1584 d->dispatch_result_ = dr;
1585 return d->dispatch_result_;
1589 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1594 BufferView * bv = current_view_->currentBufferView();
1596 if (dr.needBufferUpdate() || bv->buffer().needUpdate()) {
1597 bv->cursor().clearBufferUpdate();
1598 bv->buffer().updateBuffer();
1600 // BufferView::update() updates the ViewMetricsInfo and
1601 // also initializes the position cache for all insets in
1602 // (at least partially) visible top-level paragraphs.
1603 // We will redraw the screen only if needed.
1604 bv->processUpdateFlags(dr.screenUpdate());
1606 // Do we have a selection?
1607 theSelection().haveSelection(bv->cursor().selection());
1610 current_view_->restartCaret();
1612 if (dr.needMessageUpdate()) {
1613 // Some messages may already be translated, so we cannot use _()
1614 current_view_->message(makeDispatchMessage(
1615 translateIfPossible(dr.message()), cmd));
1620 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1621 bool switchToBuffer)
1623 if (!theSession().bookmarks().isValid(idx))
1625 BookmarksSection::Bookmark const & bm =
1626 theSession().bookmarks().bookmark(idx);
1627 LASSERT(!bm.filename.empty(), return);
1628 string const file = bm.filename.absFileName();
1629 // if the file is not opened, open it.
1630 if (!theBufferList().exists(bm.filename)) {
1632 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1636 // open may fail, so we need to test it again
1637 if (!theBufferList().exists(bm.filename))
1640 // bm can be changed when saving
1641 BookmarksSection::Bookmark tmp = bm;
1643 // Special case idx == 0 used for back-from-back jump navigation
1645 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1647 // if the current buffer is not that one, switch to it.
1648 BufferView * doc_bv = current_view_ ?
1649 current_view_->documentBufferView() : nullptr;
1650 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1651 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1652 if (switchToBuffer) {
1653 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1656 doc_bv = current_view_->documentBufferView();
1661 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1662 if (!doc_bv || !doc_bv->moveToPosition(
1663 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1666 Cursor & cur = doc_bv->cursor();
1667 if (old && cur != *old)
1668 notifyCursorLeavesOrEnters(*old, cur);
1674 // Cursor jump succeeded!
1675 pit_type new_pit = cur.pit();
1676 pos_type new_pos = cur.pos();
1677 int new_id = cur.paragraph().id();
1679 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1680 // see http://www.lyx.org/trac/ticket/3092
1681 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1682 || bm.top_id != new_id) {
1683 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1684 new_pit, new_pos, new_id);
1688 // This function runs "configure" and then rereads lyx.defaults to
1689 // reconfigure the automatic settings.
1690 void GuiApplication::reconfigure(string const & option)
1692 // emit message signal.
1693 if (current_view_) {
1694 current_view_->message(_("Running configure..."));
1695 current_view_->setCursor(Qt::WaitCursor);
1698 // Run configure in user lyx directory
1699 string const lock_file = package().getConfigureLockName();
1700 int fd = fileLock(lock_file.c_str());
1701 int const ret = package().reconfigureUserLyXDir(option);
1702 // emit message signal.
1704 current_view_->message(_("Reloading configuration..."));
1705 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1706 // Re-read packages.lst
1707 LaTeXPackages::getAvailable();
1708 fileUnlock(fd, lock_file.c_str());
1711 current_view_->unsetCursor();
1714 Alert::information(_("System reconfiguration failed"),
1715 _("The system reconfiguration has failed.\n"
1716 "Default textclass is used but LyX may\n"
1717 "not be able to work properly.\n"
1718 "Please reconfigure again if needed."));
1720 Alert::information(_("System reconfigured"),
1721 _("The system has been reconfigured.\n"
1722 "You need to restart LyX to make use of any\n"
1723 "updated document class specifications."));
1726 void GuiApplication::validateCurrentView()
1728 if (!d->views_.empty() && !current_view_) {
1729 // currently at least one view exists but no view has the focus.
1730 // choose the last view to make it current.
1731 // a view without any open document is preferred.
1732 GuiView * candidate = nullptr;
1733 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1734 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1735 for (; it != end; ++it) {
1737 if (!candidate->documentBufferView())
1740 setCurrentView(candidate);
1744 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1746 string const argument = to_utf8(cmd.argument());
1747 FuncCode const action = cmd.action();
1749 LYXERR(Debug::ACTION, "cmd: " << cmd);
1751 // we have not done anything wrong yet.
1754 FuncStatus const flag = getStatus(cmd);
1755 if (!flag.enabled()) {
1756 // We cannot use this function here
1757 LYXERR(Debug::ACTION, "action "
1758 << lyxaction.getActionName(action)
1759 << " [" << action << "] is disabled at this location");
1760 dr.setMessage(flag.message());
1762 dr.dispatched(false);
1763 dr.screenUpdate(Update::None);
1764 dr.clearBufferUpdate();
1768 if (cmd.origin() == FuncRequest::LYXSERVER) {
1769 if (current_view_ && current_view_->currentBufferView())
1770 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1771 // we will also need to redraw the screen at the end
1772 dr.screenUpdate(Update::FitCursor);
1775 // Assumes that the action will be dispatched.
1776 dr.dispatched(true);
1778 switch (cmd.action()) {
1780 case LFUN_WINDOW_NEW:
1781 createView(toqstr(cmd.argument()));
1784 case LFUN_WINDOW_CLOSE:
1785 // FIXME: this is done also in GuiView::closeBuffer()!
1786 // update bookmark pit of the current buffer before window close
1787 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1788 gotoBookmark(i, false, false);
1789 // clear the last opened list, because
1790 // maybe this will end the session
1791 theSession().lastOpened().clear();
1792 // check for valid current_view_
1793 validateCurrentView();
1795 current_view_->closeScheduled();
1799 // quitting is triggered by the gui code
1800 // (leaving the event loop).
1802 current_view_->message(from_utf8(N_("Exiting.")));
1803 if (closeAllViews())
1807 case LFUN_SCREEN_FONT_UPDATE: {
1808 // handle the screen font changes.
1809 /* FIXME: this only updates the current document, whereas all
1810 * documents should see their metrics updated.
1812 d->font_loader_.update();
1813 dr.screenUpdate(Update::Force | Update::FitCursor);
1817 case LFUN_BUFFER_NEW:
1818 validateCurrentView();
1820 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1821 createView(QString(), false); // keep hidden
1822 current_view_->newDocument(to_utf8(cmd.argument()));
1823 current_view_->show();
1824 setActiveWindow(current_view_);
1826 current_view_->newDocument(to_utf8(cmd.argument()));
1830 case LFUN_BUFFER_NEW_TEMPLATE: {
1831 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1832 string const temp = cmd.getArg(1);
1833 validateCurrentView();
1835 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1837 current_view_->newDocument(file, temp, true);
1838 if (!current_view_->documentBufferView())
1839 current_view_->close();
1841 current_view_->newDocument(file, temp, true);
1846 case LFUN_FILE_OPEN: {
1847 // FIXME: normally the code below is not needed, since getStatus makes sure that
1848 // current_view_ is not null.
1849 validateCurrentView();
1850 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1851 string const fname = trim(to_utf8(cmd.argument()), "\"");
1852 bool const is_open = FileName::isAbsolute(fname)
1853 && theBufferList().getBuffer(FileName(fname));
1855 || (!lyxrc.open_buffers_in_tabs
1856 && current_view_->documentBufferView() != nullptr
1858 // We want the ui session to be saved per document and not per
1859 // window number. The filename crc is a good enough identifier.
1860 createView(support::checksum(fname));
1861 current_view_->openDocuments(fname, cmd.origin());
1862 if (!current_view_->documentBufferView())
1863 current_view_->close();
1864 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1865 current_view_->raise();
1866 current_view_->activateWindow();
1867 current_view_->showNormal();
1870 current_view_->openDocuments(fname, cmd.origin());
1871 if (cmd.origin() == FuncRequest::LYXSERVER) {
1872 current_view_->raise();
1873 current_view_->activateWindow();
1874 current_view_->showNormal();
1880 case LFUN_HELP_OPEN: {
1881 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1882 if (current_view_ == nullptr)
1884 string const arg = to_utf8(cmd.argument());
1886 current_view_->message(_("Missing argument"));
1889 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1891 fname = i18nLibFileSearch("examples", arg, "lyx");
1893 if (fname.empty()) {
1894 lyxerr << "LyX: unable to find documentation file `"
1895 << arg << "'. Bad installation?" << endl;
1898 current_view_->message(bformat(_("Opening help file %1$s..."),
1899 makeDisplayPath(fname.absFileName())));
1900 Buffer * buf = current_view_->loadDocument(fname, false);
1902 buf->setReadonly(!current_view_->develMode());
1906 case LFUN_LYXFILES_OPEN: {
1907 // This is the actual reason for this method (#12106).
1908 validateCurrentView();
1910 || (!lyxrc.open_buffers_in_tabs
1911 && current_view_->documentBufferView() != nullptr))
1913 string arg = to_utf8(cmd.argument());
1917 if (arg != "templates" && arg != "examples") {
1918 current_view_->message(_("Wrong argument. Must be 'examples' or 'templates'."));
1921 lyx::dispatch(FuncRequest(LFUN_DIALOG_SHOW, "lyxfiles " + arg));
1925 case LFUN_SET_COLOR: {
1926 string const lyx_name = cmd.getArg(0);
1927 string x11_name = cmd.getArg(1);
1928 string x11_darkname = cmd.getArg(2);
1929 if (lyx_name.empty() || x11_name.empty()) {
1931 current_view_->message(
1932 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1937 // FIXME: The graphics cache no longer has a changeDisplay method.
1938 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1939 bool const graphicsbg_changed =
1940 lyx_name == graphicsbg && x11_name != graphicsbg;
1941 if (graphicsbg_changed)
1942 graphics::GCache::get().changeDisplay(true);
1945 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1946 x11_darkname = x11_name;
1949 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1951 current_view_->message(
1952 bformat(_("Set-color \"%1$s\" failed "
1953 "- color is undefined or "
1954 "may not be redefined"),
1955 from_utf8(lyx_name)));
1958 // Make sure we don't keep old colors in cache.
1959 d->color_cache_.clear();
1960 // Update the current view
1961 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1965 case LFUN_LYXRC_APPLY: {
1966 // reset active key sequences, since the bindings
1967 // are updated (bug 6064)
1969 LyXRC const lyxrc_orig = lyxrc;
1971 istringstream ss(to_utf8(cmd.argument()));
1972 bool const success = lyxrc.read(ss);
1975 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1976 << "Unable to read lyxrc data"
1981 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1983 // If the request comes from the minibuffer, then we can't reset
1984 // the GUI, since that would destroy the minibuffer itself and
1985 // cause a crash, since we are currently in one of the methods of
1986 // GuiCommandBuffer. See bug #8540.
1987 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1990 // FIXME Unfortunately, that leaves a bug here, since we cannot
1991 // reset the GUI in this case. If the changes to lyxrc affected the
1992 // UI, then, nothing would happen. This seems fairly unlikely, but
1993 // it definitely is a bug.
1995 dr.forceBufferUpdate();
1999 case LFUN_COMMAND_PREFIX:
2000 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
2005 d->meta_fake_bit = NoModifier;
2006 GuiView * gv = currentView();
2007 if (gv && gv->currentBufferView())
2008 // cancel any selection
2009 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
2010 dr.setMessage(from_ascii(N_("Cancel")));
2013 case LFUN_META_PREFIX:
2014 d->meta_fake_bit = AltModifier;
2015 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
2018 // --- Menus -----------------------------------------------
2019 case LFUN_RECONFIGURE:
2020 // argument is any additional parameter to the configure.py command
2021 reconfigure(to_utf8(cmd.argument()));
2024 // --- lyxserver commands ----------------------------
2025 case LFUN_SERVER_GET_FILENAME: {
2026 if (current_view_ && current_view_->documentBufferView()) {
2027 docstring const fname = from_utf8(
2028 current_view_->documentBufferView()->buffer().absFileName());
2029 dr.setMessage(fname);
2030 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
2032 dr.setMessage(docstring());
2033 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
2038 case LFUN_SERVER_NOTIFY: {
2039 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
2040 dr.setMessage(dispatch_buffer);
2041 theServer().notifyClient(to_utf8(dispatch_buffer));
2045 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
2046 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
2052 string rest = split(argument, countstr, ' ');
2053 int const count = convert<int>(countstr);
2054 // an arbitrary number to limit number of iterations
2055 int const max_iter = 10000;
2056 if (count > max_iter) {
2057 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
2060 for (int i = 0; i < count; ++i) {
2061 FuncRequest lfun = lyxaction.lookupFunc(rest);
2062 lfun.allowAsync(false);
2069 case LFUN_COMMAND_SEQUENCE: {
2070 // argument contains ';'-terminated commands
2071 string arg = argument;
2072 // FIXME: this LFUN should also work without any view.
2073 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
2074 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
2075 // This handles undo groups automagically
2076 UndoGroupHelper ugh(buffer);
2077 while (!arg.empty()) {
2079 arg = split(arg, first, ';');
2080 FuncRequest func(lyxaction.lookupFunc(first));
2081 func.allowAsync(false);
2082 func.setOrigin(cmd.origin());
2088 case LFUN_BUFFER_FORALL: {
2089 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
2090 funcToRun.allowAsync(false);
2092 map<Buffer *, GuiView *> views_lVisible;
2093 map<GuiView *, Buffer *> activeBuffers;
2095 QList<GuiView *> allViews = d->views_.values();
2097 // this for does not modify any buffer. It just collects info on local
2098 // visibility of buffers and on which buffer is active in each view.
2099 Buffer * const last = theBufferList().last();
2100 for(GuiView * view : allViews) {
2101 // all of the buffers might be locally hidden. That is, there is no
2103 if (!view || !view->currentBufferView())
2104 activeBuffers[view] = nullptr;
2106 activeBuffers[view] = &view->currentBufferView()->buffer();
2108 // find out if each is locally visible or locally hidden.
2109 // we don't use a for loop as the buffer list cycles.
2110 Buffer * b = theBufferList().first();
2112 bool const locallyVisible = view && view->workArea(*b);
2113 if (locallyVisible) {
2114 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
2115 // only need to overwrite/add if we don't already know a buffer is globally
2116 // visible or we do know but we would prefer to dispatch LFUN from the
2117 // current view because of cursor position issues.
2118 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2119 views_lVisible[b] = view;
2123 b = theBufferList().next(b);
2127 GuiView * const homeView = currentView();
2128 Buffer * b = theBufferList().first();
2129 Buffer * nextBuf = nullptr;
2130 int numProcessed = 0;
2133 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2135 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2137 // first change to a view where b is locally visible, preferably current_view_.
2138 GuiView * const vLv = views_lVisible[b];
2140 lyx::dispatch(funcToRun);
2148 // put things back to how they were (if possible).
2149 for (GuiView * view : allViews) {
2150 Buffer * originalBuf = activeBuffers[view];
2151 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2152 if (theBufferList().isLoaded(originalBuf))
2153 view->setBuffer(originalBuf);
2155 homeView->setFocus();
2157 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2161 case LFUN_COMMAND_ALTERNATIVES: {
2162 // argument contains ';'-terminated commands
2163 string arg = argument;
2164 while (!arg.empty()) {
2166 arg = split(arg, first, ';');
2167 FuncRequest func(lyxaction.lookupFunc(first));
2168 func.setOrigin(cmd.origin());
2169 FuncStatus const stat = getStatus(func);
2170 if (stat.enabled()) {
2180 if (theTopLevelCmdDef().lock(argument, func)) {
2181 func.setOrigin(cmd.origin());
2183 theTopLevelCmdDef().release(argument);
2185 if (func.action() == LFUN_UNKNOWN_ACTION) {
2186 // unknown command definition
2187 lyxerr << "Warning: unknown command definition `"
2191 // recursion detected
2192 lyxerr << "Warning: Recursion in the command definition `"
2193 << argument << "' detected"
2200 case LFUN_IF_RELATIVES: {
2201 string const lfun = to_utf8(cmd.argument());
2202 FuncRequest func(lyxaction.lookupFunc(lfun));
2203 func.setOrigin(cmd.origin());
2204 FuncStatus const stat = getStatus(func);
2205 if (stat.enabled()) {
2212 case LFUN_PREFERENCES_SAVE:
2213 lyxrc.write(support::makeAbsPath("preferences",
2214 package().user_support().absFileName()), false);
2217 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2218 string const fname = addName(addPath(package().user_support().absFileName(),
2219 "templates/"), "defaults.lyx");
2220 Buffer defaults(fname);
2222 istringstream ss(argument);
2227 // We need to make sure that, after we recreat the DocumentClass,
2228 // which we do in readHeader, we apply it to the document itself.
2229 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2230 int const unknown_tokens = defaults.readHeader(lex);
2231 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2232 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2233 cap::switchBetweenClasses(olddc, newdc, theinset);
2235 if (unknown_tokens != 0) {
2236 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2237 << unknown_tokens << " unknown token"
2238 << (unknown_tokens == 1 ? "" : "s")
2242 if (defaults.writeFile(FileName(defaults.absFileName())))
2243 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2244 makeDisplayPath(fname)));
2247 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2252 case LFUN_BOOKMARK_GOTO:
2253 // go to bookmark, open unopened file and switch to buffer if necessary
2254 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2255 dr.screenUpdate(Update::Force | Update::FitCursor);
2258 case LFUN_BOOKMARK_CLEAR:
2259 theSession().bookmarks().clear();
2260 dr.screenUpdate(Update::Force);
2263 case LFUN_DEBUG_LEVEL_SET:
2264 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2267 case LFUN_DIALOG_SHOW: {
2268 string const name = cmd.getArg(0);
2270 if ( name == "aboutlyx"
2272 || name == "texinfo"
2273 || name == "progress"
2274 || name == "compare")
2276 // work around: on Mac OS the application
2277 // is not terminated when closing the last view.
2278 // Create a new one to be able to dispatch the
2279 // LFUN_DIALOG_SHOW to this view.
2280 if (current_view_ == nullptr)
2286 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2289 current_view_->dispatch(cmd, dr);
2293 if (current_view_ && current_view_->isFullScreen()) {
2294 if (current_view_->menuBar()->isVisible() && lyxrc.full_screen_menubar)
2295 current_view_->menuBar()->hide();
2298 if (cmd.origin() == FuncRequest::LYXSERVER)
2299 updateCurrentView(cmd, dr);
2303 docstring GuiApplication::viewStatusMessage()
2305 // When meta-fake key is pressed, show the key sequence so far + "M-".
2306 if (d->meta_fake_bit != NoModifier)
2307 return d->keyseq.print(KeySequence::ForGui) + "M-";
2309 // Else, when a non-complete key sequence is pressed,
2310 // show the available options.
2311 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2312 return d->keyseq.printOptions(true);
2318 string GuiApplication::inputLanguageCode() const
2320 QLocale loc = inputMethod()->locale();
2321 //LYXERR0("input lang = " << fromqstr(loc.name()));
2322 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2326 void GuiApplication::onLocaleChanged()
2328 //LYXERR0("Change language to " << inputLanguage()->lang());
2329 if (currentView() && currentView()->currentBufferView())
2330 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2334 void GuiApplication::onPaletteChanged()
2336 colorCache().setPalette(palette());
2340 void GuiApplication::handleKeyFunc(FuncCode action)
2344 if (d->keyseq.length())
2346 GuiView * gv = currentView();
2347 LASSERT(gv && gv->currentBufferView(), return);
2348 BufferView * bv = gv->currentBufferView();
2349 bv->getIntl().getTransManager().deadkey(
2350 c, get_accent(action).accent, bv->cursor().innerText(),
2352 // Need to clear, in case the minibuffer calls these
2355 // copied verbatim from do_accent_char
2356 bv->cursor().resetAnchor();
2360 //Keep this in sync with GuiApplication::processKeySym below
2361 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2362 KeyModifier state) const
2364 // Do nothing if we have nothing
2365 if (!keysym.isOK() || keysym.isModifier())
2367 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2369 FuncRequest func = seq.addkey(keysym, state);
2370 // When not cancel or meta-fake, do the normal lookup.
2371 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2373 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2375 // Maybe user can only reach the key via holding down shift.
2376 // Let's see. But only if shift is the only modifier
2377 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2378 // If addkey looked up a command and did not find further commands then
2379 // seq has been reset at this point
2380 func = seq.addkey(keysym, NoModifier);
2382 LYXERR(Debug::KEY, " Key (queried) [action="
2383 << lyxaction.getActionName(func.action()) << "]["
2384 << seq.print(KeySequence::Portable) << ']');
2385 return func.action() != LFUN_UNKNOWN_ACTION;
2389 //Keep this in sync with GuiApplication::queryKeySym above
2390 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2392 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2394 // Do nothing if we have nothing (JMarc)
2395 if (!keysym.isOK() || keysym.isModifier()) {
2397 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2399 current_view_->restartCaret();
2403 char_type encoded_last_key = keysym.getUCSEncoded();
2405 // Do a one-deep top-level lookup for
2406 // cancel and meta-fake keys. RVDK_PATCH_5
2407 d->cancel_meta_seq.reset();
2409 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2410 LYXERR(Debug::KEY, "action first set to ["
2411 << lyxaction.getActionName(func.action()) << ']');
2413 // When not cancel or meta-fake, do the normal lookup.
2414 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2415 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2416 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2417 // remove Caps Lock and Mod2 as a modifiers
2418 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2419 LYXERR(Debug::KEY, "action now set to ["
2420 << lyxaction.getActionName(func.action()) << ']');
2423 // Don't remove this unless you know what you are doing.
2424 d->meta_fake_bit = NoModifier;
2426 // Can this happen now ?
2427 if (func.action() == LFUN_NOACTION)
2428 func = FuncRequest(LFUN_COMMAND_PREFIX);
2430 LYXERR(Debug::KEY, " Key [action="
2431 << lyxaction.getActionName(func.action()) << "]["
2432 << d->keyseq.print(KeySequence::Portable) << ']');
2434 // already here we know if it any point in going further
2435 // why not return already here if action == -1 and
2436 // num_bytes == 0? (Lgb)
2438 if (d->keyseq.length() > 1 && current_view_)
2439 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2442 // Maybe user can only reach the key via holding down shift.
2443 // Let's see. But only if shift is the only modifier
2444 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2445 LYXERR(Debug::KEY, "Trying without shift");
2446 // If addkey looked up a command and did not find further commands then
2447 // seq has been reset at this point
2448 func = d->keyseq.addkey(keysym, NoModifier);
2449 LYXERR(Debug::KEY, "Action now " << lyxaction.getActionName(func.action()));
2452 if (func.action() == LFUN_UNKNOWN_ACTION) {
2453 // We didn't match any of the key sequences.
2454 // See if it's normal insertable text not already
2455 // covered by a binding
2456 if (keysym.isText() && d->keyseq.length() == 1) {
2457 // Non-printable characters (such as ASCII control characters)
2458 // must not be inserted (#5704)
2459 if (!isPrintable(encoded_last_key)) {
2460 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2462 current_view_->restartCaret();
2465 // The following modifier check is not needed on Mac.
2466 // The keysym is either not text or it is different
2467 // from the non-modifier keysym. See #9875 for the
2468 // broken alt-modifier effect of having this code active.
2469 #if !defined(Q_OS_MAC)
2470 // If a non-Shift Modifier is used we have a non-bound key sequence
2471 // (such as Alt+j = j). This should be omitted (#5575).
2472 // On Windows, AltModifier and ControlModifier are both
2473 // set when AltGr is pressed. Therefore, in order to not
2474 // break AltGr-bound symbols (see #5575 for details),
2475 // unbound Ctrl+Alt key sequences are allowed.
2476 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2477 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2478 && !(state & AltModifier && state & ControlModifier)
2482 if (current_view_) {
2483 current_view_->message(_("Unknown function."));
2484 current_view_->restartCaret();
2489 // Since all checks above were passed, we now really have text that
2490 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2491 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2493 LYXERR(Debug::KEY, "isText() is true, inserting.");
2494 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2496 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2497 if (current_view_) {
2498 current_view_->message(_("Unknown function."));
2499 current_view_->restartCaret();
2505 if (func.action() == LFUN_SELF_INSERT) {
2506 if (encoded_last_key != 0) {
2507 docstring const arg(1, encoded_last_key);
2508 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2509 FuncRequest::KEYBOARD));
2510 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2513 processFuncRequest(func);
2517 void GuiApplication::processFuncRequest(FuncRequest const & func)
2519 lyx::dispatch(func);
2523 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2525 addToFuncRequestQueue(func);
2526 processFuncRequestQueueAsync();
2530 void GuiApplication::processFuncRequestQueue()
2532 while (!d->func_request_queue_.empty()) {
2533 // take the item from the stack _before_ processing the
2534 // request in order to avoid race conditions from nested
2535 // or parallel requests (see #10406)
2536 FuncRequest const fr(d->func_request_queue_.front());
2537 d->func_request_queue_.pop();
2538 processFuncRequest(fr);
2543 void GuiApplication::processFuncRequestQueueAsync()
2545 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2549 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2551 d->func_request_queue_.push(func);
2555 void GuiApplication::resetGui()
2557 // Set the language defined by the user.
2561 if (!readUIFile(toqstr(lyxrc.ui_file)))
2562 // Gives some error box here.
2565 if (d->global_menubar_)
2566 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2568 QHash<int, GuiView *>::iterator it;
2569 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2572 gv->setLayoutDirection(layoutDirection());
2576 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2580 bool GuiApplication::rtlContext() const
2582 if (current_view_ && current_view_->currentBufferView()) {
2583 BufferView const * bv = current_view_->currentBufferView();
2584 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2586 return layoutDirection() == Qt::RightToLeft;
2590 void GuiApplication::createView(int view_id)
2592 createView(QString(), true, view_id);
2596 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2599 // release the keyboard which might have been grabbed by the global
2600 // menubar on Mac to catch shortcuts even without any GuiView.
2601 if (d->global_menubar_)
2602 d->global_menubar_->releaseKeyboard();
2606 while (d->views_.find(id) != d->views_.end())
2609 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2610 GuiView * view = new GuiView(id);
2611 // `view' is the new current_view_. Tell coverity that is is not 0.
2612 LATTEST(current_view_);
2614 d->views_[id] = view;
2618 setActiveWindow(view);
2621 if (!geometry_arg.isEmpty()) {
2622 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2626 #if QT_VERSION < 0x060000
2627 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2628 re.indexIn(geometry_arg);
2629 w = re.cap(1).toInt();
2630 h = re.cap(2).toInt();
2631 x = re.cap(3).toInt();
2632 y = re.cap(4).toInt();
2633 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2634 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2636 QRegularExpression re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2637 QRegularExpressionMatch match = re.match(geometry_arg);
2638 w = match.captured(1).toInt();
2639 h = match.captured(2).toInt();
2640 x = match.captured(3).toInt();
2641 y = match.captured(4).toInt();
2642 sx = match.captured(3).isEmpty() ? '+' : match.captured(3).at(0);
2643 sy = match.captured(4).isEmpty() ? '+' : match.captured(4).at(0);
2645 // Set initial geometry such that we can get the frame size.
2646 view->setGeometry(x, y, w, h);
2647 int framewidth = view->geometry().x() - view->x();
2648 int titleheight = view->geometry().y() - view->y();
2649 // Negative displacements must be interpreted as distances
2650 // from the right or bottom screen borders.
2651 if (sx == '-' || sy == '-') {
2652 #if QT_VERSION < 0x060000
2653 QRect rec = QApplication::desktop()->screenGeometry();
2655 QRect rec = QGuiApplication::primaryScreen()->geometry();
2658 x += rec.width() - w - framewidth;
2660 y += rec.height() - h - titleheight;
2661 view->setGeometry(x, y, w, h);
2663 // Make sure that the left and top frame borders are visible.
2664 if (view->x() < 0 || view->y() < 0) {
2669 view->setGeometry(x, y, w, h);
2677 bool GuiApplication::unhide(Buffer * buf)
2681 currentView()->setBuffer(buf, false);
2686 Clipboard & GuiApplication::clipboard()
2688 return d->clipboard_;
2692 Selection & GuiApplication::selection()
2694 return d->selection_;
2698 FontLoader & GuiApplication::fontLoader()
2700 return d->font_loader_;
2704 Toolbars const & GuiApplication::toolbars() const
2706 return d->toolbars_;
2710 Toolbars & GuiApplication::toolbars()
2712 return d->toolbars_;
2716 Menus const & GuiApplication::menus() const
2722 Menus & GuiApplication::menus()
2728 bool GuiApplication::needsBackingStore() const
2730 /* Qt on macOS and Wayland does not respect the
2731 * Qt::WA_OpaquePaintEvent attribute and resets the widget backing
2732 * store at each update. Therefore, we use our own backing store
2733 * in these two cases. It is also possible to force the use of the
2734 * backing store for cases like x11 with transparent WM themes.
2736 return platformName() == "cocoa" || platformName().contains("wayland");
2740 QList<int> GuiApplication::viewIds() const
2742 return d->views_.keys();
2746 ColorCache & GuiApplication::colorCache()
2748 return d->color_cache_;
2752 int GuiApplication::exec()
2754 // asynchronously handle batch commands. This event will be in
2755 // the event queue in front of other asynchronous events. Hence,
2756 // we can assume in the latter that the gui is setup already.
2757 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2759 return QApplication::exec();
2763 void GuiApplication::exit(int status)
2765 QApplication::exit(status);
2769 void GuiApplication::setGuiLanguage()
2773 // install translation file for Qt built-in dialogs
2774 QString const language_name = QString("qt_") + theLocale.name();
2775 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2776 // Short-named translator can be loaded from a long name, but not the
2777 // opposite. Therefore, long name should be used without truncation.
2778 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2779 if (!d->qt_trans_.load(language_name,
2780 #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
2781 QLibraryInfo::path(QLibraryInfo::TranslationsPath))) {
2783 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2785 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2788 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2792 switch (theLocale.language()) {
2793 case QLocale::Arabic :
2794 case QLocale::Hebrew :
2795 case QLocale::Persian :
2796 case QLocale::Urdu :
2797 setLayoutDirection(Qt::RightToLeft);
2800 setLayoutDirection(Qt::LeftToRight);
2805 void GuiApplication::execBatchCommands()
2810 if (!readUIFile(toqstr(lyxrc.ui_file)))
2811 // Gives some error box here.
2815 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2816 # if QT_VERSION < 0x060000
2817 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2819 // Create the global default menubar which is shown for the dialogs
2820 // and if no GuiView is visible.
2821 // This must be done after the session was recovered to know the "last files".
2822 d->global_menubar_ = new QMenuBar(0);
2823 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2826 lyx::execBatchCommands();
2830 QAbstractItemModel * GuiApplication::languageModel()
2832 if (d->language_model_)
2833 return d->language_model_;
2835 QStandardItemModel * lang_model = new QStandardItemModel(this);
2836 lang_model->insertColumns(0, 3);
2837 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2838 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2839 Languages::const_iterator it = lyx::languages.begin();
2840 Languages::const_iterator end = lyx::languages.end();
2841 for (; it != end; ++it) {
2842 int current_row = lang_model->rowCount();
2843 lang_model->insertRows(current_row, 1);
2844 QModelIndex pl_item = lang_model->index(current_row, 0);
2845 QModelIndex sp_item = lang_model->index(current_row, 1);
2846 QModelIndex th_item = lang_model->index(current_row, 2);
2847 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2848 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2849 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2850 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2851 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2852 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2853 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2854 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2855 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2856 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2858 d->language_model_ = new QSortFilterProxyModel(this);
2859 d->language_model_->setSourceModel(lang_model);
2860 d->language_model_->setSortLocaleAware(true);
2861 return d->language_model_;
2865 void GuiApplication::restoreGuiSession()
2867 if (!lyxrc.load_session)
2870 Session & session = theSession();
2871 LastOpenedSection::LastOpened const & lastopened =
2872 session.lastOpened().getfiles();
2874 validateCurrentView();
2876 FileName active_file;
2877 // do not add to the lastfile list since these files are restored from
2878 // last session, and should be already there (regular files), or should
2879 // not be added at all (help files).
2880 for (auto const & last : lastopened) {
2881 FileName const & file_name = last.file_name;
2882 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2883 && current_view_->documentBufferView() != nullptr)) {
2884 string const & fname = file_name.absFileName();
2885 createView(support::checksum(fname));
2887 current_view_->loadDocument(file_name, false);
2890 active_file = file_name;
2893 // Restore last active buffer
2894 Buffer * buffer = theBufferList().getBuffer(active_file);
2895 if (buffer && current_view_)
2896 current_view_->setBuffer(buffer);
2898 // clear this list to save a few bytes of RAM
2899 session.lastOpened().clear();
2903 QString const GuiApplication::romanFontName()
2906 font.setStyleHint(QFont::Serif);
2907 font.setFamily("serif");
2909 return QFontInfo(font).family();
2913 QString const GuiApplication::sansFontName()
2916 font.setStyleHint(QFont::SansSerif);
2917 font.setFamily("sans");
2919 return QFontInfo(font).family();
2923 QString const GuiApplication::typewriterFontName()
2925 return QFontInfo(typewriterSystemFont()).family();
2930 // We cannot use QFont::fixedPitch() because it doesn't
2931 // return the fact but only if it is requested.
2932 static bool isFixedPitch(const QFont & font) {
2933 const QFontInfo fi(font);
2934 return fi.fixedPitch();
2939 QFont const GuiApplication::typewriterSystemFont()
2941 #if QT_VERSION >= 0x050200
2942 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2944 QFont font("monospace");
2946 if (!isFixedPitch(font)) {
2947 // try to enforce a real monospaced font
2948 font.setStyleHint(QFont::Monospace);
2949 if (!isFixedPitch(font)) {
2950 font.setStyleHint(QFont::TypeWriter);
2951 if (!isFixedPitch(font)) font.setFamily("courier");
2955 // On a Mac the result is too small and it's not practical to
2956 // rely on Qtconfig utility to change the system settings of Qt.
2957 font.setPointSize(12);
2963 void GuiApplication::handleRegularEvents()
2965 ForkedCallsController::handleCompletedProcesses();
2969 bool GuiApplication::event(QEvent * e)
2972 case QEvent::FileOpen: {
2973 // Open a file; this happens only on Mac OS X for now.
2975 // We do this asynchronously because on startup the batch
2976 // commands are not executed here yet and the gui is not ready
2978 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2979 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2980 processFuncRequestAsync(fr);
2984 case QEvent::ApplicationPaletteChange: {
2985 // runtime switch from/to dark mode
2987 return QApplication::event(e);
2990 return QApplication::event(e);
2995 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2998 return QApplication::notify(receiver, event);
3000 catch (ExceptionMessage const & e) {
3002 case ErrorException:
3004 setQuitOnLastWindowClosed(false);
3006 Alert::error(e.title_, e.details_);
3008 // Properly crash in debug mode in order to get a useful backtrace.
3011 // In release mode, try to exit gracefully.
3013 // FIXME: GCC 7 thinks we can fall through here. Can we?
3015 case BufferException: {
3016 if (!current_view_ || !current_view_->documentBufferView())
3018 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
3019 docstring details = e.details_ + '\n';
3020 details += buf->emergencyWrite();
3021 theBufferList().release(buf);
3022 details += "\n" + _("The current document was closed.");
3023 Alert::error(e.title_, details);
3026 case WarningException:
3027 Alert::warning(e.title_, e.details_);
3031 catch (exception const & e) {
3032 docstring s = _("LyX has caught an exception, it will now "
3033 "attempt to save all unsaved documents and exit."
3035 s += from_ascii(e.what());
3036 Alert::error(_("Software exception Detected"), s);
3040 docstring s = _("LyX has caught some really weird exception, it will "
3041 "now attempt to save all unsaved documents and exit.");
3042 Alert::error(_("Software exception Detected"), s);
3049 bool GuiApplication::isInDarkMode()
3051 return colorCache().isDarkMode();
3055 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
3057 QColor const & qcol = d->color_cache_.get(col);
3058 if (!qcol.isValid()) {
3064 rgbcol.r = qcol.red();
3065 rgbcol.g = qcol.green();
3066 rgbcol.b = qcol.blue();
3071 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
3073 QColor const qcol(lcolor.getX11HexName(col).c_str());
3074 if (!qcol.isValid()) {
3080 rgbcol.r = qcol.red();
3081 rgbcol.g = qcol.green();
3082 rgbcol.b = qcol.blue();
3087 string const GuiApplication::hexName(ColorCode col)
3089 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
3093 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
3095 SocketNotifier * sn = new SocketNotifier(this, fd, func);
3096 d->socket_notifiers_[fd] = sn;
3097 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
3101 void GuiApplication::socketDataReceived(int fd)
3103 d->socket_notifiers_[fd]->func_();
3107 void GuiApplication::unregisterSocketCallback(int fd)
3109 d->socket_notifiers_.take(fd)->setEnabled(false);
3113 void GuiApplication::commitData(QSessionManager & sm)
3115 /** The implementation is required to avoid an application exit
3116 ** when session state save is triggered by session manager.
3117 ** The default implementation sends a close event to all
3118 ** visible top level widgets when session management allows
3120 ** We are changing that to check the state of each buffer in all
3121 ** views and ask the users what to do if buffers are dirty.
3122 ** Furthermore, we save the session state.
3123 ** We do NOT close the views here since the user still can cancel
3124 ** the logout process (see #9277); also, this would hide LyX from
3125 ** an OSes own session handling (application restoration).
3127 #ifdef QT_NO_SESSIONMANAGER
3129 #warning Qt is compiled without session manager
3131 #pragma message("warning: Qt is compiled without session manager")
3135 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
3143 void GuiApplication::unregisterView(GuiView * gv)
3145 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
3146 d->views_.remove(gv->id());
3147 if (current_view_ == gv)
3148 current_view_ = nullptr;
3153 bool GuiApplication::closeAllViews()
3155 if (d->views_.empty())
3158 // When a view/window was closed before without quitting LyX, there
3159 // are already entries in the lastOpened list.
3160 theSession().lastOpened().clear();
3162 QList<GuiView *> const views = d->views_.values();
3163 for (GuiView * view : views) {
3164 if (!view->closeScheduled())
3173 bool GuiApplication::prepareAllViewsForLogout()
3175 if (d->views_.empty())
3178 QList<GuiView *> const views = d->views_.values();
3179 for (GuiView * view : views) {
3180 if (!view->prepareAllBuffersForLogout())
3188 GuiView & GuiApplication::view(int id) const
3190 LAPPERR(d->views_.contains(id));
3191 return *d->views_.value(id);
3195 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3197 QList<GuiView *> const views = d->views_.values();
3198 for (GuiView * view : views)
3199 view->hideDialog(name, inset);
3203 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3205 Buffer const * buf = nullptr;
3206 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3207 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3208 if (Buffer const * ptr = (*it)->updateInset(inset))
3215 bool GuiApplication::searchMenu(FuncRequest const & func,
3216 docstring_list & names) const
3218 BufferView * bv = nullptr;
3220 bv = current_view_->currentBufferView();
3221 return d->menus_.searchMenu(func, names, bv);
3225 bool GuiApplication::hasBufferView() const
3227 return (current_view_ && current_view_->currentBufferView());
3231 // Ensure that a file is read only once (prevents include loops)
3232 static QStringList uifiles;
3233 // store which ui files define Toolbars
3234 static QStringList toolbar_uifiles;
3237 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3248 LexerKeyword uitags[] = {
3249 { "format", ui_format },
3250 { "include", ui_include },
3251 { "menuset", ui_menuset },
3252 { "toolbars", ui_toolbars },
3253 { "toolbarset", ui_toolbarset }
3257 lex.setFile(ui_path);
3259 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3263 if (lyxerr.debugging(Debug::PARSER))
3264 lex.printTable(lyxerr);
3267 // format before introduction of format tag
3268 unsigned int format = 0;
3269 while (lex.isOK()) {
3270 int const status = lex.lex();
3272 // we have to do this check here, outside the switch,
3273 // because otherwise we would start reading include files,
3274 // e.g., if the first tag we hit was an include tag.
3275 if (status == ui_format)
3277 format = lex.getInteger();
3281 // this will trigger unless the first tag we hit is a format
3282 // tag, with the right format.
3283 if (format != LFUN_FORMAT)
3284 return FormatMismatch;
3287 case Lexer::LEX_FEOF:
3292 QString const file = toqstr(lex.getString());
3293 bool const success = readUIFile(file, true);
3295 LYXERR0("Failed to read included file: " << fromqstr(file));
3302 d->menus_.read(lex);
3306 d->toolbars_.readToolbars(lex);
3310 d->toolbars_.readToolbarSettings(lex);
3311 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3315 if (!rtrim(lex.getString()).empty())
3316 lex.printError("LyX::ReadUIFile: "
3317 "Unknown menu tag: `$$Token'");
3319 LYXERR0("Error with status: " << status);
3325 return (error ? ReadError : ReadOK);
3329 bool GuiApplication::readUIFile(QString const & name, bool include)
3331 LYXERR(Debug::INIT, "About to read " << name << "...");
3335 ui_path = libFileSearch("ui", name, "inc");
3336 if (ui_path.empty())
3337 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3339 ui_path = libFileSearch("ui", name, "ui");
3342 if (ui_path.empty()) {
3343 static const QString defaultUIFile = "default";
3344 LYXERR(Debug::INIT, "Could not find " << name);
3346 Alert::warning(_("Could not find UI definition file"),
3347 bformat(_("Error while reading the included file\n%1$s\n"
3348 "Please check your installation."), qstring_to_ucs4(name)));
3351 if (name == defaultUIFile) {
3352 LYXERR(Debug::INIT, "Could not find default UI file!!");
3353 Alert::warning(_("Could not find default UI file"),
3354 _("LyX could not find the default UI file!\n"
3355 "Please check your installation."));
3358 Alert::warning(_("Could not find UI definition file"),
3359 bformat(_("Error while reading the configuration file\n%1$s\n"
3360 "Falling back to default.\n"
3361 "Please look under Tools>Preferences>User Interface and\n"
3362 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3363 return readUIFile(defaultUIFile, false);
3366 QString const uifile = toqstr(ui_path.absFileName());
3367 if (uifiles.contains(uifile)) {
3369 // We are reading again the top uifile so reset the safeguard:
3372 d->toolbars_.reset();
3374 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3375 << "Is this an include loop?");
3379 uifiles.push_back(uifile);
3381 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3383 ReturnValues retval = readUIFile(ui_path);
3385 if (retval == FormatMismatch) {
3386 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3387 TempFile tmp("convertXXXXXX.ui");
3388 FileName const tempfile = tmp.name();
3389 bool const success = prefs2prefs(ui_path, tempfile, true);
3391 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3392 " to format " << LFUN_FORMAT << ".");
3394 retval = readUIFile(tempfile);
3398 if (retval != ReadOK) {
3399 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3407 settings.beginGroup("ui_files");
3408 bool touched = false;
3409 for (int i = 0; i != uifiles.size(); ++i) {
3410 QFileInfo fi(uifiles[i]);
3411 QDateTime const date_value = fi.lastModified();
3412 QString const name_key = QString::number(i);
3413 // if an ui file which defines Toolbars has changed,
3414 // we have to reset the settings
3415 if (toolbar_uifiles.contains(uifiles[i])
3416 && (!settings.contains(name_key)
3417 || settings.value(name_key).toString() != uifiles[i]
3418 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3420 settings.setValue(name_key, uifiles[i]);
3421 settings.setValue(name_key + "/date", date_value);
3424 settings.endGroup();
3426 settings.remove("views");
3432 void GuiApplication::onLastWindowClosed()
3434 if (d->global_menubar_)
3435 d->global_menubar_->grabKeyboard();
3439 #if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
3440 void GuiApplication::onApplicationStateChanged(Qt::ApplicationState state)
3442 std::string name = "unknown";
3444 case Qt::ApplicationSuspended:
3445 name = "ApplicationSuspended";
3447 case Qt::ApplicationHidden:
3448 name = "ApplicationHidden";
3450 case Qt::ApplicationInactive:
3451 name = "ApplicationInactive";
3453 case Qt::ApplicationActive:
3454 name = "ApplicationActive";
3455 /// The Dock icon click produces 2 sequential QEvent::ApplicationStateChangeEvent events.
3456 /// cmd+tab only one QEvent::ApplicationStateChangeEvent event
3457 if (d->views_.empty() && d->last_state_ == state) {
3458 LYXERR(Debug::GUI, "Open new window...");
3463 LYXERR(Debug::GUI, "onApplicationStateChanged..." << name);
3464 d->last_state_ = state;
3469 void GuiApplication::startLongOperation() {
3470 d->key_checker_.start();
3474 bool GuiApplication::longOperationCancelled() {
3475 return d->key_checker_.pressed();
3479 void GuiApplication::stopLongOperation() {
3480 d->key_checker_.stop();
3484 bool GuiApplication::longOperationStarted() {
3485 return d->key_checker_.started();
3489 ////////////////////////////////////////////////////////////////////////
3491 // X11 specific stuff goes here...
3493 #if defined(QPA_XCB)
3494 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3495 void * message, long *)
3497 if (!current_view_ || eventType != "xcb_generic_event_t")
3500 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3502 switch (ev->response_type) {
3503 case XCB_SELECTION_REQUEST: {
3504 xcb_selection_request_event_t * srev =
3505 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3506 if (srev->selection != XCB_ATOM_PRIMARY)
3508 LYXERR(Debug::SELECTION, "X requested selection.");
3509 BufferView * bv = current_view_->currentBufferView();
3511 docstring const sel = bv->requestSelection();
3513 d->selection_.put(sel);
3514 #ifdef HAVE_QT5_X11_EXTRAS
3515 // Refresh the selection request timestamp.
3516 // We have to do this by ourselves as Qt seems
3517 // not doing that, maybe because of our
3518 // "persistent selection" implementation
3519 // (see comments in GuiSelection.cpp).
3520 // It is expected that every X11 event is
3521 // 32 bytes long, even if not all 32 bytes are
3523 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3524 struct alignas(32) padded_event
3525 : xcb_selection_notify_event_t {};
3526 padded_event nev = {};
3527 nev.response_type = XCB_SELECTION_NOTIFY;
3528 nev.requestor = srev->requestor;
3529 nev.selection = srev->selection;
3530 nev.target = srev->target;
3531 nev.property = XCB_NONE;
3532 nev.time = XCB_CURRENT_TIME;
3533 xcb_connection_t * con = QX11Info::connection();
3534 xcb_send_event(con, 0, srev->requestor,
3535 XCB_EVENT_MASK_NO_EVENT,
3536 reinterpret_cast<char const *>(&nev));
3544 case XCB_SELECTION_CLEAR: {
3545 xcb_selection_clear_event_t * scev =
3546 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3547 if (scev->selection != XCB_ATOM_PRIMARY)
3549 LYXERR(Debug::SELECTION, "Lost selection.");
3550 BufferView * bv = current_view_->currentBufferView();
3552 bv->clearSelection();
3560 } // namespace frontend
3563 void hideDialogs(std::string const & name, Inset * inset)
3566 frontend::guiApp->hideDialogs(name, inset);
3570 ////////////////////////////////////////////////////////////////////
3574 ////////////////////////////////////////////////////////////////////
3576 frontend::FontLoader & theFontLoader()
3578 LAPPERR(frontend::guiApp);
3579 return frontend::guiApp->fontLoader();
3583 frontend::FontMetrics const & theFontMetrics(Font const & f)
3585 return theFontMetrics(f.fontInfo());
3589 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3591 LAPPERR(frontend::guiApp);
3592 return frontend::guiApp->fontLoader().metrics(f);
3596 ////////////////////////////////////////////////////////////////////
3600 ////////////////////////////////////////////////////////////////////
3602 frontend::Clipboard & theClipboard()
3604 LAPPERR(frontend::guiApp);
3605 return frontend::guiApp->clipboard();
3609 frontend::Selection & theSelection()
3611 LAPPERR(frontend::guiApp);
3612 return frontend::guiApp->selection();
3618 #include "moc_GuiApplication.cpp"