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"
22 #include "DispatchResult.h"
24 #include "FuncStatus.h"
25 #include "FuncRequest.h"
26 #include "LaTeXFeatures.h"
28 #include "LyX.h" // use_gui
30 #include "MetricsInfo.h"
31 #include "OutputParams.h"
32 #include "output_latex.h"
33 #include "output_xhtml.h"
34 #include "texstream.h"
35 #include "TocBackend.h"
37 #include "frontends/alert.h"
38 #include "frontends/Application.h"
40 #include "graphics/PreviewLoader.h"
42 #include "support/convert.h"
43 #include "support/debug.h"
44 #include "support/ExceptionMessage.h"
45 #include "support/filetools.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49 #include "support/lyxlib.h"
50 #include "support/TempFile.h"
56 using namespace lyx::support;
60 unsigned int const defaultLyxScale = 100;
62 string defaultTemplateName;
69 namespace Alert = frontend::Alert;
75 // must have an extension for the converter code to work correctly.
76 support::TempFile f("lyxextXXXXXX.tmp");
77 // Let f go out of scope here and delete the file ourselves in
78 // ~TempName(), since otherwise external processes would not be able
79 // to use the file on windows (bug 9925). This is not as safe as
80 // keeping a support::TempFile member would be, but the best we can do.
81 f.setAutoRemove(false);
86 TempName::TempName(TempName const & that)
94 tempname_.removeFile();
98 TempName & TempName::operator=(TempName const & other)
100 if (this != &other) {
101 if (!tempname_.empty())
102 tempname_.removeFile();
103 support::TempFile f("lyxextXXXXXX.tmp");
104 f.setAutoRemove(false);
105 tempname_ = f.name();
111 support::FileName TempName::operator()() const
116 } // namespace external
119 InsetExternalParams::InsetExternalParams()
121 preview_mode(PREVIEW_OFF),
122 lyxscale(defaultLyxScale),
125 if (defaultTemplateName.empty()) {
126 external::TemplateManager const & etm =
127 external::TemplateManager::get();
128 if (!etm.getTemplates().empty())
129 templatename_ = etm.getTemplates().begin()->first;
131 templatename_ = defaultTemplateName;
137 template <typename T>
138 void clearIfNotFound(T & data, external::TransformID value,
139 vector<external::TransformID> const & ids)
141 typedef vector<external::TransformID>::const_iterator
144 const_iterator it = ids.begin();
145 const_iterator end = ids.end();
146 it = find(it, end, value);
154 void InsetExternalParams::settemplate(string const & name)
156 templatename_ = name;
158 external::TemplateManager const & etm =
159 external::TemplateManager::get();
160 external::Template const * const et = etm.getTemplateByName(name);
162 // Be safe. Don't lose data.
165 // Ascertain which transforms the template supports.
166 // Empty all those that it doesn't.
167 vector<external::TransformID> const & ids = et->transformIds;
168 clearIfNotFound(clipdata, external::Clip, ids);
169 clearIfNotFound(extradata, external::Extra, ids);
170 clearIfNotFound(resizedata, external::Resize, ids);
171 clearIfNotFound(rotationdata, external::Rotate, ids);
174 preview_mode = et->preview_mode;
178 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
181 << "\ttemplate " << templatename() << '\n';
183 if (!filename.empty())
184 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
187 os << "\tdisplay false\n";
189 if (lyxscale != defaultLyxScale)
190 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
195 if (!clipdata.bbox.empty())
196 os << "\tboundingBox " << clipdata.bbox << '\n';
200 external::ExtraData::const_iterator it = extradata.begin();
201 external::ExtraData::const_iterator end = extradata.end();
202 for (; it != end; ++it) {
203 if (!it->second.empty())
204 os << "\textra " << it->first << " \""
205 << it->second << "\"\n";
208 if (!rotationdata.no_rotation()) {
209 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
210 if (rotationdata.origin() != external::RotationData::DEFAULT)
211 os << "\trotateOrigin "
212 << rotationdata.originString() << '\n';
215 if (!resizedata.no_resize()) {
216 double const scl = convert<double>(resizedata.scale);
217 if (!float_equal(scl, 0.0, 0.05)) {
218 if (!float_equal(scl, 100.0, 0.05))
220 << resizedata.scale << '\n';
222 if (!resizedata.width.zero())
224 << resizedata.width.asString() << '\n';
225 if (!resizedata.height.zero())
227 << resizedata.height.asString() << '\n';
229 if (resizedata.keepAspectRatio)
230 os << "\tkeepAspectRatio\n";
235 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
255 LexerKeyword external_tags[] = {
256 { "\\end_inset", EX_END },
257 { "boundingBox", EX_BOUNDINGBOX },
259 { "display", EX_DISPLAY},
260 { "draft", EX_DRAFT},
261 { "extra", EX_EXTRA },
262 { "filename", EX_FILENAME},
263 { "height", EX_HEIGHT },
264 { "keepAspectRatio", EX_KEEPASPECTRATIO },
265 { "lyxscale", EX_LYXSCALE},
266 { "rotateAngle", EX_ROTATEANGLE },
267 { "rotateOrigin", EX_ROTATEORIGIN },
268 { "scale", EX_SCALE },
269 { "template", EX_TEMPLATE },
270 { "width", EX_WIDTH }
273 PushPopHelper pph(lex, external_tags);
275 bool found_end = false;
276 bool read_error = false;
282 templatename_ = lex.getString();
287 string const name = lex.getString();
288 filename = buffer.getReferencedFileName(name);
294 display = lex.getString() != "false";
300 int const ls = lex.getInteger();
301 // negative values are not accepted.
305 lex.printError("ExternalInset::read: Wrong lyxscale: $$Token");
315 clipdata.bbox.xl = Length(lex.getString());
317 clipdata.bbox.yb = Length(lex.getString());
319 clipdata.bbox.xr = Length(lex.getString());
321 clipdata.bbox.yt = Length(lex.getString());
325 clipdata.clip = true;
330 string const name = lex.getString();
332 extradata.set(name, lex.getString());
338 resizedata.height = Length(lex.getString());
341 case EX_KEEPASPECTRATIO:
342 resizedata.keepAspectRatio = true;
347 rotationdata.angle = lex.getString();
350 case EX_ROTATEORIGIN:
352 rotationdata.origin(lex.getString());
357 resizedata.scale = lex.getString();
362 resizedata.width = Length(lex.getString());
370 lex.printError("ExternalInset::read: Wrong tag: $$Token");
375 if (found_end || read_error)
380 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
382 // This is a trick to make sure that the data are self-consistent.
383 settemplate(templatename_);
385 if (lyxerr.debugging(Debug::EXTERNAL)) {
386 lyxerr << "InsetExternalParams::read:\n";
387 write(buffer, lyxerr);
396 docstring screenLabel(InsetExternalParams const & params,
397 Buffer const & buffer)
399 external::Template const * const ptr =
400 external::getTemplatePtr(params);
403 return bformat((_("External template %1$s is not installed")),
404 from_utf8(params.templatename()));
406 docstring gui = _(ptr->guiName);
409 if (params.filename.empty())
412 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 renderer_->metrics(mi, dim);
532 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
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 void InsetExternal::updatePreview()
605 void InsetExternal::setParams(InsetExternalParams const & p)
609 // Subsequent calls to the InsetExternal::Params default constructor
611 defaultTemplateName = params_.templatename();
613 if (!external::getTemplatePtr(params_) || params_.filename.empty()
615 || !lyxrc.display_graphics
616 || params_.preview_mode == PREVIEW_OFF
617 || (params_.preview_mode == PREVIEW_INSTANT
618 && !RenderPreview::previewText())) {
619 RenderButton * button_ptr = renderer_->asButton();
621 renderer_.reset(new RenderButton);
622 button_ptr = renderer_->asButton();
624 button_ptr->update(screenLabel(params_, buffer()), true, false);
628 switch (params_.preview_mode) {
630 // Already taken care of above.
631 LASSERT(false, return);
633 case PREVIEW_INSTANT: {
634 renderer_ = make_unique<RenderMonitoredPreview>(this);
635 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
636 // This connection is closed at the same time as this is destroyed.
637 preview_ptr->connect([=]() { fileChanged(); });
638 add_preview_and_start_loading(*preview_ptr, *this, buffer());
641 case PREVIEW_GRAPHICS: {
642 RenderGraphic * graphic_ptr = renderer_->asGraphic();
644 renderer_.reset(new RenderGraphic(this));
645 graphic_ptr = renderer_->asGraphic();
647 graphic_ptr->update(get_grfx_params(params_));
654 void InsetExternal::fileChanged() const
656 Buffer const * const buffer = updateFrontend();
660 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
661 LASSERT(ptr, return);
663 ptr->removePreview(*buffer);
664 add_preview_and_start_loading(*ptr, *this, *buffer);
668 void InsetExternal::write(ostream & os) const
670 params_.write(buffer(), os);
674 void InsetExternal::read(Lexer & lex)
676 InsetExternalParams params;
677 if (params.read(buffer(), lex))
682 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
686 os << "\\fbox{\\ttfamily{}"
687 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
692 // "nice" means that the buffer is exported to LaTeX format but not
693 // run through the LaTeX compiler.
694 // If we're running through the LaTeX compiler, we should write the
695 // generated files in the buffer's temporary directory.
696 bool const external_in_tmpdir = !runparams.nice;
697 bool const dryrun = runparams.dryrun || runparams.inComment;
699 // If the template has specified a PDFLaTeX output, then we try and
701 if (runparams.flavor == OutputParams::PDFLATEX) {
702 external::Template const * const et_ptr =
703 external::getTemplatePtr(params_);
706 external::Template const & et = *et_ptr;
708 external::Template::Formats::const_iterator cit =
709 et.formats.find("PDFLaTeX");
711 if (cit != et.formats.end()) {
712 external::writeExternal(params_, "PDFLaTeX",
714 *(runparams.exportdata),
721 external::writeExternal(params_, "LaTeX", buffer(), os,
722 *(runparams.exportdata),
728 int InsetExternal::plaintext(odocstringstream & os,
729 OutputParams const & runparams, size_t) const
731 // this is too slow for constant use
732 if (runparams.for_tooltip)
735 bool const external_in_tmpdir = !runparams.nice;
736 bool const dryrun = runparams.dryrun || runparams.inComment;
738 ots << '\n'; // output external material on a new line
739 external::writeExternal(params_, "Ascii", buffer(), ots,
740 *(runparams.exportdata), external_in_tmpdir, dryrun);
741 return PLAINTEXT_NEWLINE;
745 int InsetExternal::docbook(odocstream & os,
746 OutputParams const & runparams) const
748 bool const external_in_tmpdir = !runparams.nice;
749 bool const dryrun = runparams.dryrun || runparams.inComment;
750 odocstringstream ods;
752 external::writeExternal(params_, "DocBook", buffer(), ots,
753 *(runparams.exportdata), external_in_tmpdir, dryrun);
755 return int(count(ods.str().begin(), ods.str().end(), '\n'));
759 docstring InsetExternal::xhtml(XHTMLStream & xs,
760 OutputParams const & runparams) const
762 bool const external_in_tmpdir = !runparams.nice;
763 bool const dryrun = runparams.dryrun || runparams.inComment;
764 odocstringstream ods;
766 external::writeExternal(params_, "XHTML", buffer(), ots,
767 *(runparams.exportdata), external_in_tmpdir, dryrun);
768 xs << XHTMLStream::ESCAPE_NONE << ods.str();
773 void InsetExternal::validate(LaTeXFeatures & features) const
778 external::Template const * const et_ptr =
779 external::getTemplatePtr(params_);
782 external::Template const & et = *et_ptr;
785 switch (features.runparams().flavor) {
786 case OutputParams::LATEX:
787 case OutputParams::DVILUATEX:
790 case OutputParams::LUATEX:
791 case OutputParams::PDFLATEX:
792 case OutputParams::XETEX:
795 case OutputParams::XML:
798 case OutputParams::HTML:
801 case OutputParams::TEXT:
804 case OutputParams::LYX:
808 external::Template::Formats::const_iterator cit =
809 et.formats.find(format);
811 if (cit == et.formats.end()) {
812 // If the template has not specified a PDFLaTeX output,
813 // we try the LaTeX format.
814 if (format == "PDFLaTeX") {
815 cit = et.formats.find("LaTeX");
816 if (cit == et.formats.end())
822 // FIXME: We don't need that always, see InsetGraphics
823 features.require("lyxdot");
825 vector<string>::const_iterator it = cit->second.requirements.begin();
826 vector<string>::const_iterator end = cit->second.requirements.end();
827 for (; it != end; ++it)
828 features.require(*it);
830 external::TemplateManager & etm = external::TemplateManager::get();
832 for (string const & name : cit->second.preambleNames) {
833 docstring const preamble = etm.getPreambleDefByName(name);
834 if (!preamble.empty())
835 features.addPreambleSnippet(preamble);
840 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
841 graphics::PreviewLoader & ploader) const
843 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
847 if (isPreviewWanted(params())) {
848 ptr->setAbsFile(params_.filename);
849 docstring const snippet = latexString(*this);
850 ptr->addPreview(snippet, ploader);
855 string InsetExternal::contextMenuName() const
857 return "context-external";
861 void InsetExternal::string2params(string const & in, Buffer const & buffer,
862 InsetExternalParams & params)
864 params = InsetExternalParams();
868 istringstream data(in);
874 if (!lex || name != "external") {
875 LYXERR0("InsetExternal::string2params(" << in << ")\n"
876 "Expected arg 1 to be \"external\"\n");
880 // This is part of the inset proper that is usually swallowed
881 // by Text::readInset
884 if (!lex || id != "External") {
885 LYXERR0("InsetExternal::string2params(" << in << ")\n"
886 "Expected arg 2 to be \"External\"\n");
890 params.read(buffer, lex);
894 string InsetExternal::params2string(InsetExternalParams const & params,
895 Buffer const & buffer)
898 data << "external" << ' ';
899 params.write(buffer, data);
900 data << "\\end_inset\n";