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"
35 #include "frontends/LyXView.h"
37 #include "graphics/PreviewLoader.h"
39 #include "support/filetools.h"
40 #include "support/lstrings.h"
41 #include "support/lyxlib.h"
42 #include "support/convert.h"
43 #include "support/translator.h"
45 #include <boost/bind.hpp>
49 namespace support = lyx::support;
50 namespace external = lyx::external;
51 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 string const getScreenLabel(InsetExternalParams const & params,
574 Buffer const & buffer)
576 external::Template const * const ptr =
577 external::getTemplatePtr(params);
580 return support::bformat(lyx::to_utf8(_("External template %1$s is not installed")),
581 params.templatename());
582 return external::doSubstitution(params, buffer, ptr->guiName, 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, LyXLex & lex)
672 InsetExternalParams params;
673 if (params.read(buffer, lex))
674 setParams(params, buffer);
678 int InsetExternal::latex(Buffer const & buf, ostream & os,
679 OutputParams const & runparams) const
682 os << "\\fbox{\\ttfamily{}"
683 << params_.filename.outputFilename(buf.filePath())
688 // "nice" means that the buffer is exported to LaTeX format but not
689 // run through the LaTeX compiler.
690 // If we're running through the LaTeX compiler, we should write the
691 // generated files in the bufer's temporary directory.
692 bool const external_in_tmpdir = !runparams.nice && !runparams.dryrun;
694 // If the template has specified a PDFLaTeX output, then we try and
696 if (runparams.flavor == OutputParams::PDFLATEX) {
697 external::Template const * const et_ptr =
698 external::getTemplatePtr(params_);
701 external::Template const & et = *et_ptr;
703 external::Template::Formats::const_iterator cit =
704 et.formats.find("PDFLaTeX");
705 if (cit != et.formats.end())
706 return external::writeExternal(params_, "PDFLaTeX",
708 *(runparams.exportdata),
710 runparams.inComment);
712 return external::writeExternal(params_, "LaTeX", buf, os,
713 *(runparams.exportdata),
715 runparams.inComment);
719 int InsetExternal::plaintext(Buffer const & buf, ostream & os,
720 OutputParams const & runparams) const
722 return external::writeExternal(params_, "Ascii", buf, os,
723 *(runparams.exportdata), false,
724 runparams.inComment);
728 int InsetExternal::docbook(Buffer const & buf, ostream & os,
729 OutputParams const & runparams) const
731 return external::writeExternal(params_, "DocBook", buf, os,
732 *(runparams.exportdata), false,
733 runparams.inComment);
737 void InsetExternal::validate(LaTeXFeatures & features) const
742 external::Template const * const et_ptr =
743 external::getTemplatePtr(params_);
746 external::Template const & et = *et_ptr;
749 switch (features.runparams().flavor) {
750 case OutputParams::LATEX:
753 case OutputParams::PDFLATEX:
756 case OutputParams::XML:
760 external::Template::Formats::const_iterator cit =
761 et.formats.find(format);
762 if (cit == et.formats.end())
765 // FIXME: We don't need that always
766 features.require("lyxdot");
768 vector<string>::const_iterator it = cit->second.requirements.begin();
769 vector<string>::const_iterator end = cit->second.requirements.end();
770 for (; it != end; ++it)
771 features.require(*it);
773 external::TemplateManager & etm = external::TemplateManager::get();
775 it = cit->second.preambleNames.begin();
776 end = cit->second.preambleNames.end();
777 for (; it != end; ++it) {
778 string const preamble = etm.getPreambleDefByName(*it);
779 if (!preamble.empty())
780 features.addExternalPreamble(preamble);
791 bool preview_wanted(InsetExternalParams const & params)
793 string const included_file = params.filename.absFilename();
795 return params.display == external::PreviewDisplay &&
796 support::isFileReadable(included_file);
800 string const latex_string(InsetExternal const & inset, Buffer const & buffer)
803 OutputParams runparams;
804 runparams.flavor = OutputParams::LATEX;
805 inset.latex(buffer, os, runparams);
811 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
812 InsetExternal const & inset,
813 Buffer const & buffer)
815 InsetExternalParams const & params = inset.params();
817 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
818 preview_wanted(params)) {
819 renderer.setAbsFile(params.filename.absFilename());
820 string const snippet = latex_string(inset, buffer);
821 renderer.addPreview(snippet, buffer);
822 renderer.startLoading(buffer);
829 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
831 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
835 if (preview_wanted(params())) {
836 ptr->setAbsFile(params_.filename.absFilename());
837 string const snippet = latex_string(*this, ploader.buffer());
838 ptr->addPreview(snippet, ploader);
845 string const InsetExternalMailer::name_("external");
847 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
852 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
854 return params2string(inset_.params(), buffer);
858 void InsetExternalMailer::string2params(string const & in,
859 Buffer const & buffer,
860 InsetExternalParams & params)
862 params = InsetExternalParams();
866 istringstream data(in);
872 if (!lex || name != name_)
873 return print_mailer_error("InsetExternalMailer", in, 1, name_);
875 // This is part of the inset proper that is usually swallowed
876 // by LyXText::readInset
879 if (!lex || id != "External")
880 return print_mailer_error("InsetBoxMailer", in, 2, "External");
882 params.read(buffer, lex);
887 InsetExternalMailer::params2string(InsetExternalParams const & params,
888 Buffer const & buffer)
891 data << name_ << ' ';
892 params.write(buffer, data);
893 data << "\\end_inset\n";