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::doDispatch(Cursor & cur, FuncRequest & cmd)
456 switch (cmd.action()) {
458 case LFUN_INSET_EDIT: {
459 InsetExternalParams p = params();
460 if (!cmd.argument().empty())
461 string2params(to_utf8(cmd.argument()), buffer(), p);
462 external::editExternal(p, buffer());
466 case LFUN_INSET_MODIFY: {
467 InsetExternalParams p;
468 string2params(to_utf8(cmd.argument()), buffer(), p);
474 case LFUN_INSET_DIALOG_UPDATE:
475 cur.bv().updateDialog("external",
476 params2string(params(), cur.bv().buffer()));
480 Inset::doDispatch(cur, cmd);
485 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
486 FuncStatus & flag) const
488 switch (cmd.action()) {
490 case LFUN_INSET_EDIT:
491 case LFUN_INSET_MODIFY:
492 case LFUN_INSET_DIALOG_UPDATE:
493 flag.setEnabled(true);
497 return Inset::getStatus(cur, cmd, flag);
502 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
503 UpdateType, TocBackend & backend) const
505 docstring str = screenLabel(params_, buffer());
506 TocBuilder & b = backend.builder("external");
507 b.pushItem(cpit, str, output_active);
512 bool InsetExternal::showInsetDialog(BufferView * bv) const
514 bv->showDialog("external", params2string(params(), bv->buffer()),
515 const_cast<InsetExternal *>(this));
520 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
522 if (!isRendererValid())
525 renderer_->metrics(mi, dim);
529 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
531 if (!isRendererValid())
534 if (renderer_->asButton())
535 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
536 renderer_->draw(pi, x, y);
542 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
544 graphics::Params gparams;
546 gparams.filename = eparams.filename;
547 gparams.scale = eparams.lyxscale;
548 if (eparams.clipdata.clip)
549 gparams.bb = eparams.clipdata.bbox;
550 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
551 gparams.display = eparams.display;
559 static bool isPreviewWanted(InsetExternalParams const & params)
561 return params.display && params.filename.isReadableFile();
565 static docstring latexString(InsetExternal const & inset)
567 odocstringstream ods;
569 // We don't need to set runparams.encoding since it is not used by
571 OutputParams runparams(0);
572 runparams.flavor = OutputParams::LATEX;
573 inset.latex(os, runparams);
578 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
579 InsetExternal const & inset,
580 Buffer const & buffer)
582 InsetExternalParams const & params = inset.params();
584 if (RenderPreview::previewText() && isPreviewWanted(params)) {
585 renderer.setAbsFile(params.filename);
586 docstring const snippet = latexString(inset);
587 renderer.addPreview(snippet, buffer);
588 renderer.startLoading(buffer);
593 InsetExternalParams const & InsetExternal::params() const
599 bool InsetExternal::isPreviewed() const
601 return (external::getTemplatePtr(params_) && !params_.filename.empty()
603 && lyxrc.display_graphics
604 && params_.preview_mode != PREVIEW_OFF
605 && (params_.preview_mode != PREVIEW_INSTANT
606 || RenderPreview::previewText()));
610 bool InsetExternal::isRendererValid() const
612 if (!renderer_->asButton())
613 return isPreviewed();
614 return !isPreviewed();
618 void InsetExternal::setParams(InsetExternalParams const & p)
622 // Subsequent calls to the InsetExternal::Params default constructor
624 defaultTemplateName = params_.templatename();
630 void InsetExternal::updatePreview() const
632 if (!isPreviewed()) {
633 RenderButton * button_ptr = renderer_->asButton();
635 renderer_.reset(new RenderButton);
636 button_ptr = renderer_->asButton();
638 button_ptr->update(screenLabel(params_, buffer()), true, false);
642 switch (params_.preview_mode) {
644 // Already taken care of above.
645 LASSERT(false, return);
647 case PREVIEW_INSTANT: {
648 renderer_ = make_unique<RenderMonitoredPreview>(this);
649 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
650 // This connection is closed at the same time as this is destroyed.
651 preview_ptr->connect([=]() { fileChanged(); });
652 add_preview_and_start_loading(*preview_ptr, *this, buffer());
655 case PREVIEW_GRAPHICS: {
656 RenderGraphic * graphic_ptr = renderer_->asGraphic();
658 renderer_.reset(new RenderGraphic(this));
659 graphic_ptr = renderer_->asGraphic();
661 graphic_ptr->update(get_grfx_params(params_));
668 void InsetExternal::fileChanged() const
670 Buffer const * const buffer = updateFrontend();
674 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
675 LASSERT(ptr, return);
677 ptr->removePreview(*buffer);
678 add_preview_and_start_loading(*ptr, *this, *buffer);
682 void InsetExternal::write(ostream & os) const
684 params_.write(buffer(), os);
688 void InsetExternal::read(Lexer & lex)
690 InsetExternalParams params;
691 if (params.read(buffer(), lex))
696 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
700 os << "\\fbox{\\ttfamily{}"
701 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
706 // "nice" means that the buffer is exported to LaTeX format but not
707 // run through the LaTeX compiler.
708 // If we're running through the LaTeX compiler, we should write the
709 // generated files in the buffer's temporary directory.
710 bool const external_in_tmpdir = !runparams.nice;
711 bool const dryrun = runparams.dryrun || runparams.inComment;
713 // If the template has specified a PDFLaTeX output, then we try and
715 if (runparams.flavor == OutputParams::PDFLATEX) {
716 external::Template const * const et_ptr =
717 external::getTemplatePtr(params_);
720 external::Template const & et = *et_ptr;
722 external::Template::Formats::const_iterator cit =
723 et.formats.find("PDFLaTeX");
725 if (cit != et.formats.end()) {
726 external::RetVal retval =
727 external::writeExternal(params_, "PDFLaTeX", buffer(), os,
728 *(runparams.exportdata), external_in_tmpdir, dryrun);
729 if (retval == external::KILLED) {
730 LYXERR0("External template preparation killed.");
731 if (buffer().isClone() && buffer().isExporting())
732 throw ConversionException();
738 external::RetVal retval =
739 external::writeExternal(params_, "LaTeX", buffer(), os,
740 *(runparams.exportdata), external_in_tmpdir, dryrun);
741 if (retval == external::KILLED) {
742 LYXERR0("External template preparation killed.");
743 if (buffer().isClone() && buffer().isExporting())
744 throw ConversionException();
749 int InsetExternal::plaintext(odocstringstream & os,
750 OutputParams const & runparams, size_t) const
752 // this is too slow for constant use
753 if (runparams.for_tooltip)
756 bool const external_in_tmpdir = !runparams.nice;
757 bool const dryrun = runparams.dryrun || runparams.inComment;
759 ots << '\n'; // output external material on a new line
760 external::RetVal retval =
761 external::writeExternal(params_, "Ascii", buffer(), ots,
762 *(runparams.exportdata), external_in_tmpdir, dryrun);
763 if (retval == external::KILLED) {
764 LYXERR0("External template preparation killed.");
765 if (buffer().isClone() && buffer().isExporting())
766 throw ConversionException();
768 return PLAINTEXT_NEWLINE;
772 int InsetExternal::docbook(odocstream & os,
773 OutputParams const & runparams) const
775 bool const external_in_tmpdir = !runparams.nice;
776 bool const dryrun = runparams.dryrun || runparams.inComment;
777 odocstringstream ods;
779 external::RetVal retval =
780 external::writeExternal(params_, "DocBook", buffer(), ots,
781 *(runparams.exportdata), external_in_tmpdir, dryrun);
782 if (retval == external::KILLED) {
783 LYXERR0("External template preparation killed.");
784 if (buffer().isClone() && buffer().isExporting())
785 throw ConversionException();
788 return int(count(ods.str().begin(), ods.str().end(), '\n'));
792 docstring InsetExternal::xhtml(XHTMLStream & xs,
793 OutputParams const & runparams) const
795 bool const external_in_tmpdir = !runparams.nice;
796 bool const dryrun = runparams.dryrun || runparams.inComment;
797 odocstringstream ods;
799 external::RetVal retval =
800 external::writeExternal(params_, "XHTML", buffer(), ots,
801 *(runparams.exportdata), external_in_tmpdir, dryrun);
802 if (retval == external::KILLED) {
803 LYXERR0("External template preparation killed.");
804 if (buffer().isClone() && buffer().isExporting())
805 throw ConversionException();
807 xs << XHTMLStream::ESCAPE_NONE << ods.str();
812 void InsetExternal::validate(LaTeXFeatures & features) const
817 external::Template const * const et_ptr =
818 external::getTemplatePtr(params_);
821 external::Template const & et = *et_ptr;
824 switch (features.runparams().flavor) {
825 case OutputParams::LATEX:
826 case OutputParams::DVILUATEX:
829 case OutputParams::LUATEX:
830 case OutputParams::PDFLATEX:
831 case OutputParams::XETEX:
834 case OutputParams::XML:
837 case OutputParams::HTML:
840 case OutputParams::TEXT:
843 case OutputParams::LYX:
847 external::Template::Formats::const_iterator cit =
848 et.formats.find(format);
850 if (cit == et.formats.end()) {
851 // If the template has not specified a PDFLaTeX output,
852 // we try the LaTeX format.
853 if (format == "PDFLaTeX") {
854 cit = et.formats.find("LaTeX");
855 if (cit == et.formats.end())
861 // FIXME: We don't need that always, see InsetGraphics
862 features.require("lyxdot");
864 vector<string>::const_iterator it = cit->second.requirements.begin();
865 vector<string>::const_iterator end = cit->second.requirements.end();
866 for (; it != end; ++it)
867 features.require(*it);
869 external::TemplateManager & etm = external::TemplateManager::get();
871 for (string const & name : cit->second.preambleNames) {
872 docstring const preamble = etm.getPreambleDefByName(name);
873 if (!preamble.empty())
874 features.addPreambleSnippet(preamble);
879 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
880 graphics::PreviewLoader & ploader) const
882 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
886 if (isPreviewWanted(params())) {
887 ptr->setAbsFile(params_.filename);
888 docstring const snippet = latexString(*this);
889 ptr->addPreview(snippet, ploader);
894 string InsetExternal::contextMenuName() const
896 return "context-external";
900 void InsetExternal::string2params(string const & in, Buffer const & buffer,
901 InsetExternalParams & params)
903 params = InsetExternalParams();
907 istringstream data(in);
913 if (!lex || name != "external") {
914 LYXERR0("InsetExternal::string2params(" << in << ")\n"
915 "Expected arg 1 to be \"external\"\n");
919 // This is part of the inset proper that is usually swallowed
920 // by Text::readInset
923 if (!lex || id != "External") {
924 LYXERR0("InsetExternal::string2params(" << in << ")\n"
925 "Expected arg 2 to be \"External\"\n");
929 params.read(buffer, lex);
933 string InsetExternal::params2string(InsetExternalParams const & params,
934 Buffer const & buffer)
937 data << "external" << ' ';
938 params.write(buffer, data);
939 data << "\\end_inset\n";