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 "TocBackend.h"
36 #include "frontends/alert.h"
37 #include "frontends/Application.h"
39 #include "graphics/PreviewLoader.h"
41 #include "support/bind.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 lyxscale(defaultLyxScale),
124 if (defaultTemplateName.empty()) {
125 external::TemplateManager const & etm =
126 external::TemplateManager::get();
127 if (!etm.getTemplates().empty())
128 templatename_ = etm.getTemplates().begin()->first;
130 templatename_ = defaultTemplateName;
136 template <typename T>
137 void clearIfNotFound(T & data, external::TransformID value,
138 vector<external::TransformID> const & ids)
140 typedef vector<external::TransformID>::const_iterator
143 const_iterator it = ids.begin();
144 const_iterator end = ids.end();
145 it = find(it, end, value);
153 void InsetExternalParams::settemplate(string const & name)
155 templatename_ = name;
157 external::TemplateManager const & etm =
158 external::TemplateManager::get();
159 external::Template const * const et = etm.getTemplateByName(name);
161 // Be safe. Don't lose data.
164 // Ascertain which transforms the template supports.
165 // Empty all those that it doesn't.
166 vector<external::TransformID> const & ids = et->transformIds;
167 clearIfNotFound(clipdata, external::Clip, ids);
168 clearIfNotFound(extradata, external::Extra, ids);
169 clearIfNotFound(resizedata, external::Resize, ids);
170 clearIfNotFound(rotationdata, external::Rotate, ids);
173 preview_mode = et->preview_mode;
177 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
180 << "\ttemplate " << templatename() << '\n';
182 if (!filename.empty())
183 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
186 os << "\tdisplay false\n";
188 if (lyxscale != defaultLyxScale)
189 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
194 if (!clipdata.bbox.empty())
195 os << "\tboundingBox " << clipdata.bbox << '\n';
199 external::ExtraData::const_iterator it = extradata.begin();
200 external::ExtraData::const_iterator end = extradata.end();
201 for (; it != end; ++it) {
202 if (!it->second.empty())
203 os << "\textra " << it->first << " \""
204 << it->second << "\"\n";
207 if (!rotationdata.no_rotation()) {
208 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
209 if (rotationdata.origin() != external::RotationData::DEFAULT)
210 os << "\trotateOrigin "
211 << rotationdata.originString() << '\n';
214 if (!resizedata.no_resize()) {
215 double const scl = convert<double>(resizedata.scale);
216 if (!float_equal(scl, 0.0, 0.05)) {
217 if (!float_equal(scl, 100.0, 0.05))
219 << resizedata.scale << '\n';
221 if (!resizedata.width.zero())
223 << resizedata.width.asString() << '\n';
224 if (!resizedata.height.zero())
226 << resizedata.height.asString() << '\n';
228 if (resizedata.keepAspectRatio)
229 os << "\tkeepAspectRatio\n";
234 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
254 LexerKeyword external_tags[] = {
255 { "\\end_inset", EX_END },
256 { "boundingBox", EX_BOUNDINGBOX },
258 { "display", EX_DISPLAY},
259 { "draft", EX_DRAFT},
260 { "extra", EX_EXTRA },
261 { "filename", EX_FILENAME},
262 { "height", EX_HEIGHT },
263 { "keepAspectRatio", EX_KEEPASPECTRATIO },
264 { "lyxscale", EX_LYXSCALE},
265 { "rotateAngle", EX_ROTATEANGLE },
266 { "rotateOrigin", EX_ROTATEORIGIN },
267 { "scale", EX_SCALE },
268 { "template", EX_TEMPLATE },
269 { "width", EX_WIDTH }
272 PushPopHelper pph(lex, external_tags);
274 bool found_end = false;
275 bool read_error = false;
281 templatename_ = lex.getString();
286 string const name = lex.getString();
287 filename = buffer.getReferencedFileName(name);
293 display = lex.getString() != "false";
299 lyxscale = lex.getInteger();
308 clipdata.bbox.xl = Length(lex.getString());
310 clipdata.bbox.yb = Length(lex.getString());
312 clipdata.bbox.xr = Length(lex.getString());
314 clipdata.bbox.yt = Length(lex.getString());
318 clipdata.clip = true;
323 string const name = lex.getString();
325 extradata.set(name, lex.getString());
331 resizedata.height = Length(lex.getString());
334 case EX_KEEPASPECTRATIO:
335 resizedata.keepAspectRatio = true;
340 rotationdata.angle = lex.getString();
343 case EX_ROTATEORIGIN:
345 rotationdata.origin(lex.getString());
350 resizedata.scale = lex.getString();
355 resizedata.width = Length(lex.getString());
363 lex.printError("ExternalInset::read: Wrong tag: $$Token");
368 if (found_end || read_error)
373 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
375 // This is a trick to make sure that the data are self-consistent.
376 settemplate(templatename_);
378 if (lyxerr.debugging(Debug::EXTERNAL)) {
379 lyxerr << "InsetExternalParams::read:\n";
380 write(buffer, lyxerr);
389 docstring screenLabel(InsetExternalParams const & params,
390 Buffer const & buffer)
392 external::Template const * const ptr =
393 external::getTemplatePtr(params);
396 return bformat((_("External template %1$s is not installed")),
397 from_utf8(params.templatename()));
399 docstring gui = _(ptr->guiName);
402 if (params.filename.empty())
405 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
414 InsetExternal::InsetExternal(Buffer * buf)
415 : Inset(buf), renderer_(new RenderButton)
420 // Mouse hover is not copied and remains empty
421 InsetExternal::InsetExternal(InsetExternal const & other)
423 boost::signals::trackable(),
424 params_(other.params_),
425 renderer_(other.renderer_->clone(this))
429 InsetExternal::~InsetExternal()
431 hideDialogs("external", this);
433 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
434 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
435 for (; it != end; ++it)
437 it->first->clearLastInset(this);
441 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
443 mouse_hover_[bv] = mouse_hover;
448 void InsetExternal::statusChanged() const
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,
505 DocIterator pit = cpit;
506 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
507 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
508 docstring str = screenLabel(params_, buffer());
509 toc->push_back(TocItem(pit, 0, str, output_active));
513 bool InsetExternal::showInsetDialog(BufferView * bv) const
515 bv->showDialog("external", params2string(params(), bv->buffer()),
516 const_cast<InsetExternal *>(this));
521 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
523 renderer_->metrics(mi, dim);
527 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
529 if (renderer_->asButton())
530 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
531 renderer_->draw(pi, x, y);
537 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
539 graphics::Params gparams;
541 gparams.filename = eparams.filename;
542 gparams.scale = eparams.lyxscale;
543 if (eparams.clipdata.clip)
544 gparams.bb = eparams.clipdata.bbox;
545 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
546 gparams.display = eparams.display;
554 static bool isPreviewWanted(InsetExternalParams const & params)
556 return params.display && params.filename.isReadableFile();
560 static docstring latexString(InsetExternal const & inset)
563 odocstringstream ods;
564 otexstream os(ods, texrow);
565 // We don't need to set runparams.encoding since it is not used by
567 OutputParams runparams(0);
568 runparams.flavor = OutputParams::LATEX;
569 inset.latex(os, runparams);
574 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
575 InsetExternal const & inset,
576 Buffer const & buffer)
578 InsetExternalParams const & params = inset.params();
580 if (RenderPreview::previewText() && isPreviewWanted(params)) {
581 renderer.setAbsFile(params.filename);
582 docstring const snippet = latexString(inset);
583 renderer.addPreview(snippet, buffer);
584 renderer.startLoading(buffer);
589 InsetExternalParams const & InsetExternal::params() const
595 void InsetExternal::updatePreview()
601 void InsetExternal::setParams(InsetExternalParams const & p)
605 // Subsequent calls to the InsetExternal::Params default constructor
607 defaultTemplateName = params_.templatename();
609 if (!external::getTemplatePtr(params_) || params_.filename.empty()
611 || !lyxrc.display_graphics
612 || params_.preview_mode == PREVIEW_OFF
613 || (params_.preview_mode == PREVIEW_INSTANT
614 && !RenderPreview::previewText())) {
615 RenderButton * button_ptr = renderer_->asButton();
617 renderer_.reset(new RenderButton);
618 button_ptr = renderer_->asButton();
620 button_ptr->update(screenLabel(params_, buffer()), true);
624 switch (params_.preview_mode) {
626 // Already taken care of above.
627 LASSERT(false, return);
629 case PREVIEW_INSTANT: {
630 renderer_.reset(new RenderMonitoredPreview(this));
631 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
632 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
633 if (preview_ptr->monitoring())
634 preview_ptr->stopMonitoring();
635 add_preview_and_start_loading(*preview_ptr, *this, buffer());
638 case PREVIEW_GRAPHICS: {
639 RenderGraphic * graphic_ptr = renderer_->asGraphic();
641 renderer_.reset(new RenderGraphic(this));
642 graphic_ptr = renderer_->asGraphic();
644 graphic_ptr->update(get_grfx_params(params_));
651 void InsetExternal::fileChanged() const
653 Buffer const * const buffer = updateFrontend();
657 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
658 LASSERT(ptr, return);
660 ptr->removePreview(*buffer);
661 add_preview_and_start_loading(*ptr, *this, *buffer);
665 void InsetExternal::write(ostream & os) const
667 params_.write(buffer(), os);
671 void InsetExternal::read(Lexer & lex)
673 InsetExternalParams params;
674 if (params.read(buffer(), lex))
679 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
683 os << "\\fbox{\\ttfamily{}"
684 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
689 // "nice" means that the buffer is exported to LaTeX format but not
690 // run through the LaTeX compiler.
691 // If we're running through the LaTeX compiler, we should write the
692 // generated files in the buffer's temporary directory.
693 bool const external_in_tmpdir = !runparams.nice;
694 bool const dryrun = runparams.dryrun || runparams.inComment;
696 // If the template has specified a PDFLaTeX output, then we try and
698 if (runparams.flavor == OutputParams::PDFLATEX) {
699 external::Template const * const et_ptr =
700 external::getTemplatePtr(params_);
703 external::Template const & et = *et_ptr;
705 external::Template::Formats::const_iterator cit =
706 et.formats.find("PDFLaTeX");
708 if (cit != et.formats.end()) {
709 external::writeExternal(params_, "PDFLaTeX",
711 *(runparams.exportdata),
718 external::writeExternal(params_, "LaTeX", buffer(), os,
719 *(runparams.exportdata),
725 int InsetExternal::plaintext(odocstringstream & os,
726 OutputParams const & runparams, size_t) const
728 // this is too slow for constant use
729 if (runparams.for_tooltip)
733 otexstream ots(os, texrow);
734 bool const external_in_tmpdir = !runparams.nice;
735 bool const dryrun = runparams.dryrun || runparams.inComment;
736 ots << '\n'; // output external material on a new line
737 external::writeExternal(params_, "Ascii", buffer(), ots,
738 *(runparams.exportdata), external_in_tmpdir, dryrun);
739 return PLAINTEXT_NEWLINE;
743 int InsetExternal::docbook(odocstream & os,
744 OutputParams const & runparams) const
747 odocstringstream ods;
748 otexstream ots(ods, texrow);
749 bool const external_in_tmpdir = !runparams.nice;
750 bool const dryrun = runparams.dryrun || runparams.inComment;
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;
764 odocstringstream ods;
765 otexstream ots(ods, texrow);
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 it = cit->second.preambleNames.begin();
833 end = cit->second.preambleNames.end();
834 for (; it != end; ++it) {
835 string const preamble = etm.getPreambleDefByName(*it);
836 if (!preamble.empty())
837 features.addPreambleSnippet(preamble);
842 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
843 graphics::PreviewLoader & ploader) const
845 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
849 if (isPreviewWanted(params())) {
850 ptr->setAbsFile(params_.filename);
851 docstring const snippet = latexString(*this);
852 ptr->addPreview(snippet, ploader);
857 string InsetExternal::contextMenuName() const
859 return "context-external";
863 void InsetExternal::string2params(string const & in, Buffer const & buffer,
864 InsetExternalParams & params)
866 params = InsetExternalParams();
870 istringstream data(in);
876 if (!lex || name != "external") {
877 LYXERR0("InsetExternal::string2params(" << in << ")\n"
878 "Expected arg 1 to be \"external\"\n");
882 // This is part of the inset proper that is usually swallowed
883 // by Text::readInset
886 if (!lex || id != "External") {
887 LYXERR0("InsetExternal::string2params(" << in << ")\n"
888 "Expected arg 2 to be \"External\"\n");
892 params.read(buffer, lex);
896 string InsetExternal::params2string(InsetExternalParams const & params,
897 Buffer const & buffer)
900 data << "external" << ' ';
901 params.write(buffer, data);
902 data << "\\end_inset\n";