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 "funcrequest.h"
27 #include "LaTeXFeatures.h"
31 #include "metricsinfo.h"
32 #include "outputparams.h"
34 #include "frontends/lyx_gui.h"
36 #include "graphics/PreviewLoader.h"
38 #include "support/filetools.h"
39 #include "support/lstrings.h"
40 #include "support/lyxlib.h"
41 #include "support/convert.h"
42 #include "support/translator.h"
44 #include <boost/bind.hpp>
48 namespace support = lyx::support;
49 namespace external = lyx::external;
50 namespace graphics = lyx::graphics;
55 using std::istringstream;
57 using std::ostringstream;
63 external::DisplayType const defaultDisplayType = external::NoDisplay;
65 unsigned int const defaultLyxScale = 100;
67 string defaultTemplateName = "RasterImage";
77 tempname_ = support::tempName(string(), "lyxext");
78 // FIXME: This is unsafe
79 support::unlink(tempname_);
80 // must have an extension for the converter code to work correctly.
85 TempName::TempName(TempName const &)
87 tempname_ = TempName()();
93 support::unlink(tempname_);
98 TempName::operator=(TempName const & other)
101 tempname_ = TempName()();
108 /// The translator between the Display enum and corresponding lyx string.
109 Translator<DisplayType, string> const initTranslator()
111 Translator<DisplayType, string> translator(DefaultDisplay, "default");
113 // Fill the display translator
114 translator.addPair(MonochromeDisplay, "monochrome");
115 translator.addPair(GrayscaleDisplay, "grayscale");
116 translator.addPair(ColorDisplay, "color");
117 translator.addPair(PreviewDisplay, "preview");
118 translator.addPair(NoDisplay, "none");
126 Translator<DisplayType, string> const & displayTranslator()
128 static Translator<DisplayType, string> const translator =
133 } // namespace external
137 InsetExternalParams::InsetExternalParams()
138 : display(defaultDisplayType),
139 lyxscale(defaultLyxScale),
141 templatename_(defaultTemplateName)
147 template <typename T>
148 void clearIfNotFound(T & data, external::TransformID value,
149 vector<external::TransformID> const & ids)
151 typedef vector<external::TransformID>::const_iterator
154 const_iterator it = ids.begin();
155 const_iterator end = ids.end();
156 it = std::find(it, end, value);
164 void InsetExternalParams::settemplate(string const & name)
166 templatename_ = name;
168 external::TemplateManager const & etm =
169 external::TemplateManager::get();
170 external::Template const * const et = etm.getTemplateByName(name);
172 // Be safe. Don't lose data.
175 // Ascertain which transforms the template supports.
176 // Empty all those that it doesn't.
177 vector<external::TransformID> const & ids = et->transformIds;
178 clearIfNotFound(clipdata, external::Clip, ids);
179 clearIfNotFound(extradata, external::Extra, ids);
180 clearIfNotFound(resizedata, external::Resize, ids);
181 clearIfNotFound(rotationdata, external::Rotate, ids);
185 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
188 << "\ttemplate " << templatename() << '\n';
190 if (!filename.empty())
192 << filename.outputFilename(buffer.filePath())
195 if (display != defaultDisplayType)
197 << external::displayTranslator().find(display)
200 if (lyxscale != defaultLyxScale)
201 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
206 if (!clipdata.bbox.empty())
207 os << "\tboundingBox " << clipdata.bbox << '\n';
211 external::ExtraData::const_iterator it = extradata.begin();
212 external::ExtraData::const_iterator end = extradata.end();
213 for (; it != end; ++it) {
214 if (!it->second.empty())
215 os << "\textra " << it->first << " \""
216 << it->second << "\"\n";
219 if (!rotationdata.no_rotation()) {
220 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
221 if (rotationdata.origin() != external::RotationData::DEFAULT)
222 os << "\trotateOrigin "
223 << rotationdata.originString() << '\n';
226 if (!resizedata.no_resize()) {
227 using support::float_equal;
228 double const scl = convert<double>(resizedata.scale);
229 if (!float_equal(scl, 0.0, 0.05)) {
230 if (!float_equal(scl, 100.0, 0.05))
232 << resizedata.scale << '\n';
234 if (!resizedata.width.zero())
236 << resizedata.width.asString() << '\n';
237 if (!resizedata.height.zero())
239 << resizedata.height.asString() << '\n';
241 if (resizedata.keepAspectRatio)
242 os << "\tkeepAspectRatio\n";
247 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
267 keyword_item external_tags[] = {
268 { "\\end_inset", EX_END },
269 { "boundingBox", EX_BOUNDINGBOX },
271 { "display", EX_DISPLAY},
272 { "draft", EX_DRAFT},
273 { "extra", EX_EXTRA },
274 { "filename", EX_FILENAME},
275 { "height", EX_HEIGHT },
276 { "keepAspectRatio", EX_KEEPASPECTRATIO },
277 { "lyxscale", EX_LYXSCALE},
278 { "rotateAngle", EX_ROTATEANGLE },
279 { "rotateOrigin", EX_ROTATEORIGIN },
280 { "scale", EX_SCALE },
281 { "template", EX_TEMPLATE },
282 { "width", EX_WIDTH }
285 pushpophelper pph(lex, external_tags, EX_END);
287 bool found_end = false;
288 bool read_error = false;
294 templatename_ = lex.getString();
299 string const name = lex.getString();
300 filename.set(name, buffer.filePath());
306 string const name = lex.getString();
307 display = external::displayTranslator().find(name);
313 lyxscale = lex.getInteger();
322 clipdata.bbox.xl = lex.getInteger();
324 clipdata.bbox.yb = lex.getInteger();
326 clipdata.bbox.xr = lex.getInteger();
328 clipdata.bbox.yt = lex.getInteger();
332 clipdata.clip = true;
337 string const name = lex.getString();
339 extradata.set(name, lex.getString());
345 resizedata.height = LyXLength(lex.getString());
348 case EX_KEEPASPECTRATIO:
349 resizedata.keepAspectRatio = true;
354 rotationdata.angle = lex.getString();
357 case EX_ROTATEORIGIN:
359 rotationdata.origin(lex.getString());
364 resizedata.scale = lex.getString();
369 resizedata.width = LyXLength(lex.getString());
377 lex.printError("ExternalInset::read: "
378 "Wrong tag: $$Token");
383 if (found_end || read_error)
388 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
390 // This is a trick to make sure that the data are self-consistent.
391 settemplate(templatename_);
393 if (lyxerr.debugging(Debug::EXTERNAL)) {
394 lyxerr << "InsetExternalParams::read:\n";
395 write(buffer, lyxerr);
402 InsetExternal::InsetExternal()
403 : renderer_(new RenderButton)
407 InsetExternal::InsetExternal(InsetExternal const & other)
409 boost::signals::trackable(),
410 params_(other.params_),
411 renderer_(other.renderer_->clone(this))
415 auto_ptr<InsetBase> InsetExternal::doClone() const
417 return auto_ptr<InsetBase>(new InsetExternal(*this));
421 InsetExternal::~InsetExternal()
423 InsetExternalMailer(*this).hideDialog();
427 void InsetExternal::statusChanged() const
429 LyX::cref().updateInset(this);
433 void InsetExternal::doDispatch(LCursor & cur, FuncRequest & cmd)
435 switch (cmd.action) {
437 case LFUN_EXTERNAL_EDIT: {
438 Buffer const & buffer = cur.buffer();
439 InsetExternalParams p;
440 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
441 external::editExternal(p, buffer);
445 case LFUN_INSET_MODIFY: {
446 Buffer const & buffer = cur.buffer();
447 InsetExternalParams p;
448 InsetExternalMailer::string2params(lyx::to_utf8(cmd.argument()), buffer, p);
449 setParams(p, buffer);
453 case LFUN_INSET_DIALOG_UPDATE:
454 InsetExternalMailer(*this).updateDialog(&cur.bv());
457 case LFUN_MOUSE_RELEASE:
458 InsetExternalMailer(*this).showDialog(&cur.bv());
462 InsetBase::doDispatch(cur, cmd);
467 bool InsetExternal::getStatus(LCursor & 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 InsetBase::getStatus(cur, cmd, flag);
484 void InsetExternal::edit(LCursor & cur, bool)
486 InsetExternalMailer(*this).showDialog(&cur.bv());
490 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
492 renderer_->metrics(mi, dim);
497 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
499 setPosCache(pi, x, y);
500 renderer_->draw(pi, x, y);
513 RenderType getRenderType(InsetExternalParams const & p)
515 if (!external::getTemplatePtr(p) ||
516 p.filename.empty() ||
517 p.display == external::NoDisplay)
520 if (p.display == external::PreviewDisplay) {
521 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
522 return RENDERPREVIEW;
526 if (p.display == external::DefaultDisplay &&
527 lyxrc.display_graphics == graphics::NoDisplay)
529 return RENDERGRAPHIC;
533 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
535 graphics::Params gparams;
537 gparams.filename = eparams.filename.absFilename();
538 gparams.scale = eparams.lyxscale;
539 if (eparams.clipdata.clip)
540 gparams.bb = eparams.clipdata.bbox;
541 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
543 switch (eparams.display) {
544 case external::DefaultDisplay:
545 gparams.display = graphics::DefaultDisplay;
547 case external::MonochromeDisplay:
548 gparams.display = graphics::MonochromeDisplay;
550 case external::GrayscaleDisplay:
551 gparams.display = graphics::GrayscaleDisplay;
553 case external::ColorDisplay:
554 gparams.display = graphics::ColorDisplay;
556 case external::NoDisplay:
557 gparams.display = graphics::NoDisplay;
562 if (gparams.display == graphics::DefaultDisplay)
563 gparams.display = lyxrc.display_graphics;
564 // Override the above if we're not using a gui
565 if (!lyx_gui::use_gui)
566 gparams.display = graphics::NoDisplay;
572 string const getScreenLabel(InsetExternalParams const & params,
573 Buffer const & buffer)
575 external::Template const * const ptr =
576 external::getTemplatePtr(params);
579 return lyx::to_utf8(support::bformat(_("External template %1$s is not installed"),
580 lyx::from_utf8(params.templatename())));
581 return external::doSubstitution(params, buffer, ptr->guiName, false);
584 void add_preview_and_start_loading(RenderMonitoredPreview &,
585 InsetExternal const &,
591 InsetExternalParams const & InsetExternal::params() const
597 void InsetExternal::setParams(InsetExternalParams const & p,
598 Buffer const & buffer)
602 // Subsequent calls to the InsetExternal::Params default constructor
604 defaultTemplateName = params_.templatename();
606 switch (getRenderType(params_)) {
608 RenderButton * button_ptr = renderer_->asButton();
610 renderer_.reset(new RenderButton);
611 button_ptr = renderer_->asButton();
614 button_ptr->update(getScreenLabel(params_, buffer), true);
617 } case RENDERGRAPHIC: {
618 RenderGraphic * graphic_ptr = renderer_->asGraphic();
620 renderer_.reset(new RenderGraphic(this));
621 graphic_ptr = renderer_->asGraphic();
624 graphic_ptr->update(get_grfx_params(params_));
628 } case RENDERPREVIEW: {
629 RenderMonitoredPreview * preview_ptr =
630 renderer_->asMonitoredPreview();
632 renderer_.reset(new RenderMonitoredPreview(this));
633 preview_ptr = renderer_->asMonitoredPreview();
634 preview_ptr->fileChanged(
635 boost::bind(&InsetExternal::fileChanged, this));
638 if (preview_ptr->monitoring())
639 preview_ptr->stopMonitoring();
640 add_preview_and_start_loading(*preview_ptr, *this, buffer);
648 void InsetExternal::fileChanged() const
650 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
654 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
657 Buffer const & buffer = *buffer_ptr;
658 ptr->removePreview(buffer);
659 add_preview_and_start_loading(*ptr, *this, buffer);
663 void InsetExternal::write(Buffer const & buffer, ostream & os) const
665 params_.write(buffer, os);
669 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
671 InsetExternalParams params;
672 if (params.read(buffer, lex))
673 setParams(params, buffer);
677 int InsetExternal::latex(Buffer const & buf, ostream & os,
678 OutputParams const & runparams) const
681 os << "\\fbox{\\ttfamily{}"
682 << 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");
704 if (cit != et.formats.end())
705 return external::writeExternal(params_, "PDFLaTeX",
707 *(runparams.exportdata),
709 runparams.inComment);
711 return external::writeExternal(params_, "LaTeX", buf, os,
712 *(runparams.exportdata),
714 runparams.inComment);
718 int InsetExternal::plaintext(Buffer const & buf, ostream & os,
719 OutputParams const & runparams) const
721 return external::writeExternal(params_, "Ascii", buf, os,
722 *(runparams.exportdata), false,
723 runparams.inComment);
727 int InsetExternal::docbook(Buffer const & buf, ostream & os,
728 OutputParams const & runparams) const
730 return external::writeExternal(params_, "DocBook", buf, os,
731 *(runparams.exportdata), false,
732 runparams.inComment);
736 void InsetExternal::validate(LaTeXFeatures & features) const
741 external::Template const * const et_ptr =
742 external::getTemplatePtr(params_);
745 external::Template const & et = *et_ptr;
748 switch (features.runparams().flavor) {
749 case OutputParams::LATEX:
752 case OutputParams::PDFLATEX:
755 case OutputParams::XML:
759 external::Template::Formats::const_iterator cit =
760 et.formats.find(format);
761 if (cit == et.formats.end())
764 // FIXME: We don't need that always
765 features.require("lyxdot");
767 vector<string>::const_iterator it = cit->second.requirements.begin();
768 vector<string>::const_iterator end = cit->second.requirements.end();
769 for (; it != end; ++it)
770 features.require(*it);
772 external::TemplateManager & etm = external::TemplateManager::get();
774 it = cit->second.preambleNames.begin();
775 end = cit->second.preambleNames.end();
776 for (; it != end; ++it) {
777 string const preamble = etm.getPreambleDefByName(*it);
778 if (!preamble.empty())
779 features.addExternalPreamble(preamble);
790 bool preview_wanted(InsetExternalParams const & params)
792 string const included_file = params.filename.absFilename();
794 return params.display == external::PreviewDisplay &&
795 support::isFileReadable(included_file);
799 string const latex_string(InsetExternal const & inset, Buffer const & buffer)
802 OutputParams runparams;
803 runparams.flavor = OutputParams::LATEX;
804 inset.latex(buffer, os, runparams);
810 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
811 InsetExternal const & inset,
812 Buffer const & buffer)
814 InsetExternalParams const & params = inset.params();
816 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
817 preview_wanted(params)) {
818 renderer.setAbsFile(params.filename.absFilename());
819 string const snippet = latex_string(inset, buffer);
820 renderer.addPreview(snippet, buffer);
821 renderer.startLoading(buffer);
828 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
830 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
834 if (preview_wanted(params())) {
835 ptr->setAbsFile(params_.filename.absFilename());
836 string const snippet = latex_string(*this, ploader.buffer());
837 ptr->addPreview(snippet, ploader);
844 string const InsetExternalMailer::name_("external");
846 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
851 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
853 return params2string(inset_.params(), buffer);
857 void InsetExternalMailer::string2params(string const & in,
858 Buffer const & buffer,
859 InsetExternalParams & params)
861 params = InsetExternalParams();
865 istringstream data(in);
871 if (!lex || name != name_)
872 return print_mailer_error("InsetExternalMailer", in, 1, name_);
874 // This is part of the inset proper that is usually swallowed
875 // by LyXText::readInset
878 if (!lex || id != "External")
879 return print_mailer_error("InsetBoxMailer", in, 2, "External");
881 params.read(buffer, lex);
886 InsetExternalMailer::params2string(InsetExternalParams const & params,
887 Buffer const & buffer)
890 data << name_ << ' ';
891 params.write(buffer, data);
892 data << "\\end_inset\n";