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/ExternalTemplate.h"
16 #include "insets/RenderButton.h"
17 #include "insets/RenderGraphic.h"
18 #include "insets/RenderPreview.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>
50 using std::istringstream;
52 using std::ostringstream;
58 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
60 unsigned int const defaultLyxScale = 100;
62 string defaultTemplateName = "RasterImage";
73 support::FileName const tempname(support::tempName(support::FileName(), "lyxext"));
74 // FIXME: This is unsafe
75 support::unlink(tempname);
76 // must have an extension for the converter code to work correctly.
77 tempname_ = support::FileName(tempname.absFilename() + ".tmp");
81 TempName::TempName(TempName const &)
83 tempname_ = TempName()();
89 support::unlink(tempname_);
94 TempName::operator=(TempName const & other)
97 tempname_ = TempName()();
104 /// The translator between the Display enum and corresponding lyx string.
105 Translator<DisplayType, string> const initTranslator()
107 Translator<DisplayType, string> translator(DefaultDisplay, "default");
109 // Fill the display translator
110 translator.addPair(MonochromeDisplay, "monochrome");
111 translator.addPair(GrayscaleDisplay, "grayscale");
112 translator.addPair(ColorDisplay, "color");
113 translator.addPair(PreviewDisplay, "preview");
114 translator.addPair(NoDisplay, "none");
122 Translator<DisplayType, string> const & displayTranslator()
124 static Translator<DisplayType, string> const translator =
129 } // namespace external
132 InsetExternalParams::InsetExternalParams()
133 : display(defaultDisplayType),
134 lyxscale(defaultLyxScale),
136 templatename_(defaultTemplateName)
142 template <typename T>
143 void clearIfNotFound(T & data, external::TransformID value,
144 vector<external::TransformID> const & ids)
146 typedef vector<external::TransformID>::const_iterator
149 const_iterator it = ids.begin();
150 const_iterator end = ids.end();
151 it = std::find(it, end, value);
159 void InsetExternalParams::settemplate(string const & name)
161 templatename_ = name;
163 external::TemplateManager const & etm =
164 external::TemplateManager::get();
165 external::Template const * const et = etm.getTemplateByName(name);
167 // Be safe. Don't lose data.
170 // Ascertain which transforms the template supports.
171 // Empty all those that it doesn't.
172 vector<external::TransformID> const & ids = et->transformIds;
173 clearIfNotFound(clipdata, external::Clip, ids);
174 clearIfNotFound(extradata, external::Extra, ids);
175 clearIfNotFound(resizedata, external::Resize, ids);
176 clearIfNotFound(rotationdata, external::Rotate, ids);
180 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
183 << "\ttemplate " << templatename() << '\n';
185 if (!filename.empty())
187 << filename.outputFilename(buffer.filePath())
190 if (display != defaultDisplayType)
192 << external::displayTranslator().find(display)
195 if (lyxscale != defaultLyxScale)
196 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
201 if (!clipdata.bbox.empty())
202 os << "\tboundingBox " << clipdata.bbox << '\n';
206 external::ExtraData::const_iterator it = extradata.begin();
207 external::ExtraData::const_iterator end = extradata.end();
208 for (; it != end; ++it) {
209 if (!it->second.empty())
210 os << "\textra " << it->first << " \""
211 << it->second << "\"\n";
214 if (!rotationdata.no_rotation()) {
215 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
216 if (rotationdata.origin() != external::RotationData::DEFAULT)
217 os << "\trotateOrigin "
218 << rotationdata.originString() << '\n';
221 if (!resizedata.no_resize()) {
222 using support::float_equal;
223 double const scl = convert<double>(resizedata.scale);
224 if (!float_equal(scl, 0.0, 0.05)) {
225 if (!float_equal(scl, 100.0, 0.05))
227 << resizedata.scale << '\n';
229 if (!resizedata.width.zero())
231 << resizedata.width.asString() << '\n';
232 if (!resizedata.height.zero())
234 << resizedata.height.asString() << '\n';
236 if (resizedata.keepAspectRatio)
237 os << "\tkeepAspectRatio\n";
242 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
262 keyword_item external_tags[] = {
263 { "\\end_inset", EX_END },
264 { "boundingBox", EX_BOUNDINGBOX },
266 { "display", EX_DISPLAY},
267 { "draft", EX_DRAFT},
268 { "extra", EX_EXTRA },
269 { "filename", EX_FILENAME},
270 { "height", EX_HEIGHT },
271 { "keepAspectRatio", EX_KEEPASPECTRATIO },
272 { "lyxscale", EX_LYXSCALE},
273 { "rotateAngle", EX_ROTATEANGLE },
274 { "rotateOrigin", EX_ROTATEORIGIN },
275 { "scale", EX_SCALE },
276 { "template", EX_TEMPLATE },
277 { "width", EX_WIDTH }
280 PushPopHelper pph(lex, external_tags, EX_END);
282 bool found_end = false;
283 bool read_error = false;
289 templatename_ = lex.getString();
294 string const name = lex.getString();
295 filename.set(name, buffer.filePath());
301 string const name = lex.getString();
302 display = external::displayTranslator().find(name);
308 lyxscale = lex.getInteger();
317 clipdata.bbox.xl = lex.getInteger();
319 clipdata.bbox.yb = lex.getInteger();
321 clipdata.bbox.xr = lex.getInteger();
323 clipdata.bbox.yt = lex.getInteger();
327 clipdata.clip = true;
332 string const name = lex.getString();
334 extradata.set(name, lex.getString());
340 resizedata.height = Length(lex.getString());
343 case EX_KEEPASPECTRATIO:
344 resizedata.keepAspectRatio = true;
349 rotationdata.angle = lex.getString();
352 case EX_ROTATEORIGIN:
354 rotationdata.origin(lex.getString());
359 resizedata.scale = lex.getString();
364 resizedata.width = Length(lex.getString());
372 lex.printError("ExternalInset::read: "
373 "Wrong tag: $$Token");
378 if (found_end || read_error)
383 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
385 // This is a trick to make sure that the data are self-consistent.
386 settemplate(templatename_);
388 if (lyxerr.debugging(Debug::EXTERNAL)) {
389 lyxerr << "InsetExternalParams::read:\n";
390 write(buffer, lyxerr);
397 InsetExternal::InsetExternal()
398 : renderer_(new RenderButton)
402 InsetExternal::InsetExternal(InsetExternal const & other)
404 boost::signals::trackable(),
405 params_(other.params_),
406 renderer_(other.renderer_->clone(this))
410 auto_ptr<Inset> InsetExternal::doClone() const
412 return auto_ptr<Inset>(new InsetExternal(*this));
416 InsetExternal::~InsetExternal()
418 InsetExternalMailer(*this).hideDialog();
422 void InsetExternal::statusChanged() const
424 LyX::cref().updateInset(this);
428 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
430 switch (cmd.action) {
432 case LFUN_EXTERNAL_EDIT: {
433 Buffer const & buffer = cur.buffer();
434 InsetExternalParams p;
435 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
436 external::editExternal(p, buffer);
440 case LFUN_INSET_MODIFY: {
441 Buffer const & buffer = cur.buffer();
442 InsetExternalParams p;
443 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
444 setParams(p, buffer);
448 case LFUN_INSET_DIALOG_UPDATE:
449 InsetExternalMailer(*this).updateDialog(&cur.bv());
452 case LFUN_MOUSE_RELEASE:
453 if (!cur.selection())
454 InsetExternalMailer(*this).showDialog(&cur.bv());
458 Inset::doDispatch(cur, cmd);
463 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
464 FuncStatus & flag) const
466 switch (cmd.action) {
468 case LFUN_EXTERNAL_EDIT:
469 case LFUN_INSET_MODIFY:
470 case LFUN_INSET_DIALOG_UPDATE:
475 return Inset::getStatus(cur, cmd, flag);
480 void InsetExternal::edit(Cursor & cur, bool)
482 InsetExternalMailer(*this).showDialog(&cur.bv());
486 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
488 renderer_->metrics(mi, dim);
489 bool const changed = dim_ != dim;
495 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
497 setPosCache(pi, x, y);
498 renderer_->draw(pi, x, y);
511 RenderType getRenderType(InsetExternalParams const & p)
513 if (!external::getTemplatePtr(p) ||
514 p.filename.empty() ||
515 p.display == external::NoDisplay)
518 if (p.display == external::PreviewDisplay) {
519 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
520 return RENDERPREVIEW;
524 if (p.display == external::DefaultDisplay &&
525 lyxrc.display_graphics == graphics::NoDisplay)
527 return RENDERGRAPHIC;
531 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
533 graphics::Params gparams;
535 gparams.filename = eparams.filename;
536 gparams.scale = eparams.lyxscale;
537 if (eparams.clipdata.clip)
538 gparams.bb = eparams.clipdata.bbox;
539 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
541 switch (eparams.display) {
542 case external::DefaultDisplay:
543 gparams.display = graphics::DefaultDisplay;
545 case external::MonochromeDisplay:
546 gparams.display = graphics::MonochromeDisplay;
548 case external::GrayscaleDisplay:
549 gparams.display = graphics::GrayscaleDisplay;
551 case external::ColorDisplay:
552 gparams.display = graphics::ColorDisplay;
554 case external::NoDisplay:
555 gparams.display = graphics::NoDisplay;
560 if (gparams.display == graphics::DefaultDisplay)
561 gparams.display = lyxrc.display_graphics;
562 // Override the above if we're not using a gui
564 gparams.display = graphics::NoDisplay;
570 docstring const getScreenLabel(InsetExternalParams const & params,
571 Buffer const & buffer)
573 external::Template const * const ptr =
574 external::getTemplatePtr(params);
577 return support::bformat((_("External template %1$s is not installed")),
578 from_utf8(params.templatename()));
580 docstring gui = _(ptr->guiName);
581 return from_utf8(external::doSubstitution(params, buffer,
582 to_utf8(gui), false));
585 void add_preview_and_start_loading(RenderMonitoredPreview &,
586 InsetExternal const &,
592 InsetExternalParams const & InsetExternal::params() const
598 void InsetExternal::setParams(InsetExternalParams const & p,
599 Buffer const & buffer)
603 // Subsequent calls to the InsetExternal::Params default constructor
605 defaultTemplateName = params_.templatename();
607 switch (getRenderType(params_)) {
609 RenderButton * button_ptr = renderer_->asButton();
611 renderer_.reset(new RenderButton);
612 button_ptr = renderer_->asButton();
615 button_ptr->update(getScreenLabel(params_, buffer), true);
618 } case RENDERGRAPHIC: {
619 RenderGraphic * graphic_ptr = renderer_->asGraphic();
621 renderer_.reset(new RenderGraphic(this));
622 graphic_ptr = renderer_->asGraphic();
625 graphic_ptr->update(get_grfx_params(params_));
629 } case RENDERPREVIEW: {
630 RenderMonitoredPreview * preview_ptr =
631 renderer_->asMonitoredPreview();
633 renderer_.reset(new RenderMonitoredPreview(this));
634 preview_ptr = renderer_->asMonitoredPreview();
635 preview_ptr->fileChanged(
636 boost::bind(&InsetExternal::fileChanged, this));
639 if (preview_ptr->monitoring())
640 preview_ptr->stopMonitoring();
641 add_preview_and_start_loading(*preview_ptr, *this, buffer);
649 void InsetExternal::fileChanged() const
651 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
655 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
658 Buffer const & buffer = *buffer_ptr;
659 ptr->removePreview(buffer);
660 add_preview_and_start_loading(*ptr, *this, buffer);
664 void InsetExternal::write(Buffer const & buffer, ostream & os) const
666 params_.write(buffer, os);
670 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
672 InsetExternalParams params;
673 if (params.read(buffer, lex))
674 setParams(params, buffer);
678 int InsetExternal::latex(Buffer const & buf, odocstream & os,
679 OutputParams const & runparams) const
683 os << "\\fbox{\\ttfamily{}"
684 << from_utf8(params_.filename.outputFilename(buf.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 return external::writeExternal(params_, "PDFLaTeX",
711 *(runparams.exportdata),
717 return external::writeExternal(params_, "LaTeX", buf, os,
718 *(runparams.exportdata),
724 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
725 OutputParams const & runparams) const
727 os << '\n'; // output external material on a new line
728 external::writeExternal(params_, "Ascii", buf, os,
729 *(runparams.exportdata), false,
730 runparams.dryrun || runparams.inComment);
731 return PLAINTEXT_NEWLINE;
735 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
736 OutputParams const & runparams) const
738 return external::writeExternal(params_, "DocBook", buf, os,
739 *(runparams.exportdata), false,
740 runparams.dryrun || runparams.inComment);
744 void InsetExternal::validate(LaTeXFeatures & features) const
749 external::Template const * const et_ptr =
750 external::getTemplatePtr(params_);
753 external::Template const & et = *et_ptr;
756 switch (features.runparams().flavor) {
757 case OutputParams::LATEX:
760 case OutputParams::PDFLATEX:
763 case OutputParams::XML:
767 external::Template::Formats::const_iterator cit =
768 et.formats.find(format);
769 if (cit == et.formats.end())
772 // FIXME: We don't need that always
773 features.require("lyxdot");
775 vector<string>::const_iterator it = cit->second.requirements.begin();
776 vector<string>::const_iterator end = cit->second.requirements.end();
777 for (; it != end; ++it)
778 features.require(*it);
780 external::TemplateManager & etm = external::TemplateManager::get();
782 it = cit->second.preambleNames.begin();
783 end = cit->second.preambleNames.end();
784 for (; it != end; ++it) {
785 string const preamble = etm.getPreambleDefByName(*it);
786 if (!preamble.empty())
787 features.addPreambleSnippet(preamble);
798 bool preview_wanted(InsetExternalParams const & params)
800 return params.display == external::PreviewDisplay &&
801 support::isFileReadable(params.filename);
805 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
808 // We don't need to set runparams.encoding since it is not used by
810 OutputParams runparams(0);
811 runparams.flavor = OutputParams::LATEX;
812 inset.latex(buffer, os, runparams);
817 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
818 InsetExternal const & inset,
819 Buffer const & buffer)
821 InsetExternalParams const & params = inset.params();
823 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
824 preview_wanted(params)) {
825 renderer.setAbsFile(params.filename);
826 docstring const snippet = latex_string(inset, buffer);
827 renderer.addPreview(snippet, buffer);
828 renderer.startLoading(buffer);
835 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
837 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
841 if (preview_wanted(params())) {
842 ptr->setAbsFile(params_.filename);
843 docstring const snippet = latex_string(*this, ploader.buffer());
844 ptr->addPreview(snippet, ploader);
851 string const InsetExternalMailer::name_("external");
853 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
858 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
860 return params2string(inset_.params(), buffer);
864 void InsetExternalMailer::string2params(string const & in,
865 Buffer const & buffer,
866 InsetExternalParams & params)
868 params = InsetExternalParams();
872 istringstream data(in);
878 if (!lex || name != name_)
879 return print_mailer_error("InsetExternalMailer", in, 1, name_);
881 // This is part of the inset proper that is usually swallowed
882 // by Text::readInset
885 if (!lex || id != "External")
886 return print_mailer_error("InsetBoxMailer", in, 2, "External");
888 params.read(buffer, lex);
893 InsetExternalMailer::params2string(InsetExternalParams const & params,
894 Buffer const & buffer)
897 data << name_ << ' ';
898 params.write(buffer, data);
899 data << "\\end_inset\n";