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 "funcrequest.h"
27 #include "LaTeXFeatures.h"
31 #include "metricsinfo.h"
32 #include "outputparams.h"
34 #include "frontends/lyx_gui.h"
36 #include "graphics/PreviewLoader.h"
38 #include "support/filetools.h"
39 #include "support/lstrings.h"
40 #include "support/lyxlib.h"
41 #include "support/convert.h"
42 #include "support/translator.h"
44 #include <boost/bind.hpp>
48 namespace support = lyx::support;
49 namespace external = lyx::external;
50 namespace graphics = lyx::graphics;
56 using std::istringstream;
58 using std::ostringstream;
64 external::DisplayType const defaultDisplayType = external::NoDisplay;
66 unsigned int const defaultLyxScale = 100;
68 string defaultTemplateName = "RasterImage";
78 tempname_ = support::tempName(string(), "lyxext");
79 // FIXME: This is unsafe
80 support::unlink(tempname_);
81 // must have an extension for the converter code to work correctly.
86 TempName::TempName(TempName const &)
88 tempname_ = TempName()();
94 support::unlink(tempname_);
99 TempName::operator=(TempName const & other)
102 tempname_ = TempName()();
109 /// The translator between the Display enum and corresponding lyx string.
110 Translator<DisplayType, string> const initTranslator()
112 Translator<DisplayType, string> translator(DefaultDisplay, "default");
114 // Fill the display translator
115 translator.addPair(MonochromeDisplay, "monochrome");
116 translator.addPair(GrayscaleDisplay, "grayscale");
117 translator.addPair(ColorDisplay, "color");
118 translator.addPair(PreviewDisplay, "preview");
119 translator.addPair(NoDisplay, "none");
127 Translator<DisplayType, string> const & displayTranslator()
129 static Translator<DisplayType, string> const translator =
134 } // namespace external
138 InsetExternalParams::InsetExternalParams()
139 : display(defaultDisplayType),
140 lyxscale(defaultLyxScale),
142 templatename_(defaultTemplateName)
148 template <typename T>
149 void clearIfNotFound(T & data, external::TransformID value,
150 vector<external::TransformID> const & ids)
152 typedef vector<external::TransformID>::const_iterator
155 const_iterator it = ids.begin();
156 const_iterator end = ids.end();
157 it = std::find(it, end, value);
165 void InsetExternalParams::settemplate(string const & name)
167 templatename_ = name;
169 external::TemplateManager const & etm =
170 external::TemplateManager::get();
171 external::Template const * const et = etm.getTemplateByName(name);
173 // Be safe. Don't lose data.
176 // Ascertain which transforms the template supports.
177 // Empty all those that it doesn't.
178 vector<external::TransformID> const & ids = et->transformIds;
179 clearIfNotFound(clipdata, external::Clip, ids);
180 clearIfNotFound(extradata, external::Extra, ids);
181 clearIfNotFound(resizedata, external::Resize, ids);
182 clearIfNotFound(rotationdata, external::Rotate, ids);
186 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
189 << "\ttemplate " << templatename() << '\n';
191 if (!filename.empty())
193 << filename.outputFilename(buffer.filePath())
196 if (display != defaultDisplayType)
198 << external::displayTranslator().find(display)
201 if (lyxscale != defaultLyxScale)
202 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
207 if (!clipdata.bbox.empty())
208 os << "\tboundingBox " << clipdata.bbox << '\n';
212 external::ExtraData::const_iterator it = extradata.begin();
213 external::ExtraData::const_iterator end = extradata.end();
214 for (; it != end; ++it) {
215 if (!it->second.empty())
216 os << "\textra " << it->first << " \""
217 << it->second << "\"\n";
220 if (!rotationdata.no_rotation()) {
221 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
222 if (rotationdata.origin() != external::RotationData::DEFAULT)
223 os << "\trotateOrigin "
224 << rotationdata.originString() << '\n';
227 if (!resizedata.no_resize()) {
228 using support::float_equal;
229 double const scl = convert<double>(resizedata.scale);
230 if (!float_equal(scl, 0.0, 0.05)) {
231 if (!float_equal(scl, 100.0, 0.05))
233 << resizedata.scale << '\n';
235 if (!resizedata.width.zero())
237 << resizedata.width.asString() << '\n';
238 if (!resizedata.height.zero())
240 << resizedata.height.asString() << '\n';
242 if (resizedata.keepAspectRatio)
243 os << "\tkeepAspectRatio\n";
248 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
268 keyword_item external_tags[] = {
269 { "\\end_inset", EX_END },
270 { "boundingBox", EX_BOUNDINGBOX },
272 { "display", EX_DISPLAY},
273 { "draft", EX_DRAFT},
274 { "extra", EX_EXTRA },
275 { "filename", EX_FILENAME},
276 { "height", EX_HEIGHT },
277 { "keepAspectRatio", EX_KEEPASPECTRATIO },
278 { "lyxscale", EX_LYXSCALE},
279 { "rotateAngle", EX_ROTATEANGLE },
280 { "rotateOrigin", EX_ROTATEORIGIN },
281 { "scale", EX_SCALE },
282 { "template", EX_TEMPLATE },
283 { "width", EX_WIDTH }
286 pushpophelper pph(lex, external_tags, EX_END);
288 bool found_end = false;
289 bool read_error = false;
295 templatename_ = lex.getString();
300 string const name = lex.getString();
301 filename.set(name, buffer.filePath());
307 string const name = lex.getString();
308 display = external::displayTranslator().find(name);
314 lyxscale = lex.getInteger();
323 clipdata.bbox.xl = lex.getInteger();
325 clipdata.bbox.yb = lex.getInteger();
327 clipdata.bbox.xr = lex.getInteger();
329 clipdata.bbox.yt = lex.getInteger();
333 clipdata.clip = true;
338 string const name = lex.getString();
340 extradata.set(name, lex.getString());
346 resizedata.height = LyXLength(lex.getString());
349 case EX_KEEPASPECTRATIO:
350 resizedata.keepAspectRatio = true;
355 rotationdata.angle = lex.getString();
358 case EX_ROTATEORIGIN:
360 rotationdata.origin(lex.getString());
365 resizedata.scale = lex.getString();
370 resizedata.width = LyXLength(lex.getString());
378 lex.printError("ExternalInset::read: "
379 "Wrong tag: $$Token");
384 if (found_end || read_error)
389 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
391 // This is a trick to make sure that the data are self-consistent.
392 settemplate(templatename_);
394 if (lyxerr.debugging(Debug::EXTERNAL)) {
395 lyxerr << "InsetExternalParams::read:\n";
396 write(buffer, lyxerr);
403 InsetExternal::InsetExternal()
404 : renderer_(new RenderButton)
408 InsetExternal::InsetExternal(InsetExternal const & other)
410 boost::signals::trackable(),
411 params_(other.params_),
412 renderer_(other.renderer_->clone(this))
416 auto_ptr<InsetBase> InsetExternal::doClone() const
418 return auto_ptr<InsetBase>(new InsetExternal(*this));
422 InsetExternal::~InsetExternal()
424 InsetExternalMailer(*this).hideDialog();
428 void InsetExternal::statusChanged() const
430 LyX::cref().updateInset(this);
434 void InsetExternal::doDispatch(LCursor & cur, FuncRequest & cmd)
436 switch (cmd.action) {
438 case LFUN_EXTERNAL_EDIT: {
439 Buffer const & buffer = cur.buffer();
440 InsetExternalParams p;
441 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
442 external::editExternal(p, buffer);
446 case LFUN_INSET_MODIFY: {
447 Buffer const & buffer = cur.buffer();
448 InsetExternalParams p;
449 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
450 setParams(p, buffer);
454 case LFUN_INSET_DIALOG_UPDATE:
455 InsetExternalMailer(*this).updateDialog(&cur.bv());
458 case LFUN_MOUSE_RELEASE:
459 InsetExternalMailer(*this).showDialog(&cur.bv());
463 InsetBase::doDispatch(cur, cmd);
468 bool InsetExternal::getStatus(LCursor & cur, FuncRequest const & cmd,
469 FuncStatus & flag) const
471 switch (cmd.action) {
473 case LFUN_EXTERNAL_EDIT:
474 case LFUN_INSET_MODIFY:
475 case LFUN_INSET_DIALOG_UPDATE:
480 return InsetBase::getStatus(cur, cmd, flag);
485 void InsetExternal::edit(LCursor & cur, bool)
487 InsetExternalMailer(*this).showDialog(&cur.bv());
491 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
493 renderer_->metrics(mi, dim);
498 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
500 setPosCache(pi, x, y);
501 renderer_->draw(pi, x, y);
514 RenderType getRenderType(InsetExternalParams const & p)
516 if (!external::getTemplatePtr(p) ||
517 p.filename.empty() ||
518 p.display == external::NoDisplay)
521 if (p.display == external::PreviewDisplay) {
522 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
523 return RENDERPREVIEW;
527 if (p.display == external::DefaultDisplay &&
528 lyxrc.display_graphics == graphics::NoDisplay)
530 return RENDERGRAPHIC;
534 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
536 graphics::Params gparams;
538 gparams.filename = eparams.filename.absFilename();
539 gparams.scale = eparams.lyxscale;
540 if (eparams.clipdata.clip)
541 gparams.bb = eparams.clipdata.bbox;
542 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
544 switch (eparams.display) {
545 case external::DefaultDisplay:
546 gparams.display = graphics::DefaultDisplay;
548 case external::MonochromeDisplay:
549 gparams.display = graphics::MonochromeDisplay;
551 case external::GrayscaleDisplay:
552 gparams.display = graphics::GrayscaleDisplay;
554 case external::ColorDisplay:
555 gparams.display = graphics::ColorDisplay;
557 case external::NoDisplay:
558 gparams.display = graphics::NoDisplay;
563 if (gparams.display == graphics::DefaultDisplay)
564 gparams.display = lyxrc.display_graphics;
565 // Override the above if we're not using a gui
566 if (!lyx_gui::use_gui)
567 gparams.display = graphics::NoDisplay;
573 docstring const getScreenLabel(InsetExternalParams const & params,
574 Buffer const & buffer)
576 external::Template const * const ptr =
577 external::getTemplatePtr(params);
580 return support::bformat((_("External template %1$s is not installed")),
581 lyx::from_utf8(params.templatename()));
583 return lyx::from_utf8(external::doSubstitution(params, buffer,
584 ptr->guiName, false));
587 void add_preview_and_start_loading(RenderMonitoredPreview &,
588 InsetExternal const &,
594 InsetExternalParams const & InsetExternal::params() const
600 void InsetExternal::setParams(InsetExternalParams const & p,
601 Buffer const & buffer)
605 // Subsequent calls to the InsetExternal::Params default constructor
607 defaultTemplateName = params_.templatename();
609 switch (getRenderType(params_)) {
611 RenderButton * button_ptr = renderer_->asButton();
613 renderer_.reset(new RenderButton);
614 button_ptr = renderer_->asButton();
617 button_ptr->update(getScreenLabel(params_, buffer), true);
620 } case RENDERGRAPHIC: {
621 RenderGraphic * graphic_ptr = renderer_->asGraphic();
623 renderer_.reset(new RenderGraphic(this));
624 graphic_ptr = renderer_->asGraphic();
627 graphic_ptr->update(get_grfx_params(params_));
631 } case RENDERPREVIEW: {
632 RenderMonitoredPreview * preview_ptr =
633 renderer_->asMonitoredPreview();
635 renderer_.reset(new RenderMonitoredPreview(this));
636 preview_ptr = renderer_->asMonitoredPreview();
637 preview_ptr->fileChanged(
638 boost::bind(&InsetExternal::fileChanged, this));
641 if (preview_ptr->monitoring())
642 preview_ptr->stopMonitoring();
643 add_preview_and_start_loading(*preview_ptr, *this, buffer);
651 void InsetExternal::fileChanged() const
653 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
657 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
660 Buffer const & buffer = *buffer_ptr;
661 ptr->removePreview(buffer);
662 add_preview_and_start_loading(*ptr, *this, buffer);
666 void InsetExternal::write(Buffer const & buffer, ostream & os) const
668 params_.write(buffer, os);
672 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
674 InsetExternalParams params;
675 if (params.read(buffer, lex))
676 setParams(params, buffer);
680 int InsetExternal::latex(Buffer const & buf, ostream & os,
681 OutputParams const & runparams) const
684 os << "\\fbox{\\ttfamily{}"
685 << params_.filename.outputFilename(buf.filePath())
690 // "nice" means that the buffer is exported to LaTeX format but not
691 // run through the LaTeX compiler.
692 // If we're running through the LaTeX compiler, we should write the
693 // generated files in the bufer's temporary directory.
694 bool const external_in_tmpdir = !runparams.nice && !runparams.dryrun;
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");
707 if (cit != et.formats.end())
708 return external::writeExternal(params_, "PDFLaTeX",
710 *(runparams.exportdata),
712 runparams.inComment);
714 return external::writeExternal(params_, "LaTeX", buf, os,
715 *(runparams.exportdata),
717 runparams.inComment);
721 int InsetExternal::plaintext(Buffer const & buf, lyx::odocstream & os,
722 OutputParams const & runparams) const
724 std::ostringstream oss;
725 int const retval = external::writeExternal(params_, "Ascii", buf, oss,
726 *(runparams.exportdata), false,
727 runparams.inComment);
729 os << lyx::from_utf8(oss.str());
734 int InsetExternal::docbook(Buffer const & buf, ostream & os,
735 OutputParams const & runparams) const
737 return external::writeExternal(params_, "DocBook", buf, os,
738 *(runparams.exportdata), false,
739 runparams.inComment);
743 void InsetExternal::validate(LaTeXFeatures & features) const
748 external::Template const * const et_ptr =
749 external::getTemplatePtr(params_);
752 external::Template const & et = *et_ptr;
755 switch (features.runparams().flavor) {
756 case OutputParams::LATEX:
759 case OutputParams::PDFLATEX:
762 case OutputParams::XML:
766 external::Template::Formats::const_iterator cit =
767 et.formats.find(format);
768 if (cit == et.formats.end())
771 // FIXME: We don't need that always
772 features.require("lyxdot");
774 vector<string>::const_iterator it = cit->second.requirements.begin();
775 vector<string>::const_iterator end = cit->second.requirements.end();
776 for (; it != end; ++it)
777 features.require(*it);
779 external::TemplateManager & etm = external::TemplateManager::get();
781 it = cit->second.preambleNames.begin();
782 end = cit->second.preambleNames.end();
783 for (; it != end; ++it) {
784 string const preamble = etm.getPreambleDefByName(*it);
785 if (!preamble.empty())
786 features.addExternalPreamble(preamble);
797 bool preview_wanted(InsetExternalParams const & params)
799 string const included_file = params.filename.absFilename();
801 return params.display == external::PreviewDisplay &&
802 support::isFileReadable(included_file);
806 string const latex_string(InsetExternal const & inset, Buffer const & buffer)
809 OutputParams runparams;
810 runparams.flavor = OutputParams::LATEX;
811 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.absFilename());
826 string 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.absFilename());
843 string 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 LyXText::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";