2 * \file insetexternal.C
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/ExternalTemplate.h"
16 #include "insets/render_button.h"
17 #include "insets/render_graphic.h"
18 #include "insets/render_preview.h"
23 #include "dispatchresult.h"
25 #include "FuncStatus.h"
26 #include "funcrequest.h"
28 #include "LaTeXFeatures.h"
32 #include "metricsinfo.h"
33 #include "outputparams.h"
35 #include "graphics/PreviewLoader.h"
37 #include "support/filetools.h"
38 #include "support/lstrings.h"
39 #include "support/lyxlib.h"
40 #include "support/convert.h"
41 #include "support/translator.h"
43 #include <boost/bind.hpp>
47 namespace support = lyx::support;
48 namespace external = lyx::external;
49 namespace graphics = lyx::graphics;
52 using lyx::odocstream;
57 using std::istringstream;
59 using std::ostringstream;
65 external::DisplayType const defaultDisplayType = external::NoDisplay;
67 unsigned int const defaultLyxScale = 100;
69 string defaultTemplateName = "RasterImage";
79 tempname_ = support::tempName(string(), "lyxext");
80 // FIXME: This is unsafe
81 support::unlink(tempname_);
82 // must have an extension for the converter code to work correctly.
87 TempName::TempName(TempName const &)
89 tempname_ = TempName()();
95 support::unlink(tempname_);
100 TempName::operator=(TempName const & other)
103 tempname_ = TempName()();
110 /// The translator between the Display enum and corresponding lyx string.
111 Translator<DisplayType, string> const initTranslator()
113 Translator<DisplayType, string> translator(DefaultDisplay, "default");
115 // Fill the display translator
116 translator.addPair(MonochromeDisplay, "monochrome");
117 translator.addPair(GrayscaleDisplay, "grayscale");
118 translator.addPair(ColorDisplay, "color");
119 translator.addPair(PreviewDisplay, "preview");
120 translator.addPair(NoDisplay, "none");
128 Translator<DisplayType, string> const & displayTranslator()
130 static Translator<DisplayType, string> const translator =
135 } // namespace external
139 InsetExternalParams::InsetExternalParams()
140 : display(defaultDisplayType),
141 lyxscale(defaultLyxScale),
143 templatename_(defaultTemplateName)
149 template <typename T>
150 void clearIfNotFound(T & data, external::TransformID value,
151 vector<external::TransformID> const & ids)
153 typedef vector<external::TransformID>::const_iterator
156 const_iterator it = ids.begin();
157 const_iterator end = ids.end();
158 it = std::find(it, end, value);
166 void InsetExternalParams::settemplate(string const & name)
168 templatename_ = name;
170 external::TemplateManager const & etm =
171 external::TemplateManager::get();
172 external::Template const * const et = etm.getTemplateByName(name);
174 // Be safe. Don't lose data.
177 // Ascertain which transforms the template supports.
178 // Empty all those that it doesn't.
179 vector<external::TransformID> const & ids = et->transformIds;
180 clearIfNotFound(clipdata, external::Clip, ids);
181 clearIfNotFound(extradata, external::Extra, ids);
182 clearIfNotFound(resizedata, external::Resize, ids);
183 clearIfNotFound(rotationdata, external::Rotate, ids);
187 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
190 << "\ttemplate " << templatename() << '\n';
192 if (!filename.empty())
194 << filename.outputFilename(buffer.filePath())
197 if (display != defaultDisplayType)
199 << external::displayTranslator().find(display)
202 if (lyxscale != defaultLyxScale)
203 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
208 if (!clipdata.bbox.empty())
209 os << "\tboundingBox " << clipdata.bbox << '\n';
213 external::ExtraData::const_iterator it = extradata.begin();
214 external::ExtraData::const_iterator end = extradata.end();
215 for (; it != end; ++it) {
216 if (!it->second.empty())
217 os << "\textra " << it->first << " \""
218 << it->second << "\"\n";
221 if (!rotationdata.no_rotation()) {
222 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
223 if (rotationdata.origin() != external::RotationData::DEFAULT)
224 os << "\trotateOrigin "
225 << rotationdata.originString() << '\n';
228 if (!resizedata.no_resize()) {
229 using support::float_equal;
230 double const scl = convert<double>(resizedata.scale);
231 if (!float_equal(scl, 0.0, 0.05)) {
232 if (!float_equal(scl, 100.0, 0.05))
234 << resizedata.scale << '\n';
236 if (!resizedata.width.zero())
238 << resizedata.width.asString() << '\n';
239 if (!resizedata.height.zero())
241 << resizedata.height.asString() << '\n';
243 if (resizedata.keepAspectRatio)
244 os << "\tkeepAspectRatio\n";
249 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
269 keyword_item external_tags[] = {
270 { "\\end_inset", EX_END },
271 { "boundingBox", EX_BOUNDINGBOX },
273 { "display", EX_DISPLAY},
274 { "draft", EX_DRAFT},
275 { "extra", EX_EXTRA },
276 { "filename", EX_FILENAME},
277 { "height", EX_HEIGHT },
278 { "keepAspectRatio", EX_KEEPASPECTRATIO },
279 { "lyxscale", EX_LYXSCALE},
280 { "rotateAngle", EX_ROTATEANGLE },
281 { "rotateOrigin", EX_ROTATEORIGIN },
282 { "scale", EX_SCALE },
283 { "template", EX_TEMPLATE },
284 { "width", EX_WIDTH }
287 pushpophelper pph(lex, external_tags, EX_END);
289 bool found_end = false;
290 bool read_error = false;
296 templatename_ = lex.getString();
301 string const name = lex.getString();
302 filename.set(name, buffer.filePath());
308 string const name = lex.getString();
309 display = external::displayTranslator().find(name);
315 lyxscale = lex.getInteger();
324 clipdata.bbox.xl = lex.getInteger();
326 clipdata.bbox.yb = lex.getInteger();
328 clipdata.bbox.xr = lex.getInteger();
330 clipdata.bbox.yt = lex.getInteger();
334 clipdata.clip = true;
339 string const name = lex.getString();
341 extradata.set(name, lex.getString());
347 resizedata.height = LyXLength(lex.getString());
350 case EX_KEEPASPECTRATIO:
351 resizedata.keepAspectRatio = true;
356 rotationdata.angle = lex.getString();
359 case EX_ROTATEORIGIN:
361 rotationdata.origin(lex.getString());
366 resizedata.scale = lex.getString();
371 resizedata.width = LyXLength(lex.getString());
379 lex.printError("ExternalInset::read: "
380 "Wrong tag: $$Token");
385 if (found_end || read_error)
390 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
392 // This is a trick to make sure that the data are self-consistent.
393 settemplate(templatename_);
395 if (lyxerr.debugging(Debug::EXTERNAL)) {
396 lyxerr << "InsetExternalParams::read:\n";
397 write(buffer, lyxerr);
404 InsetExternal::InsetExternal()
405 : renderer_(new RenderButton)
409 InsetExternal::InsetExternal(InsetExternal const & other)
411 boost::signals::trackable(),
412 params_(other.params_),
413 renderer_(other.renderer_->clone(this))
417 auto_ptr<InsetBase> InsetExternal::doClone() const
419 return auto_ptr<InsetBase>(new InsetExternal(*this));
423 InsetExternal::~InsetExternal()
425 InsetExternalMailer(*this).hideDialog();
429 void InsetExternal::statusChanged() const
431 LyX::cref().updateInset(this);
435 void InsetExternal::doDispatch(LCursor & cur, FuncRequest & cmd)
437 switch (cmd.action) {
439 case LFUN_EXTERNAL_EDIT: {
440 Buffer const & buffer = cur.buffer();
441 InsetExternalParams p;
442 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
443 external::editExternal(p, buffer);
447 case LFUN_INSET_MODIFY: {
448 Buffer const & buffer = cur.buffer();
449 InsetExternalParams p;
450 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
451 setParams(p, buffer);
455 case LFUN_INSET_DIALOG_UPDATE:
456 InsetExternalMailer(*this).updateDialog(&cur.bv());
459 case LFUN_MOUSE_RELEASE:
460 InsetExternalMailer(*this).showDialog(&cur.bv());
464 InsetBase::doDispatch(cur, cmd);
469 bool InsetExternal::getStatus(LCursor & cur, FuncRequest const & cmd,
470 FuncStatus & flag) const
472 switch (cmd.action) {
474 case LFUN_EXTERNAL_EDIT:
475 case LFUN_INSET_MODIFY:
476 case LFUN_INSET_DIALOG_UPDATE:
481 return InsetBase::getStatus(cur, cmd, flag);
486 void InsetExternal::edit(LCursor & cur, bool)
488 InsetExternalMailer(*this).showDialog(&cur.bv());
492 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
494 renderer_->metrics(mi, dim);
499 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
501 setPosCache(pi, x, y);
502 renderer_->draw(pi, x, y);
515 RenderType getRenderType(InsetExternalParams const & p)
517 if (!external::getTemplatePtr(p) ||
518 p.filename.empty() ||
519 p.display == external::NoDisplay)
522 if (p.display == external::PreviewDisplay) {
523 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
524 return RENDERPREVIEW;
528 if (p.display == external::DefaultDisplay &&
529 lyxrc.display_graphics == graphics::NoDisplay)
531 return RENDERGRAPHIC;
535 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
537 graphics::Params gparams;
539 gparams.filename = eparams.filename.absFilename();
540 gparams.scale = eparams.lyxscale;
541 if (eparams.clipdata.clip)
542 gparams.bb = eparams.clipdata.bbox;
543 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
545 switch (eparams.display) {
546 case external::DefaultDisplay:
547 gparams.display = graphics::DefaultDisplay;
549 case external::MonochromeDisplay:
550 gparams.display = graphics::MonochromeDisplay;
552 case external::GrayscaleDisplay:
553 gparams.display = graphics::GrayscaleDisplay;
555 case external::ColorDisplay:
556 gparams.display = graphics::ColorDisplay;
558 case external::NoDisplay:
559 gparams.display = graphics::NoDisplay;
564 if (gparams.display == graphics::DefaultDisplay)
565 gparams.display = lyxrc.display_graphics;
566 // Override the above if we're not using a gui
568 gparams.display = graphics::NoDisplay;
574 docstring const getScreenLabel(InsetExternalParams const & params,
575 Buffer const & buffer)
577 external::Template const * const ptr =
578 external::getTemplatePtr(params);
581 return support::bformat((_("External template %1$s is not installed")),
582 lyx::from_utf8(params.templatename()));
584 return lyx::from_utf8(external::doSubstitution(params, buffer,
585 ptr->guiName, false));
588 void add_preview_and_start_loading(RenderMonitoredPreview &,
589 InsetExternal const &,
595 InsetExternalParams const & InsetExternal::params() const
601 void InsetExternal::setParams(InsetExternalParams const & p,
602 Buffer const & buffer)
606 // Subsequent calls to the InsetExternal::Params default constructor
608 defaultTemplateName = params_.templatename();
610 switch (getRenderType(params_)) {
612 RenderButton * button_ptr = renderer_->asButton();
614 renderer_.reset(new RenderButton);
615 button_ptr = renderer_->asButton();
618 button_ptr->update(getScreenLabel(params_, buffer), true);
621 } case RENDERGRAPHIC: {
622 RenderGraphic * graphic_ptr = renderer_->asGraphic();
624 renderer_.reset(new RenderGraphic(this));
625 graphic_ptr = renderer_->asGraphic();
628 graphic_ptr->update(get_grfx_params(params_));
632 } case RENDERPREVIEW: {
633 RenderMonitoredPreview * preview_ptr =
634 renderer_->asMonitoredPreview();
636 renderer_.reset(new RenderMonitoredPreview(this));
637 preview_ptr = renderer_->asMonitoredPreview();
638 preview_ptr->fileChanged(
639 boost::bind(&InsetExternal::fileChanged, this));
642 if (preview_ptr->monitoring())
643 preview_ptr->stopMonitoring();
644 add_preview_and_start_loading(*preview_ptr, *this, buffer);
652 void InsetExternal::fileChanged() const
654 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
658 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
661 Buffer const & buffer = *buffer_ptr;
662 ptr->removePreview(buffer);
663 add_preview_and_start_loading(*ptr, *this, buffer);
667 void InsetExternal::write(Buffer const & buffer, ostream & os) const
669 params_.write(buffer, os);
673 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
675 InsetExternalParams params;
676 if (params.read(buffer, lex))
677 setParams(params, buffer);
681 int InsetExternal::latex(Buffer const & buf, odocstream & os,
682 OutputParams const & runparams) const
686 os << "\\fbox{\\ttfamily{}"
687 << lyx::from_utf8(params_.filename.outputFilename(buf.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 bufer's temporary directory.
696 bool const external_in_tmpdir = !runparams.nice && !runparams.dryrun;
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 return external::writeExternal(params_, "PDFLaTeX",
713 *(runparams.exportdata),
715 runparams.inComment);
720 return external::writeExternal(params_, "LaTeX", buf, os,
721 *(runparams.exportdata),
723 runparams.inComment);
727 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
728 OutputParams const & runparams) const
730 return external::writeExternal(params_, "Ascii", buf, os,
731 *(runparams.exportdata), false,
732 runparams.inComment);
736 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
737 OutputParams const & runparams) const
739 return external::writeExternal(params_, "DocBook", buf, os,
740 *(runparams.exportdata), false,
741 runparams.inComment);
745 void InsetExternal::validate(LaTeXFeatures & features) const
750 external::Template const * const et_ptr =
751 external::getTemplatePtr(params_);
754 external::Template const & et = *et_ptr;
757 switch (features.runparams().flavor) {
758 case OutputParams::LATEX:
761 case OutputParams::PDFLATEX:
764 case OutputParams::XML:
768 external::Template::Formats::const_iterator cit =
769 et.formats.find(format);
770 if (cit == et.formats.end())
773 // FIXME: We don't need that always
774 features.require("lyxdot");
776 vector<string>::const_iterator it = cit->second.requirements.begin();
777 vector<string>::const_iterator end = cit->second.requirements.end();
778 for (; it != end; ++it)
779 features.require(*it);
781 external::TemplateManager & etm = external::TemplateManager::get();
783 it = cit->second.preambleNames.begin();
784 end = cit->second.preambleNames.end();
785 for (; it != end; ++it) {
786 string const preamble = etm.getPreambleDefByName(*it);
787 if (!preamble.empty())
788 features.addExternalPreamble(preamble);
799 bool preview_wanted(InsetExternalParams const & params)
801 string const included_file = params.filename.absFilename();
803 return params.display == external::PreviewDisplay &&
804 support::isFileReadable(included_file);
808 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
810 lyx::odocstringstream os;
811 OutputParams runparams;
812 runparams.flavor = OutputParams::LATEX;
813 inset.latex(buffer, os, runparams);
819 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
820 InsetExternal const & inset,
821 Buffer const & buffer)
823 InsetExternalParams const & params = inset.params();
825 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
826 preview_wanted(params)) {
827 renderer.setAbsFile(params.filename.absFilename());
828 docstring const snippet = latex_string(inset, buffer);
829 renderer.addPreview(snippet, buffer);
830 renderer.startLoading(buffer);
837 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
839 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
843 if (preview_wanted(params())) {
844 ptr->setAbsFile(params_.filename.absFilename());
845 docstring const snippet = latex_string(*this, ploader.buffer());
846 ptr->addPreview(snippet, ploader);
853 string const InsetExternalMailer::name_("external");
855 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
860 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
862 return params2string(inset_.params(), buffer);
866 void InsetExternalMailer::string2params(string const & in,
867 Buffer const & buffer,
868 InsetExternalParams & params)
870 params = InsetExternalParams();
874 istringstream data(in);
880 if (!lex || name != name_)
881 return print_mailer_error("InsetExternalMailer", in, 1, name_);
883 // This is part of the inset proper that is usually swallowed
884 // by LyXText::readInset
887 if (!lex || id != "External")
888 return print_mailer_error("InsetBoxMailer", in, 2, "External");
890 params.read(buffer, lex);
895 InsetExternalMailer::params2string(InsetExternalParams const & params,
896 Buffer const & buffer)
899 data << name_ << ' ';
900 params.write(buffer, data);
901 data << "\\end_inset\n";