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;
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),
137 if (defaultTemplateName.empty()) {
138 external::TemplateManager const & etm =
139 external::TemplateManager::get();
140 templatename_ = etm.getTemplates().begin()->first;
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, Lexer & 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 = Length(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 = Length(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<Inset> InsetExternal::doClone() const
418 return auto_ptr<Inset>(new InsetExternal(*this));
422 InsetExternal::~InsetExternal()
424 InsetExternalMailer(*this).hideDialog();
428 void InsetExternal::statusChanged() const
430 LyX::cref().updateInset(this);
434 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
436 switch (cmd.action) {
438 case LFUN_EXTERNAL_EDIT: {
439 Buffer const & buffer = cur.buffer();
440 InsetExternalParams p;
441 InsetExternalMailer::string2params(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(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 if (!cur.selection())
460 InsetExternalMailer(*this).showDialog(&cur.bv());
464 Inset::doDispatch(cur, cmd);
469 bool InsetExternal::getStatus(Cursor & 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 Inset::getStatus(cur, cmd, flag);
486 void InsetExternal::edit(Cursor & cur, bool)
488 InsetExternalMailer(*this).showDialog(&cur.bv());
492 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
494 renderer_->metrics(mi, dim);
495 bool const changed = dim_ != dim;
501 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
503 setPosCache(pi, x, y);
504 renderer_->draw(pi, x, y);
517 RenderType getRenderType(InsetExternalParams const & p)
519 if (!external::getTemplatePtr(p) ||
520 p.filename.empty() ||
521 p.display == external::NoDisplay)
524 if (p.display == external::PreviewDisplay) {
525 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
526 return RENDERPREVIEW;
530 if (p.display == external::DefaultDisplay &&
531 lyxrc.display_graphics == graphics::NoDisplay)
533 return RENDERGRAPHIC;
537 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
539 graphics::Params gparams;
541 gparams.filename = eparams.filename;
542 gparams.scale = eparams.lyxscale;
543 if (eparams.clipdata.clip)
544 gparams.bb = eparams.clipdata.bbox;
545 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
547 switch (eparams.display) {
548 case external::DefaultDisplay:
549 gparams.display = graphics::DefaultDisplay;
551 case external::MonochromeDisplay:
552 gparams.display = graphics::MonochromeDisplay;
554 case external::GrayscaleDisplay:
555 gparams.display = graphics::GrayscaleDisplay;
557 case external::ColorDisplay:
558 gparams.display = graphics::ColorDisplay;
560 case external::NoDisplay:
561 gparams.display = graphics::NoDisplay;
566 if (gparams.display == graphics::DefaultDisplay)
567 gparams.display = lyxrc.display_graphics;
568 // Override the above if we're not using a gui
570 gparams.display = graphics::NoDisplay;
576 docstring const getScreenLabel(InsetExternalParams const & params,
577 Buffer const & buffer)
579 external::Template const * const ptr =
580 external::getTemplatePtr(params);
583 return support::bformat((_("External template %1$s is not installed")),
584 from_utf8(params.templatename()));
586 docstring gui = _(ptr->guiName);
587 return from_utf8(external::doSubstitution(params, buffer,
588 to_utf8(gui), false));
591 void add_preview_and_start_loading(RenderMonitoredPreview &,
592 InsetExternal const &,
598 InsetExternalParams const & InsetExternal::params() const
604 void InsetExternal::setParams(InsetExternalParams const & p,
605 Buffer const & buffer)
609 // Subsequent calls to the InsetExternal::Params default constructor
611 defaultTemplateName = params_.templatename();
613 switch (getRenderType(params_)) {
615 RenderButton * button_ptr = renderer_->asButton();
617 renderer_.reset(new RenderButton);
618 button_ptr = renderer_->asButton();
621 button_ptr->update(getScreenLabel(params_, buffer), true);
624 } case RENDERGRAPHIC: {
625 RenderGraphic * graphic_ptr = renderer_->asGraphic();
627 renderer_.reset(new RenderGraphic(this));
628 graphic_ptr = renderer_->asGraphic();
631 graphic_ptr->update(get_grfx_params(params_));
635 } case RENDERPREVIEW: {
636 RenderMonitoredPreview * preview_ptr =
637 renderer_->asMonitoredPreview();
639 renderer_.reset(new RenderMonitoredPreview(this));
640 preview_ptr = renderer_->asMonitoredPreview();
641 preview_ptr->fileChanged(
642 boost::bind(&InsetExternal::fileChanged, this));
645 if (preview_ptr->monitoring())
646 preview_ptr->stopMonitoring();
647 add_preview_and_start_loading(*preview_ptr, *this, buffer);
655 void InsetExternal::fileChanged() const
657 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
661 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
664 Buffer const & buffer = *buffer_ptr;
665 ptr->removePreview(buffer);
666 add_preview_and_start_loading(*ptr, *this, buffer);
670 void InsetExternal::write(Buffer const & buffer, ostream & os) const
672 params_.write(buffer, os);
676 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
678 InsetExternalParams params;
679 if (params.read(buffer, lex))
680 setParams(params, buffer);
684 int InsetExternal::latex(Buffer const & buf, odocstream & os,
685 OutputParams const & runparams) const
689 os << "\\fbox{\\ttfamily{}"
690 << from_utf8(params_.filename.outputFilename(buf.filePath()))
695 // "nice" means that the buffer is exported to LaTeX format but not
696 // run through the LaTeX compiler.
697 // If we're running through the LaTeX compiler, we should write the
698 // generated files in the buffer's temporary directory.
699 bool const external_in_tmpdir = !runparams.nice;
700 bool const dryrun = runparams.dryrun || runparams.inComment;
702 // If the template has specified a PDFLaTeX output, then we try and
704 if (runparams.flavor == OutputParams::PDFLATEX) {
705 external::Template const * const et_ptr =
706 external::getTemplatePtr(params_);
709 external::Template const & et = *et_ptr;
711 external::Template::Formats::const_iterator cit =
712 et.formats.find("PDFLaTeX");
714 if (cit != et.formats.end()) {
715 return external::writeExternal(params_, "PDFLaTeX",
717 *(runparams.exportdata),
723 return external::writeExternal(params_, "LaTeX", buf, os,
724 *(runparams.exportdata),
730 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
731 OutputParams const & runparams) const
733 os << '\n'; // output external material on a new line
734 external::writeExternal(params_, "Ascii", buf, os,
735 *(runparams.exportdata), false,
736 runparams.dryrun || runparams.inComment);
737 return PLAINTEXT_NEWLINE;
741 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
742 OutputParams const & runparams) const
744 return external::writeExternal(params_, "DocBook", buf, os,
745 *(runparams.exportdata), false,
746 runparams.dryrun || runparams.inComment);
750 void InsetExternal::validate(LaTeXFeatures & features) const
755 external::Template const * const et_ptr =
756 external::getTemplatePtr(params_);
759 external::Template const & et = *et_ptr;
762 switch (features.runparams().flavor) {
763 case OutputParams::LATEX:
766 case OutputParams::PDFLATEX:
769 case OutputParams::XML:
773 external::Template::Formats::const_iterator cit =
774 et.formats.find(format);
775 if (cit == et.formats.end())
778 // FIXME: We don't need that always
779 features.require("lyxdot");
781 vector<string>::const_iterator it = cit->second.requirements.begin();
782 vector<string>::const_iterator end = cit->second.requirements.end();
783 for (; it != end; ++it)
784 features.require(*it);
786 external::TemplateManager & etm = external::TemplateManager::get();
788 it = cit->second.preambleNames.begin();
789 end = cit->second.preambleNames.end();
790 for (; it != end; ++it) {
791 string const preamble = etm.getPreambleDefByName(*it);
792 if (!preamble.empty())
793 features.addPreambleSnippet(preamble);
804 bool preview_wanted(InsetExternalParams const & params)
806 return params.display == external::PreviewDisplay &&
807 support::isFileReadable(params.filename);
811 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
814 // We don't need to set runparams.encoding since it is not used by
816 OutputParams runparams(0);
817 runparams.flavor = OutputParams::LATEX;
818 inset.latex(buffer, os, runparams);
823 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
824 InsetExternal const & inset,
825 Buffer const & buffer)
827 InsetExternalParams const & params = inset.params();
829 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
830 preview_wanted(params)) {
831 renderer.setAbsFile(params.filename);
832 docstring const snippet = latex_string(inset, buffer);
833 renderer.addPreview(snippet, buffer);
834 renderer.startLoading(buffer);
841 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
843 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
847 if (preview_wanted(params())) {
848 ptr->setAbsFile(params_.filename);
849 docstring const snippet = latex_string(*this, ploader.buffer());
850 ptr->addPreview(snippet, ploader);
857 string const InsetExternalMailer::name_("external");
859 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
864 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
866 return params2string(inset_.params(), buffer);
870 void InsetExternalMailer::string2params(string const & in,
871 Buffer const & buffer,
872 InsetExternalParams & params)
874 params = InsetExternalParams();
878 istringstream data(in);
884 if (!lex || name != name_)
885 return print_mailer_error("InsetExternalMailer", in, 1, name_);
887 // This is part of the inset proper that is usually swallowed
888 // by Text::readInset
891 if (!lex || id != "External")
892 return print_mailer_error("InsetBoxMailer", in, 2, "External");
894 params.read(buffer, lex);
899 InsetExternalMailer::params2string(InsetExternalParams const & params,
900 Buffer const & buffer)
903 data << name_ << ' ';
904 params.write(buffer, data);
905 data << "\\end_inset\n";