3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
12 #include "InsetInfo.h"
15 #include "BufferParams.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
19 #include "FuncRequest.h"
20 #include "FuncStatus.h"
21 #include "InsetGraphics.h"
22 #include "InsetSpecialChar.h"
24 #include "LaTeXFeatures.h"
26 #include "LayoutFile.h"
28 #include "LyXAction.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
34 #include "ParagraphParameters.h"
37 #include "frontends/Application.h"
39 #include "support/convert.h"
40 #include "support/debug.h"
41 #include "support/docstream.h"
42 #include "support/docstring_list.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/FileName.h"
45 #include "support/filetools.h"
46 #include "support/gettext.h"
47 #include "support/Messages.h"
48 #include "support/lstrings.h"
49 #include "support/qstring_helpers.h"
50 #include "support/Translator.h"
54 #include <QtGui/QImage>
57 using namespace lyx::support;
63 typedef Translator<InsetInfo::info_type, string> NameTranslator;
65 NameTranslator const initTranslator()
67 NameTranslator translator(InsetInfo::UNKNOWN_INFO, "unknown");
69 translator.addPair(InsetInfo::SHORTCUTS_INFO, "shortcuts");
70 translator.addPair(InsetInfo::SHORTCUT_INFO, "shortcut");
71 translator.addPair(InsetInfo::LYXRC_INFO, "lyxrc");
72 translator.addPair(InsetInfo::PACKAGE_INFO, "package");
73 translator.addPair(InsetInfo::TEXTCLASS_INFO, "textclass");
74 translator.addPair(InsetInfo::MENU_INFO, "menu");
75 translator.addPair(InsetInfo::ICON_INFO, "icon");
76 translator.addPair(InsetInfo::BUFFER_INFO, "buffer");
77 translator.addPair(InsetInfo::LYX_INFO, "lyxinfo");
78 translator.addPair(InsetInfo::VCS_INFO, "vcs");
83 /// The translator between the information type enum and corresponding string.
84 NameTranslator const & nameTranslator()
86 static NameTranslator const translator = initTranslator();
92 /////////////////////////////////////////////////////////////////////////
96 /////////////////////////////////////////////////////////////////////////
100 InsetInfo::InsetInfo(Buffer * buf, string const & name)
101 : InsetCollapsible(buf), initialized_(false),
102 type_(UNKNOWN_INFO), name_(), force_ltr_(false)
109 Inset * InsetInfo::editXY(Cursor & cur, int x, int y)
111 // do not allow the cursor to be set in this Inset
112 return Inset::editXY(cur, x, y);
116 string InsetInfo::infoType() const
118 return nameTranslator().find(type_);
122 docstring InsetInfo::layoutName() const
124 return from_ascii("Info:" + infoType());
128 docstring InsetInfo::toolTip(BufferView const &, int, int) const
131 switch (nameTranslator().find(infoType())) {
133 result = _("Invalid information inset");
136 result = bformat(_("The keybard shortcut for the function '%1$s'"),
140 result = bformat(_("The keybard shortcuts for the function '%1$s'"),
144 result = bformat(_("The menu location for the function '%1$s'"),
148 result = bformat(_("The toolbar icon for the function '%1$s'"),
152 result = bformat(_("The preference setting for the preference key '%1$s'"),
156 result = bformat(_("Availability of the LaTeX package '%1$s'"),
160 result = bformat(_("Availability of the LaTeX class '%1$s'"),
165 result = _("The name of this file");
166 else if (name_ == "path")
167 result = _("The path where this file is saved");
168 else if (name_ == "class")
169 result = _("The class this document uses");
172 if (name_ == "revision")
173 result = _("Version control revision");
174 else if (name_ == "tree-revision")
175 result = _("Version control tree revision");
176 else if (name_ == "author")
177 result = _("Version control author");
178 else if (name_ == "date")
179 result = _("Version control date");
180 else if (name_ == "time")
181 result = _("Version control time");
184 result = _("The current LyX version");
192 void InsetInfo::read(Lexer & lex)
197 token = lex.getString();
198 if (token == "type") {
200 token = lex.getString();
201 type_ = nameTranslator().find(token);
202 } else if (token == "arg") {
204 name_ = lex.getString();
205 } else if (token == "\\end_inset")
208 if (token != "\\end_inset") {
209 lex.printError("Missing \\end_inset at this point");
210 throw ExceptionMessage(WarningException,
211 _("Missing \\end_inset at this point."),
217 void InsetInfo::write(ostream & os) const
219 os << "Info\ntype \"" << infoType()
220 << "\"\narg " << Lexer::quoteString(name_);
224 bool InsetInfo::validateModifyArgument(docstring const & arg) const
227 string const name = trim(split(to_utf8(arg), type, ' '));
229 switch (nameTranslator().find(type)) {
236 FuncRequest func = lyxaction.lookupFunc(name);
237 return func.action() != LFUN_UNKNOWN_ACTION;
241 FuncCode const action = lyxaction.lookupFunc(name).action();
242 if (action == LFUN_UNKNOWN_ACTION) {
243 string dir = "images";
244 return !imageLibFileSearch(dir, name, "svgz,png").empty();
250 set<string> rcs = lyxrc.getRCs();
251 return rcs.find(name) != rcs.end();
259 return (name == "name" || name == "path" || name == "class");
262 if (name == "revision" || name == "tree-revision"
263 || name == "author" || name == "date" || name == "time")
264 return buffer().lyxvc().inUse();
268 return name == "version";
276 set<string> getTexFileList(string const & filename)
279 FileName const file = libFileSearch(string(), filename);
284 vector<docstring> doclist =
285 getVectorFromString(file.fileContents("UTF-8"), from_ascii("\n"));
287 // Normalise paths like /foo//bar ==> /foo/bar
288 for (auto doc : doclist) {
289 subst(doc, from_ascii("\r"), docstring());
290 while (contains(doc, from_ascii("//")))
291 subst(doc, from_ascii("//"), from_ascii("/"));
293 list.insert(removeExtension(onlyFileName(to_utf8(doc))));
302 vector<pair<string,docstring>> InsetInfo::getArguments(string const & type) const
304 vector<pair<string,docstring>> result;
306 switch (nameTranslator().find(type)) {
308 result.push_back(make_pair("invalid", _("Please select a valid type!")));
315 result.push_back(make_pair("custom", _("Custom")));
316 LyXAction::const_iterator fit = lyxaction.func_begin();
317 LyXAction::const_iterator const fen = lyxaction.func_end();
318 for (; fit != fen; ++fit) {
319 string const lfun = fit->first;
321 result.push_back(make_pair(lfun, from_ascii(lfun)));
327 result.push_back(make_pair("custom", _("Custom")));
328 set<string> rcs = lyxrc.getRCs();
329 for (auto const & rc : rcs)
330 result.push_back(make_pair(rc, from_ascii(rc)));
335 case TEXTCLASS_INFO: {
336 result.push_back(make_pair("custom", _("Custom")));
337 string const filename = (type == "package") ? "styFiles.lst"
339 set<string> flist = getTexFileList(filename);
340 for (auto const & f : flist)
341 result.push_back(make_pair(f, from_utf8(f)));
346 result.push_back(make_pair("name", _("File name")));
347 result.push_back(make_pair("path", _("File path")));
348 result.push_back(make_pair("class", _("Used text class")));
352 if (!buffer().lyxvc().inUse()) {
353 result.push_back(make_pair("invalid", _("No version control!")));
356 result.push_back(make_pair("revision", _("Revision[[Version Control]]")));
357 result.push_back(make_pair("tree-revision", _("Tree revision")));
358 result.push_back(make_pair("author", _("Author")));
359 result.push_back(make_pair("date", _("Date")));
360 result.push_back(make_pair("time", _("Time")));
365 result.push_back(make_pair("version", _("LyX version")));
373 bool InsetInfo::showInsetDialog(BufferView * bv) const
375 bv->showDialog("info");
380 bool InsetInfo::getStatus(Cursor & cur, FuncRequest const & cmd,
381 FuncStatus & flag) const
383 switch (cmd.action()) {
384 case LFUN_INSET_SETTINGS:
385 return InsetCollapsible::getStatus(cur, cmd, flag);
387 case LFUN_INSET_DIALOG_UPDATE:
388 case LFUN_INSET_COPY_AS:
389 flag.setEnabled(true);
392 case LFUN_INSET_MODIFY:
393 if (validateModifyArgument(cmd.argument())) {
394 flag.setEnabled(true);
405 void InsetInfo::doDispatch(Cursor & cur, FuncRequest & cmd)
407 switch (cmd.action()) {
408 case LFUN_INSET_MODIFY:
410 setInfo(to_utf8(cmd.argument()));
411 cur.forceBufferUpdate();
412 initialized_ = false;
415 case LFUN_INSET_COPY_AS: {
416 cap::clearSelection();
418 copy.pushBackward(*this);
422 copy.pit() = copy.lastpit();
423 copy.pos() = copy.lastpos();
425 cap::copySelection(copy);
430 InsetCollapsible::doDispatch(cur, cmd);
436 void InsetInfo::setInfo(string const & name)
442 name_ = trim(split(name, type, ' '));
443 type_ = nameTranslator().find(type);
447 void InsetInfo::error(docstring const & err, Language const * lang)
449 setText(bformat(translateIfPossible(err, lang->code()), from_utf8(name_)),
450 Font(inherit_font, lang), false);
454 void InsetInfo::info(docstring const & err, Language const * lang)
456 setText(translateIfPossible(err, lang->code()),
457 Font(inherit_font, lang), false);
461 void InsetInfo::setText(docstring const & str, Language const * lang)
463 setText(str, Font(inherit_font, lang), false);
467 bool InsetInfo::forceLTR() const
473 void InsetInfo::updateBuffer(ParIterator const & it, UpdateType utype) {
474 // If the Buffer is a clone, then we neither need nor want to do any
475 // of what follows. We want, rather, just to inherit how things were
476 // in the original Buffer. This is especially important for VCS.
477 // Otherwise, we could in principle have different settings here
478 // than in the Buffer we were exporting.
479 if (buffer().isClone())
482 BufferParams const & bp = buffer().params();
483 Language const * lang = it.paragraph().getFontSettings(bp, it.pos()).language();
484 Language const * tryguilang = languages.getFromCode(Messages::guiLanguage());
485 // Some info insets use the language of the GUI (if available)
486 Language const * guilang = tryguilang ? tryguilang : lang;
488 force_ltr_ = !lang->rightToLeft();
489 // This is just to get the string into the po files
493 gui = _("Unknown Info!");
494 info(from_ascii("Unknown Info!"), lang);
495 initialized_ = false;
498 case SHORTCUTS_INFO: {
499 // shortcuts can change, so we need to re-do this each time
500 FuncRequest const func = lyxaction.lookupFunc(name_);
501 if (func.action() == LFUN_UNKNOWN_ACTION) {
502 gui = _("Unknown action %1$s");
503 error(from_ascii("Unknown action %1$s"), lang);
506 KeyMap::Bindings bindings = theTopLevelKeymap().findBindings(func);
507 if (bindings.empty()) {
508 gui = _("undefined");
509 info(from_ascii("undefined"), lang);
512 if (type_ == SHORTCUT_INFO)
513 setText(bindings.begin()->print(KeySequence::Portable), guilang);
515 setText(theTopLevelKeymap().printBindings(func, KeySequence::Portable), guilang);
516 force_ltr_ = !guilang->rightToLeft() && !lang->rightToLeft();
520 // this information could change, if the preferences are changed,
521 // so we will recalculate each time through.
524 gui = _("undefined");
525 info(from_ascii("undefined"), lang);
528 // FIXME this uses the serialization mechanism to get the info
529 // we want, which i guess works but is a bit strange.
530 lyxrc.write(oss, true, name_);
531 string result = oss.str();
532 if (result.size() < 2) {
533 gui = _("undefined");
534 info(from_ascii("undefined"), lang);
537 string::size_type loc = result.rfind("\n", result.size() - 2);
538 loc = loc == string::npos ? 0 : loc + 1;
539 if (result.size() < loc + name_.size() + 1
540 || result.substr(loc + 1, name_.size()) != name_) {
541 gui = _("undefined");
542 info(from_ascii("undefined"), lang);
545 // remove leading comments and \\name and space
546 result = result.substr(loc + name_.size() + 2);
549 result = rtrim(result, "\n");
550 result = trim(result, "\"");
551 setText(from_utf8(result), lang);
555 // only need to do this once.
558 // check in packages.lst
559 if (LaTeXFeatures::isAvailable(name_)) {
561 info(from_ascii("yes"), lang);
564 info(from_ascii("no"), lang);
569 case TEXTCLASS_INFO: {
570 // the TextClass can change
571 LayoutFileList const & list = LayoutFileList::get();
572 bool available = false;
573 // name_ is the class name
574 if (list.haveClass(name_))
575 available = list[name_].isTeXClassAvailable();
578 info(from_ascii("yes"), lang);
581 info(from_ascii("no"), lang);
586 // only need to do this once.
589 // and we will not keep trying if we fail
591 docstring_list names;
592 FuncRequest const func = lyxaction.lookupFunc(name_);
593 if (func.action() == LFUN_UNKNOWN_ACTION) {
594 gui = _("Unknown action %1$s");
595 error(from_ascii("Unknown action %1$s"), lang);
598 // iterate through the menubackend to find it
600 gui = _("Can't determine menu entry for action %1$s in batch mode");
601 error(from_ascii("Can't determine menu entry for action %1$s in batch mode"), lang);
604 if (!theApp()->searchMenu(func, names)) {
605 gui = _("No menu entry for action %1$s");
606 error(from_ascii("No menu entry for action %1$s"), lang);
609 // if found, return its path.
611 Paragraph & par = paragraphs().front();
612 Font const f(inherit_font, guilang);
613 force_ltr_ = !guilang->rightToLeft();
615 //fu.fontInfo().setUnderbar(FONT_ON);
616 for (docstring const & name : names) {
617 // do not insert > for the top level menu item
618 if (&name != &names.front())
619 par.insertInset(par.size(), new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR),
620 f, Change(Change::UNCHANGED));
621 //FIXME: add proper underlines here. This
622 // involves rewriting searchMenu used above to
623 // return a vector of menus. If we do not do
624 // that, we might as well use below
625 // Paragraph::insert on each string (JMarc)
626 for (char_type c : name)
627 par.insertChar(par.size(), c, f, Change(Change::UNCHANGED));
632 // only need to do this once.
635 // and we will not keep trying if we fail
637 FuncRequest func = lyxaction.lookupFunc(name_);
638 docstring icon_name = frontend::Application::iconName(func, true);
639 // FIXME: We should use the icon directly instead of
640 // going through FileName. The code below won't work
641 // if the icon is embedded in the executable through
642 // the Qt resource system.
643 // This is only a negligible performance problem:
644 // If the installed icon differs from the resource icon the
645 // installed one is preferred anyway, and all icons that are
646 // embedded in the resources are installed as well.
647 FileName file(to_utf8(icon_name));
648 if (file.onlyFileNameWithoutExt() == "unknown") {
649 string dir = "images";
650 FileName file2(imageLibFileSearch(dir, name_, "svgz,png"));
656 int percent_scale = 100;
658 // Compute the scale factor for the icon such that its
659 // width on screen is equal to 1em in pixels.
660 // The scale factor is rounded to the integer nearest
661 // to the float value of the ratio 100*iconsize/imgsize.
662 int imgsize = QImage(toqstr(file.absFileName())).width();
664 int iconsize = Length(1, Length::EM).inPixels(1);
665 percent_scale = (100 * iconsize + imgsize / 2)/imgsize;
668 InsetGraphics * inset = new InsetGraphics(buffer_);
669 InsetGraphicsParams igp;
671 igp.lyxscale = percent_scale;
672 igp.scale = string();
673 igp.width = Length(1, Length::EM);
674 inset->setParams(igp);
676 Font const f(inherit_font, lang);
677 paragraphs().front().insertInset(0, inset, f,
678 Change(Change::UNCHANGED));
682 // this could all change, so we will recalculate each time
684 setText(from_utf8(buffer().fileName().onlyFileName()), lang);
685 else if (name_ == "path")
686 setText(from_utf8(os::latex_path(buffer().filePath())), lang);
687 else if (name_ == "class")
688 setText(from_utf8(bp.documentClass().name()), lang);
692 // this information could change, in principle, so we will
693 // recalculate each time through
694 if (!buffer().lyxvc().inUse()) {
695 gui = _("No version control!");
696 info(from_ascii("No version control!"), lang);
699 LyXVC::RevisionInfo itype = LyXVC::Unknown;
700 if (name_ == "revision")
702 else if (name_ == "tree-revision")
704 else if (name_ == "author")
705 itype = LyXVC::Author;
706 else if (name_ == "time")
708 else if (name_ == "date")
710 string binfo = buffer().lyxvc().revisionInfo(itype);
712 gui = _("%1$s[[vcs data]] unknown");
713 error(from_ascii("%1$s[[vcs data]] unknown"), lang);
715 setText(from_utf8(binfo), lang);
719 // only need to do this once.
722 if (name_ == "version")
723 setText(from_ascii(lyx_version), lang);
727 // Just to do something with that string
728 LYXERR(Debug::INFO, "info inset text: " << gui);
729 InsetCollapsible::updateBuffer(it, utype);
733 string InsetInfo::contextMenu(BufferView const &, int, int) const
735 //FIXME: We override the implementation of InsetCollapsible,
736 //because this inset is not a collapsible inset.
737 return contextMenuName();
741 string InsetInfo::contextMenuName() const
743 return "context-info";