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"
21 #include "BufferView.h"
24 #include "dispatchresult.h"
26 #include "funcrequest.h"
28 #include "LaTeXFeatures.h"
32 #include "metricsinfo.h"
33 #include "outputparams.h"
35 #include "frontends/lyx_gui.h"
36 #include "frontends/LyXView.h"
38 #include "graphics/PreviewLoader.h"
40 #include "support/FileInfo.h"
41 #include "support/filetools.h"
42 #include "support/lstrings.h"
43 #include "support/lyxlib.h"
44 #include "support/tostr.h"
45 #include "support/translator.h"
47 #include <boost/bind.hpp>
51 namespace support = lyx::support;
52 namespace external = lyx::external;
53 namespace graphics = lyx::graphics;
58 using std::istringstream;
60 using std::ostringstream;
66 external::DisplayType const defaultDisplayType = external::NoDisplay;
68 unsigned int const defaultLyxScale = 100;
70 string defaultTemplateName = "RasterImage";
80 tempname_ = support::tempName(string(), "lyxext");
81 // FIXME: This is unsafe
82 support::unlink(tempname_);
83 // must have an extension for the converter code to work correctly.
88 TempName::TempName(TempName const &)
90 tempname_ = TempName()();
96 support::unlink(tempname_);
101 TempName::operator=(TempName const & other)
104 tempname_ = TempName()();
111 /// The translator between the Display enum and corresponding lyx string.
112 Translator<DisplayType, string> const initTranslator()
114 Translator<DisplayType, string> translator(DefaultDisplay, "default");
116 // Fill the display translator
117 translator.addPair(MonochromeDisplay, "monochrome");
118 translator.addPair(GrayscaleDisplay, "grayscale");
119 translator.addPair(ColorDisplay, "color");
120 translator.addPair(PreviewDisplay, "preview");
121 translator.addPair(NoDisplay, "none");
129 Translator<DisplayType, string> const & displayTranslator()
131 static Translator<DisplayType, string> const translator =
136 } // namespace external
140 InsetExternalParams::InsetExternalParams()
141 : display(defaultDisplayType),
142 lyxscale(defaultLyxScale),
144 templatename_(defaultTemplateName)
150 template <typename T>
151 void clearIfNotFound(T & data, external::TransformID value,
152 vector<external::TransformID> const & ids)
154 typedef vector<external::TransformID>::const_iterator
157 const_iterator it = ids.begin();
158 const_iterator end = ids.end();
159 it = std::find(it, end, value);
167 void InsetExternalParams::settemplate(string const & name)
169 templatename_ = name;
171 external::TemplateManager const & etm =
172 external::TemplateManager::get();
173 external::Template const * const et = etm.getTemplateByName(name);
175 // Be safe. Don't lose data.
178 // Ascertain which transforms the template supports.
179 // Empty all those that it doesn't.
180 vector<external::TransformID> const & ids = et->transformIds;
181 clearIfNotFound(clipdata, external::Clip, ids);
182 clearIfNotFound(extradata, external::Extra, ids);
183 clearIfNotFound(resizedata, external::Resize, ids);
184 clearIfNotFound(rotationdata, external::Rotate, ids);
188 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
191 << "\ttemplate " << templatename() << '\n';
193 if (!filename.empty())
195 << filename.outputFilename(buffer.filePath())
198 if (display != defaultDisplayType)
200 << external::displayTranslator().find(display)
203 if (lyxscale != defaultLyxScale)
204 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
209 if (!clipdata.bbox.empty())
210 os << "\tboundingBox " << clipdata.bbox << '\n';
214 external::ExtraData::const_iterator it = extradata.begin();
215 external::ExtraData::const_iterator end = extradata.end();
216 for (; it != end; ++it) {
217 if (!it->second.empty())
218 os << "\textra " << it->first << " \""
219 << it->second << "\"\n";
222 if (!rotationdata.no_rotation()) {
223 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
224 if (rotationdata.origin() != external::RotationData::DEFAULT)
225 os << "\trotateOrigin "
226 << rotationdata.originString() << '\n';
229 if (!resizedata.no_resize()) {
230 using support::float_equal;
231 double scl = support::strToDbl(resizedata.scale);
232 if (!float_equal(scl, 0.0, 0.05)) {
233 if (!float_equal(scl, 100.0, 0.05))
235 << resizedata.scale << '\n';
237 if (!resizedata.width.zero())
239 << resizedata.width.asString() << '\n';
240 if (!resizedata.height.zero())
242 << resizedata.height.asString() << '\n';
244 if (resizedata.keepAspectRatio)
245 os << "\tkeepAspectRatio\n";
250 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
270 keyword_item external_tags[] = {
271 { "\\end_inset", EX_END },
272 { "boundingBox", EX_BOUNDINGBOX },
274 { "display", EX_DISPLAY},
275 { "draft", EX_DRAFT},
276 { "extra", EX_EXTRA },
277 { "filename", EX_FILENAME},
278 { "height", EX_HEIGHT },
279 { "keepAspectRatio", EX_KEEPASPECTRATIO },
280 { "lyxscale", EX_LYXSCALE},
281 { "rotateAngle", EX_ROTATEANGLE },
282 { "rotateOrigin", EX_ROTATEORIGIN },
283 { "scale", EX_SCALE },
284 { "template", EX_TEMPLATE },
285 { "width", EX_WIDTH }
288 pushpophelper pph(lex, external_tags, EX_END);
290 bool found_end = false;
291 bool read_error = false;
297 templatename_ = lex.getString();
302 string const name = lex.getString();
303 filename.set(name, buffer.filePath());
309 string const name = lex.getString();
310 display = external::displayTranslator().find(name);
316 lyxscale = lex.getInteger();
325 clipdata.bbox.xl = lex.getInteger();
327 clipdata.bbox.yb = lex.getInteger();
329 clipdata.bbox.xr = lex.getInteger();
331 clipdata.bbox.yt = lex.getInteger();
335 clipdata.clip = true;
340 string const name = lex.getString();
342 extradata.set(name, lex.getString());
348 resizedata.height = LyXLength(lex.getString());
351 case EX_KEEPASPECTRATIO:
352 resizedata.keepAspectRatio = true;
357 rotationdata.angle = lex.getString();
360 case EX_ROTATEORIGIN:
362 rotationdata.origin(lex.getString());
367 resizedata.scale = lex.getString();
372 resizedata.width = LyXLength(lex.getString());
380 lex.printError("ExternalInset::read: "
381 "Wrong tag: $$Token");
386 if (found_end || read_error)
391 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
393 // This is a trick to make sure that the data are self-consistent.
394 settemplate(templatename_);
396 if (lyxerr.debugging(Debug::EXTERNAL)) {
397 lyxerr << "InsetExternalParams::read:\n";
398 write(buffer, lyxerr);
405 InsetExternal::InsetExternal()
406 : renderer_(new RenderButton)
410 InsetExternal::InsetExternal(InsetExternal const & other)
412 boost::signals::trackable(),
413 params_(other.params_),
414 renderer_(other.renderer_->clone(this))
418 auto_ptr<InsetBase> InsetExternal::doClone() const
420 return auto_ptr<InsetBase>(new InsetExternal(*this));
424 InsetExternal::~InsetExternal()
426 InsetExternalMailer(*this).hideDialog();
430 void InsetExternal::statusChanged() const
432 LyX::cref().updateInset(this);
436 void InsetExternal::doDispatch(LCursor & cur, FuncRequest & cmd)
438 switch (cmd.action) {
440 case LFUN_EXTERNAL_EDIT: {
441 Buffer const & buffer = cur.buffer();
442 InsetExternalParams p;
443 InsetExternalMailer::string2params(cmd.argument, buffer, p);
444 external::editExternal(p, buffer);
448 case LFUN_INSET_MODIFY: {
449 Buffer const & buffer = cur.buffer();
450 InsetExternalParams p;
451 InsetExternalMailer::string2params(cmd.argument, buffer, p);
452 setParams(p, buffer);
456 case LFUN_INSET_DIALOG_UPDATE:
457 InsetExternalMailer(*this).updateDialog(&cur.bv());
460 case LFUN_MOUSE_RELEASE:
461 InsetExternalMailer(*this).showDialog(&cur.bv());
465 InsetBase::doDispatch(cur, cmd);
470 void InsetExternal::edit(LCursor & cur, bool)
472 InsetExternalMailer(*this).showDialog(&cur.bv());
476 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
478 renderer_->metrics(mi, dim);
483 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
485 setPosCache(pi, x, y);
486 renderer_->draw(pi, x, y);
499 RenderType getRenderType(InsetExternalParams const & p)
501 if (!external::getTemplatePtr(p) ||
502 p.filename.empty() ||
503 p.display == external::NoDisplay)
506 if (p.display == external::PreviewDisplay) {
507 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
508 return RENDERPREVIEW;
512 if (p.display == external::DefaultDisplay &&
513 lyxrc.display_graphics == graphics::NoDisplay)
515 return RENDERGRAPHIC;
519 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
521 graphics::Params gparams;
523 gparams.filename = eparams.filename.absFilename();
524 gparams.scale = eparams.lyxscale;
525 if (eparams.clipdata.clip)
526 gparams.bb = eparams.clipdata.bbox;
527 gparams.angle = lyx::support::strToDbl(eparams.rotationdata.adjAngle());
529 switch (eparams.display) {
530 case external::DefaultDisplay:
531 gparams.display = graphics::DefaultDisplay;
533 case external::MonochromeDisplay:
534 gparams.display = graphics::MonochromeDisplay;
536 case external::GrayscaleDisplay:
537 gparams.display = graphics::GrayscaleDisplay;
539 case external::ColorDisplay:
540 gparams.display = graphics::ColorDisplay;
542 case external::NoDisplay:
543 gparams.display = graphics::NoDisplay;
548 if (gparams.display == graphics::DefaultDisplay)
549 gparams.display = lyxrc.display_graphics;
550 // Override the above if we're not using a gui
551 if (!lyx_gui::use_gui)
552 gparams.display = graphics::NoDisplay;
558 string const getScreenLabel(InsetExternalParams const & params,
559 Buffer const & buffer)
561 external::Template const * const ptr =
562 external::getTemplatePtr(params);
564 return support::bformat(_("External template %1$s is not installed"),
565 params.templatename());
566 return external::doSubstitution(params, buffer, ptr->guiName);
569 void add_preview_and_start_loading(RenderMonitoredPreview &,
570 InsetExternal const &,
576 InsetExternalParams const & InsetExternal::params() const
582 void InsetExternal::setParams(InsetExternalParams const & p,
583 Buffer const & buffer)
587 // Subsequent calls to the InsetExternal::Params default constructor
589 defaultTemplateName = params_.templatename();
591 switch (getRenderType(params_)) {
593 RenderButton * button_ptr = renderer_->asButton();
595 renderer_.reset(new RenderButton);
596 button_ptr = renderer_->asButton();
599 button_ptr->update(getScreenLabel(params_, buffer), true);
602 } case RENDERGRAPHIC: {
603 RenderGraphic * graphic_ptr = renderer_->asGraphic();
605 renderer_.reset(new RenderGraphic(this));
606 graphic_ptr = renderer_->asGraphic();
609 graphic_ptr->update(get_grfx_params(params_));
613 } case RENDERPREVIEW: {
614 RenderMonitoredPreview * preview_ptr =
615 renderer_->asMonitoredPreview();
617 renderer_.reset(new RenderMonitoredPreview(this));
618 preview_ptr = renderer_->asMonitoredPreview();
619 preview_ptr->fileChanged(
620 boost::bind(&InsetExternal::fileChanged, this));
623 if (preview_ptr->monitoring())
624 preview_ptr->stopMonitoring();
625 add_preview_and_start_loading(*preview_ptr, *this, buffer);
633 void InsetExternal::fileChanged() const
635 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
639 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
642 Buffer const & buffer = *buffer_ptr;
643 ptr->removePreview(buffer);
644 add_preview_and_start_loading(*ptr, *this, buffer);
648 void InsetExternal::write(Buffer const & buffer, ostream & os) const
650 params_.write(buffer, os);
654 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
656 InsetExternalParams params;
657 if (params.read(buffer, lex))
658 setParams(params, buffer);
662 int InsetExternal::latex(Buffer const & buf, ostream & os,
663 OutputParams const & runparams) const
666 os << "\\fbox{\\ttfamily{}"
667 << params_.filename.outputFilename(buf.filePath())
672 // "nice" means that the buffer is exported to LaTeX format but not
673 // run through the LaTeX compiler.
674 // If we're running through the LaTeX compiler, we should write the
675 // generated files in the bufer's temporary directory.
676 bool const external_in_tmpdir = !runparams.nice;
678 // If the template has specified a PDFLaTeX output, then we try and
680 if (runparams.flavor == OutputParams::PDFLATEX) {
681 external::Template const * const et_ptr =
682 external::getTemplatePtr(params_);
685 external::Template const & et = *et_ptr;
687 external::Template::Formats::const_iterator cit =
688 et.formats.find("PDFLaTeX");
689 if (cit != et.formats.end())
690 return external::writeExternal(params_, "PDFLaTeX",
692 *(runparams.exportdata),
695 return external::writeExternal(params_, "LaTeX", buf, os,
696 *(runparams.exportdata),
701 int InsetExternal::plaintext(Buffer const & buf, ostream & os,
702 OutputParams const & runparams) const
704 return external::writeExternal(params_, "Ascii", buf, os,
705 *(runparams.exportdata));
709 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os,
710 OutputParams const & runparams) const
712 return external::writeExternal(params_, "LinuxDoc", buf, os,
713 *(runparams.exportdata));
717 int InsetExternal::docbook(Buffer const & buf, ostream & os,
718 OutputParams const & runparams) const
720 return external::writeExternal(params_, "DocBook", buf, os,
721 *(runparams.exportdata));
725 void InsetExternal::validate(LaTeXFeatures & features) const
730 external::Template const * const et_ptr =
731 external::getTemplatePtr(params_);
734 external::Template const & et = *et_ptr;
736 external::Template::Formats::const_iterator cit =
737 et.formats.find("LaTeX");
738 if (cit == et.formats.end())
741 if (!cit->second.requirement.empty())
742 features.require(cit->second.requirement);
744 external::TemplateManager & etm = external::TemplateManager::get();
746 vector<string>::const_iterator it = cit->second.preambleNames.begin();
747 vector<string>::const_iterator end = cit->second.preambleNames.end();
748 for (; it != end; ++it) {
749 string const preamble = etm.getPreambleDefByName(*it);
750 if (!preamble.empty())
751 features.addExternalPreamble(preamble);
762 bool preview_wanted(InsetExternalParams const & params)
764 string const included_file = params.filename.absFilename();
766 return params.display == external::PreviewDisplay &&
767 support::IsFileReadable(included_file);
771 string const latex_string(InsetExternal const & inset, Buffer const & buffer)
774 OutputParams runparams;
775 runparams.flavor = OutputParams::LATEX;
776 inset.latex(buffer, os, runparams);
782 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
783 InsetExternal const & inset,
784 Buffer const & buffer)
786 InsetExternalParams const & params = inset.params();
788 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
789 preview_wanted(params)) {
790 renderer.setAbsFile(params.filename.absFilename());
791 string const snippet = latex_string(inset, buffer);
792 renderer.addPreview(snippet, buffer);
793 renderer.startLoading(buffer);
800 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
802 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
806 if (preview_wanted(params())) {
807 ptr->setAbsFile(params_.filename.absFilename());
808 string const snippet = latex_string(*this, ploader.buffer());
809 ptr->addPreview(snippet, ploader);
816 string const InsetExternalMailer::name_("external");
818 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
823 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
825 return params2string(inset_.params(), buffer);
829 void InsetExternalMailer::string2params(string const & in,
830 Buffer const & buffer,
831 InsetExternalParams & params)
833 params = InsetExternalParams();
837 istringstream data(in);
843 if (!lex || name != name_)
844 return print_mailer_error("InsetExternalMailer", in, 1, name_);
846 // This is part of the inset proper that is usually swallowed
847 // by LyXText::readInset
850 if (!lex || id != "External")
851 return print_mailer_error("InsetBoxMailer", in, 2, "External");
853 params.read(buffer, lex);
858 InsetExternalMailer::params2string(InsetExternalParams const & params,
859 Buffer const & buffer)
862 data << name_ << ' ';
863 params.write(buffer, data);
864 data << "\\end_inset\n";