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"
20 #include "GuiClipboard.h"
21 #include "GuiKeySymbol.h"
22 #include "GuiSelection.h"
25 #include "qt_helpers.h"
28 #include "frontends/alert.h"
29 #include "frontends/Application.h"
30 #include "frontends/FontLoader.h"
31 #include "frontends/FontMetrics.h"
34 #include "BufferList.h"
35 #include "BufferParams.h"
36 #include "BufferView.h"
39 #include "Converter.h"
40 #include "CutAndPaste.h"
41 #include "ErrorList.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
45 #include "GuiWorkArea.h"
49 #include "LaTeXPackages.h"
52 #include "LyXAction.h"
54 #include "Paragraph.h"
57 #include "SpellChecker.h"
58 #include "Thesaurus.h"
61 #include "insets/InsetText.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/linkback/LinkBackProxy.h"
88 #include <QDesktopWidget>
91 #include <QFileOpenEvent>
93 #include <QFontDatabase>
96 #include <QImageReader>
99 #include <QLibraryInfo>
106 #include <QSessionManager>
108 #include <QSocketNotifier>
109 #include <QSortFilterProxyModel>
110 #include <QStandardItemModel>
112 #include <QTranslator>
113 #include <QThreadPool>
117 #include <X11/Xatom.h>
118 #include <X11/Xlib.h>
122 #elif defined(QPA_XCB)
124 #ifdef HAVE_QT5_X11_EXTRAS
125 #include <QtX11Extras/QX11Info>
129 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
130 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
131 #if (QT_VERSION < 0x050000)
132 #include <QWindowsMime>
133 #define QWINDOWSMIME QWindowsMime
136 #define QWINDOWSMIME QWinMime
146 #include <QMacPasteboardMime>
149 #include <boost/crc.hpp>
156 using namespace lyx::support;
159 static void initializeResources()
161 static bool initialized = false;
163 Q_INIT_RESOURCE(Resources);
171 frontend::Application * createApplication(int & argc, char * argv[])
173 #if !defined(Q_WS_X11) && !defined(QPA_XCB)
174 // prune -geometry argument(s) by shifting
175 // the following ones 2 places down.
176 for (int i = 0 ; i < argc ; ++i) {
177 if (strcmp(argv[i], "-geometry") == 0) {
178 int const remove = (i+1) < argc ? 2 : 1;
180 for (int j = i; j < argc; ++j)
181 argv[j] = argv[j + remove];
187 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
188 // On Windows, allow bringing the LyX window to top
189 AllowSetForegroundWindow(ASFW_ANY);
192 frontend::GuiApplication * guiApp = new frontend::GuiApplication(argc, argv);
193 // I'd rather do that in the constructor, but I do not think that
194 // the palette is accessible there.
195 guiApp->colorCache().setPalette(guiApp->palette());
204 if (lyxrc.gui_language == "auto") {
205 theLocale = QLocale::system();
206 code = fromqstr(theLocale.name());
208 Language const * l = languages.getLanguage(lyxrc.gui_language);
209 code = l ? l->code() : "C";
210 theLocale = QLocale(toqstr(code));
212 // Qt tries to outsmart us and transforms en_US to C.
213 Messages::guiLanguage((code == "C") ? "en_US" : code);
214 QLocale::setDefault(theLocale);
215 setlocale(LC_NUMERIC, "C");
222 /// Return the list of loadable formats.
223 vector<string> loadableImageFormats()
227 QList<QByteArray> qt_formats = QImageReader::supportedImageFormats();
229 LYXERR(Debug::GRAPHICS,
230 "\nThe image loader can load the following directly:\n");
232 if (qt_formats.empty())
233 LYXERR(Debug::GRAPHICS, "\nQt Problem: No Format available!");
235 bool jpeg_found = false;
236 bool jpg_found = false;
237 for (QList<QByteArray>::const_iterator it = qt_formats.begin(); it != qt_formats.end(); ++it) {
239 LYXERR(Debug::GRAPHICS, (const char *) *it << ", ");
241 string ext = ascii_lowercase((const char *) *it);
249 else if (ext == "jpg") {
254 else if (lyxrc.use_converter_cache &&
255 (ext == "svg" || ext == "svgz") &&
256 theConverters().isReachable("svg", "png"))
257 // Qt only supports SVG 1.2 tiny. See #9778. We prefer displaying
258 // the SVG as in the output. However we require that the converter
259 // cache is enabled since this is expensive. We also require that
260 // an explicit svg->png converter is defined, since the default
261 // converter could produce bad quality as well. This assumes that
262 // png can always be loaded.
271 ////////////////////////////////////////////////////////////////////////
273 // Icon loading support code
275 ////////////////////////////////////////////////////////////////////////
285 bool operator<(ImgMap const & lhs, ImgMap const & rhs)
287 return lhs.key < rhs.key;
293 CompareKey(QString const & name) : name_(name) {}
294 bool operator()(ImgMap const & other) const { return other.key == name_; }
300 // this must be sorted alphabetically
301 // Upper case comes before lower case
302 // Please don't change the formatting, this list is parsed by
303 // development/tools/generate_symbols_images.py.
304 ImgMap sorted_img_map[] = {
305 { "Arrownot", "arrownot2"},
306 { "Arrowvert", "arrowvert2"},
307 { "Bowtie", "bowtie2" },
309 { "Bumpeq", "bumpeq2" },
310 { "CIRCLE", "circle3" },
312 { "CheckedBox", "checkedbox2" },
313 { "Circle", "circle2" },
314 { "Colonapprox", "colonapprox2" },
315 { "Coloneq", "coloneq2" },
316 { "Coloneqq", "coloneqq2" },
317 { "Colonsim", "colonsim2" },
319 { "DOWNarrow", "downarrow3" },
320 { "Delta", "delta2" },
321 { "Diamond", "diamond2" },
322 { "Doteq", "doteq2" },
323 { "Downarrow", "downarrow2" },
324 { "Eqcolon", "eqcolon2" },
325 { "Eqqcolon", "eqqcolon2" },
326 { "Gamma", "gamma2" },
328 { "LEFTCIRCLE", "leftcircle3" },
329 { "LEFTarrow", "leftarrow3" },
330 { "LEFTcircle", "leftcircle4" },
332 { "Lambda", "lambda2" },
334 { "Leftarrow", "leftarrow2" },
335 { "Leftcircle", "leftcircle2" },
336 { "Leftrightarrow", "leftrightarrow2" },
337 { "Longarrownot", "longarrownot2"},
338 { "Longleftarrow", "longleftarrow2" },
339 { "Longleftrightarrow", "longleftrightarrow2" },
340 { "Longmapsfrom", "longmapsfrom2"},
341 { "Longmapsto", "longmapsto2"},
342 { "Longrightarrow", "longrightarrow2" },
343 { "Mapsfrom", "mapsfrom2"},
344 { "Mapsfromchar", "mapsfromchar2"},
345 { "Mapsto", "mapsto2"},
346 { "Mapstochar", "mapstochar2"},
347 { "Omega", "omega2" },
352 { "RIGHTCIRCLE", "rightcircle3" },
353 { "RIGHTarrow", "rightarrow3" },
354 { "RIGHTcircle", "rightcircle4" },
356 { "Rightarrow", "rightarrow2" },
357 { "Rightcircle", "rightcircle2" },
358 { "Sigma", "sigma2" },
359 { "Square", "square2" },
360 { "Subset", "subset2" },
361 { "Supset", "supset2" },
362 { "Theta", "theta2" },
363 { "Thorn", "thorn2" },
364 { "UParrow", "uparrow3" },
365 { "Uparrow", "uparrow2" },
366 { "Updownarrow", "updownarrow2" },
367 { "Upsilon", "upsilon2" },
368 { "Vdash", "vdash3" },
373 { "lVert", "vert2" },
375 { "nLeftarrow", "nleftarrow2" },
376 { "nLeftrightarrow", "nleftrightarrow2" },
377 { "nRightarrow", "nrightarrow2" },
378 { "nVDash", "nvdash3" },
379 { "nVdash", "nvdash4" },
380 { "nvDash", "nvdash2" },
381 { "rVert", "vert2" },
383 { "textrm \\AA", "textrm_AA"},
384 { "textrm \\O", "textrm_O"},
385 { "vDash", "vdash2" },
386 { "varDelta", "vardelta2" },
387 { "varGamma", "vargamma2" },
388 { "varLambda", "varlambda2" },
389 { "varOmega", "varomega2" },
390 { "varPhi", "varphi2" },
391 { "varPi", "varpi2" },
392 { "varPsi", "varpsi2" },
393 { "varSigma", "varsigma2" },
394 { "varTheta", "vartheta2" },
395 { "varUpsilon", "varupsilon2" },
396 { "varXi", "varxi2" }
400 size_t const nr_sorted_img_map = sizeof(sorted_img_map) / sizeof(ImgMap);
402 // This list specifies which system's theme icon is related to which lyx
403 // command. It was based on:
404 // http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
405 // this must be sorted alphabetically
406 // Upper case comes before lower case
407 ImgMap sorted_theme_icon_map[] = {
408 { "bookmark-goto 0", "go-jump" },
409 { "buffer-new", "document-new" },
410 { "buffer-write", "document-save" },
411 { "buffer-write-as", "document-save-as" },
412 { "buffer-zoom-in", "zoom-in" },
413 { "buffer-zoom-out", "zoom-out" },
414 { "copy", "edit-copy" },
415 { "cut", "edit-cut" },
416 { "depth-decrement", "format-indent-less" },
417 { "depth-increment", "format-indent-more" },
418 { "dialog-show spellchecker", "tools-check-spelling" },
419 { "dialog-show-new-inset graphics", "insert-image" },
420 { "dialog-toggle findreplaceadv", "edit-find-replace" },
421 { "file-open", "document-open" },
422 { "font-bold", "format-text-bold" },
423 { "font-ital", "format-text-italic" },
424 { "font-strikeout", "format-text-strikethrough" },
425 { "font-underline", "format-text-underline" },
426 { "lyx-quit", "application-exit" },
427 { "paste", "edit-paste" },
428 { "redo", "edit-redo" },
429 { "undo", "edit-undo" },
430 { "window-close", "window-close" },
431 { "window-new", "window-new" }
434 size_t const nr_sorted_theme_icon_map = sizeof(sorted_theme_icon_map) / sizeof(ImgMap);
437 QString findImg(QString const & name)
439 ImgMap const * const begin = sorted_img_map;
440 ImgMap const * const end = begin + nr_sorted_img_map;
441 LATTEST(sorted(begin, end));
443 ImgMap const * const it = find_if(begin, end, CompareKey(name));
447 img_name = it->value;
450 img_name.replace('_', "underscore");
451 img_name.replace(' ', '_');
453 // This way we can have "math-delim { }" on the toolbar.
454 img_name.replace('(', "lparen");
455 img_name.replace(')', "rparen");
456 img_name.replace('[', "lbracket");
457 img_name.replace(']', "rbracket");
458 img_name.replace('{', "lbrace");
459 img_name.replace('}', "rbrace");
460 img_name.replace('|', "bars");
461 img_name.replace(',', "thinspace");
462 img_name.replace(':', "mediumspace");
463 img_name.replace(';', "thickspace");
464 img_name.replace('!', "negthinspace");
467 LYXERR(Debug::GUI, "findImg(" << name << ")\n"
468 << "Looking for math icon called \"" << img_name << '"');
475 QString themeIconName(QString const & action)
477 ImgMap const * const begin = sorted_theme_icon_map;
478 ImgMap const * const end = begin + nr_sorted_theme_icon_map;
479 LASSERT(sorted(begin, end), /**/);
481 ImgMap const * const it = find_if(begin, end, CompareKey(action));
489 QString iconName(FuncRequest const & f, bool unknown, QString const & suffix)
491 initializeResources();
495 switch (f.action()) {
496 case LFUN_MATH_INSERT:
497 if (!f.argument().empty()) {
499 name1 = findImg(toqstr(f.argument()).mid(1));
502 case LFUN_MATH_DELIM:
503 case LFUN_MATH_BIGDELIM:
505 name1 = findImg(toqstr(f.argument()));
509 name1 = toqstr(f.argument());
511 case LFUN_COMMAND_ALTERNATIVES: {
512 // use the first of the alternative commands
514 docstring dummy = split(f.argument(), firstcom, ';');
515 name1 = toqstr(firstcom);
516 name1.replace(' ', '_');
520 name2 = toqstr(lyxaction.getActionName(f.action()));
523 if (!f.argument().empty()) {
524 name1 = name2 + ' ' + toqstr(f.argument());
525 name1.replace(' ', '_');
526 name1.replace('\\', "backslash");
534 QStringList imagedirs;
535 imagedirs << "images/" << "images/ipa/";
536 search_mode mode = theGuiApp()->imageSearchMode();
537 for (int i = 0; i < imagedirs.size(); ++i) {
538 QString imagedir = imagedirs.at(i) + path;
539 FileName fname = imageLibFileSearch(imagedir, name1, "svgz,png", mode);
541 return toqstr(fname.absFileName());
543 fname = imageLibFileSearch(imagedir, name2, "svgz,png", mode);
545 return toqstr(fname.absFileName());
548 path = ":/images/" + path;
551 LYXERR0("Directory " << path << " not found in resource!");
554 if (res.exists(name1 + ".svgz"))
555 return path + name1 + ".svgz";
556 else if (res.exists(name1 + ".png"))
557 return path + name1 + ".png";
559 if (res.exists(name2 + ".svgz"))
560 return path + name2 + ".svgz";
561 else if (res.exists(name2 + ".png"))
562 return path + name2 + ".png";
564 LYXERR(Debug::GUI, "Cannot find icon with filename "
565 << "\"" << name1 << ".{svgz,png}\""
567 << "\"" << name2 << ".{svgz,png}\""
569 << lyxaction.getActionName(f.action())
570 << '(' << to_utf8(f.argument()) << ")\"");
573 QString imagedir = "images/";
574 FileName fname = imageLibFileSearch(imagedir, "unknown", "svgz,png", mode);
576 return toqstr(fname.absFileName());
577 return QString(":/images/unknown.svgz");
584 QPixmap getPixmap(QString const & path, QString const & name, QString const & ext)
586 QString imagedir = path;
587 FileName fname = imageLibFileSearch(imagedir, name, ext, theGuiApp()->imageSearchMode());
588 QString fpath = toqstr(fname.absFileName());
589 QPixmap pixmap = QPixmap();
591 if (pixmap.load(fpath)) {
595 QStringList exts = ext.split(",");
596 fpath = ":/" + path + name + ".";
597 for (int i = 0; i < exts.size(); ++i) {
598 if (pixmap.load(fpath + exts.at(i))) {
603 bool const list = ext.contains(",");
604 LYXERR0("Cannot load pixmap \""
605 << path << name << "." << (list ? "{" : "") << ext
606 << (list ? "}" : "") << "\", please verify resource system!");
612 QIcon getIcon(FuncRequest const & f, bool unknown, bool rtl)
614 #if (QT_VERSION >= 0x040600)
615 if (lyxrc.use_system_theme_icons) {
616 // use the icons from system theme that are available
617 QString action = toqstr(lyxaction.getActionName(f.action()));
618 if (!f.argument().empty())
619 action += " " + toqstr(f.argument());
620 QString const theme_icon = themeIconName(action);
621 if (QIcon::hasThemeIcon(theme_icon)) {
622 QIcon const thmicn = QIcon::fromTheme(theme_icon);
623 if (!thmicn.isNull())
632 icon = iconName(f, unknown, "+rtl");
633 // No RTL icon, we'll make it ourselves
634 flip = icon.isEmpty();
637 icon = iconName(f, unknown);
641 //LYXERR(Debug::GUI, "Found icon: " << icon);
642 QPixmap pixmap = QPixmap();
643 if (!pixmap.load(icon)) {
644 LYXERR0("Cannot load icon " << icon << " please verify resource system!");
649 return QIcon(pixmap.transformed(QTransform().scale(-1, 1)));
651 return QIcon(pixmap);
655 ////////////////////////////////////////////////////////////////////////
657 // LyX server support code.
659 ////////////////////////////////////////////////////////////////////////
661 class SocketNotifier : public QSocketNotifier
664 /// connect a connection notification from the LyXServerSocket
665 SocketNotifier(QObject * parent, int fd, Application::SocketCallback func)
666 : QSocketNotifier(fd, QSocketNotifier::Read, parent), func_(func)
670 /// The callback function
671 Application::SocketCallback func_;
675 class GuiTranslator : public QTranslator
678 GuiTranslator(QObject * parent = nullptr)
679 : QTranslator(parent)
682 virtual QString translate(const char * /* context */,
683 const char *sourceText,
684 #if QT_VERSION >= 0x050000
685 const char * /* disambiguation */ = 0, int /* n */ = -1) const
687 const char * /*comment*/ = 0) const
690 // Here we declare the strings that need to be translated from Qt own GUI
691 // This is needed to include these strings to po files
695 _("Restore Defaults");
698 // Already in po: "Cancel", "&Cancel"
699 _("Apply"); // Already in po: "&Apply"
700 _("Reset"); // Already in po: "&Reset" "R&eset" "Rese&t"
703 docstring s = getGuiMessages().getIfFound(sourceText);
704 // This test should eventually be removed when translations are updated
706 LYXERR(Debug::LOCALE, "Missing translation for `"
707 << string(sourceText) << "'");
713 ////////////////////////////////////////////////////////////////////////
715 // Mac specific stuff goes here...
717 ////////////////////////////////////////////////////////////////////////
720 // QMacPasteboardMimeGraphics can only be compiled on Mac.
722 class QMacPasteboardMimeGraphics : public QMacPasteboardMime
725 QMacPasteboardMimeGraphics()
726 : QMacPasteboardMime(MIME_QT_CONVERTOR|MIME_ALL)
729 QString convertorName() { return "Graphics"; }
731 QString flavorFor(QString const & mime)
733 LYXERR(Debug::ACTION, "flavorFor " << mime);
734 if (mime == pdfMimeType())
735 return QLatin1String("com.adobe.pdf");
739 QString mimeFor(QString flav)
741 LYXERR(Debug::ACTION, "mimeFor " << flav);
742 if (flav == QLatin1String("com.adobe.pdf"))
743 return pdfMimeType();
747 bool canConvert(QString const & mime, QString flav)
749 return mimeFor(flav) == mime;
752 QVariant convertToMime(QString const & /*mime*/, QList<QByteArray> data,
756 qWarning("QMacPasteboardMimeGraphics: Cannot handle multiple member data");
760 QList<QByteArray> convertFromMime(QString const & /*mime*/,
761 QVariant data, QString /*flav*/)
763 QList<QByteArray> ret;
764 ret.append(data.toByteArray());
770 ///////////////////////////////////////////////////////////////
772 // You can find more platform specific stuff at the end of this file...
774 ///////////////////////////////////////////////////////////////
776 ////////////////////////////////////////////////////////////////////////
777 // Windows specific stuff goes here...
779 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
780 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
781 // QWindowsMimeMetafile can only be compiled on Windows.
783 static FORMATETC cfFromMime(QString const & mimetype)
786 if (mimetype == emfMimeType()) {
787 formatetc.cfFormat = CF_ENHMETAFILE;
788 formatetc.tymed = TYMED_ENHMF;
789 } else if (mimetype == wmfMimeType()) {
790 formatetc.cfFormat = CF_METAFILEPICT;
791 formatetc.tymed = TYMED_MFPICT;
794 formatetc.dwAspect = DVASPECT_CONTENT;
795 formatetc.lindex = -1;
800 class QWindowsMimeMetafile : public QWINDOWSMIME {
802 QWindowsMimeMetafile() {}
804 bool canConvertFromMime(FORMATETC const & /*formatetc*/,
805 QMimeData const * /*mimedata*/) const
810 bool canConvertToMime(QString const & mimetype,
811 IDataObject * pDataObj) const
813 if (mimetype != emfMimeType() && mimetype != wmfMimeType())
815 FORMATETC formatetc = cfFromMime(mimetype);
816 return pDataObj->QueryGetData(&formatetc) == S_OK;
819 bool convertFromMime(FORMATETC const & /*formatetc*/,
820 const QMimeData * /*mimedata*/, STGMEDIUM * /*pmedium*/) const
825 QVariant convertToMime(QString const & mimetype, IDataObject * pDataObj,
826 QVariant::Type /*preferredType*/) const
829 if (!canConvertToMime(mimetype, pDataObj))
832 FORMATETC formatetc = cfFromMime(mimetype);
834 if (pDataObj->GetData(&formatetc, &s) != S_OK)
838 if (s.tymed == TYMED_ENHMF) {
839 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, 0, 0);
840 data.resize(dataSize);
841 dataSize = GetEnhMetaFileBits(s.hEnhMetaFile, dataSize,
842 (LPBYTE)data.data());
843 } else if (s.tymed == TYMED_MFPICT) {
844 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, 0, 0);
845 data.resize(dataSize);
846 dataSize = GetMetaFileBitsEx((HMETAFILE)s.hMetaFilePict, dataSize,
847 (LPBYTE)data.data());
850 ReleaseStgMedium(&s);
856 QVector<FORMATETC> formatsForMime(QString const & mimetype,
857 QMimeData const * /*mimedata*/) const
859 QVector<FORMATETC> formats;
860 if (mimetype == emfMimeType() || mimetype == wmfMimeType())
861 formats += cfFromMime(mimetype);
865 QString mimeForFormat(FORMATETC const & formatetc) const
867 switch (formatetc.cfFormat) {
869 return emfMimeType();
870 case CF_METAFILEPICT:
871 return wmfMimeType();
881 /// Allows to check whether ESC was pressed during a long operation
882 class KeyChecker : public QObject {
887 KeyChecker() : pressed_(false), started_(false) {}
890 QCoreApplication::instance()->installEventFilter(this);
895 QCoreApplication::instance()->removeEventFilter(this);
899 QCoreApplication::processEvents();
902 bool started() const {
905 bool eventFilter(QObject *obj, QEvent *event) {
906 LYXERR(Debug::ACTION, "Event Type: " << event->type());
907 switch (event->type()) {
911 case QEvent::UpdateRequest:
912 case QEvent::CursorChange:
913 case QEvent::ActionChanged:
914 case QEvent::EnabledChange:
915 case QEvent::SockAct:
918 case QEvent::ToolTipChange:
919 case QEvent::LayoutRequest:
920 case QEvent::MetaCall:
921 return QObject::eventFilter(obj, event);
923 // FIXME Blocking all these events is a bad idea.
924 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent*>(event);
925 if (keyEvent && keyEvent->key() == Qt::Key_Escape)
933 ////////////////////////////////////////////////////////////////////////
934 // GuiApplication::Private definition and implementation.
935 ////////////////////////////////////////////////////////////////////////
937 struct GuiApplication::Private
939 Private(): language_model_(0), meta_fake_bit(NoModifier),
942 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
943 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
944 /// WMF Mime handler for Windows clipboard.
945 wmf_mime_ = new QWindowsMimeMetafile;
948 initKeySequences(&theTopLevelKeymap());
951 void initKeySequences(KeyMap * kb)
953 keyseq = KeySequence(kb, kb);
954 cancel_meta_seq = KeySequence(kb, kb);
958 QSortFilterProxyModel * language_model_;
960 GuiClipboard clipboard_;
962 GuiSelection selection_;
964 FontLoader font_loader_;
966 ColorCache color_cache_;
967 /// the built-in Qt translation mechanism
968 QTranslator qt_trans_;
969 /// LyX gettext-based translation for Qt elements
970 GuiTranslator gui_trans_;
972 QHash<int, SocketNotifier *> socket_notifiers_;
976 /// The global instance
979 /// this timer is used for any regular events one wants to
980 /// perform. at present it is used to check if forked processes
982 QTimer general_timer_;
984 /// delayed FuncRequests
985 std::queue<FuncRequest> func_request_queue_;
990 KeySequence cancel_meta_seq;
992 KeyModifier meta_fake_bit;
994 /// The result of last dispatch action
995 DispatchResult dispatch_result_;
997 /// Multiple views container.
999 * Warning: This must not be a smart pointer as the destruction of the
1000 * object is handled by Qt when the view is closed
1001 * \sa Qt::WA_DeleteOnClose attribute.
1003 QHash<int, GuiView *> views_;
1005 /// Only used on mac.
1006 QMenuBar * global_menubar_;
1009 /// Linkback mime handler for MacOSX.
1010 QMacPasteboardMimeGraphics mac_pasteboard_mime_;
1013 #if (QT_VERSION < 0x050000) || (QT_VERSION >= 0x050400)
1014 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
1015 /// WMF Mime handler for Windows clipboard.
1016 QWindowsMimeMetafile * wmf_mime_;
1020 /// Allows to check whether ESC was pressed during a long operation
1021 KeyChecker key_checker_;
1025 GuiApplication * guiApp;
1027 GuiApplication::~GuiApplication()
1030 closeAllLinkBackLinks();
1036 GuiApplication::GuiApplication(int & argc, char ** argv)
1037 : QApplication(argc, argv), current_view_(0),
1038 d(new GuiApplication::Private)
1040 QString app_name = "LyX";
1041 QCoreApplication::setOrganizationName(app_name);
1042 QCoreApplication::setOrganizationDomain("lyx.org");
1043 QCoreApplication::setApplicationName(lyx_package);
1044 #if QT_VERSION >= 0x050000
1045 QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
1048 qsrand(QDateTime::currentDateTime().toTime_t());
1050 // Install LyX translator for missing Qt translations
1051 installTranslator(&d->gui_trans_);
1052 // Install Qt native translator for GUI elements.
1053 installTranslator(&d->qt_trans_);
1056 // Enable reception of XCB events.
1057 installNativeEventFilter(this);
1060 // FIXME: quitOnLastWindowClosed is true by default. We should have a
1061 // lyxrc setting for this in order to let the application stay resident.
1062 // But then we need some kind of dock icon, at least on Windows.
1064 if (lyxrc.quit_on_last_window_closed)
1065 setQuitOnLastWindowClosed(false);
1068 // FIXME: Do we need a lyxrc setting for this on Mac? This behaviour
1069 // seems to be the default case for applications like LyX.
1070 setQuitOnLastWindowClosed(false);
1075 #if defined(Q_WS_X11) || defined(QPA_XCB)
1076 // doubleClickInterval() is 400 ms on X11 which is just too long.
1077 // On Windows and Mac OS X, the operating system's value is used.
1078 // On Microsoft Windows, calling this function sets the double
1079 // click interval for all applications. So we don't!
1080 QApplication::setDoubleClickInterval(300);
1083 connect(this, SIGNAL(lastWindowClosed()), this, SLOT(onLastWindowClosed()));
1085 // needs to be done before reading lyxrc
1087 lyxrc.dpi = (w.logicalDpiX() + w.logicalDpiY()) / 2;
1091 // Initialize RC Fonts
1092 if (lyxrc.roman_font_name.empty())
1093 lyxrc.roman_font_name = fromqstr(romanFontName());
1095 if (lyxrc.sans_font_name.empty())
1096 lyxrc.sans_font_name = fromqstr(sansFontName());
1098 if (lyxrc.typewriter_font_name.empty())
1099 lyxrc.typewriter_font_name = fromqstr(typewriterFontName());
1101 #if (QT_VERSION >= 0x050000)
1102 // Qt4 does this in event(), see below.
1103 // Track change of keyboard
1104 connect(inputMethod(), SIGNAL(localeChanged()), this, SLOT(onLocaleChanged()));
1107 d->general_timer_.setInterval(500);
1108 connect(&d->general_timer_, SIGNAL(timeout()),
1109 this, SLOT(handleRegularEvents()));
1110 d->general_timer_.start();
1112 // maxThreadCount() defaults in general to 2 on single or dual-processor.
1113 // This is clearly not enough in a time where we use threads for
1114 // document preview and/or export. 20 should be OK.
1115 QThreadPool::globalInstance()->setMaxThreadCount(20);
1117 // make sure tooltips are formatted
1118 installEventFilter(new ToolTipFormatter(this));
1122 GuiApplication * theGuiApp()
1124 return dynamic_cast<GuiApplication *>(theApp());
1128 double GuiApplication::pixelRatio() const
1130 #if QT_VERSION >= 0x050000
1131 return qt_scale_factor * devicePixelRatio();
1138 void GuiApplication::clearSession()
1145 docstring Application::iconName(FuncRequest const & f, bool unknown)
1147 return qstring_to_ucs4(lyx::frontend::iconName(f, unknown));
1151 docstring Application::mathIcon(docstring const & c)
1153 return qstring_to_ucs4(findImg(toqstr(c)));
1157 FuncStatus GuiApplication::getStatus(FuncRequest const & cmd) const
1161 BufferView * bv = 0;
1162 BufferView * doc_bv = 0;
1164 if (cmd.action() == LFUN_NOACTION) {
1165 status.message(from_utf8(N_("Nothing to do")));
1166 status.setEnabled(false);
1169 else if (cmd.action() == LFUN_UNKNOWN_ACTION) {
1170 status.setUnknown(true);
1171 status.message(from_utf8(N_("Unknown action")));
1172 status.setEnabled(false);
1175 // Does the GuiApplication know something?
1176 else if (getStatus(cmd, status)) { }
1178 // If we do not have a GuiView, then other functions are disabled
1179 else if (!current_view_)
1180 status.setEnabled(false);
1182 // Does the GuiView know something?
1183 else if (current_view_->getStatus(cmd, status)) { }
1185 // In LyX/Mac, when a dialog is open, the menus of the
1186 // application can still be accessed without giving focus to
1187 // the main window. In this case, we want to disable the menu
1188 // entries that are buffer or view-related.
1189 //FIXME: Abdel (09/02/10) This has very bad effect on Linux, don't know why...
1191 else if (cmd.origin() == FuncRequest::MENU && !current_view_->hasFocus())
1192 status.setEnabled(false);
1195 // If we do not have a BufferView, then other functions are disabled
1196 else if (!(bv = current_view_->currentBufferView()))
1197 status.setEnabled(false);
1199 // Does the current BufferView know something?
1200 else if (bv->getStatus(cmd, status)) { }
1202 // Does the current Buffer know something?
1203 else if (bv->buffer().getStatus(cmd, status)) { }
1205 // If we do not have a document BufferView, different from the
1206 // current BufferView, then other functions are disabled
1207 else if (!(doc_bv = current_view_->documentBufferView()) || doc_bv == bv)
1208 status.setEnabled(false);
1210 // Does the document Buffer know something?
1211 else if (doc_bv->buffer().getStatus(cmd, status)) { }
1214 LYXERR(Debug::ACTION, "LFUN not handled in getStatus(): " << cmd);
1215 status.message(from_utf8(N_("Command not handled")));
1216 status.setEnabled(false);
1219 // the default error message if we disable the command
1220 if (!status.enabled() && status.message().empty())
1221 status.message(from_utf8(N_("Command disabled")));
1227 bool GuiApplication::getStatus(FuncRequest const & cmd, FuncStatus & flag) const
1229 // I would really like to avoid having this switch and rather try to
1230 // encode this in the function itself.
1231 // -- And I'd rather let an inset decide which LFUNs it is willing
1232 // to handle (Andre')
1234 switch (cmd.action()) {
1236 // This could be used for the no-GUI version. The GUI version is handled in
1237 // GuiView::getStatus(). See above.
1239 case LFUN_BUFFER_WRITE:
1240 case LFUN_BUFFER_WRITE_AS:
1241 case LFUN_BUFFER_WRITE_AS_TEMPLATE: {
1242 Buffer * b = theBufferList().getBuffer(FileName(cmd.getArg(0)));
1243 enable = b && (b->isUnnamed() || !b->isClean());
1248 case LFUN_BOOKMARK_GOTO: {
1249 const unsigned int num = convert<unsigned int>(to_utf8(cmd.argument()));
1250 enable = theSession().bookmarks().isValid(num);
1254 case LFUN_BOOKMARK_CLEAR:
1255 enable = theSession().bookmarks().hasValid();
1258 // this one is difficult to get right. As a half-baked
1259 // solution, we consider only the first action of the sequence
1260 case LFUN_COMMAND_SEQUENCE: {
1261 // argument contains ';'-terminated commands
1262 string const firstcmd = token(to_utf8(cmd.argument()), ';', 0);
1263 FuncRequest func(lyxaction.lookupFunc(firstcmd));
1264 func.setOrigin(cmd.origin());
1265 flag = getStatus(func);
1269 // we want to check if at least one of these is enabled
1270 case LFUN_COMMAND_ALTERNATIVES: {
1271 // argument contains ';'-terminated commands
1272 string arg = to_utf8(cmd.argument());
1273 while (!arg.empty()) {
1275 arg = split(arg, first, ';');
1276 FuncRequest func(lyxaction.lookupFunc(first));
1277 func.setOrigin(cmd.origin());
1278 flag = getStatus(func);
1279 // if this one is enabled, the whole thing is
1288 string name = to_utf8(cmd.argument());
1289 if (theTopLevelCmdDef().lock(name, func)) {
1290 func.setOrigin(cmd.origin());
1291 flag = getStatus(func);
1292 theTopLevelCmdDef().release(name);
1294 // catch recursion or unknown command
1295 // definition. all operations until the
1296 // recursion or unknown command definition
1297 // occurs are performed, so set the state to
1304 case LFUN_IF_RELATIVES: {
1305 string const lfun = to_utf8(cmd.argument());
1306 BufferView const * bv =
1307 current_view_ ? current_view_->currentBufferView() : nullptr;
1308 if (!bv || (bv->buffer().parent() == nullptr && !bv->buffer().hasChildren())) {
1312 FuncRequest func(lyxaction.lookupFunc(lfun));
1313 func.setOrigin(cmd.origin());
1314 flag = getStatus(func);
1318 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1320 case LFUN_PREFERENCES_SAVE:
1321 case LFUN_BUFFER_SAVE_AS_DEFAULT:
1322 case LFUN_DEBUG_LEVEL_SET:
1323 // these are handled in our dispatch()
1326 case LFUN_WINDOW_CLOSE:
1327 enable = d->views_.size() > 0;
1330 case LFUN_BUFFER_NEW:
1331 case LFUN_BUFFER_NEW_TEMPLATE:
1332 case LFUN_FILE_OPEN:
1333 case LFUN_HELP_OPEN:
1334 case LFUN_SCREEN_FONT_UPDATE:
1335 case LFUN_SET_COLOR:
1336 case LFUN_WINDOW_NEW:
1338 case LFUN_LYXRC_APPLY:
1339 case LFUN_COMMAND_PREFIX:
1341 case LFUN_META_PREFIX:
1342 case LFUN_RECONFIGURE:
1343 case LFUN_SERVER_GET_FILENAME:
1344 case LFUN_SERVER_NOTIFY:
1348 case LFUN_BUFFER_FORALL: {
1349 if (theBufferList().empty()) {
1350 flag.message(from_utf8(N_("Command not allowed without a buffer open")));
1351 flag.setEnabled(false);
1355 FuncRequest const cmdToPass = lyxaction.lookupFunc(cmd.getLongArg(0));
1356 if (cmdToPass.action() == LFUN_UNKNOWN_ACTION) {
1357 flag.message(from_utf8(N_("the <LFUN-COMMAND> argument of buffer-forall is not valid")));
1358 flag.setEnabled(false);
1363 case LFUN_DIALOG_SHOW: {
1364 string const name = cmd.getArg(0);
1365 return name == "aboutlyx"
1366 || name == "lyxfiles"
1368 || name == "texinfo"
1369 || name == "progress"
1370 || name == "compare";
1378 flag.setEnabled(false);
1382 /// make a post-dispatch status message
1383 static docstring makeDispatchMessage(docstring const & msg,
1384 FuncRequest const & cmd)
1386 const bool be_verbose = (cmd.origin() == FuncRequest::MENU
1387 || cmd.origin() == FuncRequest::TOOLBAR
1388 || cmd.origin() == FuncRequest::COMMANDBUFFER);
1390 if (cmd.action() == LFUN_SELF_INSERT || !be_verbose) {
1391 LYXERR(Debug::ACTION, "dispatch msg is `" << msg << "'");
1395 docstring dispatch_msg = msg;
1396 if (!dispatch_msg.empty())
1397 dispatch_msg += ' ';
1399 docstring comname = from_utf8(lyxaction.getActionName(cmd.action()));
1401 bool argsadded = false;
1403 if (!cmd.argument().empty()) {
1404 if (cmd.action() != LFUN_UNKNOWN_ACTION) {
1405 comname += ' ' + cmd.argument();
1409 docstring const shortcuts = theTopLevelKeymap().
1410 printBindings(cmd, KeySequence::ForGui);
1412 if (!shortcuts.empty())
1413 comname += ": " + shortcuts;
1414 else if (!argsadded && !cmd.argument().empty())
1415 comname += ' ' + cmd.argument();
1417 if (!comname.empty()) {
1418 comname = rtrim(comname);
1419 dispatch_msg += '(' + rtrim(comname) + ')';
1421 LYXERR(Debug::ACTION, "verbose dispatch msg " << to_utf8(dispatch_msg));
1422 return dispatch_msg;
1426 DispatchResult const & GuiApplication::dispatch(FuncRequest const & cmd)
1430 Buffer * buffer = 0;
1431 if (cmd.view_origin() && current_view_ != cmd.view_origin()) {
1432 //setCurrentView(cmd.view_origin); //does not work
1434 dr.setMessage(_("Wrong focus!"));
1435 d->dispatch_result_ = dr;
1436 return d->dispatch_result_;
1438 if (current_view_ && current_view_->currentBufferView()) {
1439 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1440 buffer = ¤t_view_->currentBufferView()->buffer();
1443 dr.screenUpdate(Update::FitCursor);
1445 // This handles undo groups automagically
1446 UndoGroupHelper ugh(buffer);
1448 // redraw the screen at the end (first of the two drawing steps).
1449 // This is done unless explicitly requested otherwise.
1450 // This code is kept inside the undo group because updateBuffer
1451 // can create undo actions (see #11292)
1452 updateCurrentView(cmd, dr);
1455 d->dispatch_result_ = dr;
1456 return d->dispatch_result_;
1460 void GuiApplication::updateCurrentView(FuncRequest const & cmd, DispatchResult & dr)
1465 BufferView * bv = current_view_->currentBufferView();
1467 if (dr.needBufferUpdate()) {
1468 bv->cursor().clearBufferUpdate();
1469 bv->buffer().updateBuffer();
1471 // BufferView::update() updates the ViewMetricsInfo and
1472 // also initializes the position cache for all insets in
1473 // (at least partially) visible top-level paragraphs.
1474 // We will redraw the screen only if needed.
1475 bv->processUpdateFlags(dr.screenUpdate());
1477 // Do we have a selection?
1478 theSelection().haveSelection(bv->cursor().selection());
1481 current_view_->restartCaret();
1483 if (dr.needMessageUpdate()) {
1484 // Some messages may already be translated, so we cannot use _()
1485 current_view_->message(makeDispatchMessage(
1486 translateIfPossible(dr.message()), cmd));
1491 void GuiApplication::gotoBookmark(unsigned int idx, bool openFile,
1492 bool switchToBuffer)
1494 if (!theSession().bookmarks().isValid(idx))
1496 BookmarksSection::Bookmark const & bm =
1497 theSession().bookmarks().bookmark(idx);
1498 LASSERT(!bm.filename.empty(), return);
1499 string const file = bm.filename.absFileName();
1500 // if the file is not opened, open it.
1501 if (!theBufferList().exists(bm.filename)) {
1503 dispatch(FuncRequest(LFUN_FILE_OPEN, file));
1507 // open may fail, so we need to test it again
1508 if (!theBufferList().exists(bm.filename))
1511 // bm can be changed when saving
1512 BookmarksSection::Bookmark tmp = bm;
1514 // Special case idx == 0 used for back-from-back jump navigation
1516 dispatch(FuncRequest(LFUN_BOOKMARK_SAVE, "0"));
1518 // if the current buffer is not that one, switch to it.
1519 BufferView * doc_bv = current_view_ ?
1520 current_view_->documentBufferView() : 0;
1521 Cursor const * old = doc_bv ? &doc_bv->cursor() : 0;
1522 if (!doc_bv || doc_bv->buffer().fileName() != tmp.filename) {
1523 if (switchToBuffer) {
1524 dispatch(FuncRequest(LFUN_BUFFER_SWITCH, file));
1527 doc_bv = current_view_->documentBufferView();
1532 // moveToPosition try paragraph id first and then paragraph (pit, pos).
1533 if (!doc_bv || !doc_bv->moveToPosition(
1534 tmp.bottom_pit, tmp.bottom_pos, tmp.top_id, tmp.top_pos))
1537 Cursor & cur = doc_bv->cursor();
1538 if (old && cur != *old)
1539 notifyCursorLeavesOrEnters(*old, cur);
1545 // Cursor jump succeeded!
1546 pit_type new_pit = cur.pit();
1547 pos_type new_pos = cur.pos();
1548 int new_id = cur.paragraph().id();
1550 // if bottom_pit, bottom_pos or top_id has been changed, update bookmark
1551 // see http://www.lyx.org/trac/ticket/3092
1552 if (bm.bottom_pit != new_pit || bm.bottom_pos != new_pos
1553 || bm.top_id != new_id) {
1554 const_cast<BookmarksSection::Bookmark &>(bm).updatePos(
1555 new_pit, new_pos, new_id);
1559 // This function runs "configure" and then rereads lyx.defaults to
1560 // reconfigure the automatic settings.
1561 void GuiApplication::reconfigure(string const & option)
1563 // emit message signal.
1565 current_view_->message(_("Running configure..."));
1567 // Run configure in user lyx directory
1568 string const lock_file = package().getConfigureLockName();
1569 int fd = fileLock(lock_file.c_str());
1570 int const ret = package().reconfigureUserLyXDir(option);
1571 // emit message signal.
1573 current_view_->message(_("Reloading configuration..."));
1574 lyxrc.read(libFileSearch(QString(), "lyxrc.defaults"), false);
1575 // Re-read packages.lst
1576 LaTeXPackages::getAvailable();
1577 fileUnlock(fd, lock_file.c_str());
1580 Alert::information(_("System reconfiguration failed"),
1581 _("The system reconfiguration has failed.\n"
1582 "Default textclass is used but LyX may\n"
1583 "not be able to work properly.\n"
1584 "Please reconfigure again if needed."));
1586 Alert::information(_("System reconfigured"),
1587 _("The system has been reconfigured.\n"
1588 "You need to restart LyX to make use of any\n"
1589 "updated document class specifications."));
1592 void GuiApplication::validateCurrentView()
1594 if (!d->views_.empty() && !current_view_) {
1595 // currently at least one view exists but no view has the focus.
1596 // choose the last view to make it current.
1597 // a view without any open document is preferred.
1598 GuiView * candidate = 0;
1599 QHash<int, GuiView *>::const_iterator it = d->views_.begin();
1600 QHash<int, GuiView *>::const_iterator end = d->views_.end();
1601 for (; it != end; ++it) {
1603 if (!candidate->documentBufferView())
1606 setCurrentView(candidate);
1610 void GuiApplication::dispatch(FuncRequest const & cmd, DispatchResult & dr)
1612 string const argument = to_utf8(cmd.argument());
1613 FuncCode const action = cmd.action();
1615 LYXERR(Debug::ACTION, "cmd: " << cmd);
1617 // we have not done anything wrong yet.
1620 FuncStatus const flag = getStatus(cmd);
1621 if (!flag.enabled()) {
1622 // We cannot use this function here
1623 LYXERR(Debug::ACTION, "action "
1624 << lyxaction.getActionName(action)
1625 << " [" << action << "] is disabled at this location");
1626 dr.setMessage(flag.message());
1628 dr.dispatched(false);
1629 dr.screenUpdate(Update::None);
1630 dr.clearBufferUpdate();
1634 if (cmd.origin() == FuncRequest::LYXSERVER) {
1635 if (current_view_ && current_view_->currentBufferView())
1636 current_view_->currentBufferView()->cursor().saveBeforeDispatchPosXY();
1637 // we will also need to redraw the screen at the end
1638 dr.screenUpdate(Update::FitCursor);
1641 // Assumes that the action will be dispatched.
1642 dr.dispatched(true);
1644 switch (cmd.action()) {
1646 case LFUN_WINDOW_NEW:
1647 createView(toqstr(cmd.argument()));
1650 case LFUN_WINDOW_CLOSE:
1651 // update bookmark pit of the current buffer before window close
1652 for (size_t i = 0; i < theSession().bookmarks().size(); ++i)
1653 gotoBookmark(i+1, false, false);
1654 // clear the last opened list, because
1655 // maybe this will end the session
1656 theSession().lastOpened().clear();
1657 // check for valid current_view_
1658 validateCurrentView();
1660 current_view_->closeScheduled();
1664 // quitting is triggered by the gui code
1665 // (leaving the event loop).
1667 current_view_->message(from_utf8(N_("Exiting.")));
1668 if (closeAllViews())
1672 case LFUN_SCREEN_FONT_UPDATE: {
1673 // handle the screen font changes.
1674 /* FIXME: this only updates the current document, whereas all
1675 * documents should see their metrics updated.
1677 d->font_loader_.update();
1678 dr.screenUpdate(Update::Force | Update::FitCursor);
1682 case LFUN_BUFFER_NEW:
1683 validateCurrentView();
1685 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1686 createView(QString(), false); // keep hidden
1687 current_view_->newDocument(to_utf8(cmd.argument()));
1688 current_view_->show();
1689 setActiveWindow(current_view_);
1691 current_view_->newDocument(to_utf8(cmd.argument()));
1695 case LFUN_BUFFER_NEW_TEMPLATE: {
1696 string const file = (cmd.getArg(0) == "newfile") ? string() : cmd.getArg(0);
1697 string const temp = cmd.getArg(1);
1698 validateCurrentView();
1700 || (!lyxrc.open_buffers_in_tabs && current_view_->documentBufferView() != 0)) {
1702 current_view_->newDocument(file, temp, true);
1703 if (!current_view_->documentBufferView())
1704 current_view_->close();
1706 current_view_->newDocument(file, temp, true);
1711 case LFUN_FILE_OPEN: {
1712 // FIXME: normally the code below is not needed, since getStatus makes sure that
1713 // current_view_ is not null.
1714 validateCurrentView();
1715 // FIXME: create a new method shared with LFUN_HELP_OPEN.
1716 string const fname = to_utf8(cmd.argument());
1717 bool const is_open = FileName::isAbsolute(fname)
1718 && theBufferList().getBuffer(FileName(fname));
1720 || (!lyxrc.open_buffers_in_tabs
1721 && current_view_->documentBufferView() != 0
1723 // We want the ui session to be saved per document and not per
1724 // window number. The filename crc is a good enough identifier.
1725 boost::crc_32_type crc;
1726 crc = for_each(fname.begin(), fname.end(), crc);
1727 createView(crc.checksum());
1728 current_view_->openDocument(fname);
1729 if (!current_view_->documentBufferView())
1730 current_view_->close();
1731 else if (cmd.origin() == FuncRequest::LYXSERVER) {
1732 current_view_->raise();
1733 current_view_->activateWindow();
1734 current_view_->showNormal();
1737 current_view_->openDocument(fname);
1738 if (cmd.origin() == FuncRequest::LYXSERVER) {
1739 current_view_->raise();
1740 current_view_->activateWindow();
1741 current_view_->showNormal();
1747 case LFUN_HELP_OPEN: {
1748 // FIXME: create a new method shared with LFUN_FILE_OPEN.
1749 if (current_view_ == 0)
1751 string const arg = to_utf8(cmd.argument());
1753 current_view_->message(_("Missing argument"));
1756 FileName fname = i18nLibFileSearch("doc", arg, "lyx");
1758 fname = i18nLibFileSearch("examples", arg, "lyx");
1760 if (fname.empty()) {
1761 lyxerr << "LyX: unable to find documentation file `"
1762 << arg << "'. Bad installation?" << endl;
1765 current_view_->message(bformat(_("Opening help file %1$s..."),
1766 makeDisplayPath(fname.absFileName())));
1767 Buffer * buf = current_view_->loadDocument(fname, false);
1769 buf->setReadonly(!current_view_->develMode());
1773 case LFUN_SET_COLOR: {
1774 string const lyx_name = cmd.getArg(0);
1775 string const x11_name = cmd.getArg(1);
1776 if (lyx_name.empty() || x11_name.empty()) {
1778 current_view_->message(
1779 _("Syntax: set-color <lyx_name> <x11_name>"));
1784 // FIXME: The graphics cache no longer has a changeDisplay method.
1785 string const graphicsbg = lcolor.getLyXName(Color_graphicsbg);
1786 bool const graphicsbg_changed =
1787 lyx_name == graphicsbg && x11_name != graphicsbg;
1788 if (graphicsbg_changed)
1789 graphics::GCache::get().changeDisplay(true);
1792 if (!lcolor.setColor(lyx_name, x11_name)) {
1794 current_view_->message(
1795 bformat(_("Set-color \"%1$s\" failed "
1796 "- color is undefined or "
1797 "may not be redefined"),
1798 from_utf8(lyx_name)));
1801 // Make sure we don't keep old colors in cache.
1802 d->color_cache_.clear();
1803 // Update the current view
1804 lyx::dispatch(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
1808 case LFUN_LYXRC_APPLY: {
1809 // reset active key sequences, since the bindings
1810 // are updated (bug 6064)
1812 LyXRC const lyxrc_orig = lyxrc;
1814 istringstream ss(to_utf8(cmd.argument()));
1815 bool const success = lyxrc.read(ss);
1818 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1819 << "Unable to read lyxrc data"
1824 actOnUpdatedPrefs(lyxrc_orig, lyxrc);
1826 // If the request comes from the minibuffer, then we can't reset
1827 // the GUI, since that would destory the minibuffer itself and
1828 // cause a crash, since we are currently in one of the methods of
1829 // GuiCommandBuffer. See bug #8540.
1830 if (cmd.origin() != FuncRequest::COMMANDBUFFER)
1833 // FIXME Unfortunately, that leaves a bug here, since we cannot
1834 // reset the GUI in this case. If the changes to lyxrc affected the
1835 // UI, then, nothing would happen. This seems fairly unlikely, but
1836 // it definitely is a bug.
1838 dr.forceBufferUpdate();
1842 case LFUN_COMMAND_PREFIX:
1843 dispatch(FuncRequest(LFUN_MESSAGE, d->keyseq.printOptions(true)));
1848 d->meta_fake_bit = NoModifier;
1849 GuiView * gv = currentView();
1850 if (gv && gv->currentBufferView())
1851 // cancel any selection
1852 processFuncRequest(FuncRequest(LFUN_MARK_OFF));
1853 dr.setMessage(from_ascii(N_("Cancel")));
1856 case LFUN_META_PREFIX:
1857 d->meta_fake_bit = AltModifier;
1858 dr.setMessage(d->keyseq.print(KeySequence::ForGui));
1861 // --- Menus -----------------------------------------------
1862 case LFUN_RECONFIGURE:
1863 // argument is any additional parameter to the configure.py command
1864 reconfigure(to_utf8(cmd.argument()));
1867 // --- lyxserver commands ----------------------------
1868 case LFUN_SERVER_GET_FILENAME: {
1869 if (current_view_ && current_view_->documentBufferView()) {
1870 docstring const fname = from_utf8(
1871 current_view_->documentBufferView()->buffer().absFileName());
1872 dr.setMessage(fname);
1873 LYXERR(Debug::INFO, "FNAME[" << fname << ']');
1875 dr.setMessage(docstring());
1876 LYXERR(Debug::INFO, "No current file for LFUN_SERVER_GET_FILENAME");
1881 case LFUN_SERVER_NOTIFY: {
1882 docstring const dispatch_buffer = d->keyseq.print(KeySequence::Portable);
1883 dr.setMessage(dispatch_buffer);
1884 theServer().notifyClient(to_utf8(dispatch_buffer));
1888 case LFUN_CURSOR_FOLLOWS_SCROLLBAR_TOGGLE:
1889 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1895 string rest = split(argument, countstr, ' ');
1896 int const count = convert<int>(countstr);
1897 // an arbitrary number to limit number of iterations
1898 int const max_iter = 10000;
1899 if (count > max_iter) {
1900 dr.setMessage(bformat(_("Cannot iterate more than %1$d times"), max_iter));
1903 for (int i = 0; i < count; ++i) {
1904 FuncRequest lfun = lyxaction.lookupFunc(rest);
1905 lfun.allowAsync(false);
1912 case LFUN_COMMAND_SEQUENCE: {
1913 // argument contains ';'-terminated commands
1914 string arg = argument;
1915 // FIXME: this LFUN should also work without any view.
1916 Buffer * buffer = (current_view_ && current_view_->documentBufferView())
1917 ? &(current_view_->documentBufferView()->buffer()) : 0;
1918 // This handles undo groups automagically
1919 UndoGroupHelper ugh(buffer);
1920 while (!arg.empty()) {
1922 arg = split(arg, first, ';');
1923 FuncRequest func(lyxaction.lookupFunc(first));
1924 func.allowAsync(false);
1925 func.setOrigin(cmd.origin());
1931 case LFUN_BUFFER_FORALL: {
1932 FuncRequest funcToRun = lyxaction.lookupFunc(cmd.getLongArg(0));
1933 funcToRun.allowAsync(false);
1935 map<Buffer *, GuiView *> views_lVisible;
1936 map<GuiView *, Buffer *> activeBuffers;
1938 QList<GuiView *> allViews = d->views_.values();
1940 // this for does not modify any buffer. It just collects info on local
1941 // visibility of buffers and on which buffer is active in each view.
1942 Buffer * const last = theBufferList().last();
1943 for(GuiView * view : allViews) {
1944 // all of the buffers might be locally hidden. That is, there is no
1946 if (!view || !view->currentBufferView())
1947 activeBuffers[view] = 0;
1949 activeBuffers[view] = &view->currentBufferView()->buffer();
1951 // find out if each is locally visible or locally hidden.
1952 // we don't use a for loop as the buffer list cycles.
1953 Buffer * b = theBufferList().first();
1955 bool const locallyVisible = view && view->workArea(*b);
1956 if (locallyVisible) {
1957 bool const exists_ = (views_lVisible.find(b) != views_lVisible.end());
1958 // only need to overwrite/add if we don't already know a buffer is globally
1959 // visible or we do know but we would prefer to dispatch LFUN from the
1960 // current view because of cursor position issues.
1961 if (!exists_ || (exists_ && views_lVisible[b] != current_view_))
1962 views_lVisible[b] = view;
1966 b = theBufferList().next(b);
1970 GuiView * const homeView = currentView();
1971 Buffer * b = theBufferList().first();
1972 Buffer * nextBuf = 0;
1973 int numProcessed = 0;
1976 nextBuf = theBufferList().next(b); // get next now bc LFUN might close current.
1978 bool const visible = (views_lVisible.find(b) != views_lVisible.end());
1980 // first change to a view where b is locally visible, preferably current_view_.
1981 GuiView * const vLv = views_lVisible[b];
1983 lyx::dispatch(funcToRun);
1991 // put things back to how they were (if possible).
1992 for (GuiView * view : allViews) {
1993 Buffer * originalBuf = activeBuffers[view];
1994 // there might not have been an active buffer in this view or it might have been closed by the LFUN.
1995 if (theBufferList().isLoaded(originalBuf))
1996 view->setBuffer(originalBuf);
1998 homeView->setFocus();
2000 dr.setMessage(bformat(_("Applied \"%1$s\" to %2$d buffer(s)"), from_utf8(cmd.getLongArg(0)), numProcessed));
2004 case LFUN_COMMAND_ALTERNATIVES: {
2005 // argument contains ';'-terminated commands
2006 string arg = argument;
2007 while (!arg.empty()) {
2009 arg = split(arg, first, ';');
2010 FuncRequest func(lyxaction.lookupFunc(first));
2011 func.setOrigin(cmd.origin());
2012 FuncStatus const stat = getStatus(func);
2013 if (stat.enabled()) {
2023 if (theTopLevelCmdDef().lock(argument, func)) {
2024 func.setOrigin(cmd.origin());
2026 theTopLevelCmdDef().release(argument);
2028 if (func.action() == LFUN_UNKNOWN_ACTION) {
2029 // unknown command definition
2030 lyxerr << "Warning: unknown command definition `"
2034 // recursion detected
2035 lyxerr << "Warning: Recursion in the command definition `"
2036 << argument << "' detected"
2043 case LFUN_IF_RELATIVES: {
2044 string const lfun = to_utf8(cmd.argument());
2045 FuncRequest func(lyxaction.lookupFunc(lfun));
2046 func.setOrigin(cmd.origin());
2047 FuncStatus const stat = getStatus(func);
2048 if (stat.enabled()) {
2055 case LFUN_PREFERENCES_SAVE:
2056 lyxrc.write(support::makeAbsPath("preferences",
2057 package().user_support().absFileName()), false);
2060 case LFUN_BUFFER_SAVE_AS_DEFAULT: {
2061 string const fname = addName(addPath(package().user_support().absFileName(),
2062 "templates/"), "defaults.lyx");
2063 Buffer defaults(fname);
2065 istringstream ss(argument);
2070 // We need to make sure that, after we recreat the DocumentClass,
2071 // which we do in readHeader, we apply it to the document itself.
2072 DocumentClassConstPtr olddc = defaults.params().documentClassPtr();
2073 int const unknown_tokens = defaults.readHeader(lex);
2074 DocumentClassConstPtr newdc = defaults.params().documentClassPtr();
2076 InsetText & theinset = static_cast<InsetText &>(defaults.inset());
2077 cap::switchBetweenClasses(olddc, newdc, theinset, el);
2079 if (unknown_tokens != 0) {
2080 lyxerr << "Warning in LFUN_BUFFER_SAVE_AS_DEFAULT!\n"
2081 << unknown_tokens << " unknown token"
2082 << (unknown_tokens == 1 ? "" : "s")
2086 if (defaults.writeFile(FileName(defaults.absFileName())))
2087 dr.setMessage(bformat(_("Document defaults saved in %1$s"),
2088 makeDisplayPath(fname)));
2091 dr.setMessage(from_ascii(N_("Unable to save document defaults")));
2096 case LFUN_BOOKMARK_GOTO:
2097 // go to bookmark, open unopened file and switch to buffer if necessary
2098 gotoBookmark(convert<unsigned int>(to_utf8(cmd.argument())), true, true);
2099 dr.screenUpdate(Update::Force | Update::FitCursor);
2102 case LFUN_BOOKMARK_CLEAR:
2103 theSession().bookmarks().clear();
2106 case LFUN_DEBUG_LEVEL_SET:
2107 lyxerr.setLevel(Debug::value(to_utf8(cmd.argument())));
2110 case LFUN_DIALOG_SHOW: {
2111 string const name = cmd.getArg(0);
2113 if ( name == "aboutlyx"
2115 || name == "texinfo"
2116 || name == "progress"
2117 || name == "compare")
2119 // work around: on Mac OS the application
2120 // is not terminated when closing the last view.
2121 // Create a new one to be able to dispatch the
2122 // LFUN_DIALOG_SHOW to this view.
2123 if (current_view_ == 0)
2129 // The LFUN must be for one of GuiView, BufferView, Buffer or Cursor;
2132 current_view_->dispatch(cmd, dr);
2136 if (cmd.origin() == FuncRequest::LYXSERVER)
2137 updateCurrentView(cmd, dr);
2141 docstring GuiApplication::viewStatusMessage()
2143 // When meta-fake key is pressed, show the key sequence so far + "M-".
2144 if (d->meta_fake_bit != NoModifier)
2145 return d->keyseq.print(KeySequence::ForGui) + "M-";
2147 // Else, when a non-complete key sequence is pressed,
2148 // show the available options.
2149 if (d->keyseq.length() > 0 && !d->keyseq.deleted())
2150 return d->keyseq.printOptions(true);
2156 string GuiApplication::inputLanguageCode() const
2158 #if (QT_VERSION < 0x050000)
2159 QLocale loc = keyboardInputLocale();
2161 QLocale loc = inputMethod()->locale();
2163 //LYXERR0("input lang = " << fromqstr(loc.name()));
2164 return loc.name() == "C" ? "en_US" : fromqstr(loc.name());
2168 void GuiApplication::onLocaleChanged()
2170 //LYXERR0("Change language to " << inputLanguage()->lang());
2171 if (currentView() && currentView()->currentBufferView())
2172 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2176 void GuiApplication::handleKeyFunc(FuncCode action)
2180 if (d->keyseq.length())
2182 GuiView * gv = currentView();
2183 LASSERT(gv && gv->currentBufferView(), return);
2184 BufferView * bv = gv->currentBufferView();
2185 bv->getIntl().getTransManager().deadkey(
2186 c, get_accent(action).accent, bv->cursor().innerText(),
2188 // Need to clear, in case the minibuffer calls these
2191 // copied verbatim from do_accent_char
2192 bv->cursor().resetAnchor();
2196 //Keep this in sync with GuiApplication::processKeySym below
2197 bool GuiApplication::queryKeySym(KeySymbol const & keysym,
2198 KeyModifier state) const
2200 // Do nothing if we have nothing
2201 if (!keysym.isOK() || keysym.isModifier())
2203 // Do a one-deep top-level lookup for cancel and meta-fake keys.
2205 FuncRequest func = seq.addkey(keysym, state);
2206 // When not cancel or meta-fake, do the normal lookup.
2207 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2209 func = seq.addkey(keysym, (state | d->meta_fake_bit));
2211 // Maybe user can only reach the key via holding down shift.
2212 // Let's see. But only if shift is the only modifier
2213 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier)
2214 // If addkey looked up a command and did not find further commands then
2215 // seq has been reset at this point
2216 func = seq.addkey(keysym, NoModifier);
2218 LYXERR(Debug::KEY, " Key (queried) [action=" << func.action() << "]["
2219 << seq.print(KeySequence::Portable) << ']');
2220 return func.action() != LFUN_UNKNOWN_ACTION;
2224 //Keep this in sync with GuiApplication::queryKeySym above
2225 void GuiApplication::processKeySym(KeySymbol const & keysym, KeyModifier state)
2227 LYXERR(Debug::KEY, "KeySym is " << keysym.getSymbolName());
2229 // Do nothing if we have nothing (JMarc)
2230 if (!keysym.isOK() || keysym.isModifier()) {
2232 LYXERR(Debug::KEY, "Empty kbd action (probably composing)");
2234 current_view_->restartCaret();
2238 char_type encoded_last_key = keysym.getUCSEncoded();
2240 // Do a one-deep top-level lookup for
2241 // cancel and meta-fake keys. RVDK_PATCH_5
2242 d->cancel_meta_seq.reset();
2244 FuncRequest func = d->cancel_meta_seq.addkey(keysym, state);
2245 LYXERR(Debug::KEY, "action first set to [" << func.action() << ']');
2247 // When not cancel or meta-fake, do the normal lookup.
2248 // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
2249 // Mostly, meta_fake_bit = NoModifier. RVDK_PATCH_5.
2250 if ((func.action() != LFUN_CANCEL) && (func.action() != LFUN_META_PREFIX)) {
2251 // remove Caps Lock and Mod2 as a modifiers
2252 func = d->keyseq.addkey(keysym, (state | d->meta_fake_bit));
2253 LYXERR(Debug::KEY, "action now set to [" << func.action() << ']');
2256 // Dont remove this unless you know what you are doing.
2257 d->meta_fake_bit = NoModifier;
2259 // Can this happen now ?
2260 if (func.action() == LFUN_NOACTION)
2261 func = FuncRequest(LFUN_COMMAND_PREFIX);
2263 LYXERR(Debug::KEY, " Key [action=" << func.action() << "]["
2264 << d->keyseq.print(KeySequence::Portable) << ']');
2266 // already here we know if it any point in going further
2267 // why not return already here if action == -1 and
2268 // num_bytes == 0? (Lgb)
2270 if (d->keyseq.length() > 1 && current_view_)
2271 current_view_->message(d->keyseq.print(KeySequence::ForGui));
2274 // Maybe user can only reach the key via holding down shift.
2275 // Let's see. But only if shift is the only modifier
2276 if (func.action() == LFUN_UNKNOWN_ACTION && state == ShiftModifier) {
2277 LYXERR(Debug::KEY, "Trying without shift");
2278 // If addkey looked up a command and did not find further commands then
2279 // seq has been reset at this point
2280 func = d->keyseq.addkey(keysym, NoModifier);
2281 LYXERR(Debug::KEY, "Action now " << func.action());
2284 if (func.action() == LFUN_UNKNOWN_ACTION) {
2285 // We didn't match any of the key sequences.
2286 // See if it's normal insertable text not already
2287 // covered by a binding
2288 if (keysym.isText() && d->keyseq.length() == 1) {
2289 // Non-printable characters (such as ASCII control characters)
2290 // must not be inserted (#5704)
2291 if (!isPrintable(encoded_last_key)) {
2292 LYXERR(Debug::KEY, "Non-printable character! Omitting.");
2294 current_view_->restartCaret();
2297 // The following modifier check is not needed on Mac.
2298 // The keysym is either not text or it is different
2299 // from the non-modifier keysym. See #9875 for the
2300 // broken alt-modifier effect of having this code active.
2301 #if !defined(Q_OS_MAC)
2302 // If a non-Shift Modifier is used we have a non-bound key sequence
2303 // (such as Alt+j = j). This should be omitted (#5575).
2304 // On Windows, AltModifier and ControlModifier are both
2305 // set when AltGr is pressed. Therefore, in order to not
2306 // break AltGr-bound symbols (see #5575 for details),
2307 // unbound Ctrl+Alt key sequences are allowed.
2308 if ((state & AltModifier || state & ControlModifier || state & MetaModifier)
2309 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2310 && !(state & AltModifier && state & ControlModifier)
2314 if (current_view_) {
2315 current_view_->message(_("Unknown function."));
2316 current_view_->restartCaret();
2321 // Since all checks above were passed, we now really have text that
2322 // is to be inserted (e.g., AltGr-bound symbols). Thus change the
2323 // func to LFUN_SELF_INSERT and thus cause the text to be inserted
2325 LYXERR(Debug::KEY, "isText() is true, inserting.");
2326 func = FuncRequest(LFUN_SELF_INSERT, FuncRequest::KEYBOARD);
2328 LYXERR(Debug::KEY, "Unknown Action and not isText() -- giving up");
2329 if (current_view_) {
2330 current_view_->message(_("Unknown function."));
2331 current_view_->restartCaret();
2337 if (func.action() == LFUN_SELF_INSERT) {
2338 if (encoded_last_key != 0) {
2339 docstring const arg(1, encoded_last_key);
2340 processFuncRequest(FuncRequest(LFUN_SELF_INSERT, arg,
2341 FuncRequest::KEYBOARD));
2342 LYXERR(Debug::KEY, "SelfInsert arg[`" << to_utf8(arg) << "']");
2345 processFuncRequest(func);
2349 void GuiApplication::processFuncRequest(FuncRequest const & func)
2351 lyx::dispatch(func);
2355 void GuiApplication::processFuncRequestAsync(FuncRequest const & func)
2357 addToFuncRequestQueue(func);
2358 processFuncRequestQueueAsync();
2362 void GuiApplication::processFuncRequestQueue()
2364 while (!d->func_request_queue_.empty()) {
2365 // take the item from the stack _before_ processing the
2366 // request in order to avoid race conditions from nested
2367 // or parallel requests (see #10406)
2368 FuncRequest const fr(d->func_request_queue_.front());
2369 d->func_request_queue_.pop();
2370 processFuncRequest(fr);
2375 void GuiApplication::processFuncRequestQueueAsync()
2377 QTimer::singleShot(0, this, SLOT(slotProcessFuncRequestQueue()));
2381 void GuiApplication::addToFuncRequestQueue(FuncRequest const & func)
2383 d->func_request_queue_.push(func);
2387 void GuiApplication::resetGui()
2389 // Set the language defined by the user.
2393 if (!readUIFile(toqstr(lyxrc.ui_file)))
2394 // Gives some error box here.
2397 if (d->global_menubar_)
2398 d->menus_.fillMenuBar(d->global_menubar_, 0, false);
2400 QHash<int, GuiView *>::iterator it;
2401 for (it = d->views_.begin(); it != d->views_.end(); ++it) {
2404 gv->setLayoutDirection(layoutDirection());
2408 processFuncRequest(FuncRequest(LFUN_SCREEN_FONT_UPDATE));
2412 bool GuiApplication::rtlContext() const
2414 if (current_view_ && current_view_->currentBufferView()) {
2415 BufferView const * bv = current_view_->currentBufferView();
2416 return bv->cursor().innerParagraph().isRTL(bv->buffer().params());
2418 return layoutDirection() == Qt::RightToLeft;
2422 void GuiApplication::createView(int view_id)
2424 createView(QString(), true, view_id);
2428 void GuiApplication::createView(QString const & geometry_arg, bool autoShow,
2431 // release the keyboard which might have been grabed by the global
2432 // menubar on Mac to catch shortcuts even without any GuiView.
2433 if (d->global_menubar_)
2434 d->global_menubar_->releaseKeyboard();
2438 while (d->views_.find(id) != d->views_.end())
2441 LYXERR(Debug::GUI, "About to create new window with ID " << id);
2442 GuiView * view = new GuiView(id);
2443 // `view' is the new current_view_. Tell coverity that is is not 0.
2444 LATTEST(current_view_);
2446 d->views_[id] = view;
2450 setActiveWindow(view);
2453 if (!geometry_arg.isEmpty()) {
2454 #if defined(Q_OS_WIN) || defined(Q_CYGWIN_WIN)
2458 QRegExp re( "[=]*(?:([0-9]+)[xX]([0-9]+)){0,1}[ ]*(?:([+-][0-9]*)){0,1}(?:([+-][0-9]*)){0,1}" );
2459 re.indexIn(geometry_arg);
2460 w = re.cap(1).toInt();
2461 h = re.cap(2).toInt();
2462 x = re.cap(3).toInt();
2463 y = re.cap(4).toInt();
2464 sx = re.cap(3).isEmpty() ? '+' : re.cap(3).at(0);
2465 sy = re.cap(4).isEmpty() ? '+' : re.cap(4).at(0);
2466 // Set initial geometry such that we can get the frame size.
2467 view->setGeometry(x, y, w, h);
2468 int framewidth = view->geometry().x() - view->x();
2469 int titleheight = view->geometry().y() - view->y();
2470 // Negative displacements must be interpreted as distances
2471 // from the right or bottom screen borders.
2472 if (sx == '-' || sy == '-') {
2473 QRect rec = QApplication::desktop()->screenGeometry();
2475 x += rec.width() - w - framewidth;
2477 y += rec.height() - h - titleheight;
2478 view->setGeometry(x, y, w, h);
2480 // Make sure that the left and top frame borders are visible.
2481 if (view->x() < 0 || view->y() < 0) {
2486 view->setGeometry(x, y, w, h);
2494 bool GuiApplication::unhide(Buffer * buf)
2498 currentView()->setBuffer(buf, false);
2503 Clipboard & GuiApplication::clipboard()
2505 return d->clipboard_;
2509 Selection & GuiApplication::selection()
2511 return d->selection_;
2515 FontLoader & GuiApplication::fontLoader()
2517 return d->font_loader_;
2521 Toolbars const & GuiApplication::toolbars() const
2523 return d->toolbars_;
2527 Toolbars & GuiApplication::toolbars()
2529 return d->toolbars_;
2533 Menus const & GuiApplication::menus() const
2539 Menus & GuiApplication::menus()
2545 QList<int> GuiApplication::viewIds() const
2547 return d->views_.keys();
2551 ColorCache & GuiApplication::colorCache()
2553 return d->color_cache_;
2557 int GuiApplication::exec()
2559 // asynchronously handle batch commands. This event will be in
2560 // the event queue in front of other asynchronous events. Hence,
2561 // we can assume in the latter that the gui is setup already.
2562 QTimer::singleShot(0, this, SLOT(execBatchCommands()));
2564 return QApplication::exec();
2568 void GuiApplication::exit(int status)
2570 QApplication::exit(status);
2574 void GuiApplication::setGuiLanguage()
2578 // install translation file for Qt built-in dialogs
2579 QString const language_name = QString("qt_") + theLocale.name();
2580 // language_name can be short (e.g. qt_zh) or long (e.g. qt_zh_CN).
2581 // Short-named translator can be loaded from a long name, but not the
2582 // opposite. Therefore, long name should be used without truncation.
2583 // c.f. http://doc.trolltech.com/4.1/qtranslator.html#load
2584 if (!d->qt_trans_.load(language_name,
2585 QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
2586 LYXERR(Debug::LOCALE, "Could not find Qt translations for locale "
2589 LYXERR(Debug::LOCALE, "Successfully installed Qt translations for locale "
2593 switch (theLocale.language()) {
2594 case QLocale::Arabic :
2595 case QLocale::Hebrew :
2596 case QLocale::Persian :
2597 case QLocale::Urdu :
2598 setLayoutDirection(Qt::RightToLeft);
2601 setLayoutDirection(Qt::LeftToRight);
2606 void GuiApplication::execBatchCommands()
2611 if (!readUIFile(toqstr(lyxrc.ui_file)))
2612 // Gives some error box here.
2616 #if QT_VERSION > 0x040600
2617 setAttribute(Qt::AA_MacDontSwapCtrlAndMeta,lyxrc.mac_dontswap_ctrl_meta);
2619 #if QT_VERSION > 0x050100
2620 setAttribute(Qt::AA_UseHighDpiPixmaps,true);
2622 // Create the global default menubar which is shown for the dialogs
2623 // and if no GuiView is visible.
2624 // This must be done after the session was recovered to know the "last files".
2625 d->global_menubar_ = new QMenuBar(0);
2626 d->menus_.fillMenuBar(d->global_menubar_, 0, true);
2629 lyx::execBatchCommands();
2633 QAbstractItemModel * GuiApplication::languageModel()
2635 if (d->language_model_)
2636 return d->language_model_;
2638 QStandardItemModel * lang_model = new QStandardItemModel(this);
2639 lang_model->insertColumns(0, 3);
2640 QIcon speller(getPixmap("images/", "dialog-show_spellchecker", "svgz,png"));
2641 QIcon saurus(getPixmap("images/", "thesaurus-entry", "svgz,png"));
2642 Languages::const_iterator it = lyx::languages.begin();
2643 Languages::const_iterator end = lyx::languages.end();
2644 for (; it != end; ++it) {
2645 int current_row = lang_model->rowCount();
2646 lang_model->insertRows(current_row, 1);
2647 QModelIndex pl_item = lang_model->index(current_row, 0);
2648 QModelIndex sp_item = lang_model->index(current_row, 1);
2649 QModelIndex th_item = lang_model->index(current_row, 2);
2650 lang_model->setData(pl_item, qt_(it->second.display()), Qt::DisplayRole);
2651 lang_model->setData(pl_item, toqstr(it->second.lang()), Qt::UserRole);
2652 lang_model->setData(sp_item, qt_(it->second.display()), Qt::DisplayRole);
2653 lang_model->setData(sp_item, toqstr(it->second.lang()), Qt::UserRole);
2654 if (theSpellChecker() && theSpellChecker()->hasDictionary(&it->second))
2655 lang_model->setData(sp_item, speller, Qt::DecorationRole);
2656 lang_model->setData(th_item, qt_(it->second.display()), Qt::DisplayRole);
2657 lang_model->setData(th_item, toqstr(it->second.lang()), Qt::UserRole);
2658 if (thesaurus.thesaurusInstalled(from_ascii(it->second.code())))
2659 lang_model->setData(th_item, saurus, Qt::DecorationRole);
2661 d->language_model_ = new QSortFilterProxyModel(this);
2662 d->language_model_->setSourceModel(lang_model);
2663 d->language_model_->setSortLocaleAware(true);
2664 return d->language_model_;
2668 void GuiApplication::restoreGuiSession()
2670 if (!lyxrc.load_session)
2673 Session & session = theSession();
2674 LastOpenedSection::LastOpened const & lastopened =
2675 session.lastOpened().getfiles();
2677 validateCurrentView();
2679 FileName active_file;
2680 // do not add to the lastfile list since these files are restored from
2681 // last session, and should be already there (regular files), or should
2682 // not be added at all (help files).
2683 for (size_t i = 0; i < lastopened.size(); ++i) {
2684 FileName const & file_name = lastopened[i].file_name;
2685 if (!current_view_ || (!lyxrc.open_buffers_in_tabs
2686 && current_view_->documentBufferView() != 0)) {
2687 boost::crc_32_type crc;
2688 string const & fname = file_name.absFileName();
2689 crc = for_each(fname.begin(), fname.end(), crc);
2690 createView(crc.checksum());
2692 current_view_->loadDocument(file_name, false);
2694 if (lastopened[i].active)
2695 active_file = file_name;
2698 // Restore last active buffer
2699 Buffer * buffer = theBufferList().getBuffer(active_file);
2700 if (buffer && current_view_)
2701 current_view_->setBuffer(buffer);
2703 // clear this list to save a few bytes of RAM
2704 session.lastOpened().clear();
2708 QString const GuiApplication::romanFontName()
2711 font.setStyleHint(QFont::Serif);
2712 font.setFamily("serif");
2714 return QFontInfo(font).family();
2718 QString const GuiApplication::sansFontName()
2721 font.setStyleHint(QFont::SansSerif);
2722 font.setFamily("sans");
2724 return QFontInfo(font).family();
2728 QString const GuiApplication::typewriterFontName()
2730 return QFontInfo(typewriterSystemFont()).family();
2735 // We cannot use QFont::fixedPitch() because it doesn't
2736 // return the fact but only if it is requested.
2737 static bool isFixedPitch(const QFont & font) {
2738 const QFontInfo fi(font);
2739 return fi.fixedPitch();
2744 QFont const GuiApplication::typewriterSystemFont()
2746 #if QT_VERSION >= 0x050200
2747 QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
2749 QFont font("monospace");
2751 if (!isFixedPitch(font)) {
2752 // try to enforce a real monospaced font
2753 font.setStyleHint(QFont::Monospace);
2754 if (!isFixedPitch(font)) {
2755 font.setStyleHint(QFont::TypeWriter);
2756 if (!isFixedPitch(font)) font.setFamily("courier");
2760 // On a Mac the result is too small and it's not practical to
2761 // rely on Qtconfig utility to change the system settings of Qt.
2762 font.setPointSize(12);
2768 void GuiApplication::handleRegularEvents()
2770 ForkedCallsController::handleCompletedProcesses();
2774 bool GuiApplication::event(QEvent * e)
2777 case QEvent::FileOpen: {
2778 // Open a file; this happens only on Mac OS X for now.
2780 // We do this asynchronously because on startup the batch
2781 // commands are not executed here yet and the gui is not ready
2783 QFileOpenEvent * foe = static_cast<QFileOpenEvent *>(e);
2784 FuncRequest const fr(LFUN_FILE_OPEN, qstring_to_ucs4(foe->file()));
2785 processFuncRequestAsync(fr);
2789 #if (QT_VERSION < 0x050000)
2790 // Qt5 uses a signal for that, see above.
2791 case QEvent::KeyboardLayoutChange:
2792 //LYXERR0("keyboard change");
2793 if (currentView() && currentView()->currentBufferView())
2794 currentView()->currentBufferView()->cursor().setLanguageFromInput();
2799 return QApplication::event(e);
2804 bool GuiApplication::notify(QObject * receiver, QEvent * event)
2807 return QApplication::notify(receiver, event);
2809 catch (ExceptionMessage const & e) {
2811 case ErrorException:
2813 setQuitOnLastWindowClosed(false);
2815 Alert::error(e.title_, e.details_);
2817 // Properly crash in debug mode in order to get a useful backtrace.
2820 // In release mode, try to exit gracefully.
2822 // FIXME: GCC 7 thinks we can fall through here. Can we?
2824 case BufferException: {
2825 if (!current_view_ || !current_view_->documentBufferView())
2827 Buffer * buf = ¤t_view_->documentBufferView()->buffer();
2828 docstring details = e.details_ + '\n';
2829 details += buf->emergencyWrite();
2830 theBufferList().release(buf);
2831 details += "\n" + _("The current document was closed.");
2832 Alert::error(e.title_, details);
2835 case WarningException:
2836 Alert::warning(e.title_, e.details_);
2840 catch (exception const & e) {
2841 docstring s = _("LyX has caught an exception, it will now "
2842 "attempt to save all unsaved documents and exit."
2844 s += from_ascii(e.what());
2845 Alert::error(_("Software exception Detected"), s);
2849 docstring s = _("LyX has caught some really weird exception, it will "
2850 "now attempt to save all unsaved documents and exit.");
2851 Alert::error(_("Software exception Detected"), s);
2859 bool GuiApplication::getRgbColor(ColorCode col, RGBColor & rgbcol)
2861 QColor const & qcol = d->color_cache_.get(col);
2862 if (!qcol.isValid()) {
2868 rgbcol.r = qcol.red();
2869 rgbcol.g = qcol.green();
2870 rgbcol.b = qcol.blue();
2875 bool Application::getRgbColorUncached(ColorCode col, RGBColor & rgbcol)
2877 QColor const qcol(lcolor.getX11Name(col).c_str());
2878 if (!qcol.isValid()) {
2884 rgbcol.r = qcol.red();
2885 rgbcol.g = qcol.green();
2886 rgbcol.b = qcol.blue();
2891 string const GuiApplication::hexName(ColorCode col)
2893 return ltrim(fromqstr(d->color_cache_.get(col).name()), "#");
2897 void GuiApplication::registerSocketCallback(int fd, SocketCallback func)
2899 SocketNotifier * sn = new SocketNotifier(this, fd, func);
2900 d->socket_notifiers_[fd] = sn;
2901 connect(sn, SIGNAL(activated(int)), this, SLOT(socketDataReceived(int)));
2905 void GuiApplication::socketDataReceived(int fd)
2907 d->socket_notifiers_[fd]->func_();
2911 void GuiApplication::unregisterSocketCallback(int fd)
2913 d->socket_notifiers_.take(fd)->setEnabled(false);
2917 void GuiApplication::commitData(QSessionManager & sm)
2919 /** The implementation is required to avoid an application exit
2920 ** when session state save is triggered by session manager.
2921 ** The default implementation sends a close event to all
2922 ** visible top level widgets when session managment allows
2924 ** We are changing that to check the state of each buffer in all
2925 ** views and ask the users what to do if buffers are dirty.
2926 ** Furthermore, we save the session state.
2927 ** We do NOT close the views here since the user still can cancel
2928 ** the logout process (see #9277); also, this would hide LyX from
2929 ** an OSes own session handling (application restoration).
2931 #ifdef QT_NO_SESSIONMANAGER
2933 #warning Qt is compiled without session manager
2935 #pragma message("warning: Qt is compiled without session manager")
2939 if (sm.allowsInteraction() && !prepareAllViewsForLogout())
2947 void GuiApplication::unregisterView(GuiView * gv)
2949 if(d->views_.contains(gv->id()) && d->views_.value(gv->id()) == gv) {
2950 d->views_.remove(gv->id());
2951 if (current_view_ == gv)
2957 bool GuiApplication::closeAllViews()
2959 if (d->views_.empty())
2962 // When a view/window was closed before without quitting LyX, there
2963 // are already entries in the lastOpened list.
2964 theSession().lastOpened().clear();
2966 QList<GuiView *> const views = d->views_.values();
2967 for (GuiView * view : views) {
2968 if (!view->closeScheduled())
2977 bool GuiApplication::prepareAllViewsForLogout()
2979 if (d->views_.empty())
2982 QList<GuiView *> const views = d->views_.values();
2983 for (GuiView * view : views) {
2984 if (!view->prepareAllBuffersForLogout())
2992 GuiView & GuiApplication::view(int id) const
2994 LAPPERR(d->views_.contains(id));
2995 return *d->views_.value(id);
2999 void GuiApplication::hideDialogs(string const & name, Inset * inset) const
3001 QList<GuiView *> const views = d->views_.values();
3002 for (GuiView * view : views)
3003 view->hideDialog(name, inset);
3007 Buffer const * GuiApplication::updateInset(Inset const * inset) const
3009 Buffer const * buf = 0;
3010 QHash<int, GuiView *>::const_iterator end = d->views_.end();
3011 for (QHash<int, GuiView *>::iterator it = d->views_.begin(); it != end; ++it) {
3012 if (Buffer const * ptr = (*it)->updateInset(inset))
3019 bool GuiApplication::searchMenu(FuncRequest const & func,
3020 docstring_list & names) const
3022 BufferView * bv = 0;
3024 bv = current_view_->currentBufferView();
3025 return d->menus_.searchMenu(func, names, bv);
3029 bool GuiApplication::hasBufferView() const
3031 return (current_view_ && current_view_->currentBufferView());
3035 // Ensure that a file is read only once (prevents include loops)
3036 static QStringList uifiles;
3037 // store which ui files define Toolbars
3038 static QStringList toolbar_uifiles;
3041 GuiApplication::ReturnValues GuiApplication::readUIFile(FileName ui_path)
3052 LexerKeyword uitags[] = {
3053 { "format", ui_format },
3054 { "include", ui_include },
3055 { "menuset", ui_menuset },
3056 { "toolbars", ui_toolbars },
3057 { "toolbarset", ui_toolbarset }
3061 lex.setFile(ui_path);
3063 lyxerr << "Unable to set LyXLeX for ui file: " << ui_path
3067 if (lyxerr.debugging(Debug::PARSER))
3068 lex.printTable(lyxerr);
3071 // format before introduction of format tag
3072 unsigned int format = 0;
3073 while (lex.isOK()) {
3074 int const status = lex.lex();
3076 // we have to do this check here, outside the switch,
3077 // because otherwise we would start reading include files,
3078 // e.g., if the first tag we hit was an include tag.
3079 if (status == ui_format)
3081 format = lex.getInteger();
3085 // this will trigger unless the first tag we hit is a format
3086 // tag, with the right format.
3087 if (format != LFUN_FORMAT)
3088 return FormatMismatch;
3091 case Lexer::LEX_FEOF:
3096 QString const file = toqstr(lex.getString());
3097 bool const success = readUIFile(file, true);
3099 LYXERR0("Failed to read included file: " << fromqstr(file));
3106 d->menus_.read(lex);
3110 d->toolbars_.readToolbars(lex);
3114 d->toolbars_.readToolbarSettings(lex);
3115 toolbar_uifiles.push_back(toqstr(ui_path.absFileName()));
3119 if (!rtrim(lex.getString()).empty())
3120 lex.printError("LyX::ReadUIFile: "
3121 "Unknown menu tag: `$$Token'");
3123 LYXERR0("Error with status: " << status);
3129 return (error ? ReadError : ReadOK);
3133 bool GuiApplication::readUIFile(QString const & name, bool include)
3135 LYXERR(Debug::INIT, "About to read " << name << "...");
3139 ui_path = libFileSearch("ui", name, "inc");
3140 if (ui_path.empty())
3141 ui_path = libFileSearch("ui", changeExtension(name, "inc"));
3143 ui_path = libFileSearch("ui", name, "ui");
3146 if (ui_path.empty()) {
3147 static const QString defaultUIFile = "default";
3148 LYXERR(Debug::INIT, "Could not find " << name);
3150 Alert::warning(_("Could not find UI definition file"),
3151 bformat(_("Error while reading the included file\n%1$s\n"
3152 "Please check your installation."), qstring_to_ucs4(name)));
3155 if (name == defaultUIFile) {
3156 LYXERR(Debug::INIT, "Could not find default UI file!!");
3157 Alert::warning(_("Could not find default UI file"),
3158 _("LyX could not find the default UI file!\n"
3159 "Please check your installation."));
3162 Alert::warning(_("Could not find UI definition file"),
3163 bformat(_("Error while reading the configuration file\n%1$s\n"
3164 "Falling back to default.\n"
3165 "Please look under Tools>Preferences>User Interface and\n"
3166 "check which User Interface file you are using."), qstring_to_ucs4(name)));
3167 return readUIFile(defaultUIFile, false);
3170 QString const uifile = toqstr(ui_path.absFileName());
3171 if (uifiles.contains(uifile)) {
3173 // We are reading again the top uifile so reset the safeguard:
3176 d->toolbars_.reset();
3178 LYXERR(Debug::INIT, "UI file '" << name << "' has been read already. "
3179 << "Is this an include loop?");
3183 uifiles.push_back(uifile);
3185 LYXERR(Debug::INIT, "Found " << name << " in " << ui_path);
3187 ReturnValues retval = readUIFile(ui_path);
3189 if (retval == FormatMismatch) {
3190 LYXERR(Debug::FILES, "Converting ui file to format " << LFUN_FORMAT);
3191 TempFile tmp("convertXXXXXX.ui");
3192 FileName const tempfile = tmp.name();
3193 bool const success = prefs2prefs(ui_path, tempfile, true);
3195 LYXERR0("Unable to convert " << ui_path.absFileName() <<
3196 " to format " << LFUN_FORMAT << ".");
3198 retval = readUIFile(tempfile);
3202 if (retval != ReadOK) {
3203 LYXERR0("Unable to read UI file: " << ui_path.absFileName());
3211 settings.beginGroup("ui_files");
3212 bool touched = false;
3213 for (int i = 0; i != uifiles.size(); ++i) {
3214 QFileInfo fi(uifiles[i]);
3215 QDateTime const date_value = fi.lastModified();
3216 QString const name_key = QString::number(i);
3217 // if an ui file which defines Toolbars has changed,
3218 // we have to reset the settings
3219 if (toolbar_uifiles.contains(uifiles[i])
3220 && (!settings.contains(name_key)
3221 || settings.value(name_key).toString() != uifiles[i]
3222 || settings.value(name_key + "/date").toDateTime() != date_value)) {
3224 settings.setValue(name_key, uifiles[i]);
3225 settings.setValue(name_key + "/date", date_value);
3228 settings.endGroup();
3230 settings.remove("views");
3236 void GuiApplication::onLastWindowClosed()
3238 if (d->global_menubar_)
3239 d->global_menubar_->grabKeyboard();
3243 void GuiApplication::startLongOperation() {
3244 d->key_checker_.start();
3248 bool GuiApplication::longOperationCancelled() {
3249 return d->key_checker_.pressed();
3253 void GuiApplication::stopLongOperation() {
3254 d->key_checker_.stop();
3258 bool GuiApplication::longOperationStarted() {
3259 return d->key_checker_.started();
3263 ////////////////////////////////////////////////////////////////////////
3265 // X11 specific stuff goes here...
3268 bool GuiApplication::x11EventFilter(XEvent * xev)
3273 switch (xev->type) {
3274 case SelectionRequest: {
3275 if (xev->xselectionrequest.selection != XA_PRIMARY)
3277 LYXERR(Debug::SELECTION, "X requested selection.");
3278 BufferView * bv = current_view_->currentBufferView();
3280 docstring const sel = bv->requestSelection();
3282 d->selection_.put(sel);
3283 // Refresh the selection request timestamp.
3284 // We have to do this by ourselves as Qt seems
3285 // not doing that, maybe because of our
3286 // "persistent selection" implementation
3287 // (see comments in GuiSelection.cpp).
3288 XSelectionEvent nev;
3289 nev.type = SelectionNotify;
3290 nev.display = xev->xselectionrequest.display;
3291 nev.requestor = xev->xselectionrequest.requestor;
3292 nev.selection = xev->xselectionrequest.selection;
3293 nev.target = xev->xselectionrequest.target;
3294 nev.property = 0L; // None
3295 nev.time = CurrentTime;
3296 XSendEvent(QX11Info::display(),
3297 nev.requestor, False, 0,
3298 reinterpret_cast<XEvent *>(&nev));
3304 case SelectionClear: {
3305 if (xev->xselectionclear.selection != XA_PRIMARY)
3307 LYXERR(Debug::SELECTION, "Lost selection.");
3308 BufferView * bv = current_view_->currentBufferView();
3310 bv->clearSelection();
3316 #elif defined(QPA_XCB)
3317 bool GuiApplication::nativeEventFilter(const QByteArray & eventType,
3318 void * message, long *)
3320 if (!current_view_ || eventType != "xcb_generic_event_t")
3323 xcb_generic_event_t * ev = static_cast<xcb_generic_event_t *>(message);
3325 switch (ev->response_type) {
3326 case XCB_SELECTION_REQUEST: {
3327 xcb_selection_request_event_t * srev =
3328 reinterpret_cast<xcb_selection_request_event_t *>(ev);
3329 if (srev->selection != XCB_ATOM_PRIMARY)
3331 LYXERR(Debug::SELECTION, "X requested selection.");
3332 BufferView * bv = current_view_->currentBufferView();
3334 docstring const sel = bv->requestSelection();
3336 d->selection_.put(sel);
3337 #ifdef HAVE_QT5_X11_EXTRAS
3338 // Refresh the selection request timestamp.
3339 // We have to do this by ourselves as Qt seems
3340 // not doing that, maybe because of our
3341 // "persistent selection" implementation
3342 // (see comments in GuiSelection.cpp).
3343 // It is expected that every X11 event is
3344 // 32 bytes long, even if not all 32 bytes are
3346 // https://www.x.org/releases/current/doc/man/man3/xcb_send_event.3.xhtml
3347 struct alignas(32) padded_event
3348 : xcb_selection_notify_event_t {};
3349 padded_event nev = {};
3350 nev.response_type = XCB_SELECTION_NOTIFY;
3351 nev.requestor = srev->requestor;
3352 nev.selection = srev->selection;
3353 nev.target = srev->target;
3354 nev.property = XCB_NONE;
3355 nev.time = XCB_CURRENT_TIME;
3356 xcb_connection_t * con = QX11Info::connection();
3357 xcb_send_event(con, 0, srev->requestor,
3358 XCB_EVENT_MASK_NO_EVENT,
3359 reinterpret_cast<char const *>(&nev));
3367 case XCB_SELECTION_CLEAR: {
3368 xcb_selection_clear_event_t * scev =
3369 reinterpret_cast<xcb_selection_clear_event_t *>(ev);
3370 if (scev->selection != XCB_ATOM_PRIMARY)
3372 LYXERR(Debug::SELECTION, "Lost selection.");
3373 BufferView * bv = current_view_->currentBufferView();
3375 bv->clearSelection();
3383 } // namespace frontend
3386 void hideDialogs(std::string const & name, Inset * inset)
3389 frontend::guiApp->hideDialogs(name, inset);
3393 ////////////////////////////////////////////////////////////////////
3397 ////////////////////////////////////////////////////////////////////
3399 frontend::FontLoader & theFontLoader()
3401 LAPPERR(frontend::guiApp);
3402 return frontend::guiApp->fontLoader();
3406 frontend::FontMetrics const & theFontMetrics(Font const & f)
3408 return theFontMetrics(f.fontInfo());
3412 frontend::FontMetrics const & theFontMetrics(FontInfo const & f)
3414 LAPPERR(frontend::guiApp);
3415 return frontend::guiApp->fontLoader().metrics(f);
3419 ////////////////////////////////////////////////////////////////////
3423 ////////////////////////////////////////////////////////////////////
3425 frontend::Clipboard & theClipboard()
3427 LAPPERR(frontend::guiApp);
3428 return frontend::guiApp->clipboard();
3432 frontend::Selection & theSelection()
3434 LAPPERR(frontend::guiApp);
3435 return frontend::guiApp->selection();
3441 #include "moc_GuiApplication.cpp"