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"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
34 #include "graphics/PreviewLoader.h"
36 #include "support/filetools.h"
37 #include "support/lstrings.h"
38 #include "support/lyxlib.h"
39 #include "support/convert.h"
40 #include "support/Translator.h"
42 #include <boost/bind.hpp>
47 using namespace lyx::support;
51 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
53 unsigned int const defaultLyxScale = 100;
55 string defaultTemplateName;
68 FileName const tempname = FileName::tempName("lyxext");
69 // FIXME: This is unsafe
70 tempname.removeFile();
71 // must have an extension for the converter code to work correctly.
72 tempname_ = FileName(tempname.absFilename() + ".tmp");
76 TempName::TempName(TempName const &)
78 tempname_ = TempName()();
84 tempname_.removeFile();
88 TempName & TempName::operator=(TempName const & other)
91 tempname_ = TempName()();
98 /// The translator between the Display enum and corresponding lyx string.
99 Translator<DisplayType, string> const initTranslator()
101 Translator<DisplayType, string> translator(DefaultDisplay, "default");
103 // Fill the display translator
104 translator.addPair(MonochromeDisplay, "monochrome");
105 translator.addPair(GrayscaleDisplay, "grayscale");
106 translator.addPair(ColorDisplay, "color");
107 translator.addPair(PreviewDisplay, "preview");
108 translator.addPair(NoDisplay, "none");
116 Translator<DisplayType, string> const & displayTranslator()
118 static Translator<DisplayType, string> const translator =
123 } // namespace external
126 InsetExternalParams::InsetExternalParams()
127 : display(defaultDisplayType),
128 lyxscale(defaultLyxScale),
131 if (defaultTemplateName.empty()) {
132 external::TemplateManager const & etm =
133 external::TemplateManager::get();
134 templatename_ = etm.getTemplates().begin()->first;
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 = 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())
186 os << "\tfilename " << filename.outputFilename(buffer.filePath()) << '\n';
188 if (display != defaultDisplayType)
190 << external::displayTranslator().find(display)
193 if (lyxscale != defaultLyxScale)
194 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
199 if (!clipdata.bbox.empty())
200 os << "\tboundingBox " << clipdata.bbox << '\n';
204 external::ExtraData::const_iterator it = extradata.begin();
205 external::ExtraData::const_iterator end = extradata.end();
206 for (; it != end; ++it) {
207 if (!it->second.empty())
208 os << "\textra " << it->first << " \""
209 << it->second << "\"\n";
212 if (!rotationdata.no_rotation()) {
213 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
214 if (rotationdata.origin() != external::RotationData::DEFAULT)
215 os << "\trotateOrigin "
216 << rotationdata.originString() << '\n';
219 if (!resizedata.no_resize()) {
220 double const scl = convert<double>(resizedata.scale);
221 if (!float_equal(scl, 0.0, 0.05)) {
222 if (!float_equal(scl, 100.0, 0.05))
224 << resizedata.scale << '\n';
226 if (!resizedata.width.zero())
228 << resizedata.width.asString() << '\n';
229 if (!resizedata.height.zero())
231 << resizedata.height.asString() << '\n';
233 if (resizedata.keepAspectRatio)
234 os << "\tkeepAspectRatio\n";
239 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
259 keyword_item external_tags[] = {
260 { "\\end_inset", EX_END },
261 { "boundingBox", EX_BOUNDINGBOX },
263 { "display", EX_DISPLAY},
264 { "draft", EX_DRAFT},
265 { "extra", EX_EXTRA },
266 { "filename", EX_FILENAME},
267 { "height", EX_HEIGHT },
268 { "keepAspectRatio", EX_KEEPASPECTRATIO },
269 { "lyxscale", EX_LYXSCALE},
270 { "rotateAngle", EX_ROTATEANGLE },
271 { "rotateOrigin", EX_ROTATEORIGIN },
272 { "scale", EX_SCALE },
273 { "template", EX_TEMPLATE },
274 { "width", EX_WIDTH }
277 PushPopHelper pph(lex, external_tags, EX_END);
279 bool found_end = false;
280 bool read_error = false;
286 templatename_ = lex.getString();
291 string const name = lex.getString();
292 filename.set(name, buffer.filePath());
298 string const name = lex.getString();
299 display = external::displayTranslator().find(name);
305 lyxscale = lex.getInteger();
314 clipdata.bbox.xl = lex.getInteger();
316 clipdata.bbox.yb = lex.getInteger();
318 clipdata.bbox.xr = lex.getInteger();
320 clipdata.bbox.yt = lex.getInteger();
324 clipdata.clip = true;
329 string const name = lex.getString();
331 extradata.set(name, lex.getString());
337 resizedata.height = Length(lex.getString());
340 case EX_KEEPASPECTRATIO:
341 resizedata.keepAspectRatio = true;
346 rotationdata.angle = lex.getString();
349 case EX_ROTATEORIGIN:
351 rotationdata.origin(lex.getString());
356 resizedata.scale = lex.getString();
361 resizedata.width = Length(lex.getString());
369 lex.printError("ExternalInset::read: Wrong tag: $$Token");
374 if (found_end || read_error)
379 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
381 // This is a trick to make sure that the data are self-consistent.
382 settemplate(templatename_);
384 if (lyxerr.debugging(Debug::EXTERNAL)) {
385 lyxerr << "InsetExternalParams::read:\n";
386 write(buffer, lyxerr);
393 InsetExternal::InsetExternal()
394 : renderer_(new RenderButton)
398 InsetExternal::InsetExternal(InsetExternal const & other)
400 boost::signals::trackable(),
401 params_(other.params_),
402 renderer_(other.renderer_->clone(this))
406 Inset * InsetExternal::clone() const
408 return new InsetExternal(*this);
412 InsetExternal::~InsetExternal()
414 InsetExternalMailer(*this).hideDialog();
418 void InsetExternal::statusChanged() const
424 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
426 switch (cmd.action) {
428 case LFUN_EXTERNAL_EDIT: {
429 Buffer const & buffer = cur.buffer();
430 InsetExternalParams p;
431 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
432 external::editExternal(p, buffer);
436 case LFUN_INSET_MODIFY: {
437 Buffer const & buffer = cur.buffer();
438 InsetExternalParams p;
439 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
440 setParams(p, buffer);
444 case LFUN_INSET_DIALOG_UPDATE:
445 InsetExternalMailer(*this).updateDialog(&cur.bv());
448 case LFUN_MOUSE_RELEASE:
449 if (!cur.selection())
450 InsetExternalMailer(*this).showDialog(&cur.bv());
454 Inset::doDispatch(cur, cmd);
459 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
460 FuncStatus & flag) const
462 switch (cmd.action) {
464 case LFUN_EXTERNAL_EDIT:
465 case LFUN_INSET_MODIFY:
466 case LFUN_INSET_DIALOG_UPDATE:
471 return Inset::getStatus(cur, cmd, flag);
476 void InsetExternal::registerEmbeddedFiles(Buffer const &,
477 EmbeddedFiles & files) const
479 // temporarily disable embedding for this inset
480 /* files.registerFile(params_.filename, this); */
484 void InsetExternal::edit(Cursor & cur, bool)
486 InsetExternalMailer(*this).showDialog(&cur.bv());
490 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
492 renderer_->metrics(mi, dim);
496 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
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 = graphics::DisplayType(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 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);
619 case RENDERGRAPHIC: {
620 RenderGraphic * graphic_ptr = renderer_->asGraphic();
622 renderer_.reset(new RenderGraphic(this));
623 graphic_ptr = renderer_->asGraphic();
626 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 = updateFrontend();
657 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
660 ptr->removePreview(*buffer);
661 add_preview_and_start_loading(*ptr, *this, *buffer);
665 void InsetExternal::write(Buffer const & buffer, ostream & os) const
667 params_.write(buffer, os);
671 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
673 InsetExternalParams params;
674 if (params.read(buffer, lex))
675 setParams(params, buffer);
679 int InsetExternal::latex(Buffer const & buf, odocstream & os,
680 OutputParams const & runparams) const
684 os << "\\fbox{\\ttfamily{}"
685 << from_utf8(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 buffer's temporary directory.
694 bool const external_in_tmpdir = !runparams.nice;
695 bool const dryrun = runparams.dryrun || runparams.inComment;
697 // If the template has specified a PDFLaTeX output, then we try and
699 if (runparams.flavor == OutputParams::PDFLATEX) {
700 external::Template const * const et_ptr =
701 external::getTemplatePtr(params_);
704 external::Template const & et = *et_ptr;
706 external::Template::Formats::const_iterator cit =
707 et.formats.find("PDFLaTeX");
709 if (cit != et.formats.end()) {
710 return external::writeExternal(params_, "PDFLaTeX",
712 *(runparams.exportdata),
718 return external::writeExternal(params_, "LaTeX", buf, os,
719 *(runparams.exportdata),
725 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
726 OutputParams const & runparams) const
728 os << '\n'; // output external material on a new line
729 external::writeExternal(params_, "Ascii", buf, os,
730 *(runparams.exportdata), false,
731 runparams.dryrun || runparams.inComment);
732 return PLAINTEXT_NEWLINE;
736 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
737 OutputParams const & runparams) const
739 return external::writeExternal(params_, "DocBook", buf, os,
740 *(runparams.exportdata), false,
741 runparams.dryrun || runparams.inComment);
745 void InsetExternal::validate(LaTeXFeatures & features) const
750 external::Template const * const et_ptr =
751 external::getTemplatePtr(params_);
754 external::Template const & et = *et_ptr;
757 switch (features.runparams().flavor) {
758 case OutputParams::LATEX:
761 case OutputParams::PDFLATEX:
764 case OutputParams::XML:
768 external::Template::Formats::const_iterator cit =
769 et.formats.find(format);
770 if (cit == et.formats.end())
773 // FIXME: We don't need that always
774 features.require("lyxdot");
776 vector<string>::const_iterator it = cit->second.requirements.begin();
777 vector<string>::const_iterator end = cit->second.requirements.end();
778 for (; it != end; ++it)
779 features.require(*it);
781 external::TemplateManager & etm = external::TemplateManager::get();
783 it = cit->second.preambleNames.begin();
784 end = cit->second.preambleNames.end();
785 for (; it != end; ++it) {
786 string const preamble = etm.getPreambleDefByName(*it);
787 if (!preamble.empty())
788 features.addPreambleSnippet(preamble);
799 bool preview_wanted(InsetExternalParams const & params)
801 return params.display == external::PreviewDisplay &&
802 params.filename.isReadableFile();
806 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
809 // We don't need to set runparams.encoding since it is not used by
811 OutputParams runparams(0);
812 runparams.flavor = OutputParams::LATEX;
813 inset.latex(buffer, os, runparams);
818 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
819 InsetExternal const & inset,
820 Buffer const & buffer)
822 InsetExternalParams const & params = inset.params();
824 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
825 preview_wanted(params)) {
826 renderer.setAbsFile(params.filename);
827 docstring const snippet = latex_string(inset, buffer);
828 renderer.addPreview(snippet, buffer);
829 renderer.startLoading(buffer);
836 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
838 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
842 if (preview_wanted(params())) {
843 ptr->setAbsFile(params_.filename);
844 docstring const snippet = latex_string(*this, ploader.buffer());
845 ptr->addPreview(snippet, ploader);
852 string const InsetExternalMailer::name_("external");
854 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
859 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
861 return params2string(inset_.params(), buffer);
865 void InsetExternalMailer::string2params(string const & in,
866 Buffer const & buffer,
867 InsetExternalParams & params)
869 params = InsetExternalParams();
873 istringstream data(in);
879 if (!lex || name != name_)
880 return print_mailer_error("InsetExternalMailer", in, 1, name_);
882 // This is part of the inset proper that is usually swallowed
883 // by Text::readInset
886 if (!lex || id != "External")
887 return print_mailer_error("InsetBoxMailer", in, 2, "External");
889 params.read(buffer, lex);
894 InsetExternalMailer::params2string(InsetExternalParams const & params,
895 Buffer const & buffer)
898 data << name_ << ' ';
899 params.write(buffer, data);
900 data << "\\end_inset\n";