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/bind.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 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 lyxscale = lex.getInteger();
309 clipdata.bbox.xl = Length(lex.getString());
311 clipdata.bbox.yb = Length(lex.getString());
313 clipdata.bbox.xr = Length(lex.getString());
315 clipdata.bbox.yt = Length(lex.getString());
319 clipdata.clip = true;
324 string const name = lex.getString();
326 extradata.set(name, lex.getString());
332 resizedata.height = Length(lex.getString());
335 case EX_KEEPASPECTRATIO:
336 resizedata.keepAspectRatio = true;
341 rotationdata.angle = lex.getString();
344 case EX_ROTATEORIGIN:
346 rotationdata.origin(lex.getString());
351 resizedata.scale = lex.getString();
356 resizedata.width = Length(lex.getString());
364 lex.printError("ExternalInset::read: Wrong tag: $$Token");
369 if (found_end || read_error)
374 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
376 // This is a trick to make sure that the data are self-consistent.
377 settemplate(templatename_);
379 if (lyxerr.debugging(Debug::EXTERNAL)) {
380 lyxerr << "InsetExternalParams::read:\n";
382 // coverity[NEGATIVE_RETURNS]
383 write(buffer, lyxerr);
392 docstring screenLabel(InsetExternalParams const & params,
393 Buffer const & buffer)
395 external::Template const * const ptr =
396 external::getTemplatePtr(params);
399 return bformat((_("External template %1$s is not installed")),
400 from_utf8(params.templatename()));
402 docstring gui = _(ptr->guiName);
405 if (params.filename.empty())
408 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
417 InsetExternal::InsetExternal(Buffer * buf)
418 : Inset(buf), renderer_(new RenderButton)
423 // Mouse hover is not copied and remains empty
424 InsetExternal::InsetExternal(InsetExternal const & other)
426 boost::signals2::trackable(),
427 params_(other.params_),
428 renderer_(other.renderer_->clone(this))
432 InsetExternal::~InsetExternal()
434 hideDialogs("external", this);
436 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
437 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
438 for (; it != end; ++it)
440 it->first->clearLastInset(this);
444 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
446 mouse_hover_[bv] = mouse_hover;
451 void InsetExternal::statusChanged() const
457 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
459 switch (cmd.action()) {
461 case LFUN_INSET_EDIT: {
462 InsetExternalParams p = params();
463 if (!cmd.argument().empty())
464 string2params(to_utf8(cmd.argument()), buffer(), p);
465 external::editExternal(p, buffer());
469 case LFUN_INSET_MODIFY: {
470 InsetExternalParams p;
471 string2params(to_utf8(cmd.argument()), buffer(), p);
477 case LFUN_INSET_DIALOG_UPDATE:
478 cur.bv().updateDialog("external",
479 params2string(params(), cur.bv().buffer()));
483 Inset::doDispatch(cur, cmd);
488 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
489 FuncStatus & flag) const
491 switch (cmd.action()) {
493 case LFUN_INSET_EDIT:
494 case LFUN_INSET_MODIFY:
495 case LFUN_INSET_DIALOG_UPDATE:
496 flag.setEnabled(true);
500 return Inset::getStatus(cur, cmd, flag);
505 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
508 DocIterator pit = cpit;
509 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
510 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
511 docstring str = screenLabel(params_, buffer());
512 toc->push_back(TocItem(pit, 0, str, output_active));
516 bool InsetExternal::showInsetDialog(BufferView * bv) const
518 bv->showDialog("external", params2string(params(), bv->buffer()),
519 const_cast<InsetExternal *>(this));
524 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
526 renderer_->metrics(mi, dim);
530 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
532 if (renderer_->asButton())
533 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
534 renderer_->draw(pi, x, y);
540 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
542 graphics::Params gparams;
544 gparams.filename = eparams.filename;
545 gparams.scale = eparams.lyxscale;
546 if (eparams.clipdata.clip)
547 gparams.bb = eparams.clipdata.bbox;
548 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
549 gparams.display = eparams.display;
557 static bool isPreviewWanted(InsetExternalParams const & params)
559 return params.display && params.filename.isReadableFile();
563 static docstring latexString(InsetExternal const & inset)
565 odocstringstream ods;
567 // We don't need to set runparams.encoding since it is not used by
569 OutputParams runparams(0);
570 runparams.flavor = OutputParams::LATEX;
571 inset.latex(os, runparams);
576 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
577 InsetExternal const & inset,
578 Buffer const & buffer)
580 InsetExternalParams const & params = inset.params();
582 if (RenderPreview::previewText() && isPreviewWanted(params)) {
583 renderer.setAbsFile(params.filename);
584 docstring const snippet = latexString(inset);
585 renderer.addPreview(snippet, buffer);
586 renderer.startLoading(buffer);
591 InsetExternalParams const & InsetExternal::params() const
597 void InsetExternal::updatePreview()
603 void InsetExternal::setParams(InsetExternalParams const & p)
607 // Subsequent calls to the InsetExternal::Params default constructor
609 defaultTemplateName = params_.templatename();
611 if (!external::getTemplatePtr(params_) || params_.filename.empty()
613 || !lyxrc.display_graphics
614 || params_.preview_mode == PREVIEW_OFF
615 || (params_.preview_mode == PREVIEW_INSTANT
616 && !RenderPreview::previewText())) {
617 RenderButton * button_ptr = renderer_->asButton();
619 renderer_.reset(new RenderButton);
620 button_ptr = renderer_->asButton();
622 button_ptr->update(screenLabel(params_, buffer()), true);
626 switch (params_.preview_mode) {
628 // Already taken care of above.
629 LASSERT(false, return);
631 case PREVIEW_INSTANT: {
632 renderer_.reset(new RenderMonitoredPreview(this));
633 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
634 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
635 if (preview_ptr->monitoring())
636 preview_ptr->stopMonitoring();
637 add_preview_and_start_loading(*preview_ptr, *this, buffer());
640 case PREVIEW_GRAPHICS: {
641 RenderGraphic * graphic_ptr = renderer_->asGraphic();
643 renderer_.reset(new RenderGraphic(this));
644 graphic_ptr = renderer_->asGraphic();
646 graphic_ptr->update(get_grfx_params(params_));
653 void InsetExternal::fileChanged() const
655 Buffer const * const buffer = updateFrontend();
659 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
660 LASSERT(ptr, return);
662 ptr->removePreview(*buffer);
663 add_preview_and_start_loading(*ptr, *this, *buffer);
667 void InsetExternal::write(ostream & os) const
669 params_.write(buffer(), os);
673 void InsetExternal::read(Lexer & lex)
675 InsetExternalParams params;
676 if (params.read(buffer(), lex))
681 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
685 os << "\\fbox{\\ttfamily{}"
686 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
691 // "nice" means that the buffer is exported to LaTeX format but not
692 // run through the LaTeX compiler.
693 // If we're running through the LaTeX compiler, we should write the
694 // generated files in the buffer's temporary directory.
695 bool const external_in_tmpdir = !runparams.nice;
696 bool const dryrun = runparams.dryrun || runparams.inComment;
698 // If the template has specified a PDFLaTeX output, then we try and
700 if (runparams.flavor == OutputParams::PDFLATEX) {
701 external::Template const * const et_ptr =
702 external::getTemplatePtr(params_);
705 external::Template const & et = *et_ptr;
707 external::Template::Formats::const_iterator cit =
708 et.formats.find("PDFLaTeX");
710 if (cit != et.formats.end()) {
711 external::writeExternal(params_, "PDFLaTeX",
713 *(runparams.exportdata),
720 external::writeExternal(params_, "LaTeX", buffer(), os,
721 *(runparams.exportdata),
727 int InsetExternal::plaintext(odocstringstream & os,
728 OutputParams const & runparams, size_t) const
730 // this is too slow for constant use
731 if (runparams.for_tooltip)
734 bool const external_in_tmpdir = !runparams.nice;
735 bool const dryrun = runparams.dryrun || runparams.inComment;
737 ots << '\n'; // output external material on a new line
738 external::writeExternal(params_, "Ascii", buffer(), ots,
739 *(runparams.exportdata), external_in_tmpdir, dryrun);
740 return PLAINTEXT_NEWLINE;
744 int InsetExternal::docbook(odocstream & os,
745 OutputParams const & runparams) const
747 bool const external_in_tmpdir = !runparams.nice;
748 bool const dryrun = runparams.dryrun || runparams.inComment;
749 odocstringstream ods;
751 external::writeExternal(params_, "DocBook", buffer(), ots,
752 *(runparams.exportdata), external_in_tmpdir, dryrun);
754 return int(count(ods.str().begin(), ods.str().end(), '\n'));
758 docstring InsetExternal::xhtml(XHTMLStream & xs,
759 OutputParams const & runparams) const
761 bool const external_in_tmpdir = !runparams.nice;
762 bool const dryrun = runparams.dryrun || runparams.inComment;
763 odocstringstream ods;
765 external::writeExternal(params_, "XHTML", buffer(), ots,
766 *(runparams.exportdata), external_in_tmpdir, dryrun);
767 xs << XHTMLStream::ESCAPE_NONE << ods.str();
772 void InsetExternal::validate(LaTeXFeatures & features) const
777 external::Template const * const et_ptr =
778 external::getTemplatePtr(params_);
781 external::Template const & et = *et_ptr;
784 switch (features.runparams().flavor) {
785 case OutputParams::LATEX:
786 case OutputParams::DVILUATEX:
789 case OutputParams::LUATEX:
790 case OutputParams::PDFLATEX:
791 case OutputParams::XETEX:
794 case OutputParams::XML:
797 case OutputParams::HTML:
800 case OutputParams::TEXT:
803 case OutputParams::LYX:
807 external::Template::Formats::const_iterator cit =
808 et.formats.find(format);
810 if (cit == et.formats.end()) {
811 // If the template has not specified a PDFLaTeX output,
812 // we try the LaTeX format.
813 if (format == "PDFLaTeX") {
814 cit = et.formats.find("LaTeX");
815 if (cit == et.formats.end())
821 // FIXME: We don't need that always, see InsetGraphics
822 features.require("lyxdot");
824 vector<string>::const_iterator it = cit->second.requirements.begin();
825 vector<string>::const_iterator end = cit->second.requirements.end();
826 for (; it != end; ++it)
827 features.require(*it);
829 external::TemplateManager & etm = external::TemplateManager::get();
831 for (string const & name : cit->second.preambleNames) {
832 docstring const preamble = etm.getPreambleDefByName(name);
833 if (!preamble.empty())
834 features.addPreambleSnippet(preamble);
839 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
840 graphics::PreviewLoader & ploader) const
842 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
846 if (isPreviewWanted(params())) {
847 ptr->setAbsFile(params_.filename);
848 docstring const snippet = latexString(*this);
849 ptr->addPreview(snippet, ploader);
854 string InsetExternal::contextMenuName() const
856 return "context-external";
860 void InsetExternal::string2params(string const & in, Buffer const & buffer,
861 InsetExternalParams & params)
863 params = InsetExternalParams();
867 istringstream data(in);
873 if (!lex || name != "external") {
874 LYXERR0("InsetExternal::string2params(" << in << ")\n"
875 "Expected arg 1 to be \"external\"\n");
879 // This is part of the inset proper that is usually swallowed
880 // by Text::readInset
883 if (!lex || id != "External") {
884 LYXERR0("InsetExternal::string2params(" << in << ")\n"
885 "Expected arg 2 to be \"External\"\n");
889 params.read(buffer, lex);
893 string InsetExternal::params2string(InsetExternalParams const & params,
894 Buffer const & buffer)
897 data << "external" << ' ';
898 params.write(buffer, data);
899 data << "\\end_inset\n";