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>
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 string const tempname = support::tempName(string(), "lyxext");
74 // FIXME: This is unsafe
75 support::unlink(support::FileName(tempname));
76 // must have an extension for the converter code to work correctly.
77 tempname_ = support::FileName(tempname + ".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, LyXLex & 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 = LyXLength(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 = LyXLength(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<InsetBase> InsetExternal::doClone() const
412 return auto_ptr<InsetBase>(new InsetExternal(*this));
416 InsetExternal::~InsetExternal()
418 InsetExternalMailer(*this).hideDialog();
422 void InsetExternal::statusChanged() const
424 LyX::cref().updateInset(this);
428 void InsetExternal::doDispatch(LCursor & 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 InsetExternalMailer(*this).showDialog(&cur.bv());
457 InsetBase::doDispatch(cur, cmd);
462 bool InsetExternal::getStatus(LCursor & cur, FuncRequest const & cmd,
463 FuncStatus & flag) const
465 switch (cmd.action) {
467 case LFUN_EXTERNAL_EDIT:
468 case LFUN_INSET_MODIFY:
469 case LFUN_INSET_DIALOG_UPDATE:
474 return InsetBase::getStatus(cur, cmd, flag);
479 void InsetExternal::edit(LCursor & cur, bool)
481 InsetExternalMailer(*this).showDialog(&cur.bv());
485 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
487 renderer_->metrics(mi, dim);
488 bool const changed = dim_ != dim;
494 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
496 setPosCache(pi, x, y);
497 renderer_->draw(pi, x, y);
510 RenderType getRenderType(InsetExternalParams const & p)
512 if (!external::getTemplatePtr(p) ||
513 p.filename.empty() ||
514 p.display == external::NoDisplay)
517 if (p.display == external::PreviewDisplay) {
518 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
519 return RENDERPREVIEW;
523 if (p.display == external::DefaultDisplay &&
524 lyxrc.display_graphics == graphics::NoDisplay)
526 return RENDERGRAPHIC;
530 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
532 graphics::Params gparams;
534 gparams.filename = eparams.filename;
535 gparams.scale = eparams.lyxscale;
536 if (eparams.clipdata.clip)
537 gparams.bb = eparams.clipdata.bbox;
538 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
540 switch (eparams.display) {
541 case external::DefaultDisplay:
542 gparams.display = graphics::DefaultDisplay;
544 case external::MonochromeDisplay:
545 gparams.display = graphics::MonochromeDisplay;
547 case external::GrayscaleDisplay:
548 gparams.display = graphics::GrayscaleDisplay;
550 case external::ColorDisplay:
551 gparams.display = graphics::ColorDisplay;
553 case external::NoDisplay:
554 gparams.display = graphics::NoDisplay;
559 if (gparams.display == graphics::DefaultDisplay)
560 gparams.display = lyxrc.display_graphics;
561 // Override the above if we're not using a gui
563 gparams.display = graphics::NoDisplay;
569 docstring const getScreenLabel(InsetExternalParams const & params,
570 Buffer const & buffer)
572 external::Template const * const ptr =
573 external::getTemplatePtr(params);
576 return support::bformat((_("External template %1$s is not installed")),
577 from_utf8(params.templatename()));
579 return from_utf8(external::doSubstitution(params, buffer,
580 ptr->guiName, false));
583 void add_preview_and_start_loading(RenderMonitoredPreview &,
584 InsetExternal const &,
590 InsetExternalParams const & InsetExternal::params() const
596 void InsetExternal::setParams(InsetExternalParams const & p,
597 Buffer const & buffer)
601 // Subsequent calls to the InsetExternal::Params default constructor
603 defaultTemplateName = params_.templatename();
605 switch (getRenderType(params_)) {
607 RenderButton * button_ptr = renderer_->asButton();
609 renderer_.reset(new RenderButton);
610 button_ptr = renderer_->asButton();
613 button_ptr->update(getScreenLabel(params_, buffer), true);
616 } case RENDERGRAPHIC: {
617 RenderGraphic * graphic_ptr = renderer_->asGraphic();
619 renderer_.reset(new RenderGraphic(this));
620 graphic_ptr = renderer_->asGraphic();
623 graphic_ptr->update(get_grfx_params(params_));
627 } case RENDERPREVIEW: {
628 RenderMonitoredPreview * preview_ptr =
629 renderer_->asMonitoredPreview();
631 renderer_.reset(new RenderMonitoredPreview(this));
632 preview_ptr = renderer_->asMonitoredPreview();
633 preview_ptr->fileChanged(
634 boost::bind(&InsetExternal::fileChanged, this));
637 if (preview_ptr->monitoring())
638 preview_ptr->stopMonitoring();
639 add_preview_and_start_loading(*preview_ptr, *this, buffer);
647 void InsetExternal::fileChanged() const
649 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
653 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
656 Buffer const & buffer = *buffer_ptr;
657 ptr->removePreview(buffer);
658 add_preview_and_start_loading(*ptr, *this, buffer);
662 void InsetExternal::write(Buffer const & buffer, ostream & os) const
664 params_.write(buffer, os);
668 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
670 InsetExternalParams params;
671 if (params.read(buffer, lex))
672 setParams(params, buffer);
676 int InsetExternal::latex(Buffer const & buf, odocstream & os,
677 OutputParams const & runparams) const
681 os << "\\fbox{\\ttfamily{}"
682 << from_utf8(params_.filename.outputFilename(buf.filePath()))
687 // "nice" means that the buffer is exported to LaTeX format but not
688 // run through the LaTeX compiler.
689 // If we're running through the LaTeX compiler, we should write the
690 // generated files in the bufer's temporary directory.
691 bool const external_in_tmpdir = !runparams.nice && !runparams.dryrun;
693 // If the template has specified a PDFLaTeX output, then we try and
695 if (runparams.flavor == OutputParams::PDFLATEX) {
696 external::Template const * const et_ptr =
697 external::getTemplatePtr(params_);
700 external::Template const & et = *et_ptr;
702 external::Template::Formats::const_iterator cit =
703 et.formats.find("PDFLaTeX");
705 if (cit != et.formats.end()) {
706 return external::writeExternal(params_, "PDFLaTeX",
708 *(runparams.exportdata),
710 runparams.inComment);
715 return external::writeExternal(params_, "LaTeX", buf, os,
716 *(runparams.exportdata),
718 runparams.inComment);
722 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
723 OutputParams const & runparams) const
725 return external::writeExternal(params_, "Ascii", buf, os,
726 *(runparams.exportdata), false,
727 runparams.inComment);
731 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
732 OutputParams const & runparams) const
734 return external::writeExternal(params_, "DocBook", buf, os,
735 *(runparams.exportdata), false,
736 runparams.inComment);
740 void InsetExternal::validate(LaTeXFeatures & features) const
745 external::Template const * const et_ptr =
746 external::getTemplatePtr(params_);
749 external::Template const & et = *et_ptr;
752 switch (features.runparams().flavor) {
753 case OutputParams::LATEX:
756 case OutputParams::PDFLATEX:
759 case OutputParams::XML:
763 external::Template::Formats::const_iterator cit =
764 et.formats.find(format);
765 if (cit == et.formats.end())
768 // FIXME: We don't need that always
769 features.require("lyxdot");
771 vector<string>::const_iterator it = cit->second.requirements.begin();
772 vector<string>::const_iterator end = cit->second.requirements.end();
773 for (; it != end; ++it)
774 features.require(*it);
776 external::TemplateManager & etm = external::TemplateManager::get();
778 it = cit->second.preambleNames.begin();
779 end = cit->second.preambleNames.end();
780 for (; it != end; ++it) {
781 string const preamble = etm.getPreambleDefByName(*it);
782 if (!preamble.empty())
783 features.addExternalPreamble(preamble);
794 bool preview_wanted(InsetExternalParams const & params)
796 return params.display == external::PreviewDisplay &&
797 support::isFileReadable(params.filename);
801 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
804 OutputParams runparams;
805 runparams.flavor = OutputParams::LATEX;
806 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);
820 docstring 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);
837 docstring 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";