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"
25 #include "funcrequest.h"
27 #include "LaTeXFeatures.h"
31 #include "metricsinfo.h"
32 #include "outputparams.h"
34 #include "frontends/lyx_gui.h"
35 #include "frontends/LyXView.h"
37 #include "graphics/PreviewLoader.h"
39 #include "support/FileInfo.h"
40 #include "support/filetools.h"
41 #include "support/lstrings.h"
42 #include "support/lyxlib.h"
43 #include "support/tostr.h"
44 #include "support/translator.h"
45 #include "support/std_sstream.h"
47 #include <boost/bind.hpp>
50 namespace support = lyx::support;
51 namespace external = lyx::external;
52 namespace graphics = lyx::graphics;
57 using std::istringstream;
59 using std::ostringstream;
65 external::DisplayType const defaultDisplayType = external::NoDisplay;
67 unsigned int const defaultLyxScale = 100;
69 string defaultTemplateName = "RasterImage";
79 tempname_ = support::tempName(string(), "lyxext");
80 support::unlink(tempname_);
81 // must have an extension for the converter code to work correctly.
86 TempName::TempName(TempName const &)
88 tempname_ = TempName()();
94 support::unlink(tempname_);
99 TempName::operator=(TempName const & other)
102 tempname_ = TempName()();
109 /// The translator between the Display enum and corresponding lyx string.
110 Translator<DisplayType, string> const initTranslator()
112 Translator<DisplayType, string> translator(DefaultDisplay, "default");
114 // Fill the display translator
115 translator.addPair(MonochromeDisplay, "monochrome");
116 translator.addPair(GrayscaleDisplay, "grayscale");
117 translator.addPair(ColorDisplay, "color");
118 translator.addPair(PreviewDisplay, "preview");
119 translator.addPair(NoDisplay, "none");
127 Translator<DisplayType, string> const & displayTranslator()
129 static Translator<DisplayType, string> const translator =
134 } // namespace external
138 InsetExternalParams::InsetExternalParams()
139 : display(defaultDisplayType),
140 lyxscale(defaultLyxScale),
142 templatename_(defaultTemplateName)
148 template <typename T>
149 void clearIfNotFound(T & data, external::TransformID value,
150 vector<external::TransformID> const & ids)
152 typedef vector<external::TransformID>::const_iterator
155 const_iterator it = ids.begin();
156 const_iterator end = ids.end();
157 it = std::find(it, end, value);
165 void InsetExternalParams::settemplate(string const & name)
167 templatename_ = name;
169 external::TemplateManager const & etm =
170 external::TemplateManager::get();
171 external::Template const * const et = etm.getTemplateByName(name);
173 // Be safe. Don't lose data.
176 // Ascertain which transforms the template supports.
177 // Empty all those that it doesn't.
178 vector<external::TransformID> const & ids = et->transformIds;
179 clearIfNotFound(clipdata, external::Clip, ids);
180 clearIfNotFound(extradata, external::Extra, ids);
181 clearIfNotFound(resizedata, external::Resize, ids);
182 clearIfNotFound(rotationdata, external::Rotate, ids);
186 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
189 << "\ttemplate " << templatename() << '\n';
191 if (!filename.empty())
193 << filename.outputFilename(buffer.filePath())
196 if (display != defaultDisplayType)
198 << external::displayTranslator().find(display)
201 if (lyxscale != defaultLyxScale)
202 os << "\tlyxscale " << tostr(lyxscale) << '\n';
207 if (!clipdata.bbox.empty())
208 os << "\tboundingBox " << clipdata.bbox << '\n';
212 external::ExtraData::const_iterator it = extradata.begin();
213 external::ExtraData::const_iterator end = extradata.end();
214 for (; it != end; ++it) {
215 if (!it->second.empty())
216 os << "\textra " << it->first << " \""
217 << it->second << "\"\n";
220 if (!rotationdata.no_rotation()) {
221 os << "\trotateAngle " << rotationdata.angle() << '\n';
222 if (rotationdata.origin() != external::RotationData::DEFAULT)
223 os << "\trotateOrigin "
224 << rotationdata.originString() << '\n';
227 if (!resizedata.no_resize()) {
228 using support::float_equal;
230 if (!float_equal(resizedata.scale, 0.0, 0.05)) {
231 if (!float_equal(resizedata.scale, 100.0, 0.05))
233 << resizedata.scale << '\n';
235 if (!resizedata.width.zero())
237 << resizedata.width.asString() << '\n';
238 if (!resizedata.height.zero())
240 << resizedata.height.asString() << '\n';
242 if (resizedata.keepAspectRatio)
243 os << "\tkeepAspectRatio\n";
248 bool InsetExternalParams::read(Buffer const & buffer, LyXLex & lex)
268 keyword_item external_tags[] = {
269 { "\\end_inset", EX_END },
270 { "boundingBox", EX_BOUNDINGBOX },
272 { "display", EX_DISPLAY},
273 { "draft", EX_DRAFT},
274 { "extra", EX_EXTRA },
275 { "filename", EX_FILENAME},
276 { "height", EX_HEIGHT },
277 { "keepAspectRatio", EX_KEEPASPECTRATIO },
278 { "lyxscale", EX_LYXSCALE},
279 { "rotateAngle", EX_ROTATEANGLE },
280 { "rotateOrigin", EX_ROTATEORIGIN },
281 { "scale", EX_SCALE },
282 { "template", EX_TEMPLATE },
283 { "width", EX_WIDTH }
286 pushpophelper pph(lex, external_tags, EX_END);
288 bool found_end = false;
289 bool read_error = false;
295 templatename_ = lex.getString();
300 string const name = lex.getString();
301 filename.set(name, buffer.filePath());
307 string const name = lex.getString();
308 display = external::displayTranslator().find(name);
314 lyxscale = lex.getInteger();
323 clipdata.bbox.xl = lex.getInteger();
325 clipdata.bbox.yb = lex.getInteger();
327 clipdata.bbox.xr = lex.getInteger();
329 clipdata.bbox.yt = lex.getInteger();
333 clipdata.clip = true;
338 string const name = lex.getString();
340 extradata.set(name, lex.getString());
346 resizedata.height = LyXLength(lex.getString());
349 case EX_KEEPASPECTRATIO:
350 resizedata.keepAspectRatio = true;
355 rotationdata.angle(lex.getFloat());
358 case EX_ROTATEORIGIN:
360 rotationdata.origin(lex.getString());
365 resizedata.scale = lex.getFloat();
370 resizedata.width = LyXLength(lex.getString());
378 lex.printError("ExternalInset::read: "
379 "Wrong tag: $$Token");
384 if (found_end || read_error)
389 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
391 // This is a trick to make sure that the data are self-consistent.
392 settemplate(templatename_);
394 if (lyxerr.debugging(Debug::EXTERNAL)) {
395 lyxerr << "InsetExternalParams::read:\n";
396 write(buffer, lyxerr);
403 InsetExternal::InsetExternal()
404 : renderer_(new RenderButton)
408 InsetExternal::InsetExternal(InsetExternal const & other)
410 boost::signals::trackable(),
411 params_(other.params_),
412 renderer_(other.renderer_->clone())
414 if (renderer_->asMonitoredPreview() != 0) {
415 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
416 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
417 ptr->fileChanged(boost::bind(&InsetExternal::fileChanged, this));
419 } else if (renderer_->asGraphic() != 0 ) {
420 RenderGraphic * const ptr = renderer_->asGraphic();
421 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
426 auto_ptr<InsetBase> InsetExternal::clone() const
428 return auto_ptr<InsetBase>(new InsetExternal(*this));
432 InsetExternal::~InsetExternal()
434 InsetExternalMailer(*this).hideDialog();
438 void InsetExternal::statusChanged() const
440 LyX::cref().updateInset(this);
445 InsetExternal::priv_dispatch(LCursor & cur, FuncRequest const & cmd)
447 switch (cmd.action) {
449 case LFUN_EXTERNAL_EDIT: {
450 Buffer const & buffer = *cur.bv().buffer();
451 InsetExternalParams p;
452 InsetExternalMailer::string2params(cmd.argument, buffer, p);
453 external::editExternal(p, buffer);
454 return DispatchResult(true);
457 case LFUN_INSET_MODIFY: {
458 Buffer const & buffer = *cur.bv().buffer();
459 InsetExternalParams p;
460 InsetExternalMailer::string2params(cmd.argument, buffer, p);
461 setParams(p, buffer);
463 return DispatchResult(true, true);
466 case LFUN_INSET_DIALOG_UPDATE:
467 InsetExternalMailer(*this).updateDialog(&cur.bv());
468 return DispatchResult(true, true);
470 case LFUN_MOUSE_RELEASE:
471 InsetExternalMailer(*this).showDialog(&cur.bv());
472 return DispatchResult(true, true);
475 return DispatchResult(false);
480 void InsetExternal::edit(LCursor & cur, bool)
482 InsetExternalMailer(*this).showDialog(&cur.bv());
486 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
488 renderer_->metrics(mi, dim);
493 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
497 renderer_->draw(pi, x, y);
510 RenderType getRenderType(InsetExternalParams const & p)
512 if (!external::getTemplatePtr(p) ||
513 p.filename.empty() ||
514 p.display == external::NoDisplay)
517 if (p.display == external::PreviewDisplay) {
518 if (RenderPreview::activated())
519 return RENDERPREVIEW;
523 if (p.display == external::DefaultDisplay &&
524 lyxrc.display_graphics == graphics::NoDisplay)
526 return RENDERGRAPHIC;
530 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
532 graphics::Params gparams;
534 gparams.filename = eparams.filename.absFilename();
535 gparams.scale = eparams.lyxscale;
536 if (eparams.clipdata.clip)
537 gparams.bb = eparams.clipdata.bbox;
538 gparams.angle = eparams.rotationdata.angle();
540 switch (eparams.display) {
541 case external::DefaultDisplay:
542 gparams.display = graphics::DefaultDisplay;
544 case external::MonochromeDisplay:
545 gparams.display = graphics::MonochromeDisplay;
547 case external::GrayscaleDisplay:
548 gparams.display = graphics::GrayscaleDisplay;
550 case external::ColorDisplay:
551 gparams.display = graphics::ColorDisplay;
553 case external::NoDisplay:
554 gparams.display = graphics::NoDisplay;
559 if (gparams.display == graphics::DefaultDisplay)
560 gparams.display = lyxrc.display_graphics;
561 // Override the above if we're not using a gui
562 if (!lyx_gui::use_gui)
563 gparams.display = graphics::NoDisplay;
569 string const getScreenLabel(InsetExternalParams const & params,
570 Buffer const & buffer)
572 external::Template const * const ptr =
573 external::getTemplatePtr(params);
575 return support::bformat(_("External template %1$s is not installed"),
576 params.templatename());
577 return external::doSubstitution(params, buffer, ptr->guiName);
580 void add_preview(RenderMonitoredPreview &, InsetExternal const &, Buffer const &);
585 InsetExternalParams const & InsetExternal::params() const
591 void InsetExternal::setParams(InsetExternalParams const & p,
592 Buffer const & buffer)
596 // Subsequent calls to the InsetExternal::Params default constructor
598 defaultTemplateName = params_.templatename();
600 switch (getRenderType(params_)) {
602 RenderButton * button_ptr = renderer_->asButton();
604 renderer_.reset(new RenderButton);
605 button_ptr = renderer_->asButton();
608 button_ptr->update(getScreenLabel(params_, buffer), true);
611 } case RENDERGRAPHIC: {
612 RenderGraphic * graphic_ptr = renderer_->asGraphic();
614 renderer_.reset(new RenderGraphic);
615 graphic_ptr = renderer_->asGraphic();
616 graphic_ptr->connect(
617 boost::bind(&InsetExternal::statusChanged, this));
620 graphic_ptr->update(get_grfx_params(params_));
624 } case RENDERPREVIEW: {
625 RenderMonitoredPreview * preview_ptr =
626 renderer_->asMonitoredPreview();
628 renderer_.reset(new RenderMonitoredPreview);
629 preview_ptr = renderer_->asMonitoredPreview();
630 preview_ptr->connect(
631 boost::bind(&InsetExternal::statusChanged, this));
632 preview_ptr->fileChanged(
633 boost::bind(&InsetExternal::fileChanged, this));
636 if (preview_ptr->monitoring())
637 preview_ptr->stopMonitoring();
638 add_preview(*preview_ptr, *this, buffer);
646 void InsetExternal::fileChanged() const
648 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
652 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
655 Buffer const & buffer = *buffer_ptr;
656 ptr->removePreview(buffer);
657 add_preview(*ptr, *this, buffer);
658 ptr->startLoading(buffer);
662 void InsetExternal::write(Buffer const & buffer, ostream & os) const
664 params_.write(buffer, os);
668 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
670 InsetExternalParams params;
671 if (params.read(buffer, lex))
672 setParams(params, buffer);
676 int InsetExternal::latex(Buffer const & buf, ostream & os,
677 OutputParams const & runparams) const
680 os << "\\fbox{\\ttfamily{}"
681 << params_.filename.outputFilename(buf.filePath())
686 // "nice" means that the buffer is exported to LaTeX format but not
687 // run through the LaTeX compiler.
688 // If we're running through the LaTeX compiler, we should write the
689 // generated files in the bufer's temporary directory.
690 bool const external_in_tmpdir =
691 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
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",
706 buf, os, external_in_tmpdir);
709 return external::writeExternal(params_, "LaTeX",
710 buf, os, external_in_tmpdir);
714 int InsetExternal::plaintext(Buffer const & buf, ostream & os,
715 OutputParams const &) const
717 return external::writeExternal(params_, "Ascii", buf, os);
721 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os,
722 OutputParams const &) const
724 return external::writeExternal(params_, "LinuxDoc", buf, os);
728 int InsetExternal::docbook(Buffer const & buf, ostream & os,
729 OutputParams const &) const
731 return external::writeExternal(params_, "DocBook", buf, os);
735 void InsetExternal::validate(LaTeXFeatures & features) const
740 external::Template const * const et_ptr =
741 external::getTemplatePtr(params_);
744 external::Template const & et = *et_ptr;
746 external::Template::Formats::const_iterator cit =
747 et.formats.find("LaTeX");
748 if (cit == et.formats.end())
751 if (!cit->second.requirement.empty())
752 features.require(cit->second.requirement);
754 external::TemplateManager & etm = external::TemplateManager::get();
756 vector<string>::const_iterator it = cit->second.preambleNames.begin();
757 vector<string>::const_iterator end = cit->second.preambleNames.end();
758 for (; it != end; ++it) {
759 string const preamble = etm.getPreambleDefByName(*it);
760 if (!preamble.empty())
761 features.addExternalPreamble(preamble);
772 bool preview_wanted(InsetExternalParams const & params)
774 string const included_file = params.filename.absFilename();
776 return params.display == external::PreviewDisplay &&
777 support::IsFileReadable(included_file);
781 string const latex_string(InsetExternal const & inset, Buffer const & buffer)
784 OutputParams runparams;
785 runparams.flavor = OutputParams::LATEX;
786 inset.latex(buffer, os, runparams);
792 void add_preview(RenderMonitoredPreview & renderer, InsetExternal const & inset,
793 Buffer const & buffer)
795 InsetExternalParams const & params = inset.params();
796 if (RenderPreview::activated() && preview_wanted(params)) {
797 renderer.setAbsFile(params.filename.absFilename());
798 string const snippet = latex_string(inset, buffer);
799 renderer.addPreview(snippet, buffer);
806 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
808 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
812 if (preview_wanted(params())) {
813 ptr->setAbsFile(params_.filename.absFilename());
814 string const snippet = latex_string(*this, ploader.buffer());
815 ptr->addPreview(snippet, ploader);
822 string const InsetExternalMailer::name_("external");
824 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
829 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
831 return params2string(inset_.params(), buffer);
835 void InsetExternalMailer::string2params(string const & in,
836 Buffer const & buffer,
837 InsetExternalParams & params)
839 params = InsetExternalParams();
843 istringstream data(in);
849 if (!lex || name != name_)
850 return print_mailer_error("InsetExternalMailer", in, 1, name_);
852 // This is part of the inset proper that is usually swallowed
853 // by LyXText::readInset
856 if (!lex || id != "External")
857 return print_mailer_error("InsetBoxMailer", in, 2, "External");
859 params.read(buffer, lex);
864 InsetExternalMailer::params2string(InsetExternalParams const & params,
865 Buffer const & buffer)
868 data << name_ << ' ';
869 params.write(buffer, data);
870 data << "\\end_inset\n";