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>
48 using std::istringstream;
50 using std::ostringstream;
56 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
58 unsigned int const defaultLyxScale = 100;
60 string defaultTemplateName;
71 support::FileName const tempname(support::tempName(support::FileName(), "lyxext"));
72 // FIXME: This is unsafe
73 support::unlink(tempname);
74 // must have an extension for the converter code to work correctly.
75 tempname_ = support::FileName(tempname.absFilename() + ".tmp");
79 TempName::TempName(TempName const &)
81 tempname_ = TempName()();
87 support::unlink(tempname_);
92 TempName::operator=(TempName const & other)
95 tempname_ = TempName()();
102 /// The translator between the Display enum and corresponding lyx string.
103 Translator<DisplayType, string> const initTranslator()
105 Translator<DisplayType, string> translator(DefaultDisplay, "default");
107 // Fill the display translator
108 translator.addPair(MonochromeDisplay, "monochrome");
109 translator.addPair(GrayscaleDisplay, "grayscale");
110 translator.addPair(ColorDisplay, "color");
111 translator.addPair(PreviewDisplay, "preview");
112 translator.addPair(NoDisplay, "none");
120 Translator<DisplayType, string> const & displayTranslator()
122 static Translator<DisplayType, string> const translator =
127 } // namespace external
130 InsetExternalParams::InsetExternalParams()
131 : display(defaultDisplayType),
132 lyxscale(defaultLyxScale),
135 if (defaultTemplateName.empty()) {
136 external::TemplateManager const & etm =
137 external::TemplateManager::get();
138 templatename_ = etm.getTemplates().begin()->first;
140 templatename_ = defaultTemplateName;
146 template <typename T>
147 void clearIfNotFound(T & data, external::TransformID value,
148 vector<external::TransformID> const & ids)
150 typedef vector<external::TransformID>::const_iterator
153 const_iterator it = ids.begin();
154 const_iterator end = ids.end();
155 it = std::find(it, end, value);
163 void InsetExternalParams::settemplate(string const & name)
165 templatename_ = name;
167 external::TemplateManager const & etm =
168 external::TemplateManager::get();
169 external::Template const * const et = etm.getTemplateByName(name);
171 // Be safe. Don't lose data.
174 // Ascertain which transforms the template supports.
175 // Empty all those that it doesn't.
176 vector<external::TransformID> const & ids = et->transformIds;
177 clearIfNotFound(clipdata, external::Clip, ids);
178 clearIfNotFound(extradata, external::Extra, ids);
179 clearIfNotFound(resizedata, external::Resize, ids);
180 clearIfNotFound(rotationdata, external::Rotate, ids);
184 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
187 << "\ttemplate " << templatename() << '\n';
189 if (!filename.empty())
191 << filename.outputFilename(buffer.filePath())
194 if (display != defaultDisplayType)
196 << external::displayTranslator().find(display)
199 if (lyxscale != defaultLyxScale)
200 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
205 if (!clipdata.bbox.empty())
206 os << "\tboundingBox " << clipdata.bbox << '\n';
210 external::ExtraData::const_iterator it = extradata.begin();
211 external::ExtraData::const_iterator end = extradata.end();
212 for (; it != end; ++it) {
213 if (!it->second.empty())
214 os << "\textra " << it->first << " \""
215 << it->second << "\"\n";
218 if (!rotationdata.no_rotation()) {
219 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
220 if (rotationdata.origin() != external::RotationData::DEFAULT)
221 os << "\trotateOrigin "
222 << rotationdata.originString() << '\n';
225 if (!resizedata.no_resize()) {
226 using support::float_equal;
227 double const scl = convert<double>(resizedata.scale);
228 if (!float_equal(scl, 0.0, 0.05)) {
229 if (!float_equal(scl, 100.0, 0.05))
231 << resizedata.scale << '\n';
233 if (!resizedata.width.zero())
235 << resizedata.width.asString() << '\n';
236 if (!resizedata.height.zero())
238 << resizedata.height.asString() << '\n';
240 if (resizedata.keepAspectRatio)
241 os << "\tkeepAspectRatio\n";
246 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
266 keyword_item external_tags[] = {
267 { "\\end_inset", EX_END },
268 { "boundingBox", EX_BOUNDINGBOX },
270 { "display", EX_DISPLAY},
271 { "draft", EX_DRAFT},
272 { "extra", EX_EXTRA },
273 { "filename", EX_FILENAME},
274 { "height", EX_HEIGHT },
275 { "keepAspectRatio", EX_KEEPASPECTRATIO },
276 { "lyxscale", EX_LYXSCALE},
277 { "rotateAngle", EX_ROTATEANGLE },
278 { "rotateOrigin", EX_ROTATEORIGIN },
279 { "scale", EX_SCALE },
280 { "template", EX_TEMPLATE },
281 { "width", EX_WIDTH }
284 PushPopHelper pph(lex, external_tags, EX_END);
286 bool found_end = false;
287 bool read_error = false;
293 templatename_ = lex.getString();
298 string const name = lex.getString();
299 filename.set(name, buffer.filePath());
305 string const name = lex.getString();
306 display = external::displayTranslator().find(name);
312 lyxscale = lex.getInteger();
321 clipdata.bbox.xl = lex.getInteger();
323 clipdata.bbox.yb = lex.getInteger();
325 clipdata.bbox.xr = lex.getInteger();
327 clipdata.bbox.yt = lex.getInteger();
331 clipdata.clip = true;
336 string const name = lex.getString();
338 extradata.set(name, lex.getString());
344 resizedata.height = Length(lex.getString());
347 case EX_KEEPASPECTRATIO:
348 resizedata.keepAspectRatio = true;
353 rotationdata.angle = lex.getString();
356 case EX_ROTATEORIGIN:
358 rotationdata.origin(lex.getString());
363 resizedata.scale = lex.getString();
368 resizedata.width = Length(lex.getString());
376 lex.printError("ExternalInset::read: "
377 "Wrong tag: $$Token");
382 if (found_end || read_error)
387 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
389 // This is a trick to make sure that the data are self-consistent.
390 settemplate(templatename_);
392 if (lyxerr.debugging(Debug::EXTERNAL)) {
393 lyxerr << "InsetExternalParams::read:\n";
394 write(buffer, lyxerr);
401 InsetExternal::InsetExternal()
402 : renderer_(new RenderButton)
406 InsetExternal::InsetExternal(InsetExternal const & other)
408 boost::signals::trackable(),
409 params_(other.params_),
410 renderer_(other.renderer_->clone(this))
414 Inset * InsetExternal::clone() const
416 return new InsetExternal(*this);
420 InsetExternal::~InsetExternal()
422 InsetExternalMailer(*this).hideDialog();
426 void InsetExternal::statusChanged() const
428 LyX::cref().updateInset(this);
432 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
434 switch (cmd.action) {
436 case LFUN_EXTERNAL_EDIT: {
437 Buffer const & buffer = cur.buffer();
438 InsetExternalParams p;
439 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
440 external::editExternal(p, buffer);
444 case LFUN_INSET_MODIFY: {
445 Buffer const & buffer = cur.buffer();
446 InsetExternalParams p;
447 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
448 setParams(p, buffer);
452 case LFUN_INSET_DIALOG_UPDATE:
453 InsetExternalMailer(*this).updateDialog(&cur.bv());
456 case LFUN_MOUSE_RELEASE:
457 if (!cur.selection())
458 InsetExternalMailer(*this).showDialog(&cur.bv());
462 Inset::doDispatch(cur, cmd);
467 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
468 FuncStatus & flag) const
470 switch (cmd.action) {
472 case LFUN_EXTERNAL_EDIT:
473 case LFUN_INSET_MODIFY:
474 case LFUN_INSET_DIALOG_UPDATE:
479 return Inset::getStatus(cur, cmd, flag);
484 void InsetExternal::registerEmbeddedFiles(Buffer const &,
485 EmbeddedFiles & files, ParConstIterator const & pit) const
487 files.registerFile(params_.filename.absFilename(), EmbeddedFile::AUTO, pit);
491 void InsetExternal::edit(Cursor & cur, bool)
493 InsetExternalMailer(*this).showDialog(&cur.bv());
497 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
499 renderer_->metrics(mi, dim);
500 bool const changed = dim_ != dim;
506 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
508 setPosCache(pi, x, y);
509 renderer_->draw(pi, x, y);
522 RenderType getRenderType(InsetExternalParams const & p)
524 if (!external::getTemplatePtr(p) ||
525 p.filename.empty() ||
526 p.display == external::NoDisplay)
529 if (p.display == external::PreviewDisplay) {
530 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
531 return RENDERPREVIEW;
535 if (p.display == external::DefaultDisplay &&
536 lyxrc.display_graphics == graphics::NoDisplay)
538 return RENDERGRAPHIC;
542 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
544 graphics::Params gparams;
546 gparams.filename = eparams.filename;
547 gparams.scale = eparams.lyxscale;
548 if (eparams.clipdata.clip)
549 gparams.bb = eparams.clipdata.bbox;
550 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
552 switch (eparams.display) {
553 case external::DefaultDisplay:
554 gparams.display = graphics::DefaultDisplay;
556 case external::MonochromeDisplay:
557 gparams.display = graphics::MonochromeDisplay;
559 case external::GrayscaleDisplay:
560 gparams.display = graphics::GrayscaleDisplay;
562 case external::ColorDisplay:
563 gparams.display = graphics::ColorDisplay;
565 case external::NoDisplay:
566 gparams.display = graphics::NoDisplay;
571 if (gparams.display == graphics::DefaultDisplay)
572 gparams.display = lyxrc.display_graphics;
573 // Override the above if we're not using a gui
575 gparams.display = graphics::NoDisplay;
581 docstring const getScreenLabel(InsetExternalParams const & params,
582 Buffer const & buffer)
584 external::Template const * const ptr =
585 external::getTemplatePtr(params);
588 return support::bformat((_("External template %1$s is not installed")),
589 from_utf8(params.templatename()));
591 docstring gui = _(ptr->guiName);
592 return from_utf8(external::doSubstitution(params, buffer,
593 to_utf8(gui), false));
596 void add_preview_and_start_loading(RenderMonitoredPreview &,
597 InsetExternal const &,
603 InsetExternalParams const & InsetExternal::params() const
609 void InsetExternal::setParams(InsetExternalParams const & p,
610 Buffer const & buffer)
614 // Subsequent calls to the InsetExternal::Params default constructor
616 defaultTemplateName = params_.templatename();
618 switch (getRenderType(params_)) {
620 RenderButton * button_ptr = renderer_->asButton();
622 renderer_.reset(new RenderButton);
623 button_ptr = renderer_->asButton();
626 button_ptr->update(getScreenLabel(params_, buffer), true);
629 } case RENDERGRAPHIC: {
630 RenderGraphic * graphic_ptr = renderer_->asGraphic();
632 renderer_.reset(new RenderGraphic(this));
633 graphic_ptr = renderer_->asGraphic();
636 graphic_ptr->update(get_grfx_params(params_));
640 } case RENDERPREVIEW: {
641 RenderMonitoredPreview * preview_ptr =
642 renderer_->asMonitoredPreview();
644 renderer_.reset(new RenderMonitoredPreview(this));
645 preview_ptr = renderer_->asMonitoredPreview();
646 preview_ptr->fileChanged(
647 boost::bind(&InsetExternal::fileChanged, this));
650 if (preview_ptr->monitoring())
651 preview_ptr->stopMonitoring();
652 add_preview_and_start_loading(*preview_ptr, *this, buffer);
660 void InsetExternal::fileChanged() const
662 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
666 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
669 Buffer const & buffer = *buffer_ptr;
670 ptr->removePreview(buffer);
671 add_preview_and_start_loading(*ptr, *this, buffer);
675 void InsetExternal::write(Buffer const & buffer, ostream & os) const
677 params_.write(buffer, os);
681 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
683 InsetExternalParams params;
684 if (params.read(buffer, lex))
685 setParams(params, buffer);
689 int InsetExternal::latex(Buffer const & buf, odocstream & os,
690 OutputParams const & runparams) const
694 os << "\\fbox{\\ttfamily{}"
695 << from_utf8(params_.filename.outputFilename(buf.filePath()))
700 // "nice" means that the buffer is exported to LaTeX format but not
701 // run through the LaTeX compiler.
702 // If we're running through the LaTeX compiler, we should write the
703 // generated files in the buffer's temporary directory.
704 bool const external_in_tmpdir = !runparams.nice;
705 bool const dryrun = runparams.dryrun || runparams.inComment;
707 // If the template has specified a PDFLaTeX output, then we try and
709 if (runparams.flavor == OutputParams::PDFLATEX) {
710 external::Template const * const et_ptr =
711 external::getTemplatePtr(params_);
714 external::Template const & et = *et_ptr;
716 external::Template::Formats::const_iterator cit =
717 et.formats.find("PDFLaTeX");
719 if (cit != et.formats.end()) {
720 return external::writeExternal(params_, "PDFLaTeX",
722 *(runparams.exportdata),
728 return external::writeExternal(params_, "LaTeX", buf, os,
729 *(runparams.exportdata),
735 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
736 OutputParams const & runparams) const
738 os << '\n'; // output external material on a new line
739 external::writeExternal(params_, "Ascii", buf, os,
740 *(runparams.exportdata), false,
741 runparams.dryrun || runparams.inComment);
742 return PLAINTEXT_NEWLINE;
746 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
747 OutputParams const & runparams) const
749 return external::writeExternal(params_, "DocBook", buf, os,
750 *(runparams.exportdata), false,
751 runparams.dryrun || runparams.inComment);
755 void InsetExternal::validate(LaTeXFeatures & features) const
760 external::Template const * const et_ptr =
761 external::getTemplatePtr(params_);
764 external::Template const & et = *et_ptr;
767 switch (features.runparams().flavor) {
768 case OutputParams::LATEX:
771 case OutputParams::PDFLATEX:
774 case OutputParams::XML:
778 external::Template::Formats::const_iterator cit =
779 et.formats.find(format);
780 if (cit == et.formats.end())
783 // FIXME: We don't need that always
784 features.require("lyxdot");
786 vector<string>::const_iterator it = cit->second.requirements.begin();
787 vector<string>::const_iterator end = cit->second.requirements.end();
788 for (; it != end; ++it)
789 features.require(*it);
791 external::TemplateManager & etm = external::TemplateManager::get();
793 it = cit->second.preambleNames.begin();
794 end = cit->second.preambleNames.end();
795 for (; it != end; ++it) {
796 string const preamble = etm.getPreambleDefByName(*it);
797 if (!preamble.empty())
798 features.addPreambleSnippet(preamble);
809 bool preview_wanted(InsetExternalParams const & params)
811 return params.display == external::PreviewDisplay &&
812 support::isFileReadable(params.filename);
816 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
819 // We don't need to set runparams.encoding since it is not used by
821 OutputParams runparams(0);
822 runparams.flavor = OutputParams::LATEX;
823 inset.latex(buffer, os, runparams);
828 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
829 InsetExternal const & inset,
830 Buffer const & buffer)
832 InsetExternalParams const & params = inset.params();
834 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
835 preview_wanted(params)) {
836 renderer.setAbsFile(params.filename);
837 docstring const snippet = latex_string(inset, buffer);
838 renderer.addPreview(snippet, buffer);
839 renderer.startLoading(buffer);
846 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
848 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
852 if (preview_wanted(params())) {
853 ptr->setAbsFile(params_.filename);
854 docstring const snippet = latex_string(*this, ploader.buffer());
855 ptr->addPreview(snippet, ploader);
862 string const InsetExternalMailer::name_("external");
864 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
869 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
871 return params2string(inset_.params(), buffer);
875 void InsetExternalMailer::string2params(string const & in,
876 Buffer const & buffer,
877 InsetExternalParams & params)
879 params = InsetExternalParams();
883 istringstream data(in);
889 if (!lex || name != name_)
890 return print_mailer_error("InsetExternalMailer", in, 1, name_);
892 // This is part of the inset proper that is usually swallowed
893 // by Text::readInset
896 if (!lex || id != "External")
897 return print_mailer_error("InsetBoxMailer", in, 2, "External");
899 params.read(buffer, lex);
904 InsetExternalMailer::params2string(InsetExternalParams const & params,
905 Buffer const & buffer)
908 data << name_ << ' ';
909 params.write(buffer, data);
910 data << "\\end_inset\n";