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/FileName.h"
67 #include "support/filetools.h"
68 #include "support/ForkedCalls.h"
69 #include "support/gettext.h"
70 #include "support/lassert.h"
71 #include "support/lstrings.h"
72 #include "support/lyxalgo.h" // sorted
73 #include "support/textutils.h"
74 #include "support/Messages.h"
75 #include "support/os.h"
76 #include "support/Package.h"
77 #include "support/TempFile.h"
80 #include "support/AppleScript.h"
81 #include "support/AppleSupport.h"
82 #include "support/linkback/LinkBackProxy.h"
91 #include <QDesktopWidget>
93 #include <QFileOpenEvent>
95 #include <QFontDatabase>
98 #include <QImageReader>
101 #include <QLibraryInfo>
109 #include <QSessionManager>
111 #include <QSocketNotifier>
112 #include <QSortFilterProxyModel>
113 #include <QStandardItemModel>
115 #include <QTranslator>
116 #include <QThreadPool>
120 #include <X11/Xatom.h>
121 #include <X11/Xlib.h>
125 #elif defined(QPA_XCB)
127 #ifdef HAVE_QT5_X11_EXTRAS
128 #include <QtX11Extras/QX11Info>
132 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
133 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
134 #if (QT_VERSION < 0x050000)
135 #include <QWindowsMime>
136 #define QWINDOWSMIME QWindowsMime
139 #define QWINDOWSMIME QWinMime
149 #include <QMacPasteboardMime>
157 using namespace lyx::support;
162 frontend::Application * createApplication(int & argc, char * argv[])
164 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
165 // prune -geometry argument(s) by shifting
166 // the following ones 2 places down.
167 for (int i = 0 ; i < argc ; ++i) {
168 if (strcmp(argv[i], "-geometry") == 0) {
169 int const remove = (i+1) < argc ? 2 : 1;
171 for (int j = i; j < argc; ++j)
172 argv[j] = argv[j + remove];
178 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
179 // On Windows, allow bringing the LyX window to top
180 AllowSetForegroundWindow(ASFW_ANY);
183 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
184 // I'd rather do that in the constructor, but I do not think that
185 // the palette is accessible there.
186 guiApp->colorCache().setPalette(guiApp->palette());
195 if (lyxrc.gui_language == "auto") {
196 theLocale = QLocale::system();
197 code = fromqstr(theLocale.name());
199 Language const * l = languages.getLanguage(lyxrc.gui_language);
200 code = l ? l->code() : "C";
201 theLocale = QLocale(toqstr(code));
203 // Qt tries to outsmart us and transforms en_US to C.
204 Messages::guiLanguage((code == "C") ? "en_US" : code);
205 QLocale::setDefault(theLocale);
206 setlocale(LC_NUMERIC, "C");
213 /// Return the list of loadable formats.
214 vector<string> loadableImageFormats()
218 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
220 LYXERR(Debug::GRAPHICS,
221 "\nThe image loader can load the following directly:\n");
223 if (qt_formats.empty())
224 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
226 bool jpeg_found = false;
227 bool jpg_found = false;
228 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
230 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
232 string ext = ascii_lowercase((const char *) *it);
240 else if (ext == "jpg") {
245 else if (lyxrc.use_converter_cache &&
246 (ext == "svg" || ext == "svgz") &&
247 theConverters().isReachable("svg", "png"))
248 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
249 // the SVG as in the output. However we require that the converter
250 // cache is enabled since this is expensive. We also require that
251 // an explicit svg->png converter is defined, since the default
252 // converter could produce bad quality as well. This assumes that
253 // png can always be loaded.
262 ////////////////////////////////////////////////////////////////////////
264 // Icon loading support code
266 ////////////////////////////////////////////////////////////////////////
276 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
278 return lhs.key < rhs.key;
284 CompareKey(QString const & name) : name_(name) {}
285 bool operator()(ImgMap const & other) const { return other.key == name_; }
291 // this must be sorted alphabetically
292 // Upper case comes before lower case
293 // Please don't change the formatting, this list is parsed by
294 // development/tools/generate_symbols_images.py.
295 ImgMap sorted_img_map[] = {
296 { "Arrownot", "arrownot2"},
297 { "Arrowvert", "arrowvert2"},
298 { "Bowtie", "bowtie2" },
300 { "Bumpeq", "bumpeq2" },
301 { "CIRCLE", "circle3" },
303 { "CheckedBox", "checkedbox2" },
304 { "Circle", "circle2" },
305 { "Colonapprox", "colonapprox2" },
306 { "Coloneq", "coloneq2" },
307 { "Coloneqq", "coloneqq2" },
308 { "Colonsim", "colonsim2" },
310 { "DOWNarrow", "downarrow3" },
311 { "Delta", "delta2" },
312 { "Diamond", "diamond2" },
313 { "Doteq", "doteq2" },
314 { "Downarrow", "downarrow2" },
315 { "Eqcolon", "eqcolon2" },
316 { "Eqqcolon", "eqqcolon2" },
317 { "Gamma", "gamma2" },
319 { "LEFTCIRCLE", "leftcircle3" },
320 { "LEFTarrow", "leftarrow3" },
321 { "LEFTcircle", "leftcircle4" },
323 { "Lambda", "lambda2" },
325 { "Leftarrow", "leftarrow2" },
326 { "Leftcircle", "leftcircle2" },
327 { "Leftrightarrow", "leftrightarrow2" },
328 { "Longarrownot", "longarrownot2"},
329 { "Longleftarrow", "longleftarrow2" },
330 { "Longleftrightarrow", "longleftrightarrow2" },
331 { "Longmapsfrom", "longmapsfrom2"},
332 { "Longmapsto", "longmapsto2"},
333 { "Longrightarrow", "longrightarrow2" },
334 { "Mapsfrom", "mapsfrom2"},
335 { "Mapsfromchar", "mapsfromchar2"},
336 { "Mapsto", "mapsto2"},
337 { "Mapstochar", "mapstochar2"},
338 { "Omega", "omega2" },
343 { "RIGHTCIRCLE", "rightcircle3" },
344 { "RIGHTarrow", "rightarrow3" },
345 { "RIGHTcircle", "rightcircle4" },
347 { "Rightarrow", "rightarrow2" },
348 { "Rightcircle", "rightcircle2" },
349 { "Sigma", "sigma2" },
350 { "Square", "square2" },
351 { "Subset", "subset2" },
352 { "Supset", "supset2" },
353 { "Theta", "theta2" },
354 { "Thorn", "thorn2" },
355 { "UParrow", "uparrow3" },
356 { "Uparrow", "uparrow2" },
357 { "Updownarrow", "updownarrow2" },
358 { "Upsilon", "upsilon2" },
359 { "Vdash", "vdash3" },
364 { "lVert", "vert2" },
366 { "nLeftarrow", "nleftarrow2" },
367 { "nLeftrightarrow", "nleftrightarrow2" },
368 { "nRightarrow", "nrightarrow2" },
369 { "nVDash", "nvdash3" },
370 { "nVdash", "nvdash4" },
371 { "nvDash", "nvdash2" },
372 { "rVert", "vert2" },
374 { "textrm \\AA", "textrm_AA"},
375 { "textrm \\O", "textrm_O"},
376 { "vDash", "vdash2" },
377 { "varDelta", "vardelta2" },
378 { "varGamma", "vargamma2" },
379 { "varLambda", "varlambda2" },
380 { "varOmega", "varomega2" },
381 { "varPhi", "varphi2" },
382 { "varPi", "varpi2" },
383 { "varPsi", "varpsi2" },
384 { "varSigma", "varsigma2" },
385 { "varTheta", "vartheta2" },
386 { "varUpsilon", "varupsilon2" },
387 { "varXi", "varxi2" }
391 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
393 // This list specifies which system's theme icon is related to which lyx
394 // command. It was based on:
395 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
396 // this must be sorted alphabetically
397 // Upper case comes before lower case
398 ImgMap sorted_theme_icon_map[] = {
399 { "bookmark-goto 0", "go-jump" },
400 { "buffer-new", "document-new" },
401 { "buffer-write", "document-save" },
402 { "buffer-write-as", "document-save-as" },
403 { "buffer-zoom-in", "zoom-in" },
404 { "buffer-zoom-out", "zoom-out" },
405 { "copy", "edit-copy" },
406 { "cut", "edit-cut" },
407 { "depth-decrement", "format-indent-less" },
408 { "depth-increment", "format-indent-more" },
409 { "dialog-show spellchecker", "tools-check-spelling" },
410 { "dialog-show-new-inset graphics", "insert-image" },
411 { "dialog-toggle findreplaceadv", "edit-find-replace" },
412 { "file-open", "document-open" },
413 { "font-bold", "format-text-bold" },
414 { "font-ital", "format-text-italic" },
415 { "font-strikeout", "format-text-strikethrough" },
416 { "font-underline", "format-text-underline" },
417 { "lyx-quit", "application-exit" },
418 { "paste", "edit-paste" },
419 { "redo", "edit-redo" },
420 { "undo", "edit-undo" },
421 { "window-close", "window-close" },
422 { "window-new", "window-new" }
425 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
428 QString findImg(QString const & name)
430 ImgMap const * const begin = sorted_img_map;
431 ImgMap const * const end = begin + nr_sorted_img_map;
432 LATTEST(sorted(begin, end));
434 ImgMap const * const it = find_if(begin, end, CompareKey(name));
438 img_name = it->value;
441 img_name.replace('_', "underscore");
442 img_name.replace(' ', '_');
444 // This way we can have "math-delim { }" on the toolbar.
445 img_name.replace('(', "lparen");
446 img_name.replace(')', "rparen");
447 img_name.replace('[', "lbracket");
448 img_name.replace(']', "rbracket");
449 img_name.replace('{', "lbrace");
450 img_name.replace('}', "rbrace");
451 img_name.replace('|', "bars");
452 img_name.replace(',', "thinspace");
453 img_name.replace(':', "mediumspace");
454 img_name.replace(';', "thickspace");
455 img_name.replace('!', "negthinspace");
458 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
459 << "Looking for math icon called \"" << img_name << '"');
466 QString themeIconName(QString const & action)
468 ImgMap const * const begin = sorted_theme_icon_map;
469 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
470 LASSERT(sorted(begin, end), /**/);
472 ImgMap const * const it = find_if(begin, end, CompareKey(action));
480 IconInfo iconInfo(FuncRequest const & f, bool unknown, bool rtl)
485 QString lfunname = toqstr(lyxaction.getActionName(f.action()));
487 if (!f.argument().empty()) {
488 // if there are arguments, first search an icon which name is the full thing
489 QString name = lfunname + ' ' + toqstr(f.argument());
490 name.replace(' ', '_');
491 name.replace(';', '_');
492 name.replace('\\', "backslash");
495 // then special default icon for some lfuns
496 switch (f.action()) {
497 case LFUN_MATH_INSERT:
498 names << "math/" + findImg(toqstr(f.argument()).mid(1));
500 case LFUN_MATH_DELIM:
501 case LFUN_MATH_BIGDELIM:
502 names << "math/" + findImg(toqstr(f.argument()));
505 names << "commands/" + toqstr(f.argument());
507 case LFUN_COMMAND_ALTERNATIVES: {
508 // use the first of the alternative commands
510 docstring dummy = split(f.argument(), firstcom, ';');
511 QString name1 = toqstr(firstcom);
512 name1.replace(' ', '_');
513 name1.replace(';', '_');
514 name1.replace('\\', "backslash");
523 // next thing to try is function name alone
526 // and finally maybe the unknown icon
530 search_mode const mode = theGuiApp()->imageSearchMode();
531 // The folders where icons are searched for
532 QStringList imagedirs;
533 imagedirs << "images/ipa/" << "images/";
534 // This is used to search for rtl version of icons which have the +rrtl suffix.
535 QStringList suffixes;
538 suffixes << QString();
540 for (QString const & imagedir : imagedirs)
541 for (QString const & name : names)
542 for (QString const & suffix : suffixes) {
543 QString id = imagedir;
544 FileName fname = imageLibFileSearch(id, name + suffix, "svgz,png", mode);
545 if (fname.exists()) {
546 docstring const fpath = fname.absoluteFilePath();
547 res.filepath = toqstr(fname.absFileName());
548 // these icons are subject to inversion in dark mode
549 res.invert = (contains(fpath, from_ascii("math")) || contains(fpath, from_ascii("ert-insert"))
550 || suffixIs(fname.onlyPath().absoluteFilePath(), from_ascii("ipa")));
551 res.swap = rtl && suffix.isEmpty();
556 LYXERR(Debug::GUI, "Cannot find icon for command \""
557 << lyxaction.getActionName(f.action())
558 << '(' << to_utf8(f.argument()) << ")\"");
564 QPixmap prepareForDarkMode(QPixmap pixmap)
566 QPalette palette = QPalette();
567 QColor text_color = palette.color(QPalette::Active, QPalette::WindowText);
568 QColor bg_color = palette.color(QPalette::Active, QPalette::Window);
570 // guess whether we are in dark mode
571 if (text_color.black() > bg_color.black())
572 // not in dark mode, do nothing
575 // create a layer with black text turned to QPalette::WindowText
576 QPixmap black_overlay(pixmap.size());
577 black_overlay.fill(text_color);
578 black_overlay.setMask(pixmap.createMaskFromColor(Qt::black, Qt::MaskOutColor));
580 // create a layer with blue text turned to lighter blue
581 QPixmap blue_overlay(pixmap.size());
582 QColor math_blue(0, 0, 255);
583 blue_overlay.fill(guiApp->colorCache().get(Color(Color_math)));
584 blue_overlay.setMask(pixmap.createMaskFromColor(math_blue, Qt::MaskOutColor));
586 // create a layer with ("latex") red text turned to lighter red
587 QPixmap red_overlay(pixmap.size());
588 QColor math_red(128, 0, 0);
589 red_overlay.fill(guiApp->colorCache().get(Color(Color_latex)));
590 red_overlay.setMask(pixmap.createMaskFromColor(math_red, Qt::MaskOutColor));
592 // put layers on top of existing pixmap
593 QPainter painter(&pixmap);
594 painter.drawPixmap(pixmap.rect(), black_overlay);
595 painter.drawPixmap(pixmap.rect(), blue_overlay);
596 painter.drawPixmap(pixmap.rect(), red_overlay);
602 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
604 QString imagedir = path;
605 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
606 QString fpath = toqstr(fname.absFileName());
607 QPixmap pixmap = QPixmap();
609 if (pixmap.load(fpath)) {
610 if (fpath.contains("math") || fpath.contains("ipa"))
611 return prepareForDarkMode(pixmap);
615 bool const list = ext.contains(",");
616 LYXERR(Debug::GUI, "Cannot load pixmap \""
617 << path << "/" << name << "." << (list ? "{" : "") << ext
618 << (list ? "}" : "") << "\".");
624 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
626 #if (QT_VERSION >= 0x040600)
627 if (lyxrc.use_system_theme_icons) {
628 // use the icons from system theme that are available
629 QString action = toqstr(lyxaction.getActionName(f.action()));
630 if (!f.argument().empty())
631 action += " " + toqstr(f.argument());
632 QString const theme_icon = themeIconName(action);
633 if (QIcon::hasThemeIcon(theme_icon)) {
634 QIcon const thmicn = QIcon::fromTheme(theme_icon);
635 if (!thmicn.isNull())
641 IconInfo icondata = iconInfo(f, unknown, rtl);
642 if (icondata.filepath.isEmpty())
645 //LYXERR(Debug::GUI, "Found icon: " << icon);
646 QPixmap pixmap = QPixmap();
647 if (!pixmap.load(icondata.filepath)) {
648 LYXERR0("Cannot load icon " << icondata.filepath << ".");
653 pixmap = prepareForDarkMode(pixmap);
656 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
658 return QIcon(pixmap);
662 ////////////////////////////////////////////////////////////////////////
664 // LyX server support code.
666 ////////////////////////////////////////////////////////////////////////
668 class SocketNotifier : public QSocketNotifier
671 /// connect a connection notification from the LyXServerSocket
672 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
673 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
677 /// The callback function
678 Application::SocketCallback func_;
682 class GuiTranslator : public QTranslator
685 GuiTranslator(QObject * parent = nullptr)
686 : QTranslator(parent)
689 QString translate(const char * /* context */,
690 const char *sourceText,
691 #if QT_VERSION >= 0x050000
692 const char * /* disambiguation */ = nullptr, int /* n */ = -1) const override
694 const char * /*comment*/ = 0) const override
697 // Here we declare the strings that need to be translated from Qt own GUI
698 // This is needed to include these strings to po files
702 _("Restore Defaults");
705 // Already in po: "Cancel", "&Cancel"
706 _("Apply"); // Already in po: "&Apply"
707 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
710 docstring s = getGuiMessages().getIfFound(sourceText);
711 // This test should eventually be removed when translations are updated
713 LYXERR(Debug::LOCALE, "Missing translation for `"
714 << string(sourceText) << "'");
720 ////////////////////////////////////////////////////////////////////////
722 // Mac specific stuff goes here...
724 ////////////////////////////////////////////////////////////////////////
727 // QMacPasteboardMimeGraphics can only be compiled on Mac.
729 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
732 QMacPasteboardMimeGraphics()
733 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
736 QString convertorName() { return "Graphics"; }
738 QString flavorFor(QString const & mime)
740 LYXERR(Debug::ACTION, "flavorFor " << mime);
741 if (mime == pdfMimeType())
742 return QLatin1String("com.adobe.pdf");
746 QString mimeFor(QString flav)
748 LYXERR(Debug::ACTION, "mimeFor " << flav);
749 if (flav == QLatin1String("com.adobe.pdf"))
750 return pdfMimeType();
754 bool canConvert(QString const & mime, QString flav)
756 return mimeFor(flav) == mime;
759 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
763 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
767 QList<QByteArray> convertFromMime(QString const & /*mime*/,
768 QVariant data, QString /*flav*/)
770 QList<QByteArray> ret;
771 ret.append(data.toByteArray());
777 ///////////////////////////////////////////////////////////////
779 // You can find more platform specific stuff at the end of this file...
781 ///////////////////////////////////////////////////////////////
783 ////////////////////////////////////////////////////////////////////////
784 // Windows specific stuff goes here...
786 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
787 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
788 // QWindowsMimeMetafile can only be compiled on Windows.
790 static FORMATETC cfFromMime(QString const & mimetype)
793 if (mimetype == emfMimeType()) {
794 formatetc.cfFormat = CF_ENHMETAFILE;
795 formatetc.tymed = TYMED_ENHMF;
796 } else if (mimetype == wmfMimeType()) {
797 formatetc.cfFormat = CF_METAFILEPICT;
798 formatetc.tymed = TYMED_MFPICT;
801 formatetc.dwAspect = DVASPECT_CONTENT;
802 formatetc.lindex = -1;
807 class QWindowsMimeMetafile : public QWINDOWSMIME {
809 QWindowsMimeMetafile() {}
811 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
812 QMimeData const * /*mimedata*/) const override
817 bool canConvertToMime(QString const & mimetype,
818 IDataObject * pDataObj) const override
820 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
822 FORMATETC formatetc = cfFromMime(mimetype);
823 return pDataObj->QueryGetData(&formatetc) == S_OK;
826 bool convertFromMime(FORMATETC const & /*formatetc*/,
827 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const override
832 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
833 QVariant::Type /*preferredType*/) const override
836 if (!canConvertToMime(mimetype, pDataObj))
839 FORMATETC formatetc = cfFromMime(mimetype);
841 if (pDataObj->GetData(&formatetc, &s) != S_OK)
845 if (s.tymed == TYMED_ENHMF) {
846 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
847 data.resize(dataSize);
848 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
849 (LPBYTE)data.data());
850 } else if (s.tymed == TYMED_MFPICT) {
851 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
852 data.resize(dataSize);
853 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
854 (LPBYTE)data.data());
857 ReleaseStgMedium(&s);
863 QVector<FORMATETC> formatsForMime(QString const & mimetype,
864 QMimeData const * /*mimedata*/) const override
866 QVector<FORMATETC> formats;
867 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
868 formats += cfFromMime(mimetype);
872 QString mimeForFormat(FORMATETC const & formatetc) const override
874 switch (formatetc.cfFormat) {
876 return emfMimeType();
877 case CF_METAFILEPICT:
878 return wmfMimeType();
888 /// Allows to check whether ESC was pressed during a long operation
889 class KeyChecker : public QObject {
894 KeyChecker() : pressed_(false), started_(false) {}
897 QCoreApplication::instance()->installEventFilter(this);
902 QCoreApplication::instance()->removeEventFilter(this);
906 QCoreApplication::processEvents();
909 bool started() const {
912 bool eventFilter(QObject *obj, QEvent *event) override {
913 LYXERR(Debug::ACTION, "Event Type: " << event->type());
914 switch (event->type()) {
918 case QEvent::UpdateRequest:
919 case QEvent::CursorChange:
920 case QEvent::ActionChanged:
921 case QEvent::EnabledChange:
922 case QEvent::SockAct:
925 case QEvent::ToolTipChange:
926 case QEvent::LayoutRequest:
927 case QEvent::MetaCall:
928 return QObject::eventFilter(obj, event);
930 // FIXME Blocking all these events is a bad idea.
931 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
932 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
940 ////////////////////////////////////////////////////////////////////////
941 // GuiApplication::Private definition and implementation.
942 ////////////////////////////////////////////////////////////////////////
944 struct GuiApplication::Private
946 Private(): language_model_(nullptr), meta_fake_bit(NoModifier),
947 global_menubar_(nullptr)
949 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
950 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
951 /// WMF Mime handler for Windows clipboard.
952 wmf_mime_ = new QWindowsMimeMetafile;
955 initKeySequences(&theTopLevelKeymap());
958 void initKeySequences(KeyMap * kb)
960 keyseq = KeySequence(kb, kb);
961 cancel_meta_seq = KeySequence(kb, kb);
965 QSortFilterProxyModel * language_model_;
967 GuiClipboard clipboard_;
969 GuiSelection selection_;
971 FontLoader font_loader_;
973 ColorCache color_cache_;
974 /// the built-in Qt translation mechanism
975 QTranslator qt_trans_;
976 /// LyX gettext-based translation for Qt elements
977 GuiTranslator gui_trans_;
979 QHash<int, SocketNotifier *> socket_notifiers_;
983 /// The global instance
986 /// this timer is used for any regular events one wants to
987 /// perform. at present it is used to check if forked processes
989 QTimer general_timer_;
991 /// delayed FuncRequests
992 std::queue<FuncRequest> func_request_queue_;
997 KeySequence cancel_meta_seq;
999 KeyModifier meta_fake_bit;
1001 /// The result of last dispatch action
1002 DispatchResult dispatch_result_;
1004 /// Multiple views container.
1006 * Warning: This must not be a smart pointer as the destruction of the
1007 * object is handled by Qt when the view is closed
1008 * \sa Qt::WA_DeleteOnClose attribute.
1010 QHash<int, GuiView *> views_;
1012 /// Only used on mac.
1013 QMenuBar * global_menubar_;
1016 /// Linkback mime handler for MacOSX.
1017 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1020 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1021 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1022 /// WMF Mime handler for Windows clipboard.
1023 QWindowsMimeMetafile * wmf_mime_;
1027 /// Allows to check whether ESC was pressed during a long operation
1028 KeyChecker key_checker_;
1032 GuiApplication * guiApp;
1034 GuiApplication::~GuiApplication()
1037 closeAllLinkBackLinks();
1043 GuiApplication::GuiApplication(int & argc, char ** argv)
1044 : QApplication(argc, argv), current_view_(nullptr),
1045 d(new GuiApplication::Private)
1047 QString app_name = "LyX";
1048 QCoreApplication::setOrganizationName(app_name);
1049 QCoreApplication::setOrganizationDomain("lyx.org");
1050 QCoreApplication::setApplicationName(lyx_package);
1051 #if QT_VERSION >= 0x050000
1052 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1055 #if QT_VERSION >= 0x050700
1056 setDesktopFileName(lyx_package);
1059 // FIXME Deprecated. Should use QRandomGenerator since 5.10
1060 qsrand(QDateTime::currentDateTime().toTime_t());
1062 // Install LyX translator for missing Qt translations
1063 installTranslator(&d->gui_trans_);
1064 // Install Qt native translator for GUI elements.
1065 installTranslator(&d->qt_trans_);
1068 // Enable reception of XCB events.
1069 installNativeEventFilter(this);
1072 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1073 // lyxrc setting for this in order to let the application stay resident.
1074 // But then we need some kind of dock icon, at least on Windows.
1076 if (lyxrc.quit_on_last_window_closed)
1077 setQuitOnLastWindowClosed(false);
1080 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1081 // seems to be the default case for applications like LyX.
1082 setQuitOnLastWindowClosed(false);
1085 appleCleanupEditMenu();
1086 appleCleanupViewMenu();
1089 #if defined(Q_WS_X11) || defined(QPA_XCB)
1090 // doubleClickInterval() is 400 ms on X11 which is just too long.
1091 // On Windows and Mac OS X, the operating system's value is used.
1092 // On Microsoft Windows, calling this function sets the double
1093 // click interval for all applications. So we don't!
1094 QApplication::setDoubleClickInterval(300);
1097 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1099 // needs to be done before reading lyxrc
1101 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1105 // Initialize RC Fonts
1106 if (lyxrc.roman_font_name.empty())
1107 lyxrc.roman_font_name = fromqstr(romanFontName());
1109 if (lyxrc.sans_font_name.empty())
1110 lyxrc.sans_font_name = fromqstr(sansFontName());
1112 if (lyxrc.typewriter_font_name.empty())
1113 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1115 #if (QT_VERSION >= 0x050000)
1116 // Qt4 does this in event(), see below.
1117 // Track change of keyboard
1118 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1121 d->general_timer_.setInterval(500);
1122 connect(&d->general_timer_, SIGNAL(timeout()),
1123 this, SLOT(handleRegularEvents()));
1124 d->general_timer_.start();
1126 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1127 // This is clearly not enough in a time where we use threads for
1128 // document preview and/or export. 20 should be OK.
1129 QThreadPool::globalInstance()->setMaxThreadCount(20);
1131 // make sure tooltips are formatted
1132 installEventFilter(new ToolTipFormatter(this));
1136 GuiApplication * theGuiApp()
1138 return dynamic_cast<GuiApplication *>(theApp());
1142 #if QT_VERSION < 0x050000
1143 // Emulate platformName() for Qt4
1145 // FIXME: when ditching this method, remove all tests
1146 // platformName() == "qt4x11"
1148 QString GuiApplication::platformName() const
1150 # if defined(Q_WS_X11)
1151 // Note that this one does not really exist
1153 # elif defined(Q_OS_MAC)
1155 # elif defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1158 LYXERR0("Unknown platform!");
1165 double GuiApplication::pixelRatio() const
1167 #if QT_VERSION >= 0x050000
1168 return qt_scale_factor * devicePixelRatio();
1175 void GuiApplication::clearSession()
1182 docstring Application::iconName(FuncRequest const & f, bool unknown)
1184 return qstring_to_ucs4(lyx::frontend::iconInfo(f, unknown, false).filepath);
1188 docstring Application::mathIcon(docstring const & c)
1190 return qstring_to_ucs4(findImg(toqstr(c)));
1194 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1198 BufferView * bv = nullptr;
1199 BufferView * doc_bv = nullptr;
1201 if (cmd.action() == LFUN_NOACTION) {
1202 status.message(from_utf8(N_("Nothing to do")));
1203 status.setEnabled(false);
1206 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1207 status.setUnknown(true);
1208 status.message(from_utf8(N_("Unknown action")));
1209 status.setEnabled(false);
1212 // Does the GuiApplication know something?
1213 else if (getStatus(cmd, status)) { }
1215 // If we do not have a GuiView, then other functions are disabled
1216 else if (!current_view_)
1217 status.setEnabled(false);
1219 // Does the GuiView know something?
1220 else if (current_view_->getStatus(cmd, status)) { }
1222 // In LyX/Mac, when a dialog is open, the menus of the
1223 // application can still be accessed without giving focus to
1224 // the main window. In this case, we want to disable the menu
1225 // entries that are buffer or view-related.
1226 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1228 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1229 status.setEnabled(false);
1232 // If we do not have a BufferView, then other functions are disabled
1233 else if (!(bv = current_view_->currentBufferView()))
1234 status.setEnabled(false);
1236 // Does the current BufferView know something?
1237 else if (bv->getStatus(cmd, status)) { }
1239 // Does the current Buffer know something?
1240 else if (bv->buffer().getStatus(cmd, status)) { }
1242 // If we do not have a document BufferView, different from the
1243 // current BufferView, then other functions are disabled
1244 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1245 status.setEnabled(false);
1247 // Does the document Buffer know something?
1248 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1251 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1252 status.message(from_utf8(N_("Command not handled")));
1253 status.setEnabled(false);
1256 // the default error message if we disable the command
1257 if (!status.enabled() && status.message().empty())
1258 status.message(from_utf8(N_("Command disabled")));
1264 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1266 // I would really like to avoid having this switch and rather try to
1267 // encode this in the function itself.
1268 // -- And I'd rather let an inset decide which LFUNs it is willing
1269 // to handle (Andre')
1271 switch (cmd.action()) {
1273 // This could be used for the no-GUI version. The GUI version is handled in
1274 // GuiView::getStatus(). See above.
1276 case LFUN_BUFFER_WRITE:
1277 case LFUN_BUFFER_WRITE_AS:
1278 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1279 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1280 enable = b && (b->isUnnamed() || !b->isClean());
1285 case LFUN_BOOKMARK_GOTO: {
1286 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1287 enable = theSession().bookmarks().isValid(num);
1291 case LFUN_BOOKMARK_CLEAR:
1292 enable = theSession().bookmarks().hasValid();
1295 // this one is difficult to get right. As a half-baked
1296 // solution, we consider only the first action of the sequence
1297 case LFUN_COMMAND_SEQUENCE: {
1298 // argument contains ';'-terminated commands
1299 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1300 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1301 func.setOrigin(cmd.origin());
1302 flag = getStatus(func);
1306 // we want to check if at least one of these is enabled
1307 case LFUN_COMMAND_ALTERNATIVES: {
1308 // argument contains ';'-terminated commands
1309 string arg = to_utf8(cmd.argument());
1310 while (!arg.empty()) {
1312 arg = split(arg, first, ';');
1313 FuncRequest func(lyxaction.lookupFunc(first));
1314 func.setOrigin(cmd.origin());
1315 flag = getStatus(func);
1316 // if this one is enabled, the whole thing is
1325 string name = to_utf8(cmd.argument());
1326 if (theTopLevelCmdDef().lock(name, func)) {
1327 func.setOrigin(cmd.origin());
1328 flag = getStatus(func);
1329 theTopLevelCmdDef().release(name);
1331 // catch recursion or unknown command
1332 // definition. all operations until the
1333 // recursion or unknown command definition
1334 // occurs are performed, so set the state to
1341 case LFUN_IF_RELATIVES: {
1342 string const lfun = to_utf8(cmd.argument());
1343 BufferView const * bv =
1344 current_view_ ? current_view_->currentBufferView() : nullptr;
1345 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1349 FuncRequest func(lyxaction.lookupFunc(lfun));
1350 func.setOrigin(cmd.origin());
1351 flag = getStatus(func);
1355 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1357 case LFUN_PREFERENCES_SAVE:
1358 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1359 case LFUN_DEBUG_LEVEL_SET:
1360 // these are handled in our dispatch()
1363 case LFUN_WINDOW_CLOSE:
1364 enable = !d->views_.empty();
1367 case LFUN_BUFFER_NEW:
1368 case LFUN_BUFFER_NEW_TEMPLATE:
1369 case LFUN_FILE_OPEN:
1370 case LFUN_HELP_OPEN:
1371 case LFUN_SCREEN_FONT_UPDATE:
1372 case LFUN_SET_COLOR:
1373 case LFUN_WINDOW_NEW:
1375 case LFUN_LYXRC_APPLY:
1376 case LFUN_COMMAND_PREFIX:
1378 case LFUN_META_PREFIX:
1379 case LFUN_RECONFIGURE:
1380 case LFUN_SERVER_GET_FILENAME:
1381 case LFUN_SERVER_NOTIFY:
1385 case LFUN_BUFFER_FORALL: {
1386 if (theBufferList().empty()) {
1387 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1388 flag.setEnabled(false);
1392 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1393 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1394 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1395 flag.setEnabled(false);
1400 case LFUN_DIALOG_SHOW: {
1401 string const name = cmd.getArg(0);
1402 return name == "aboutlyx"
1403 || name == "lyxfiles"
1405 || name == "texinfo"
1406 || name == "progress"
1407 || name == "compare";
1415 flag.setEnabled(false);
1419 /// make a post-dispatch status message
1420 static docstring makeDispatchMessage(docstring const & msg,
1421 FuncRequest const & cmd)
1423 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1424 || cmd.origin() == FuncRequest::TOOLBAR
1425 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1427 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1428 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1432 docstring dispatch_msg = msg;
1433 if (!dispatch_msg.empty())
1434 dispatch_msg += ' ';
1436 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1438 bool argsadded = false;
1440 if (!cmd.argument().empty()) {
1441 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1442 comname += ' ' + cmd.argument();
1446 docstring const shortcuts = theTopLevelKeymap().
1447 printBindings(cmd, KeySequence::ForGui);
1449 if (!shortcuts.empty())
1450 comname += ": " + shortcuts;
1451 else if (!argsadded && !cmd.argument().empty())
1452 comname += ' ' + cmd.argument();
1454 if (!comname.empty()) {
1455 comname = rtrim(comname);
1456 dispatch_msg += '(' + rtrim(comname) + ')';
1458 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1459 return dispatch_msg;
1463 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1467 Buffer * buffer = nullptr;
1468 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1469 //setCurrentView(cmd.view_origin); //does not work
1471 dr.setMessage(_("Wrong focus!"));
1472 d->dispatch_result_ = dr;
1473 return d->dispatch_result_;
1475 if (current_view_ && current_view_->currentBufferView()) {
1476 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1477 buffer = ¤t_view_->currentBufferView()->buffer();
1480 dr.screenUpdate(Update::FitCursor);
1482 // This handles undo groups automagically
1483 UndoGroupHelper ugh(buffer);
1485 // redraw the screen at the end (first of the two drawing steps).
1486 // This is done unless explicitly requested otherwise.
1487 // This code is kept inside the undo group because updateBuffer
1488 // can create undo actions (see #11292)
1489 updateCurrentView(cmd, dr);
1492 d->dispatch_result_ = dr;
1493 return d->dispatch_result_;
1497 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1502 BufferView * bv = current_view_->currentBufferView();
1504 if (dr.needBufferUpdate()) {
1505 bv->cursor().clearBufferUpdate();
1506 bv->buffer().updateBuffer();
1508 // BufferView::update() updates the ViewMetricsInfo and
1509 // also initializes the position cache for all insets in
1510 // (at least partially) visible top-level paragraphs.
1511 // We will redraw the screen only if needed.
1512 bv->processUpdateFlags(dr.screenUpdate());
1514 // Do we have a selection?
1515 theSelection().haveSelection(bv->cursor().selection());
1518 current_view_->restartCaret();
1520 if (dr.needMessageUpdate()) {
1521 // Some messages may already be translated, so we cannot use _()
1522 current_view_->message(makeDispatchMessage(
1523 translateIfPossible(dr.message()), cmd));
1528 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1529 bool switchToBuffer)
1531 if (!theSession().bookmarks().isValid(idx))
1533 BookmarksSection::Bookmark const & bm =
1534 theSession().bookmarks().bookmark(idx);
1535 LASSERT(!bm.filename.empty(), return);
1536 string const file = bm.filename.absFileName();
1537 // if the file is not opened, open it.
1538 if (!theBufferList().exists(bm.filename)) {
1540 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1544 // open may fail, so we need to test it again
1545 if (!theBufferList().exists(bm.filename))
1548 // bm can be changed when saving
1549 BookmarksSection::Bookmark tmp = bm;
1551 // Special case idx == 0 used for back-from-back jump navigation
1553 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1555 // if the current buffer is not that one, switch to it.
1556 BufferView * doc_bv = current_view_ ?
1557 current_view_->documentBufferView() : nullptr;
1558 Cursor const * old = doc_bv ? &doc_bv->cursor() : nullptr;
1559 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1560 if (switchToBuffer) {
1561 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1564 doc_bv = current_view_->documentBufferView();
1569 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1570 if (!doc_bv || !doc_bv->moveToPosition(
1571 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1574 Cursor & cur = doc_bv->cursor();
1575 if (old && cur != *old)
1576 notifyCursorLeavesOrEnters(*old, cur);
1582 // Cursor jump succeeded!
1583 pit_type new_pit = cur.pit();
1584 pos_type new_pos = cur.pos();
1585 int new_id = cur.paragraph().id();
1587 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1588 // see http://www.lyx.org/trac/ticket/3092
1589 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1590 || bm.top_id != new_id) {
1591 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1592 new_pit, new_pos, new_id);
1596 // This function runs "configure" and then rereads lyx.defaults to
1597 // reconfigure the automatic settings.
1598 void GuiApplication::reconfigure(string const & option)
1600 // emit message signal.
1602 current_view_->message(_("Running configure..."));
1604 // Run configure in user lyx directory
1605 string const lock_file = package().getConfigureLockName();
1606 int fd = fileLock(lock_file.c_str());
1607 int const ret = package().reconfigureUserLyXDir(option);
1608 // emit message signal.
1610 current_view_->message(_("Reloading configuration..."));
1611 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1612 // Re-read packages.lst
1613 LaTeXPackages::getAvailable();
1614 fileUnlock(fd, lock_file.c_str());
1617 Alert::information(_("System reconfiguration failed"),
1618 _("The system reconfiguration has failed.\n"
1619 "Default textclass is used but LyX may\n"
1620 "not be able to work properly.\n"
1621 "Please reconfigure again if needed."));
1623 Alert::information(_("System reconfigured"),
1624 _("The system has been reconfigured.\n"
1625 "You need to restart LyX to make use of any\n"
1626 "updated document class specifications."));
1629 void GuiApplication::validateCurrentView()
1631 if (!d->views_.empty() && !current_view_) {
1632 // currently at least one view exists but no view has the focus.
1633 // choose the last view to make it current.
1634 // a view without any open document is preferred.
1635 GuiView * candidate = nullptr;
1636 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1637 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1638 for (; it != end; ++it) {
1640 if (!candidate->documentBufferView())
1643 setCurrentView(candidate);
1647 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1649 string const argument = to_utf8(cmd.argument());
1650 FuncCode const action = cmd.action();
1652 LYXERR(Debug::ACTION, "cmd: " << cmd);
1654 // we have not done anything wrong yet.
1657 FuncStatus const flag = getStatus(cmd);
1658 if (!flag.enabled()) {
1659 // We cannot use this function here
1660 LYXERR(Debug::ACTION, "action "
1661 << lyxaction.getActionName(action)
1662 << " [" << action << "] is disabled at this location");
1663 dr.setMessage(flag.message());
1665 dr.dispatched(false);
1666 dr.screenUpdate(Update::None);
1667 dr.clearBufferUpdate();
1671 if (cmd.origin() == FuncRequest::LYXSERVER) {
1672 if (current_view_ && current_view_->currentBufferView())
1673 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1674 // we will also need to redraw the screen at the end
1675 dr.screenUpdate(Update::FitCursor);
1678 // Assumes that the action will be dispatched.
1679 dr.dispatched(true);
1681 switch (cmd.action()) {
1683 case LFUN_WINDOW_NEW:
1684 createView(toqstr(cmd.argument()));
1687 case LFUN_WINDOW_CLOSE:
1688 // FIXME: this is done also in GuiView::closeBuffer()!
1689 // update bookmark pit of the current buffer before window close
1690 for (size_t i = 1; i < theSession().bookmarks().size(); ++i)
1691 gotoBookmark(i, false, false);
1692 // clear the last opened list, because
1693 // maybe this will end the session
1694 theSession().lastOpened().clear();
1695 // check for valid current_view_
1696 validateCurrentView();
1698 current_view_->closeScheduled();
1702 // quitting is triggered by the gui code
1703 // (leaving the event loop).
1705 current_view_->message(from_utf8(N_("Exiting.")));
1706 if (closeAllViews())
1710 case LFUN_SCREEN_FONT_UPDATE: {
1711 // handle the screen font changes.
1712 /* FIXME: this only updates the current document, whereas all
1713 * documents should see their metrics updated.
1715 d->font_loader_.update();
1716 dr.screenUpdate(Update::Force | Update::FitCursor);
1720 case LFUN_BUFFER_NEW:
1721 validateCurrentView();
1723 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1724 createView(QString(), false); // keep hidden
1725 current_view_->newDocument(to_utf8(cmd.argument()));
1726 current_view_->show();
1727 setActiveWindow(current_view_);
1729 current_view_->newDocument(to_utf8(cmd.argument()));
1733 case LFUN_BUFFER_NEW_TEMPLATE: {
1734 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1735 string const temp = cmd.getArg(1);
1736 validateCurrentView();
1738 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != nullptr)) {
1740 current_view_->newDocument(file, temp, true);
1741 if (!current_view_->documentBufferView())
1742 current_view_->close();
1744 current_view_->newDocument(file, temp, true);
1749 case LFUN_FILE_OPEN: {
1750 // FIXME: normally the code below is not needed, since getStatus makes sure that
1751 // current_view_ is not null.
1752 validateCurrentView();
1753 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1754 string const fname = to_utf8(cmd.argument());
1755 bool const is_open = FileName::isAbsolute(fname)
1756 && theBufferList().getBuffer(FileName(fname));
1758 || (!lyxrc.open_buffers_in_tabs
1759 && current_view_->documentBufferView() != nullptr
1761 // We want the ui session to be saved per document and not per
1762 // window number. The filename crc is a good enough identifier.
1763 createView(support::checksum(fname));
1764 current_view_->openDocument(fname);
1765 if (!current_view_->documentBufferView())
1766 current_view_->close();
1767 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1768 current_view_->raise();
1769 current_view_->activateWindow();
1770 current_view_->showNormal();
1773 current_view_->openDocument(fname);
1774 if (cmd.origin() == FuncRequest::LYXSERVER) {
1775 current_view_->raise();
1776 current_view_->activateWindow();
1777 current_view_->showNormal();
1783 case LFUN_HELP_OPEN: {
1784 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1785 if (current_view_ == nullptr)
1787 string const arg = to_utf8(cmd.argument());
1789 current_view_->message(_("Missing argument"));
1792 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1794 fname = i18nLibFileSearch("examples", arg, "lyx");
1796 if (fname.empty()) {
1797 lyxerr << "LyX: unable to find documentation file `"
1798 << arg << "'. Bad installation?" << endl;
1801 current_view_->message(bformat(_("Opening help file %1$s..."),
1802 makeDisplayPath(fname.absFileName())));
1803 Buffer * buf = current_view_->loadDocument(fname, false);
1805 buf->setReadonly(!current_view_->develMode());
1809 case LFUN_SET_COLOR: {
1810 string const lyx_name = cmd.getArg(0);
1811 string x11_name = cmd.getArg(1);
1812 string x11_darkname = cmd.getArg(2);
1813 if (lyx_name.empty() || x11_name.empty()) {
1815 current_view_->message(
1816 _("Syntax: set-color <lyx_name> <x11_name> <x11_darkname>"));
1821 // FIXME: The graphics cache no longer has a changeDisplay method.
1822 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1823 bool const graphicsbg_changed =
1824 lyx_name == graphicsbg && x11_name != graphicsbg;
1825 if (graphicsbg_changed)
1826 graphics::GCache::get().changeDisplay(true);
1829 if (x11_darkname.empty() && colorCache().isDarkMode()) {
1830 x11_darkname = x11_name;
1833 if (!lcolor.setColor(lyx_name, x11_name, x11_darkname)) {
1835 current_view_->message(
1836 bformat(_("Set-color \"%1$s\" failed "
1837 "- color is undefined or "
1838 "may not be redefined"),
1839 from_utf8(lyx_name)));
1842 // Make sure we don't keep old colors in cache.
1843 d->color_cache_.clear();
1844 // Update the current view
1845 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1849 case LFUN_LYXRC_APPLY: {
1850 // reset active key sequences, since the bindings
1851 // are updated (bug 6064)
1853 LyXRC const lyxrc_orig = lyxrc;
1855 istringstream ss(to_utf8(cmd.argument()));
1856 bool const success = lyxrc.read(ss);
1859 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1860 << "Unable to read lyxrc data"
1865 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1867 // If the request comes from the minibuffer, then we can't reset
1868 // the GUI, since that would destroy the minibuffer itself and
1869 // cause a crash, since we are currently in one of the methods of
1870 // GuiCommandBuffer. See bug #8540.
1871 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1874 // FIXME Unfortunately, that leaves a bug here, since we cannot
1875 // reset the GUI in this case. If the changes to lyxrc affected the
1876 // UI, then, nothing would happen. This seems fairly unlikely, but
1877 // it definitely is a bug.
1879 dr.forceBufferUpdate();
1883 case LFUN_COMMAND_PREFIX:
1884 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1889 d->meta_fake_bit = NoModifier;
1890 GuiView * gv = currentView();
1891 if (gv && gv->currentBufferView())
1892 // cancel any selection
1893 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1894 dr.setMessage(from_ascii(N_("Cancel")));
1897 case LFUN_META_PREFIX:
1898 d->meta_fake_bit = AltModifier;
1899 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1902 // --- Menus -----------------------------------------------
1903 case LFUN_RECONFIGURE:
1904 // argument is any additional parameter to the configure.py command
1905 reconfigure(to_utf8(cmd.argument()));
1908 // --- lyxserver commands ----------------------------
1909 case LFUN_SERVER_GET_FILENAME: {
1910 if (current_view_ && current_view_->documentBufferView()) {
1911 docstring const fname = from_utf8(
1912 current_view_->documentBufferView()->buffer().absFileName());
1913 dr.setMessage(fname);
1914 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1916 dr.setMessage(docstring());
1917 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1922 case LFUN_SERVER_NOTIFY: {
1923 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1924 dr.setMessage(dispatch_buffer);
1925 theServer().notifyClient(to_utf8(dispatch_buffer));
1929 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1930 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1936 string rest = split(argument, countstr, ' ');
1937 int const count = convert<int>(countstr);
1938 // an arbitrary number to limit number of iterations
1939 int const max_iter = 10000;
1940 if (count > max_iter) {
1941 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1944 for (int i = 0; i < count; ++i) {
1945 FuncRequest lfun = lyxaction.lookupFunc(rest);
1946 lfun.allowAsync(false);
1953 case LFUN_COMMAND_SEQUENCE: {
1954 // argument contains ';'-terminated commands
1955 string arg = argument;
1956 // FIXME: this LFUN should also work without any view.
1957 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1958 ? &(current_view_->documentBufferView()->buffer()) : nullptr;
1959 // This handles undo groups automagically
1960 UndoGroupHelper ugh(buffer);
1961 while (!arg.empty()) {
1963 arg = split(arg, first, ';');
1964 FuncRequest func(lyxaction.lookupFunc(first));
1965 func.allowAsync(false);
1966 func.setOrigin(cmd.origin());
1972 case LFUN_BUFFER_FORALL: {
1973 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1974 funcToRun.allowAsync(false);
1976 map<Buffer *, GuiView *> views_lVisible;
1977 map<GuiView *, Buffer *> activeBuffers;
1979 QList<GuiView *> allViews = d->views_.values();
1981 // this for does not modify any buffer. It just collects info on local
1982 // visibility of buffers and on which buffer is active in each view.
1983 Buffer * const last = theBufferList().last();
1984 for(GuiView * view : allViews) {
1985 // all of the buffers might be locally hidden. That is, there is no
1987 if (!view || !view->currentBufferView())
1988 activeBuffers[view] = nullptr;
1990 activeBuffers[view] = &view->currentBufferView()->buffer();
1992 // find out if each is locally visible or locally hidden.
1993 // we don't use a for loop as the buffer list cycles.
1994 Buffer * b = theBufferList().first();
1996 bool const locallyVisible = view && view->workArea(*b);
1997 if (locallyVisible) {
1998 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1999 // only need to overwrite/add if we don't already know a buffer is globally
2000 // visible or we do know but we would prefer to dispatch LFUN from the
2001 // current view because of cursor position issues.
2002 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
2003 views_lVisible[b] = view;
2007 b = theBufferList().next(b);
2011 GuiView * const homeView = currentView();
2012 Buffer * b = theBufferList().first();
2013 Buffer * nextBuf = nullptr;
2014 int numProcessed = 0;
2017 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
2019 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
2021 // first change to a view where b is locally visible, preferably current_view_.
2022 GuiView * const vLv = views_lVisible[b];
2024 lyx::dispatch(funcToRun);
2032 // put things back to how they were (if possible).
2033 for (GuiView * view : allViews) {
2034 Buffer * originalBuf = activeBuffers[view];
2035 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
2036 if (theBufferList().isLoaded(originalBuf))
2037 view->setBuffer(originalBuf);
2039 homeView->setFocus();
2041 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2045 case LFUN_COMMAND_ALTERNATIVES: {
2046 // argument contains ';'-terminated commands
2047 string arg = argument;
2048 while (!arg.empty()) {
2050 arg = split(arg, first, ';');
2051 FuncRequest func(lyxaction.lookupFunc(first));
2052 func.setOrigin(cmd.origin());
2053 FuncStatus const stat = getStatus(func);
2054 if (stat.enabled()) {
2064 if (theTopLevelCmdDef().lock(argument, func)) {
2065 func.setOrigin(cmd.origin());
2067 theTopLevelCmdDef().release(argument);
2069 if (func.action() == LFUN_UNKNOWN_ACTION) {
2070 // unknown command definition
2071 lyxerr << "Warning: unknown command definition `"
2075 // recursion detected
2076 lyxerr << "Warning: Recursion in the command definition `"
2077 << argument << "' detected"
2084 case LFUN_IF_RELATIVES: {
2085 string const lfun = to_utf8(cmd.argument());
2086 FuncRequest func(lyxaction.lookupFunc(lfun));
2087 func.setOrigin(cmd.origin());
2088 FuncStatus const stat = getStatus(func);
2089 if (stat.enabled()) {
2096 case LFUN_PREFERENCES_SAVE:
2097 lyxrc.write(support::makeAbsPath("preferences",
2098 package().user_support().absFileName()), false);
2101 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2102 string const fname = addName(addPath(package().user_support().absFileName(),
2103 "templates/"), "defaults.lyx");
2104 Buffer defaults(fname);
2106 istringstream ss(argument);
2111 // We need to make sure that, after we recreat the DocumentClass,
2112 // which we do in readHeader, we apply it to the document itself.
2113 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2114 int const unknown_tokens = defaults.readHeader(lex);
2115 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2117 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2118 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2120 if (unknown_tokens != 0) {
2121 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2122 << unknown_tokens << " unknown token"
2123 << (unknown_tokens == 1 ? "" : "s")
2127 if (defaults.writeFile(FileName(defaults.absFileName())))
2128 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2129 makeDisplayPath(fname)));
2132 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2137 case LFUN_BOOKMARK_GOTO:
2138 // go to bookmark, open unopened file and switch to buffer if necessary
2139 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2140 dr.screenUpdate(Update::Force | Update::FitCursor);
2143 case LFUN_BOOKMARK_CLEAR:
2144 theSession().bookmarks().clear();
2145 dr.screenUpdate(Update::Force);
2148 case LFUN_DEBUG_LEVEL_SET:
2149 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2152 case LFUN_DIALOG_SHOW: {
2153 string const name = cmd.getArg(0);
2155 if ( name == "aboutlyx"
2157 || name == "texinfo"
2158 || name == "progress"
2159 || name == "compare")
2161 // work around: on Mac OS the application
2162 // is not terminated when closing the last view.
2163 // Create a new one to be able to dispatch the
2164 // LFUN_DIALOG_SHOW to this view.
2165 if (current_view_ == nullptr)
2171 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2174 current_view_->dispatch(cmd, dr);
2178 if (cmd.origin() == FuncRequest::LYXSERVER)
2179 updateCurrentView(cmd, dr);
2183 docstring GuiApplication::viewStatusMessage()
2185 // When meta-fake key is pressed, show the key sequence so far + "M-".
2186 if (d->meta_fake_bit != NoModifier)
2187 return d->keyseq.print(KeySequence::ForGui) + "M-";
2189 // Else, when a non-complete key sequence is pressed,
2190 // show the available options.
2191 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2192 return d->keyseq.printOptions(true);
2198 string GuiApplication::inputLanguageCode() const
2200 #if (QT_VERSION < 0x050000)
2201 QLocale loc = keyboardInputLocale();
2203 QLocale loc = inputMethod()->locale();
2205 //LYXERR0("input lang = " << fromqstr(loc.name()));
2206 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2210 void GuiApplication::onLocaleChanged()
2212 //LYXERR0("Change language to " << inputLanguage()->lang());
2213 if (currentView() && currentView()->currentBufferView())
2214 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2218 void GuiApplication::handleKeyFunc(FuncCode action)
2222 if (d->keyseq.length())
2224 GuiView * gv = currentView();
2225 LASSERT(gv && gv->currentBufferView(), return);
2226 BufferView * bv = gv->currentBufferView();
2227 bv->getIntl().getTransManager().deadkey(
2228 c, get_accent(action).accent, bv->cursor().innerText(),
2230 // Need to clear, in case the minibuffer calls these
2233 // copied verbatim from do_accent_char
2234 bv->cursor().resetAnchor();
2238 //Keep this in sync with GuiApplication::processKeySym below
2239 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2240 KeyModifier state) const
2242 // Do nothing if we have nothing
2243 if (!keysym.isOK() || keysym.isModifier())
2245 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2247 FuncRequest func = seq.addkey(keysym, state);
2248 // When not cancel or meta-fake, do the normal lookup.
2249 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2251 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2253 // Maybe user can only reach the key via holding down shift.
2254 // Let's see. But only if shift is the only modifier
2255 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2256 // If addkey looked up a command and did not find further commands then
2257 // seq has been reset at this point
2258 func = seq.addkey(keysym, NoModifier);
2260 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2261 << seq.print(KeySequence::Portable) << ']');
2262 return func.action() != LFUN_UNKNOWN_ACTION;
2266 //Keep this in sync with GuiApplication::queryKeySym above
2267 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2269 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2271 // Do nothing if we have nothing (JMarc)
2272 if (!keysym.isOK() || keysym.isModifier()) {
2274 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2276 current_view_->restartCaret();
2280 char_type encoded_last_key = keysym.getUCSEncoded();
2282 // Do a one-deep top-level lookup for
2283 // cancel and meta-fake keys. RVDK_PATCH_5
2284 d->cancel_meta_seq.reset();
2286 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2287 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2289 // When not cancel or meta-fake, do the normal lookup.
2290 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2291 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2292 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2293 // remove Caps Lock and Mod2 as a modifiers
2294 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2295 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2298 // Don't remove this unless you know what you are doing.
2299 d->meta_fake_bit = NoModifier;
2301 // Can this happen now ?
2302 if (func.action() == LFUN_NOACTION)
2303 func = FuncRequest(LFUN_COMMAND_PREFIX);
2305 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2306 << d->keyseq.print(KeySequence::Portable) << ']');
2308 // already here we know if it any point in going further
2309 // why not return already here if action == -1 and
2310 // num_bytes == 0? (Lgb)
2312 if (d->keyseq.length() > 1 && current_view_)
2313 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2316 // Maybe user can only reach the key via holding down shift.
2317 // Let's see. But only if shift is the only modifier
2318 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2319 LYXERR(Debug::KEY, "Trying without shift");
2320 // If addkey looked up a command and did not find further commands then
2321 // seq has been reset at this point
2322 func = d->keyseq.addkey(keysym, NoModifier);
2323 LYXERR(Debug::KEY, "Action now " << func.action());
2326 if (func.action() == LFUN_UNKNOWN_ACTION) {
2327 // We didn't match any of the key sequences.
2328 // See if it's normal insertable text not already
2329 // covered by a binding
2330 if (keysym.isText() && d->keyseq.length() == 1) {
2331 // Non-printable characters (such as ASCII control characters)
2332 // must not be inserted (#5704)
2333 if (!isPrintable(encoded_last_key)) {
2334 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2336 current_view_->restartCaret();
2339 // The following modifier check is not needed on Mac.
2340 // The keysym is either not text or it is different
2341 // from the non-modifier keysym. See #9875 for the
2342 // broken alt-modifier effect of having this code active.
2343 #if !defined(Q_OS_MAC)
2344 // If a non-Shift Modifier is used we have a non-bound key sequence
2345 // (such as Alt+j = j). This should be omitted (#5575).
2346 // On Windows, AltModifier and ControlModifier are both
2347 // set when AltGr is pressed. Therefore, in order to not
2348 // break AltGr-bound symbols (see #5575 for details),
2349 // unbound Ctrl+Alt key sequences are allowed.
2350 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2351 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2352 && !(state & AltModifier && state & ControlModifier)
2356 if (current_view_) {
2357 current_view_->message(_("Unknown function."));
2358 current_view_->restartCaret();
2363 // Since all checks above were passed, we now really have text that
2364 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2365 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2367 LYXERR(Debug::KEY, "isText() is true, inserting.");
2368 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2370 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2371 if (current_view_) {
2372 current_view_->message(_("Unknown function."));
2373 current_view_->restartCaret();
2379 if (func.action() == LFUN_SELF_INSERT) {
2380 if (encoded_last_key != 0) {
2381 docstring const arg(1, encoded_last_key);
2382 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2383 FuncRequest::KEYBOARD));
2384 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2387 processFuncRequest(func);
2391 void GuiApplication::processFuncRequest(FuncRequest const & func)
2393 lyx::dispatch(func);
2397 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2399 addToFuncRequestQueue(func);
2400 processFuncRequestQueueAsync();
2404 void GuiApplication::processFuncRequestQueue()
2406 while (!d->func_request_queue_.empty()) {
2407 // take the item from the stack _before_ processing the
2408 // request in order to avoid race conditions from nested
2409 // or parallel requests (see #10406)
2410 FuncRequest const fr(d->func_request_queue_.front());
2411 d->func_request_queue_.pop();
2412 processFuncRequest(fr);
2417 void GuiApplication::processFuncRequestQueueAsync()
2419 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2423 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2425 d->func_request_queue_.push(func);
2429 void GuiApplication::resetGui()
2431 // Set the language defined by the user.
2435 if (!readUIFile(toqstr(lyxrc.ui_file)))
2436 // Gives some error box here.
2439 if (d->global_menubar_)
2440 d->menus_.fillMenuBar(d->global_menubar_, nullptr, false);
2442 QHash<int, GuiView *>::iterator it;
2443 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2446 gv->setLayoutDirection(layoutDirection());
2450 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2454 bool GuiApplication::rtlContext() const
2456 if (current_view_ && current_view_->currentBufferView()) {
2457 BufferView const * bv = current_view_->currentBufferView();
2458 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2460 return layoutDirection() == Qt::RightToLeft;
2464 void GuiApplication::createView(int view_id)
2466 createView(QString(), true, view_id);
2470 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2473 // release the keyboard which might have been grabbed by the global
2474 // menubar on Mac to catch shortcuts even without any GuiView.
2475 if (d->global_menubar_)
2476 d->global_menubar_->releaseKeyboard();
2480 while (d->views_.find(id) != d->views_.end())
2483 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2484 GuiView * view = new GuiView(id);
2485 // `view' is the new current_view_. Tell coverity that is is not 0.
2486 LATTEST(current_view_);
2488 d->views_[id] = view;
2492 setActiveWindow(view);
2495 if (!geometry_arg.isEmpty()) {
2496 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2500 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2501 re.indexIn(geometry_arg);
2502 w = re.cap(1).toInt();
2503 h = re.cap(2).toInt();
2504 x = re.cap(3).toInt();
2505 y = re.cap(4).toInt();
2506 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2507 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2508 // Set initial geometry such that we can get the frame size.
2509 view->setGeometry(x, y, w, h);
2510 int framewidth = view->geometry().x() - view->x();
2511 int titleheight = view->geometry().y() - view->y();
2512 // Negative displacements must be interpreted as distances
2513 // from the right or bottom screen borders.
2514 if (sx == '-' || sy == '-') {
2515 QRect rec = QApplication::desktop()->screenGeometry();
2517 x += rec.width() - w - framewidth;
2519 y += rec.height() - h - titleheight;
2520 view->setGeometry(x, y, w, h);
2522 // Make sure that the left and top frame borders are visible.
2523 if (view->x() < 0 || view->y() < 0) {
2528 view->setGeometry(x, y, w, h);
2536 bool GuiApplication::unhide(Buffer * buf)
2540 currentView()->setBuffer(buf, false);
2545 Clipboard & GuiApplication::clipboard()
2547 return d->clipboard_;
2551 Selection & GuiApplication::selection()
2553 return d->selection_;
2557 FontLoader & GuiApplication::fontLoader()
2559 return d->font_loader_;
2563 Toolbars const & GuiApplication::toolbars() const
2565 return d->toolbars_;
2569 Toolbars & GuiApplication::toolbars()
2571 return d->toolbars_;
2575 Menus const & GuiApplication::menus() const
2581 Menus & GuiApplication::menus()
2587 QList<int> GuiApplication::viewIds() const
2589 return d->views_.keys();
2593 ColorCache & GuiApplication::colorCache()
2595 return d->color_cache_;
2599 int GuiApplication::exec()
2601 // asynchronously handle batch commands. This event will be in
2602 // the event queue in front of other asynchronous events. Hence,
2603 // we can assume in the latter that the gui is setup already.
2604 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2606 return QApplication::exec();
2610 void GuiApplication::exit(int status)
2612 QApplication::exit(status);
2616 void GuiApplication::setGuiLanguage()
2620 // install translation file for Qt built-in dialogs
2621 QString const language_name = QString("qt_") + theLocale.name();
2622 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2623 // Short-named translator can be loaded from a long name, but not the
2624 // opposite. Therefore, long name should be used without truncation.
2625 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2626 if (!d->qt_trans_.load(language_name,
2627 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2628 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2631 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2635 switch (theLocale.language()) {
2636 case QLocale::Arabic :
2637 case QLocale::Hebrew :
2638 case QLocale::Persian :
2639 case QLocale::Urdu :
2640 setLayoutDirection(Qt::RightToLeft);
2643 setLayoutDirection(Qt::LeftToRight);
2648 void GuiApplication::execBatchCommands()
2653 if (!readUIFile(toqstr(lyxrc.ui_file)))
2654 // Gives some error box here.
2658 #if QT_VERSION > 0x040600
2659 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2661 #if QT_VERSION > 0x050100
2662 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2664 // Create the global default menubar which is shown for the dialogs
2665 // and if no GuiView is visible.
2666 // This must be done after the session was recovered to know the "last files".
2667 d->global_menubar_ = new QMenuBar(0);
2668 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2671 lyx::execBatchCommands();
2675 QAbstractItemModel * GuiApplication::languageModel()
2677 if (d->language_model_)
2678 return d->language_model_;
2680 QStandardItemModel * lang_model = new QStandardItemModel(this);
2681 lang_model->insertColumns(0, 3);
2682 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2683 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2684 Languages::const_iterator it = lyx::languages.begin();
2685 Languages::const_iterator end = lyx::languages.end();
2686 for (; it != end; ++it) {
2687 int current_row = lang_model->rowCount();
2688 lang_model->insertRows(current_row, 1);
2689 QModelIndex pl_item = lang_model->index(current_row, 0);
2690 QModelIndex sp_item = lang_model->index(current_row, 1);
2691 QModelIndex th_item = lang_model->index(current_row, 2);
2692 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2693 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2694 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2695 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2696 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2697 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2698 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2699 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2700 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2701 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2703 d->language_model_ = new QSortFilterProxyModel(this);
2704 d->language_model_->setSourceModel(lang_model);
2705 d->language_model_->setSortLocaleAware(true);
2706 return d->language_model_;
2710 void GuiApplication::restoreGuiSession()
2712 if (!lyxrc.load_session)
2715 Session & session = theSession();
2716 LastOpenedSection::LastOpened const & lastopened =
2717 session.lastOpened().getfiles();
2719 validateCurrentView();
2721 FileName active_file;
2722 // do not add to the lastfile list since these files are restored from
2723 // last session, and should be already there (regular files), or should
2724 // not be added at all (help files).
2725 for (auto const & last : lastopened) {
2726 FileName const & file_name = last.file_name;
2727 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2728 && current_view_->documentBufferView() != nullptr)) {
2729 string const & fname = file_name.absFileName();
2730 createView(support::checksum(fname));
2732 current_view_->loadDocument(file_name, false);
2735 active_file = file_name;
2738 // Restore last active buffer
2739 Buffer * buffer = theBufferList().getBuffer(active_file);
2740 if (buffer && current_view_)
2741 current_view_->setBuffer(buffer);
2743 // clear this list to save a few bytes of RAM
2744 session.lastOpened().clear();
2748 QString const GuiApplication::romanFontName()
2751 font.setStyleHint(QFont::Serif);
2752 font.setFamily("serif");
2754 return QFontInfo(font).family();
2758 QString const GuiApplication::sansFontName()
2761 font.setStyleHint(QFont::SansSerif);
2762 font.setFamily("sans");
2764 return QFontInfo(font).family();
2768 QString const GuiApplication::typewriterFontName()
2770 return QFontInfo(typewriterSystemFont()).family();
2775 // We cannot use QFont::fixedPitch() because it doesn't
2776 // return the fact but only if it is requested.
2777 static bool isFixedPitch(const QFont & font) {
2778 const QFontInfo fi(font);
2779 return fi.fixedPitch();
2784 QFont const GuiApplication::typewriterSystemFont()
2786 #if QT_VERSION >= 0x050200
2787 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2789 QFont font("monospace");
2791 if (!isFixedPitch(font)) {
2792 // try to enforce a real monospaced font
2793 font.setStyleHint(QFont::Monospace);
2794 if (!isFixedPitch(font)) {
2795 font.setStyleHint(QFont::TypeWriter);
2796 if (!isFixedPitch(font)) font.setFamily("courier");
2800 // On a Mac the result is too small and it's not practical to
2801 // rely on Qtconfig utility to change the system settings of Qt.
2802 font.setPointSize(12);
2808 void GuiApplication::handleRegularEvents()
2810 ForkedCallsController::handleCompletedProcesses();
2814 bool GuiApplication::event(QEvent * e)
2817 case QEvent::FileOpen: {
2818 // Open a file; this happens only on Mac OS X for now.
2820 // We do this asynchronously because on startup the batch
2821 // commands are not executed here yet and the gui is not ready
2823 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2824 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2825 processFuncRequestAsync(fr);
2829 #if (QT_VERSION < 0x050000)
2830 // Qt5 uses a signal for that, see above.
2831 case QEvent::KeyboardLayoutChange:
2832 //LYXERR0("keyboard change");
2833 if (currentView() && currentView()->currentBufferView())
2834 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2839 return QApplication::event(e);
2844 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2847 return QApplication::notify(receiver, event);
2849 catch (ExceptionMessage const & e) {
2851 case ErrorException:
2853 setQuitOnLastWindowClosed(false);
2855 Alert::error(e.title_, e.details_);
2857 // Properly crash in debug mode in order to get a useful backtrace.
2860 // In release mode, try to exit gracefully.
2862 // FIXME: GCC 7 thinks we can fall through here. Can we?
2864 case BufferException: {
2865 if (!current_view_ || !current_view_->documentBufferView())
2867 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2868 docstring details = e.details_ + '\n';
2869 details += buf->emergencyWrite();
2870 theBufferList().release(buf);
2871 details += "\n" + _("The current document was closed.");
2872 Alert::error(e.title_, details);
2875 case WarningException:
2876 Alert::warning(e.title_, e.details_);
2880 catch (exception const & e) {
2881 docstring s = _("LyX has caught an exception, it will now "
2882 "attempt to save all unsaved documents and exit."
2884 s += from_ascii(e.what());
2885 Alert::error(_("Software exception Detected"), s);
2889 docstring s = _("LyX has caught some really weird exception, it will "
2890 "now attempt to save all unsaved documents and exit.");
2891 Alert::error(_("Software exception Detected"), s);
2899 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2901 QColor const & qcol = d->color_cache_.get(col);
2902 if (!qcol.isValid()) {
2908 rgbcol.r = qcol.red();
2909 rgbcol.g = qcol.green();
2910 rgbcol.b = qcol.blue();
2915 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2917 QColor const qcol(lcolor.getX11HexName(col).c_str());
2918 if (!qcol.isValid()) {
2924 rgbcol.r = qcol.red();
2925 rgbcol.g = qcol.green();
2926 rgbcol.b = qcol.blue();
2931 string const GuiApplication::hexName(ColorCode col)
2933 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2937 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2939 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2940 d->socket_notifiers_[fd] = sn;
2941 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2945 void GuiApplication::socketDataReceived(int fd)
2947 d->socket_notifiers_[fd]->func_();
2951 void GuiApplication::unregisterSocketCallback(int fd)
2953 d->socket_notifiers_.take(fd)->setEnabled(false);
2957 void GuiApplication::commitData(QSessionManager & sm)
2959 /** The implementation is required to avoid an application exit
2960 ** when session state save is triggered by session manager.
2961 ** The default implementation sends a close event to all
2962 ** visible top level widgets when session management allows
2964 ** We are changing that to check the state of each buffer in all
2965 ** views and ask the users what to do if buffers are dirty.
2966 ** Furthermore, we save the session state.
2967 ** We do NOT close the views here since the user still can cancel
2968 ** the logout process (see #9277); also, this would hide LyX from
2969 ** an OSes own session handling (application restoration).
2971 #ifdef QT_NO_SESSIONMANAGER
2973 #warning Qt is compiled without session manager
2975 #pragma message("warning: Qt is compiled without session manager")
2979 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2987 void GuiApplication::unregisterView(GuiView * gv)
2989 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2990 d->views_.remove(gv->id());
2991 if (current_view_ == gv)
2992 current_view_ = nullptr;
2997 bool GuiApplication::closeAllViews()
2999 if (d->views_.empty())
3002 // When a view/window was closed before without quitting LyX, there
3003 // are already entries in the lastOpened list.
3004 theSession().lastOpened().clear();
3006 QList<GuiView *> const views = d->views_.values();
3007 for (GuiView * view : views) {
3008 if (!view->closeScheduled())
3017 bool GuiApplication::prepareAllViewsForLogout()
3019 if (d->views_.empty())
3022 QList<GuiView *> const views = d->views_.values();
3023 for (GuiView * view : views) {
3024 if (!view->prepareAllBuffersForLogout())
3032 GuiView & GuiApplication::view(int id) const
3034 LAPPERR(d->views_.contains(id));
3035 return *d->views_.value(id);
3039 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3041 QList<GuiView *> const views = d->views_.values();
3042 for (GuiView * view : views)
3043 view->hideDialog(name, inset);
3047 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3049 Buffer const * buf = nullptr;
3050 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3051 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3052 if (Buffer const * ptr = (*it)->updateInset(inset))
3059 bool GuiApplication::searchMenu(FuncRequest const & func,
3060 docstring_list & names) const
3062 BufferView * bv = nullptr;
3064 bv = current_view_->currentBufferView();
3065 return d->menus_.searchMenu(func, names, bv);
3069 bool GuiApplication::hasBufferView() const
3071 return (current_view_ && current_view_->currentBufferView());
3075 // Ensure that a file is read only once (prevents include loops)
3076 static QStringList uifiles;
3077 // store which ui files define Toolbars
3078 static QStringList toolbar_uifiles;
3081 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName const & ui_path)
3092 LexerKeyword uitags[] = {
3093 { "format", ui_format },
3094 { "include", ui_include },
3095 { "menuset", ui_menuset },
3096 { "toolbars", ui_toolbars },
3097 { "toolbarset", ui_toolbarset }
3101 lex.setFile(ui_path);
3103 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3107 if (lyxerr.debugging(Debug::PARSER))
3108 lex.printTable(lyxerr);
3111 // format before introduction of format tag
3112 unsigned int format = 0;
3113 while (lex.isOK()) {
3114 int const status = lex.lex();
3116 // we have to do this check here, outside the switch,
3117 // because otherwise we would start reading include files,
3118 // e.g., if the first tag we hit was an include tag.
3119 if (status == ui_format)
3121 format = lex.getInteger();
3125 // this will trigger unless the first tag we hit is a format
3126 // tag, with the right format.
3127 if (format != LFUN_FORMAT)
3128 return FormatMismatch;
3131 case Lexer::LEX_FEOF:
3136 QString const file = toqstr(lex.getString());
3137 bool const success = readUIFile(file, true);
3139 LYXERR0("Failed to read included file: " << fromqstr(file));
3146 d->menus_.read(lex);
3150 d->toolbars_.readToolbars(lex);
3154 d->toolbars_.readToolbarSettings(lex);
3155 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3159 if (!rtrim(lex.getString()).empty())
3160 lex.printError("LyX::ReadUIFile: "
3161 "Unknown menu tag: `$$Token'");
3163 LYXERR0("Error with status: " << status);
3169 return (error ? ReadError : ReadOK);
3173 bool GuiApplication::readUIFile(QString const & name, bool include)
3175 LYXERR(Debug::INIT, "About to read " << name << "...");
3179 ui_path = libFileSearch("ui", name, "inc");
3180 if (ui_path.empty())
3181 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3183 ui_path = libFileSearch("ui", name, "ui");
3186 if (ui_path.empty()) {
3187 static const QString defaultUIFile = "default";
3188 LYXERR(Debug::INIT, "Could not find " << name);
3190 Alert::warning(_("Could not find UI definition file"),
3191 bformat(_("Error while reading the included file\n%1$s\n"
3192 "Please check your installation."), qstring_to_ucs4(name)));
3195 if (name == defaultUIFile) {
3196 LYXERR(Debug::INIT, "Could not find default UI file!!");
3197 Alert::warning(_("Could not find default UI file"),
3198 _("LyX could not find the default UI file!\n"
3199 "Please check your installation."));
3202 Alert::warning(_("Could not find UI definition file"),
3203 bformat(_("Error while reading the configuration file\n%1$s\n"
3204 "Falling back to default.\n"
3205 "Please look under Tools>Preferences>User Interface and\n"
3206 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3207 return readUIFile(defaultUIFile, false);
3210 QString const uifile = toqstr(ui_path.absFileName());
3211 if (uifiles.contains(uifile)) {
3213 // We are reading again the top uifile so reset the safeguard:
3216 d->toolbars_.reset();
3218 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3219 << "Is this an include loop?");
3223 uifiles.push_back(uifile);
3225 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3227 ReturnValues retval = readUIFile(ui_path);
3229 if (retval == FormatMismatch) {
3230 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3231 TempFile tmp("convertXXXXXX.ui");
3232 FileName const tempfile = tmp.name();
3233 bool const success = prefs2prefs(ui_path, tempfile, true);
3235 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3236 " to format " << LFUN_FORMAT << ".");
3238 retval = readUIFile(tempfile);
3242 if (retval != ReadOK) {
3243 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3251 settings.beginGroup("ui_files");
3252 bool touched = false;
3253 for (int i = 0; i != uifiles.size(); ++i) {
3254 QFileInfo fi(uifiles[i]);
3255 QDateTime const date_value = fi.lastModified();
3256 QString const name_key = QString::number(i);
3257 // if an ui file which defines Toolbars has changed,
3258 // we have to reset the settings
3259 if (toolbar_uifiles.contains(uifiles[i])
3260 && (!settings.contains(name_key)
3261 || settings.value(name_key).toString() != uifiles[i]
3262 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3264 settings.setValue(name_key, uifiles[i]);
3265 settings.setValue(name_key + "/date", date_value);
3268 settings.endGroup();
3270 settings.remove("views");
3276 void GuiApplication::onLastWindowClosed()
3278 if (d->global_menubar_)
3279 d->global_menubar_->grabKeyboard();
3283 void GuiApplication::startLongOperation() {
3284 d->key_checker_.start();
3288 bool GuiApplication::longOperationCancelled() {
3289 return d->key_checker_.pressed();
3293 void GuiApplication::stopLongOperation() {
3294 d->key_checker_.stop();
3298 bool GuiApplication::longOperationStarted() {
3299 return d->key_checker_.started();
3303 ////////////////////////////////////////////////////////////////////////
3305 // X11 specific stuff goes here...
3308 bool GuiApplication::x11EventFilter(XEvent * xev)
3313 switch (xev->type) {
3314 case SelectionRequest: {
3315 if (xev->xselectionrequest.selection != XA_PRIMARY)
3317 LYXERR(Debug::SELECTION, "X requested selection.");
3318 BufferView * bv = current_view_->currentBufferView();
3320 docstring const sel = bv->requestSelection();
3322 d->selection_.put(sel);
3323 // Refresh the selection request timestamp.
3324 // We have to do this by ourselves as Qt seems
3325 // not doing that, maybe because of our
3326 // "persistent selection" implementation
3327 // (see comments in GuiSelection.cpp).
3328 XSelectionEvent nev;
3329 nev.type = SelectionNotify;
3330 nev.display = xev->xselectionrequest.display;
3331 nev.requestor = xev->xselectionrequest.requestor;
3332 nev.selection = xev->xselectionrequest.selection;
3333 nev.target = xev->xselectionrequest.target;
3334 nev.property = 0L; // None
3335 nev.time = CurrentTime;
3336 XSendEvent(QX11Info::display(),
3337 nev.requestor, False, 0,
3338 reinterpret_cast<XEvent *>(&nev));
3344 case SelectionClear: {
3345 if (xev->xselectionclear.selection != XA_PRIMARY)
3347 LYXERR(Debug::SELECTION, "Lost selection.");
3348 BufferView * bv = current_view_->currentBufferView();
3350 bv->clearSelection();
3356 #elif defined(QPA_XCB)
3357 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3358 void * message, long *)
3360 if (!current_view_ || eventType != "xcb_generic_event_t")
3363 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3365 switch (ev->response_type) {
3366 case XCB_SELECTION_REQUEST: {
3367 xcb_selection_request_event_t * srev =
3368 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3369 if (srev->selection != XCB_ATOM_PRIMARY)
3371 LYXERR(Debug::SELECTION, "X requested selection.");
3372 BufferView * bv = current_view_->currentBufferView();
3374 docstring const sel = bv->requestSelection();
3376 d->selection_.put(sel);
3377 #ifdef HAVE_QT5_X11_EXTRAS
3378 // Refresh the selection request timestamp.
3379 // We have to do this by ourselves as Qt seems
3380 // not doing that, maybe because of our
3381 // "persistent selection" implementation
3382 // (see comments in GuiSelection.cpp).
3383 // It is expected that every X11 event is
3384 // 32 bytes long, even if not all 32 bytes are
3386 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3387 struct alignas(32) padded_event
3388 : xcb_selection_notify_event_t {};
3389 padded_event nev = {};
3390 nev.response_type = XCB_SELECTION_NOTIFY;
3391 nev.requestor = srev->requestor;
3392 nev.selection = srev->selection;
3393 nev.target = srev->target;
3394 nev.property = XCB_NONE;
3395 nev.time = XCB_CURRENT_TIME;
3396 xcb_connection_t * con = QX11Info::connection();
3397 xcb_send_event(con, 0, srev->requestor,
3398 XCB_EVENT_MASK_NO_EVENT,
3399 reinterpret_cast<char const *>(&nev));
3407 case XCB_SELECTION_CLEAR: {
3408 xcb_selection_clear_event_t * scev =
3409 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3410 if (scev->selection != XCB_ATOM_PRIMARY)
3412 LYXERR(Debug::SELECTION, "Lost selection.");
3413 BufferView * bv = current_view_->currentBufferView();
3415 bv->clearSelection();
3423 } // namespace frontend
3426 void hideDialogs(std::string const & name, Inset * inset)
3429 frontend::guiApp->hideDialogs(name, inset);
3433 ////////////////////////////////////////////////////////////////////
3437 ////////////////////////////////////////////////////////////////////
3439 frontend::FontLoader & theFontLoader()
3441 LAPPERR(frontend::guiApp);
3442 return frontend::guiApp->fontLoader();
3446 frontend::FontMetrics const & theFontMetrics(Font const & f)
3448 return theFontMetrics(f.fontInfo());
3452 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3454 LAPPERR(frontend::guiApp);
3455 return frontend::guiApp->fontLoader().metrics(f);
3459 ////////////////////////////////////////////////////////////////////
3463 ////////////////////////////////////////////////////////////////////
3465 frontend::Clipboard & theClipboard()
3467 LAPPERR(frontend::guiApp);
3468 return frontend::guiApp->clipboard();
3472 frontend::Selection & theSelection()
3474 LAPPERR(frontend::guiApp);
3475 return frontend::guiApp->selection();
3481 #include "moc_GuiApplication.cpp"