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::edit(Cursor & cur, bool)
486 InsetExternalMailer(*this).showDialog(&cur.bv());
490 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
492 renderer_->metrics(mi, dim);
493 bool const changed = dim_ != dim;
499 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
501 setPosCache(pi, x, y);
502 renderer_->draw(pi, x, y);
515 RenderType getRenderType(InsetExternalParams const & p)
517 if (!external::getTemplatePtr(p) ||
518 p.filename.empty() ||
519 p.display == external::NoDisplay)
522 if (p.display == external::PreviewDisplay) {
523 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
524 return RENDERPREVIEW;
528 if (p.display == external::DefaultDisplay &&
529 lyxrc.display_graphics == graphics::NoDisplay)
531 return RENDERGRAPHIC;
535 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
537 graphics::Params gparams;
539 gparams.filename = eparams.filename;
540 gparams.scale = eparams.lyxscale;
541 if (eparams.clipdata.clip)
542 gparams.bb = eparams.clipdata.bbox;
543 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
545 switch (eparams.display) {
546 case external::DefaultDisplay:
547 gparams.display = graphics::DefaultDisplay;
549 case external::MonochromeDisplay:
550 gparams.display = graphics::MonochromeDisplay;
552 case external::GrayscaleDisplay:
553 gparams.display = graphics::GrayscaleDisplay;
555 case external::ColorDisplay:
556 gparams.display = graphics::ColorDisplay;
558 case external::NoDisplay:
559 gparams.display = graphics::NoDisplay;
564 if (gparams.display == graphics::DefaultDisplay)
565 gparams.display = lyxrc.display_graphics;
566 // Override the above if we're not using a gui
568 gparams.display = graphics::NoDisplay;
574 docstring const getScreenLabel(InsetExternalParams const & params,
575 Buffer const & buffer)
577 external::Template const * const ptr =
578 external::getTemplatePtr(params);
581 return support::bformat((_("External template %1$s is not installed")),
582 from_utf8(params.templatename()));
584 docstring gui = _(ptr->guiName);
585 return from_utf8(external::doSubstitution(params, buffer,
586 to_utf8(gui), false));
589 void add_preview_and_start_loading(RenderMonitoredPreview &,
590 InsetExternal const &,
596 InsetExternalParams const & InsetExternal::params() const
602 void InsetExternal::setParams(InsetExternalParams const & p,
603 Buffer const & buffer)
607 // Subsequent calls to the InsetExternal::Params default constructor
609 defaultTemplateName = params_.templatename();
611 switch (getRenderType(params_)) {
613 RenderButton * button_ptr = renderer_->asButton();
615 renderer_.reset(new RenderButton);
616 button_ptr = renderer_->asButton();
619 button_ptr->update(getScreenLabel(params_, buffer), true);
622 } case RENDERGRAPHIC: {
623 RenderGraphic * graphic_ptr = renderer_->asGraphic();
625 renderer_.reset(new RenderGraphic(this));
626 graphic_ptr = renderer_->asGraphic();
629 graphic_ptr->update(get_grfx_params(params_));
633 } case RENDERPREVIEW: {
634 RenderMonitoredPreview * preview_ptr =
635 renderer_->asMonitoredPreview();
637 renderer_.reset(new RenderMonitoredPreview(this));
638 preview_ptr = renderer_->asMonitoredPreview();
639 preview_ptr->fileChanged(
640 boost::bind(&InsetExternal::fileChanged, this));
643 if (preview_ptr->monitoring())
644 preview_ptr->stopMonitoring();
645 add_preview_and_start_loading(*preview_ptr, *this, buffer);
653 void InsetExternal::fileChanged() const
655 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
659 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
662 Buffer const & buffer = *buffer_ptr;
663 ptr->removePreview(buffer);
664 add_preview_and_start_loading(*ptr, *this, buffer);
668 void InsetExternal::write(Buffer const & buffer, ostream & os) const
670 params_.write(buffer, os);
674 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
676 InsetExternalParams params;
677 if (params.read(buffer, lex))
678 setParams(params, buffer);
682 int InsetExternal::latex(Buffer const & buf, odocstream & os,
683 OutputParams const & runparams) const
687 os << "\\fbox{\\ttfamily{}"
688 << from_utf8(params_.filename.outputFilename(buf.filePath()))
693 // "nice" means that the buffer is exported to LaTeX format but not
694 // run through the LaTeX compiler.
695 // If we're running through the LaTeX compiler, we should write the
696 // generated files in the buffer's temporary directory.
697 bool const external_in_tmpdir = !runparams.nice;
698 bool const dryrun = runparams.dryrun || runparams.inComment;
700 // If the template has specified a PDFLaTeX output, then we try and
702 if (runparams.flavor == OutputParams::PDFLATEX) {
703 external::Template const * const et_ptr =
704 external::getTemplatePtr(params_);
707 external::Template const & et = *et_ptr;
709 external::Template::Formats::const_iterator cit =
710 et.formats.find("PDFLaTeX");
712 if (cit != et.formats.end()) {
713 return external::writeExternal(params_, "PDFLaTeX",
715 *(runparams.exportdata),
721 return external::writeExternal(params_, "LaTeX", buf, os,
722 *(runparams.exportdata),
728 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
729 OutputParams const & runparams) const
731 os << '\n'; // output external material on a new line
732 external::writeExternal(params_, "Ascii", buf, os,
733 *(runparams.exportdata), false,
734 runparams.dryrun || runparams.inComment);
735 return PLAINTEXT_NEWLINE;
739 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
740 OutputParams const & runparams) const
742 return external::writeExternal(params_, "DocBook", buf, os,
743 *(runparams.exportdata), false,
744 runparams.dryrun || runparams.inComment);
748 void InsetExternal::validate(LaTeXFeatures & features) const
753 external::Template const * const et_ptr =
754 external::getTemplatePtr(params_);
757 external::Template const & et = *et_ptr;
760 switch (features.runparams().flavor) {
761 case OutputParams::LATEX:
764 case OutputParams::PDFLATEX:
767 case OutputParams::XML:
771 external::Template::Formats::const_iterator cit =
772 et.formats.find(format);
773 if (cit == et.formats.end())
776 // FIXME: We don't need that always
777 features.require("lyxdot");
779 vector<string>::const_iterator it = cit->second.requirements.begin();
780 vector<string>::const_iterator end = cit->second.requirements.end();
781 for (; it != end; ++it)
782 features.require(*it);
784 external::TemplateManager & etm = external::TemplateManager::get();
786 it = cit->second.preambleNames.begin();
787 end = cit->second.preambleNames.end();
788 for (; it != end; ++it) {
789 string const preamble = etm.getPreambleDefByName(*it);
790 if (!preamble.empty())
791 features.addPreambleSnippet(preamble);
802 bool preview_wanted(InsetExternalParams const & params)
804 return params.display == external::PreviewDisplay &&
805 support::isFileReadable(params.filename);
809 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
812 // We don't need to set runparams.encoding since it is not used by
814 OutputParams runparams(0);
815 runparams.flavor = OutputParams::LATEX;
816 inset.latex(buffer, os, runparams);
821 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
822 InsetExternal const & inset,
823 Buffer const & buffer)
825 InsetExternalParams const & params = inset.params();
827 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
828 preview_wanted(params)) {
829 renderer.setAbsFile(params.filename);
830 docstring const snippet = latex_string(inset, buffer);
831 renderer.addPreview(snippet, buffer);
832 renderer.startLoading(buffer);
839 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
841 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
845 if (preview_wanted(params())) {
846 ptr->setAbsFile(params_.filename);
847 docstring const snippet = latex_string(*this, ploader.buffer());
848 ptr->addPreview(snippet, ploader);
855 string const InsetExternalMailer::name_("external");
857 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
862 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
864 return params2string(inset_.params(), buffer);
868 void InsetExternalMailer::string2params(string const & in,
869 Buffer const & buffer,
870 InsetExternalParams & params)
872 params = InsetExternalParams();
876 istringstream data(in);
882 if (!lex || name != name_)
883 return print_mailer_error("InsetExternalMailer", in, 1, name_);
885 // This is part of the inset proper that is usually swallowed
886 // by Text::readInset
889 if (!lex || id != "External")
890 return print_mailer_error("InsetBoxMailer", in, 2, "External");
892 params.read(buffer, lex);
897 InsetExternalMailer::params2string(InsetExternalParams const & params,
898 Buffer const & buffer)
901 data << name_ << ' ';
902 params.write(buffer, data);
903 data << "\\end_inset\n";