2 * \file InsetExternal.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup Nielsen
8 * Full author contact details are available in file CREDITS.
13 #include "InsetExternal.h"
14 #include "insets/ExternalSupport.h"
15 #include "insets/RenderButton.h"
16 #include "insets/RenderGraphic.h"
17 #include "insets/RenderPreview.h"
20 #include "BufferView.h"
21 #include "Converter.h"
23 #include "DispatchResult.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "LaTeXFeatures.h"
29 #include "LyX.h" // use_gui
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
33 #include "output_latex.h"
34 #include "output_xhtml.h"
35 #include "texstream.h"
37 #include "TocBackend.h"
39 #include "frontends/alert.h"
40 #include "frontends/Application.h"
42 #include "graphics/PreviewLoader.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/ExceptionMessage.h"
47 #include "support/filetools.h"
48 #include "support/gettext.h"
49 #include "support/lassert.h"
50 #include "support/lstrings.h"
51 #include "support/lyxlib.h"
52 #include "support/TempFile.h"
58 using namespace lyx::support;
62 unsigned int const defaultLyxScale = 100;
64 string defaultTemplateName;
71 namespace Alert = frontend::Alert;
77 // must have an extension for the converter code to work correctly.
78 support::TempFile f("lyxextXXXXXX.tmp");
79 // Let f go out of scope here and delete the file ourselves in
80 // ~TempName(), since otherwise external processes would not be able
81 // to use the file on windows (bug 9925). This is not as safe as
82 // keeping a support::TempFile member would be, but the best we can do.
83 f.setAutoRemove(false);
88 TempName::TempName(TempName const & that)
96 tempname_.removeFile();
100 TempName & TempName::operator=(TempName const & other)
102 if (this != &other) {
103 if (!tempname_.empty())
104 tempname_.removeFile();
105 support::TempFile f("lyxextXXXXXX.tmp");
106 f.setAutoRemove(false);
107 tempname_ = f.name();
113 support::FileName TempName::operator()() const
118 } // namespace external
121 InsetExternalParams::InsetExternalParams()
123 preview_mode(PREVIEW_OFF),
124 lyxscale(defaultLyxScale),
127 if (defaultTemplateName.empty()) {
128 external::TemplateManager const & etm =
129 external::TemplateManager::get();
130 if (!etm.getTemplates().empty())
131 templatename_ = etm.getTemplates().begin()->first;
133 templatename_ = defaultTemplateName;
139 template <typename T>
140 void clearIfNotFound(T & data, external::TransformID value,
141 vector<external::TransformID> const & ids)
143 typedef vector<external::TransformID>::const_iterator
146 const_iterator it = ids.begin();
147 const_iterator end = ids.end();
148 it = find(it, end, value);
156 void InsetExternalParams::settemplate(string const & name)
158 templatename_ = name;
160 external::TemplateManager const & etm =
161 external::TemplateManager::get();
162 external::Template const * const et = etm.getTemplateByName(name);
164 // Be safe. Don't lose data.
167 // Ascertain which transforms the template supports.
168 // Empty all those that it doesn't.
169 vector<external::TransformID> const & ids = et->transformIds;
170 clearIfNotFound(clipdata, external::Clip, ids);
171 clearIfNotFound(extradata, external::Extra, ids);
172 clearIfNotFound(resizedata, external::Resize, ids);
173 clearIfNotFound(rotationdata, external::Rotate, ids);
176 preview_mode = et->preview_mode;
180 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
183 << "\ttemplate " << templatename() << '\n';
185 if (!filename.empty())
186 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
189 os << "\tdisplay false\n";
191 if (lyxscale != defaultLyxScale)
192 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
197 if (!clipdata.bbox.empty())
198 os << "\tboundingBox " << clipdata.bbox << '\n';
202 external::ExtraData::const_iterator it = extradata.begin();
203 external::ExtraData::const_iterator end = extradata.end();
204 for (; it != end; ++it) {
205 if (!it->second.empty())
206 os << "\textra " << it->first << " \""
207 << it->second << "\"\n";
210 if (!rotationdata.no_rotation()) {
211 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
212 if (rotationdata.origin() != external::RotationData::DEFAULT)
213 os << "\trotateOrigin "
214 << rotationdata.originString() << '\n';
217 if (!resizedata.no_resize()) {
218 double const scl = convert<double>(resizedata.scale);
219 if (!float_equal(scl, 0.0, 0.05)) {
220 if (!float_equal(scl, 100.0, 0.05))
222 << resizedata.scale << '\n';
224 if (!resizedata.width.zero())
226 << resizedata.width.asString() << '\n';
227 if (!resizedata.height.zero())
229 << resizedata.height.asString() << '\n';
231 if (resizedata.keepAspectRatio)
232 os << "\tkeepAspectRatio\n";
237 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
257 LexerKeyword external_tags[] = {
258 { "\\end_inset", EX_END },
259 { "boundingBox", EX_BOUNDINGBOX },
261 { "display", EX_DISPLAY},
262 { "draft", EX_DRAFT},
263 { "extra", EX_EXTRA },
264 { "filename", EX_FILENAME},
265 { "height", EX_HEIGHT },
266 { "keepAspectRatio", EX_KEEPASPECTRATIO },
267 { "lyxscale", EX_LYXSCALE},
268 { "rotateAngle", EX_ROTATEANGLE },
269 { "rotateOrigin", EX_ROTATEORIGIN },
270 { "scale", EX_SCALE },
271 { "template", EX_TEMPLATE },
272 { "width", EX_WIDTH }
275 PushPopHelper pph(lex, external_tags);
277 bool found_end = false;
278 bool read_error = false;
284 templatename_ = lex.getString();
289 string const name = lex.getString();
290 filename = buffer.getReferencedFileName(name);
296 display = lex.getString() != "false";
302 int const ls = lex.getInteger();
303 // negative values are not accepted.
307 lex.printError("ExternalInset::read: Wrong lyxscale: $$Token");
317 clipdata.bbox.xl = Length(lex.getString());
319 clipdata.bbox.yb = Length(lex.getString());
321 clipdata.bbox.xr = Length(lex.getString());
323 clipdata.bbox.yt = Length(lex.getString());
327 clipdata.clip = true;
332 string const name = lex.getString();
334 extradata.set(name, lex.getString());
340 resizedata.height = Length(lex.getString());
343 case EX_KEEPASPECTRATIO:
344 resizedata.keepAspectRatio = true;
349 rotationdata.angle = lex.getString();
352 case EX_ROTATEORIGIN:
354 rotationdata.origin(lex.getString());
359 resizedata.scale = lex.getString();
364 resizedata.width = Length(lex.getString());
372 lex.printError("ExternalInset::read: Wrong tag: $$Token");
377 if (found_end || read_error)
382 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
384 // This is a trick to make sure that the data are self-consistent.
385 settemplate(templatename_);
387 if (lyxerr.debugging(Debug::EXTERNAL)) {
388 lyxerr << "InsetExternalParams::read:\n";
389 write(buffer, lyxerr);
398 docstring screenLabel(InsetExternalParams const & params,
399 Buffer const & buffer)
401 external::Template const * const ptr =
402 external::getTemplatePtr(params);
405 return bformat((_("External template %1$s is not installed")),
406 from_utf8(params.templatename()));
408 docstring gui = _(ptr->guiName);
411 if (params.filename.empty())
414 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
422 InsetExternal::InsetExternal(Buffer * buf)
423 : Inset(buf), renderer_(new RenderButton)
428 // Mouse hover is not copied and remains empty
429 InsetExternal::InsetExternal(InsetExternal const & other)
431 params_(other.params_),
432 renderer_(other.renderer_->clone(this))
436 InsetExternal::~InsetExternal()
438 hideDialogs("external", this);
440 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
441 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
442 for (; it != end; ++it)
444 it->first->clearLastInset(this);
448 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
450 mouse_hover_[bv] = mouse_hover;
455 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
457 switch (cmd.action()) {
459 case LFUN_INSET_EDIT: {
460 InsetExternalParams p = params();
461 if (!cmd.argument().empty())
462 string2params(to_utf8(cmd.argument()), buffer(), p);
463 external::editExternal(p, buffer());
467 case LFUN_INSET_MODIFY: {
468 InsetExternalParams p;
469 string2params(to_utf8(cmd.argument()), buffer(), p);
475 case LFUN_INSET_DIALOG_UPDATE:
476 cur.bv().updateDialog("external",
477 params2string(params(), cur.bv().buffer()));
481 Inset::doDispatch(cur, cmd);
486 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
487 FuncStatus & flag) const
489 switch (cmd.action()) {
491 case LFUN_INSET_EDIT:
492 case LFUN_INSET_MODIFY:
493 case LFUN_INSET_DIALOG_UPDATE:
494 flag.setEnabled(true);
498 return Inset::getStatus(cur, cmd, flag);
503 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
504 UpdateType, TocBackend & backend) const
506 docstring str = screenLabel(params_, buffer());
507 TocBuilder & b = backend.builder("external");
508 b.pushItem(cpit, str, output_active);
513 bool InsetExternal::showInsetDialog(BufferView * bv) const
515 bv->showDialog("external", params2string(params(), bv->buffer()),
516 const_cast<InsetExternal *>(this));
521 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
523 if (!isRendererValid())
526 renderer_->metrics(mi, dim);
530 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
532 if (!isRendererValid())
535 if (renderer_->asButton())
536 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
537 renderer_->draw(pi, x, y);
543 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
545 graphics::Params gparams;
547 gparams.filename = eparams.filename;
548 gparams.scale = eparams.lyxscale;
549 if (eparams.clipdata.clip)
550 gparams.bb = eparams.clipdata.bbox;
551 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
552 gparams.display = eparams.display;
560 static bool isPreviewWanted(InsetExternalParams const & params)
562 return params.display && params.filename.isReadableFile();
566 static docstring latexString(InsetExternal const & inset)
568 odocstringstream ods;
570 // We don't need to set runparams.encoding since it is not used by
572 OutputParams runparams(0);
573 runparams.flavor = OutputParams::LATEX;
574 inset.latex(os, runparams);
579 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
580 InsetExternal const & inset,
581 Buffer const & buffer)
583 InsetExternalParams const & params = inset.params();
585 if (RenderPreview::previewText() && isPreviewWanted(params)) {
586 renderer.setAbsFile(params.filename);
587 docstring const snippet = latexString(inset);
588 renderer.addPreview(snippet, buffer);
589 renderer.startLoading(buffer);
594 InsetExternalParams const & InsetExternal::params() const
600 bool InsetExternal::isPreviewed() const
602 return (external::getTemplatePtr(params_) && !params_.filename.empty()
604 && lyxrc.display_graphics
605 && params_.preview_mode != PREVIEW_OFF
606 && (params_.preview_mode != PREVIEW_INSTANT
607 || RenderPreview::previewText()));
611 bool InsetExternal::isRendererValid() const
613 if (!renderer_->asButton())
614 return isPreviewed();
615 return !isPreviewed();
619 void InsetExternal::setParams(InsetExternalParams const & p)
623 // Subsequent calls to the InsetExternal::Params default constructor
625 defaultTemplateName = params_.templatename();
631 void InsetExternal::updatePreview() const
633 if (!isPreviewed()) {
634 RenderButton * button_ptr = renderer_->asButton();
636 renderer_.reset(new RenderButton);
637 button_ptr = renderer_->asButton();
639 button_ptr->update(screenLabel(params_, buffer()), true, false);
643 switch (params_.preview_mode) {
645 // Already taken care of above.
646 LASSERT(false, return);
648 case PREVIEW_INSTANT: {
649 renderer_ = make_unique<RenderMonitoredPreview>(this);
650 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
651 // This connection is closed at the same time as this is destroyed.
652 preview_ptr->connect([=]() { fileChanged(); });
653 add_preview_and_start_loading(*preview_ptr, *this, buffer());
656 case PREVIEW_GRAPHICS: {
657 RenderGraphic * graphic_ptr = renderer_->asGraphic();
659 renderer_.reset(new RenderGraphic(this));
660 graphic_ptr = renderer_->asGraphic();
662 graphic_ptr->update(get_grfx_params(params_));
669 void InsetExternal::fileChanged() const
671 Buffer const * const buffer = updateFrontend();
675 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
676 LASSERT(ptr, return);
678 ptr->removePreview(*buffer);
679 add_preview_and_start_loading(*ptr, *this, *buffer);
683 void InsetExternal::write(ostream & os) const
685 params_.write(buffer(), os);
689 void InsetExternal::read(Lexer & lex)
691 InsetExternalParams params;
692 if (params.read(buffer(), lex))
697 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
701 os << "\\fbox{\\ttfamily{}"
702 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
707 // "nice" means that the buffer is exported to LaTeX format but not
708 // run through the LaTeX compiler.
709 // If we're running through the LaTeX compiler, we should write the
710 // generated files in the buffer's temporary directory.
711 bool const external_in_tmpdir = !runparams.nice;
712 bool const dryrun = runparams.dryrun || runparams.inComment;
714 // If the template has specified a PDFLaTeX output, then we try and
716 if (runparams.flavor == OutputParams::PDFLATEX) {
717 external::Template const * const et_ptr =
718 external::getTemplatePtr(params_);
721 external::Template const & et = *et_ptr;
723 external::Template::Formats::const_iterator cit =
724 et.formats.find("PDFLaTeX");
726 if (cit != et.formats.end()) {
727 external::RetVal retval =
728 external::writeExternal(params_, "PDFLaTeX", buffer(), os,
729 *(runparams.exportdata), external_in_tmpdir, dryrun);
730 if (retval == external::KILLED) {
731 LYXERR0("External template preparation killed.");
732 if (buffer().isClone() && buffer().isExporting())
733 throw ConversionException();
739 external::RetVal retval =
740 external::writeExternal(params_, "LaTeX", buffer(), os,
741 *(runparams.exportdata), external_in_tmpdir, dryrun);
742 if (retval == external::KILLED) {
743 LYXERR0("External template preparation killed.");
744 if (buffer().isClone() && buffer().isExporting())
745 throw ConversionException();
750 int InsetExternal::plaintext(odocstringstream & os,
751 OutputParams const & runparams, size_t) const
753 // this is too slow for constant use
754 if (runparams.for_tooltip)
757 bool const external_in_tmpdir = !runparams.nice;
758 bool const dryrun = runparams.dryrun || runparams.inComment;
760 ots << '\n'; // output external material on a new line
761 external::RetVal retval =
762 external::writeExternal(params_, "Ascii", buffer(), ots,
763 *(runparams.exportdata), external_in_tmpdir, dryrun);
764 if (retval == external::KILLED) {
765 LYXERR0("External template preparation killed.");
766 if (buffer().isClone() && buffer().isExporting())
767 throw ConversionException();
769 return PLAINTEXT_NEWLINE;
773 int InsetExternal::docbook(odocstream & os,
774 OutputParams const & runparams) const
776 bool const external_in_tmpdir = !runparams.nice;
777 bool const dryrun = runparams.dryrun || runparams.inComment;
778 odocstringstream ods;
780 external::RetVal retval =
781 external::writeExternal(params_, "DocBook", buffer(), ots,
782 *(runparams.exportdata), external_in_tmpdir, dryrun);
783 if (retval == external::KILLED) {
784 LYXERR0("External template preparation killed.");
785 if (buffer().isClone() && buffer().isExporting())
786 throw ConversionException();
789 return int(count(ods.str().begin(), ods.str().end(), '\n'));
793 docstring InsetExternal::xhtml(XMLStream & xs,
794 OutputParams const & runparams) const
796 bool const external_in_tmpdir = !runparams.nice;
797 bool const dryrun = runparams.dryrun || runparams.inComment;
798 odocstringstream ods;
800 external::RetVal retval =
801 external::writeExternal(params_, "XHTML", buffer(), ots,
802 *(runparams.exportdata), external_in_tmpdir, dryrun);
803 if (retval == external::KILLED) {
804 LYXERR0("External template preparation killed.");
805 if (buffer().isClone() && buffer().isExporting())
806 throw ConversionException();
808 xs << XMLStream::ESCAPE_NONE << ods.str();
813 void InsetExternal::validate(LaTeXFeatures & features) const
818 external::Template const * const et_ptr =
819 external::getTemplatePtr(params_);
822 external::Template const & et = *et_ptr;
825 switch (features.runparams().flavor) {
826 case OutputParams::LATEX:
827 case OutputParams::DVILUATEX:
830 case OutputParams::LUATEX:
831 case OutputParams::PDFLATEX:
832 case OutputParams::XETEX:
835 case OutputParams::XML:
838 case OutputParams::HTML:
841 case OutputParams::TEXT:
844 case OutputParams::LYX:
848 external::Template::Formats::const_iterator cit =
849 et.formats.find(format);
851 if (cit == et.formats.end()) {
852 // If the template has not specified a PDFLaTeX output,
853 // we try the LaTeX format.
854 if (format == "PDFLaTeX") {
855 cit = et.formats.find("LaTeX");
856 if (cit == et.formats.end())
862 // FIXME: We don't need that always, see InsetGraphics
863 features.require("lyxdot");
865 vector<string>::const_iterator it = cit->second.requirements.begin();
866 vector<string>::const_iterator end = cit->second.requirements.end();
867 for (; it != end; ++it)
868 features.require(*it);
870 external::TemplateManager & etm = external::TemplateManager::get();
872 for (string const & name : cit->second.preambleNames) {
873 docstring const preamble = etm.getPreambleDefByName(name);
874 if (!preamble.empty())
875 features.addPreambleSnippet(preamble);
880 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
881 graphics::PreviewLoader & ploader) const
883 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
887 if (isPreviewWanted(params())) {
888 ptr->setAbsFile(params_.filename);
889 docstring const snippet = latexString(*this);
890 ptr->addPreview(snippet, ploader);
895 string InsetExternal::contextMenuName() const
897 return "context-external";
901 void InsetExternal::string2params(string const & in, Buffer const & buffer,
902 InsetExternalParams & params)
904 params = InsetExternalParams();
908 istringstream data(in);
914 if (!lex || name != "external") {
915 LYXERR0("InsetExternal::string2params(" << in << ")\n"
916 "Expected arg 1 to be \"external\"\n");
920 // This is part of the inset proper that is usually swallowed
921 // by Text::readInset
924 if (!lex || id != "External") {
925 LYXERR0("InsetExternal::string2params(" << in << ")\n"
926 "Expected arg 2 to be \"External\"\n");
930 params.read(buffer, lex);
934 string InsetExternal::params2string(InsetExternalParams const & params,
935 Buffer const & buffer)
938 data << "external" << ' ';
939 params.write(buffer, data);
940 data << "\\end_inset\n";