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"
36 #include "TocBackend.h"
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
41 #include "graphics/PreviewLoader.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/ExceptionMessage.h"
46 #include "support/filetools.h"
47 #include "support/gettext.h"
48 #include "support/lassert.h"
49 #include "support/lstrings.h"
50 #include "support/lyxlib.h"
51 #include "support/TempFile.h"
57 using namespace lyx::support;
61 unsigned int const defaultLyxScale = 100;
63 string defaultTemplateName;
70 namespace Alert = frontend::Alert;
76 // must have an extension for the converter code to work correctly.
77 support::TempFile f("lyxextXXXXXX.tmp");
78 // Let f go out of scope here and delete the file ourselves in
79 // ~TempName(), since otherwise external processes would not be able
80 // to use the file on windows (bug 9925). This is not as safe as
81 // keeping a support::TempFile member would be, but the best we can do.
82 f.setAutoRemove(false);
87 TempName::TempName(TempName const & that)
95 tempname_.removeFile();
99 TempName & TempName::operator=(TempName const & other)
101 if (this != &other) {
102 if (!tempname_.empty())
103 tempname_.removeFile();
104 support::TempFile f("lyxextXXXXXX.tmp");
105 f.setAutoRemove(false);
106 tempname_ = f.name();
112 support::FileName TempName::operator()() const
117 } // namespace external
120 InsetExternalParams::InsetExternalParams()
122 preview_mode(PREVIEW_OFF),
123 lyxscale(defaultLyxScale),
126 if (defaultTemplateName.empty()) {
127 external::TemplateManager const & etm =
128 external::TemplateManager::get();
129 if (!etm.getTemplates().empty())
130 templatename_ = etm.getTemplates().begin()->first;
132 templatename_ = defaultTemplateName;
138 template <typename T>
139 void clearIfNotFound(T & data, external::TransformID value,
140 vector<external::TransformID> const & ids)
142 typedef vector<external::TransformID>::const_iterator
145 const_iterator it = ids.begin();
146 const_iterator end = ids.end();
147 it = find(it, end, value);
155 void InsetExternalParams::settemplate(string const & name)
157 templatename_ = name;
159 external::TemplateManager const & etm =
160 external::TemplateManager::get();
161 external::Template const * const et = etm.getTemplateByName(name);
163 // Be safe. Don't lose data.
166 // Ascertain which transforms the template supports.
167 // Empty all those that it doesn't.
168 vector<external::TransformID> const & ids = et->transformIds;
169 clearIfNotFound(clipdata, external::Clip, ids);
170 clearIfNotFound(extradata, external::Extra, ids);
171 clearIfNotFound(resizedata, external::Resize, ids);
172 clearIfNotFound(rotationdata, external::Rotate, ids);
175 preview_mode = et->preview_mode;
179 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
182 << "\ttemplate " << templatename() << '\n';
184 if (!filename.empty())
185 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
188 os << "\tdisplay false\n";
190 if (lyxscale != defaultLyxScale)
191 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
196 if (!clipdata.bbox.empty())
197 os << "\tboundingBox " << clipdata.bbox << '\n';
201 external::ExtraData::const_iterator it = extradata.begin();
202 external::ExtraData::const_iterator end = extradata.end();
203 for (; it != end; ++it) {
204 if (!it->second.empty())
205 os << "\textra " << it->first << " \""
206 << it->second << "\"\n";
209 if (!rotationdata.no_rotation()) {
210 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
211 if (rotationdata.origin() != external::RotationData::DEFAULT)
212 os << "\trotateOrigin "
213 << rotationdata.originString() << '\n';
216 if (!resizedata.no_resize()) {
217 double const scl = convert<double>(resizedata.scale);
218 if (!float_equal(scl, 0.0, 0.05)) {
219 if (!float_equal(scl, 100.0, 0.05))
221 << resizedata.scale << '\n';
223 if (!resizedata.width.zero())
225 << resizedata.width.asString() << '\n';
226 if (!resizedata.height.zero())
228 << resizedata.height.asString() << '\n';
230 if (resizedata.keepAspectRatio)
231 os << "\tkeepAspectRatio\n";
236 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
256 LexerKeyword external_tags[] = {
257 { "\\end_inset", EX_END },
258 { "boundingBox", EX_BOUNDINGBOX },
260 { "display", EX_DISPLAY},
261 { "draft", EX_DRAFT},
262 { "extra", EX_EXTRA },
263 { "filename", EX_FILENAME},
264 { "height", EX_HEIGHT },
265 { "keepAspectRatio", EX_KEEPASPECTRATIO },
266 { "lyxscale", EX_LYXSCALE},
267 { "rotateAngle", EX_ROTATEANGLE },
268 { "rotateOrigin", EX_ROTATEORIGIN },
269 { "scale", EX_SCALE },
270 { "template", EX_TEMPLATE },
271 { "width", EX_WIDTH }
274 PushPopHelper pph(lex, external_tags);
276 bool found_end = false;
277 bool read_error = false;
283 templatename_ = lex.getString();
288 string const name = lex.getString();
289 filename = buffer.getReferencedFileName(name);
295 display = lex.getString() != "false";
301 int const ls = lex.getInteger();
302 // negative values are not accepted.
306 lex.printError("ExternalInset::read: Wrong lyxscale: $$Token");
316 clipdata.bbox.xl = Length(lex.getString());
318 clipdata.bbox.yb = Length(lex.getString());
320 clipdata.bbox.xr = Length(lex.getString());
322 clipdata.bbox.yt = Length(lex.getString());
326 clipdata.clip = true;
331 string const name = lex.getString();
333 extradata.set(name, lex.getString());
339 resizedata.height = Length(lex.getString());
342 case EX_KEEPASPECTRATIO:
343 resizedata.keepAspectRatio = true;
348 rotationdata.angle = lex.getString();
351 case EX_ROTATEORIGIN:
353 rotationdata.origin(lex.getString());
358 resizedata.scale = lex.getString();
363 resizedata.width = Length(lex.getString());
371 lex.printError("ExternalInset::read: Wrong tag: $$Token");
376 if (found_end || read_error)
381 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
383 // This is a trick to make sure that the data are self-consistent.
384 settemplate(templatename_);
386 if (lyxerr.debugging(Debug::EXTERNAL)) {
387 lyxerr << "InsetExternalParams::read:\n";
388 write(buffer, lyxerr);
397 docstring screenLabel(InsetExternalParams const & params,
398 Buffer const & buffer)
400 external::Template const * const ptr =
401 external::getTemplatePtr(params);
404 return bformat((_("External template %1$s is not installed")),
405 from_utf8(params.templatename()));
407 docstring gui = _(ptr->guiName);
410 if (params.filename.empty())
413 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
421 InsetExternal::InsetExternal(Buffer * buf)
422 : Inset(buf), renderer_(new RenderButton)
427 // Mouse hover is not copied and remains empty
428 InsetExternal::InsetExternal(InsetExternal const & other)
430 params_(other.params_),
431 renderer_(other.renderer_->clone(this))
435 InsetExternal::~InsetExternal()
437 hideDialogs("external", this);
439 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
440 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
441 for (; it != end; ++it)
443 it->first->clearLastInset(this);
447 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
449 mouse_hover_[bv] = mouse_hover;
454 void InsetExternal::statusChanged() const
460 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
462 switch (cmd.action()) {
464 case LFUN_INSET_EDIT: {
465 InsetExternalParams p = params();
466 if (!cmd.argument().empty())
467 string2params(to_utf8(cmd.argument()), buffer(), p);
468 external::editExternal(p, buffer());
472 case LFUN_INSET_MODIFY: {
473 InsetExternalParams p;
474 string2params(to_utf8(cmd.argument()), buffer(), p);
480 case LFUN_INSET_DIALOG_UPDATE:
481 cur.bv().updateDialog("external",
482 params2string(params(), cur.bv().buffer()));
486 Inset::doDispatch(cur, cmd);
491 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
492 FuncStatus & flag) const
494 switch (cmd.action()) {
496 case LFUN_INSET_EDIT:
497 case LFUN_INSET_MODIFY:
498 case LFUN_INSET_DIALOG_UPDATE:
499 flag.setEnabled(true);
503 return Inset::getStatus(cur, cmd, flag);
508 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
509 UpdateType, TocBackend & backend) const
511 docstring str = screenLabel(params_, buffer());
512 TocBuilder & b = backend.builder("external");
513 b.pushItem(cpit, str, output_active);
518 bool InsetExternal::showInsetDialog(BufferView * bv) const
520 bv->showDialog("external", params2string(params(), bv->buffer()),
521 const_cast<InsetExternal *>(this));
526 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
528 if (!isRendererValid())
531 renderer_->metrics(mi, dim);
535 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
537 if (!isRendererValid())
540 if (renderer_->asButton())
541 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
542 renderer_->draw(pi, x, y);
548 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
550 graphics::Params gparams;
552 gparams.filename = eparams.filename;
553 gparams.scale = eparams.lyxscale;
554 if (eparams.clipdata.clip)
555 gparams.bb = eparams.clipdata.bbox;
556 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
557 gparams.display = eparams.display;
565 static bool isPreviewWanted(InsetExternalParams const & params)
567 return params.display && params.filename.isReadableFile();
571 static docstring latexString(InsetExternal const & inset)
573 odocstringstream ods;
575 // We don't need to set runparams.encoding since it is not used by
577 OutputParams runparams(0);
578 runparams.flavor = OutputParams::LATEX;
579 inset.latex(os, runparams);
584 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
585 InsetExternal const & inset,
586 Buffer const & buffer)
588 InsetExternalParams const & params = inset.params();
590 if (RenderPreview::previewText() && isPreviewWanted(params)) {
591 renderer.setAbsFile(params.filename);
592 docstring const snippet = latexString(inset);
593 renderer.addPreview(snippet, buffer);
594 renderer.startLoading(buffer);
599 InsetExternalParams const & InsetExternal::params() const
605 bool InsetExternal::isPreviewed() const
607 return (external::getTemplatePtr(params_) && !params_.filename.empty()
609 && lyxrc.display_graphics
610 && params_.preview_mode != PREVIEW_OFF
611 && (params_.preview_mode != PREVIEW_INSTANT
612 || RenderPreview::previewText()));
616 bool InsetExternal::isRendererValid() const
618 if (!renderer_->asButton())
619 return isPreviewed();
620 return !isPreviewed();
624 void InsetExternal::setParams(InsetExternalParams const & p)
628 // Subsequent calls to the InsetExternal::Params default constructor
630 defaultTemplateName = params_.templatename();
636 void InsetExternal::updatePreview() const
638 if (!isPreviewed()) {
639 RenderButton * button_ptr = renderer_->asButton();
641 renderer_.reset(new RenderButton);
642 button_ptr = renderer_->asButton();
644 button_ptr->update(screenLabel(params_, buffer()), true, false);
648 switch (params_.preview_mode) {
650 // Already taken care of above.
651 LASSERT(false, return);
653 case PREVIEW_INSTANT: {
654 renderer_ = make_unique<RenderMonitoredPreview>(this);
655 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
656 // This connection is closed at the same time as this is destroyed.
657 preview_ptr->connect([=]() { fileChanged(); });
658 add_preview_and_start_loading(*preview_ptr, *this, buffer());
661 case PREVIEW_GRAPHICS: {
662 RenderGraphic * graphic_ptr = renderer_->asGraphic();
664 renderer_.reset(new RenderGraphic(this));
665 graphic_ptr = renderer_->asGraphic();
667 graphic_ptr->update(get_grfx_params(params_));
674 void InsetExternal::fileChanged() const
676 Buffer const * const buffer = updateFrontend();
680 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
681 LASSERT(ptr, return);
683 ptr->removePreview(*buffer);
684 add_preview_and_start_loading(*ptr, *this, *buffer);
688 void InsetExternal::write(ostream & os) const
690 params_.write(buffer(), os);
694 void InsetExternal::read(Lexer & lex)
696 InsetExternalParams params;
697 if (params.read(buffer(), lex))
702 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
706 os << "\\fbox{\\ttfamily{}"
707 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
712 // "nice" means that the buffer is exported to LaTeX format but not
713 // run through the LaTeX compiler.
714 // If we're running through the LaTeX compiler, we should write the
715 // generated files in the buffer's temporary directory.
716 bool const external_in_tmpdir = !runparams.nice;
717 bool const dryrun = runparams.dryrun || runparams.inComment;
719 // If the template has specified a PDFLaTeX output, then we try and
721 if (runparams.flavor == OutputParams::PDFLATEX) {
722 external::Template const * const et_ptr =
723 external::getTemplatePtr(params_);
726 external::Template const & et = *et_ptr;
728 external::Template::Formats::const_iterator cit =
729 et.formats.find("PDFLaTeX");
731 if (cit != et.formats.end()) {
732 external::RetVal retval =
733 external::writeExternal(params_, "PDFLaTeX", buffer(), os,
734 *(runparams.exportdata), external_in_tmpdir, dryrun);
735 if (retval == external::KILLED) {
736 LYXERR0("External template preparation killed.");
737 if (buffer().isClone() && buffer().isExporting())
738 throw ConversionException();
744 external::RetVal retval =
745 external::writeExternal(params_, "LaTeX", buffer(), os,
746 *(runparams.exportdata), external_in_tmpdir, dryrun);
747 if (retval == external::KILLED) {
748 LYXERR0("External template preparation killed.");
749 if (buffer().isClone() && buffer().isExporting())
750 throw ConversionException();
755 int InsetExternal::plaintext(odocstringstream & os,
756 OutputParams const & runparams, size_t) const
758 // this is too slow for constant use
759 if (runparams.for_tooltip)
762 bool const external_in_tmpdir = !runparams.nice;
763 bool const dryrun = runparams.dryrun || runparams.inComment;
765 ots << '\n'; // output external material on a new line
766 external::RetVal retval =
767 external::writeExternal(params_, "Ascii", buffer(), ots,
768 *(runparams.exportdata), external_in_tmpdir, dryrun);
769 if (retval == external::KILLED) {
770 LYXERR0("External template preparation killed.");
771 if (buffer().isClone() && buffer().isExporting())
772 throw ConversionException();
774 return PLAINTEXT_NEWLINE;
778 int InsetExternal::docbook(odocstream & os,
779 OutputParams const & runparams) const
781 bool const external_in_tmpdir = !runparams.nice;
782 bool const dryrun = runparams.dryrun || runparams.inComment;
783 odocstringstream ods;
785 external::RetVal retval =
786 external::writeExternal(params_, "DocBook", buffer(), ots,
787 *(runparams.exportdata), external_in_tmpdir, dryrun);
788 if (retval == external::KILLED) {
789 LYXERR0("External template preparation killed.");
790 if (buffer().isClone() && buffer().isExporting())
791 throw ConversionException();
794 return int(count(ods.str().begin(), ods.str().end(), '\n'));
798 docstring InsetExternal::xhtml(XHTMLStream & xs,
799 OutputParams const & runparams) const
801 bool const external_in_tmpdir = !runparams.nice;
802 bool const dryrun = runparams.dryrun || runparams.inComment;
803 odocstringstream ods;
805 external::RetVal retval =
806 external::writeExternal(params_, "XHTML", buffer(), ots,
807 *(runparams.exportdata), external_in_tmpdir, dryrun);
808 if (retval == external::KILLED) {
809 LYXERR0("External template preparation killed.");
810 if (buffer().isClone() && buffer().isExporting())
811 throw ConversionException();
813 xs << XHTMLStream::ESCAPE_NONE << ods.str();
818 void InsetExternal::validate(LaTeXFeatures & features) const
823 external::Template const * const et_ptr =
824 external::getTemplatePtr(params_);
827 external::Template const & et = *et_ptr;
830 switch (features.runparams().flavor) {
831 case OutputParams::LATEX:
832 case OutputParams::DVILUATEX:
835 case OutputParams::LUATEX:
836 case OutputParams::PDFLATEX:
837 case OutputParams::XETEX:
840 case OutputParams::XML:
843 case OutputParams::HTML:
846 case OutputParams::TEXT:
849 case OutputParams::LYX:
853 external::Template::Formats::const_iterator cit =
854 et.formats.find(format);
856 if (cit == et.formats.end()) {
857 // If the template has not specified a PDFLaTeX output,
858 // we try the LaTeX format.
859 if (format == "PDFLaTeX") {
860 cit = et.formats.find("LaTeX");
861 if (cit == et.formats.end())
867 // FIXME: We don't need that always, see InsetGraphics
868 features.require("lyxdot");
870 vector<string>::const_iterator it = cit->second.requirements.begin();
871 vector<string>::const_iterator end = cit->second.requirements.end();
872 for (; it != end; ++it)
873 features.require(*it);
875 external::TemplateManager & etm = external::TemplateManager::get();
877 for (string const & name : cit->second.preambleNames) {
878 docstring const preamble = etm.getPreambleDefByName(name);
879 if (!preamble.empty())
880 features.addPreambleSnippet(preamble);
885 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
886 graphics::PreviewLoader & ploader) const
888 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
892 if (isPreviewWanted(params())) {
893 ptr->setAbsFile(params_.filename);
894 docstring const snippet = latexString(*this);
895 ptr->addPreview(snippet, ploader);
900 string InsetExternal::contextMenuName() const
902 return "context-external";
906 void InsetExternal::string2params(string const & in, Buffer const & buffer,
907 InsetExternalParams & params)
909 params = InsetExternalParams();
913 istringstream data(in);
919 if (!lex || name != "external") {
920 LYXERR0("InsetExternal::string2params(" << in << ")\n"
921 "Expected arg 1 to be \"external\"\n");
925 // This is part of the inset proper that is usually swallowed
926 // by Text::readInset
929 if (!lex || id != "External") {
930 LYXERR0("InsetExternal::string2params(" << in << ")\n"
931 "Expected arg 2 to be \"External\"\n");
935 params.read(buffer, lex);
939 string InsetExternal::params2string(InsetExternalParams const & params,
940 Buffer const & buffer)
943 data << "external" << ' ';
944 params.write(buffer, data);
945 data << "\\end_inset\n";