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()));
420 InsetExternal::InsetExternal(Buffer * buf)
421 : Inset(buf), renderer_(new RenderButton)
426 // Mouse hover is not copied and remains empty
427 InsetExternal::InsetExternal(InsetExternal const & other)
429 params_(other.params_),
430 renderer_(other.renderer_->clone(this))
434 InsetExternal::~InsetExternal()
436 hideDialogs("external", this);
438 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
439 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
440 for (; it != end; ++it)
442 it->first->clearLastInset(this);
446 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
448 mouse_hover_[bv] = mouse_hover;
453 void InsetExternal::statusChanged() const
459 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
461 switch (cmd.action()) {
463 case LFUN_INSET_EDIT: {
464 InsetExternalParams p = params();
465 if (!cmd.argument().empty())
466 string2params(to_utf8(cmd.argument()), buffer(), p);
467 external::editExternal(p, buffer());
471 case LFUN_INSET_MODIFY: {
472 InsetExternalParams p;
473 string2params(to_utf8(cmd.argument()), buffer(), p);
479 case LFUN_INSET_DIALOG_UPDATE:
480 cur.bv().updateDialog("external",
481 params2string(params(), cur.bv().buffer()));
485 Inset::doDispatch(cur, cmd);
490 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
491 FuncStatus & flag) const
493 switch (cmd.action()) {
495 case LFUN_INSET_EDIT:
496 case LFUN_INSET_MODIFY:
497 case LFUN_INSET_DIALOG_UPDATE:
498 flag.setEnabled(true);
502 return Inset::getStatus(cur, cmd, flag);
507 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
508 UpdateType, TocBackend & backend) const
510 docstring str = screenLabel(params_, buffer());
511 TocBuilder & b = backend.builder("external");
512 b.pushItem(cpit, str, output_active);
517 bool InsetExternal::showInsetDialog(BufferView * bv) const
519 bv->showDialog("external", params2string(params(), bv->buffer()),
520 const_cast<InsetExternal *>(this));
525 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
527 if (!isRendererValid())
530 renderer_->metrics(mi, dim);
534 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
536 if (!isRendererValid())
539 if (renderer_->asButton())
540 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
541 renderer_->draw(pi, x, y);
547 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
549 graphics::Params gparams;
551 gparams.filename = eparams.filename;
552 gparams.scale = eparams.lyxscale;
553 if (eparams.clipdata.clip)
554 gparams.bb = eparams.clipdata.bbox;
555 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
556 gparams.display = eparams.display;
564 static bool isPreviewWanted(InsetExternalParams const & params)
566 return params.display && params.filename.isReadableFile();
570 static docstring latexString(InsetExternal const & inset)
572 odocstringstream ods;
574 // We don't need to set runparams.encoding since it is not used by
576 OutputParams runparams(0);
577 runparams.flavor = OutputParams::LATEX;
578 inset.latex(os, runparams);
583 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
584 InsetExternal const & inset,
585 Buffer const & buffer)
587 InsetExternalParams const & params = inset.params();
589 if (RenderPreview::previewText() && isPreviewWanted(params)) {
590 renderer.setAbsFile(params.filename);
591 docstring const snippet = latexString(inset);
592 renderer.addPreview(snippet, buffer);
593 renderer.startLoading(buffer);
598 InsetExternalParams const & InsetExternal::params() const
604 bool InsetExternal::isPreviewed() const
606 return (external::getTemplatePtr(params_) && !params_.filename.empty()
608 && lyxrc.display_graphics
609 && params_.preview_mode != PREVIEW_OFF
610 && (params_.preview_mode != PREVIEW_INSTANT
611 || RenderPreview::previewText()));
615 bool InsetExternal::isRendererValid() const
617 if (!renderer_->asButton())
618 return isPreviewed();
619 return !isPreviewed();
623 void InsetExternal::setParams(InsetExternalParams const & p)
627 // Subsequent calls to the InsetExternal::Params default constructor
629 defaultTemplateName = params_.templatename();
635 void InsetExternal::updatePreview() const
637 if (!isPreviewed()) {
638 RenderButton * button_ptr = renderer_->asButton();
640 renderer_.reset(new RenderButton);
641 button_ptr = renderer_->asButton();
643 button_ptr->update(screenLabel(params_, buffer()), true, false);
647 switch (params_.preview_mode) {
649 // Already taken care of above.
650 LASSERT(false, return);
652 case PREVIEW_INSTANT: {
653 renderer_ = make_unique<RenderMonitoredPreview>(this);
654 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
655 // This connection is closed at the same time as this is destroyed.
656 preview_ptr->connect([=]() { fileChanged(); });
657 add_preview_and_start_loading(*preview_ptr, *this, buffer());
660 case PREVIEW_GRAPHICS: {
661 RenderGraphic * graphic_ptr = renderer_->asGraphic();
663 renderer_.reset(new RenderGraphic(this));
664 graphic_ptr = renderer_->asGraphic();
666 graphic_ptr->update(get_grfx_params(params_));
673 void InsetExternal::fileChanged() const
675 Buffer const * const buffer = updateFrontend();
679 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
680 LASSERT(ptr, return);
682 ptr->removePreview(*buffer);
683 add_preview_and_start_loading(*ptr, *this, *buffer);
687 void InsetExternal::write(ostream & os) const
689 params_.write(buffer(), os);
693 void InsetExternal::read(Lexer & lex)
695 InsetExternalParams params;
696 if (params.read(buffer(), lex))
701 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
705 os << "\\fbox{\\ttfamily{}"
706 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
711 // "nice" means that the buffer is exported to LaTeX format but not
712 // run through the LaTeX compiler.
713 // If we're running through the LaTeX compiler, we should write the
714 // generated files in the buffer's temporary directory.
715 bool const external_in_tmpdir = !runparams.nice;
716 bool const dryrun = runparams.dryrun || runparams.inComment;
718 // If the template has specified a PDFLaTeX output, then we try and
720 if (runparams.flavor == OutputParams::PDFLATEX) {
721 external::Template const * const et_ptr =
722 external::getTemplatePtr(params_);
725 external::Template const & et = *et_ptr;
727 external::Template::Formats::const_iterator cit =
728 et.formats.find("PDFLaTeX");
730 if (cit != et.formats.end()) {
731 external::writeExternal(params_, "PDFLaTeX",
733 *(runparams.exportdata),
740 external::writeExternal(params_, "LaTeX", buffer(), os,
741 *(runparams.exportdata),
747 int InsetExternal::plaintext(odocstringstream & os,
748 OutputParams const & runparams, size_t) const
750 // this is too slow for constant use
751 if (runparams.for_tooltip)
754 bool const external_in_tmpdir = !runparams.nice;
755 bool const dryrun = runparams.dryrun || runparams.inComment;
757 ots << '\n'; // output external material on a new line
758 external::writeExternal(params_, "Ascii", buffer(), ots,
759 *(runparams.exportdata), external_in_tmpdir, dryrun);
760 return PLAINTEXT_NEWLINE;
764 int InsetExternal::docbook(odocstream & os,
765 OutputParams const & runparams) const
767 bool const external_in_tmpdir = !runparams.nice;
768 bool const dryrun = runparams.dryrun || runparams.inComment;
769 odocstringstream ods;
771 external::writeExternal(params_, "DocBook", buffer(), ots,
772 *(runparams.exportdata), external_in_tmpdir, dryrun);
774 return int(count(ods.str().begin(), ods.str().end(), '\n'));
778 docstring InsetExternal::xhtml(XHTMLStream & xs,
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::writeExternal(params_, "XHTML", buffer(), ots,
786 *(runparams.exportdata), external_in_tmpdir, dryrun);
787 xs << XHTMLStream::ESCAPE_NONE << ods.str();
792 void InsetExternal::validate(LaTeXFeatures & features) const
797 external::Template const * const et_ptr =
798 external::getTemplatePtr(params_);
801 external::Template const & et = *et_ptr;
804 switch (features.runparams().flavor) {
805 case OutputParams::LATEX:
806 case OutputParams::DVILUATEX:
809 case OutputParams::LUATEX:
810 case OutputParams::PDFLATEX:
811 case OutputParams::XETEX:
814 case OutputParams::XML:
817 case OutputParams::HTML:
820 case OutputParams::TEXT:
823 case OutputParams::LYX:
827 external::Template::Formats::const_iterator cit =
828 et.formats.find(format);
830 if (cit == et.formats.end()) {
831 // If the template has not specified a PDFLaTeX output,
832 // we try the LaTeX format.
833 if (format == "PDFLaTeX") {
834 cit = et.formats.find("LaTeX");
835 if (cit == et.formats.end())
841 // FIXME: We don't need that always, see InsetGraphics
842 features.require("lyxdot");
844 vector<string>::const_iterator it = cit->second.requirements.begin();
845 vector<string>::const_iterator end = cit->second.requirements.end();
846 for (; it != end; ++it)
847 features.require(*it);
849 external::TemplateManager & etm = external::TemplateManager::get();
851 for (string const & name : cit->second.preambleNames) {
852 docstring const preamble = etm.getPreambleDefByName(name);
853 if (!preamble.empty())
854 features.addPreambleSnippet(preamble);
859 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
860 graphics::PreviewLoader & ploader) const
862 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
866 if (isPreviewWanted(params())) {
867 ptr->setAbsFile(params_.filename);
868 docstring const snippet = latexString(*this);
869 ptr->addPreview(snippet, ploader);
874 string InsetExternal::contextMenuName() const
876 return "context-external";
880 void InsetExternal::string2params(string const & in, Buffer const & buffer,
881 InsetExternalParams & params)
883 params = InsetExternalParams();
887 istringstream data(in);
893 if (!lex || name != "external") {
894 LYXERR0("InsetExternal::string2params(" << in << ")\n"
895 "Expected arg 1 to be \"external\"\n");
899 // This is part of the inset proper that is usually swallowed
900 // by Text::readInset
903 if (!lex || id != "External") {
904 LYXERR0("InsetExternal::string2params(" << in << ")\n"
905 "Expected arg 2 to be \"External\"\n");
909 params.read(buffer, lex);
913 string InsetExternal::params2string(InsetExternalParams const & params,
914 Buffer const & buffer)
917 data << "external" << ' ';
918 params.write(buffer, data);
919 data << "\\end_inset\n";