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;
53 using lyx::support::DocFileName;
57 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
59 unsigned int const defaultLyxScale = 100;
61 string defaultTemplateName;
72 support::FileName const tempname(support::tempName(support::FileName(), "lyxext"));
73 // FIXME: This is unsafe
74 support::unlink(tempname);
75 // must have an extension for the converter code to work correctly.
76 tempname_ = support::FileName(tempname.absFilename() + ".tmp");
80 TempName::TempName(TempName const &)
82 tempname_ = TempName()();
88 support::unlink(tempname_);
93 TempName::operator=(TempName const & other)
96 tempname_ = TempName()();
103 /// The translator between the Display enum and corresponding lyx string.
104 Translator<DisplayType, string> const initTranslator()
106 Translator<DisplayType, string> translator(DefaultDisplay, "default");
108 // Fill the display translator
109 translator.addPair(MonochromeDisplay, "monochrome");
110 translator.addPair(GrayscaleDisplay, "grayscale");
111 translator.addPair(ColorDisplay, "color");
112 translator.addPair(PreviewDisplay, "preview");
113 translator.addPair(NoDisplay, "none");
121 Translator<DisplayType, string> const & displayTranslator()
123 static Translator<DisplayType, string> const translator =
128 } // namespace external
131 InsetExternalParams::InsetExternalParams()
132 : display(defaultDisplayType),
133 lyxscale(defaultLyxScale),
136 if (defaultTemplateName.empty()) {
137 external::TemplateManager const & etm =
138 external::TemplateManager::get();
139 templatename_ = etm.getTemplates().begin()->first;
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()) {
191 // when we save, we still use the original filename
192 EmbeddedFiles::EmbeddedFileList::const_iterator it =
193 buffer.embeddedFiles().find(filename.toFilesystemEncoding());
194 if (it != buffer.embeddedFiles().end())
195 os << "\tfilename " << DocFileName(it->absFilename()).outputFilename(buffer.filePath()) << '\n';
197 os << "\tfilename " << filename.outputFilename(buffer.filePath()) << '\n';
200 if (display != defaultDisplayType)
202 << external::displayTranslator().find(display)
205 if (lyxscale != defaultLyxScale)
206 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
211 if (!clipdata.bbox.empty())
212 os << "\tboundingBox " << clipdata.bbox << '\n';
216 external::ExtraData::const_iterator it = extradata.begin();
217 external::ExtraData::const_iterator end = extradata.end();
218 for (; it != end; ++it) {
219 if (!it->second.empty())
220 os << "\textra " << it->first << " \""
221 << it->second << "\"\n";
224 if (!rotationdata.no_rotation()) {
225 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
226 if (rotationdata.origin() != external::RotationData::DEFAULT)
227 os << "\trotateOrigin "
228 << rotationdata.originString() << '\n';
231 if (!resizedata.no_resize()) {
232 using support::float_equal;
233 double const scl = convert<double>(resizedata.scale);
234 if (!float_equal(scl, 0.0, 0.05)) {
235 if (!float_equal(scl, 100.0, 0.05))
237 << resizedata.scale << '\n';
239 if (!resizedata.width.zero())
241 << resizedata.width.asString() << '\n';
242 if (!resizedata.height.zero())
244 << resizedata.height.asString() << '\n';
246 if (resizedata.keepAspectRatio)
247 os << "\tkeepAspectRatio\n";
252 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
272 keyword_item external_tags[] = {
273 { "\\end_inset", EX_END },
274 { "boundingBox", EX_BOUNDINGBOX },
276 { "display", EX_DISPLAY},
277 { "draft", EX_DRAFT},
278 { "extra", EX_EXTRA },
279 { "filename", EX_FILENAME},
280 { "height", EX_HEIGHT },
281 { "keepAspectRatio", EX_KEEPASPECTRATIO },
282 { "lyxscale", EX_LYXSCALE},
283 { "rotateAngle", EX_ROTATEANGLE },
284 { "rotateOrigin", EX_ROTATEORIGIN },
285 { "scale", EX_SCALE },
286 { "template", EX_TEMPLATE },
287 { "width", EX_WIDTH }
290 PushPopHelper pph(lex, external_tags, EX_END);
292 bool found_end = false;
293 bool read_error = false;
299 templatename_ = lex.getString();
304 string const name = lex.getString();
305 filename.set(name, buffer.filePath());
306 // maybe this file is embedded
307 EmbeddedFiles::EmbeddedFileList::const_iterator it = buffer.embeddedFiles().find(filename.toFilesystemEncoding());
308 if (it != buffer.embeddedFiles().end())
309 // using available file, embedded or external, depending on file availability and
311 filename = DocFileName(it->availableFile(&buffer));
317 string const name = lex.getString();
318 display = external::displayTranslator().find(name);
324 lyxscale = lex.getInteger();
333 clipdata.bbox.xl = lex.getInteger();
335 clipdata.bbox.yb = lex.getInteger();
337 clipdata.bbox.xr = lex.getInteger();
339 clipdata.bbox.yt = lex.getInteger();
343 clipdata.clip = true;
348 string const name = lex.getString();
350 extradata.set(name, lex.getString());
356 resizedata.height = Length(lex.getString());
359 case EX_KEEPASPECTRATIO:
360 resizedata.keepAspectRatio = true;
365 rotationdata.angle = lex.getString();
368 case EX_ROTATEORIGIN:
370 rotationdata.origin(lex.getString());
375 resizedata.scale = lex.getString();
380 resizedata.width = Length(lex.getString());
388 lex.printError("ExternalInset::read: "
389 "Wrong tag: $$Token");
394 if (found_end || read_error)
399 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
401 // This is a trick to make sure that the data are self-consistent.
402 settemplate(templatename_);
404 if (lyxerr.debugging(Debug::EXTERNAL)) {
405 lyxerr << "InsetExternalParams::read:\n";
406 write(buffer, lyxerr);
413 InsetExternal::InsetExternal()
414 : renderer_(new RenderButton)
418 InsetExternal::InsetExternal(InsetExternal const & other)
420 boost::signals::trackable(),
421 params_(other.params_),
422 renderer_(other.renderer_->clone(this))
426 Inset * InsetExternal::clone() const
428 return new InsetExternal(*this);
432 InsetExternal::~InsetExternal()
434 InsetExternalMailer(*this).hideDialog();
438 void InsetExternal::statusChanged() const
440 LyX::cref().updateInset(this);
444 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
446 switch (cmd.action) {
448 case LFUN_EXTERNAL_EDIT: {
449 Buffer const & buffer = cur.buffer();
450 InsetExternalParams p;
451 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
452 external::editExternal(p, buffer);
456 case LFUN_INSET_MODIFY: {
457 Buffer const & buffer = cur.buffer();
458 InsetExternalParams p;
459 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
460 setParams(p, buffer);
464 case LFUN_INSET_DIALOG_UPDATE:
465 InsetExternalMailer(*this).updateDialog(&cur.bv());
468 case LFUN_MOUSE_RELEASE:
469 if (!cur.selection())
470 InsetExternalMailer(*this).showDialog(&cur.bv());
474 Inset::doDispatch(cur, cmd);
479 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
480 FuncStatus & flag) const
482 switch (cmd.action) {
484 case LFUN_EXTERNAL_EDIT:
485 case LFUN_INSET_MODIFY:
486 case LFUN_INSET_DIALOG_UPDATE:
491 return Inset::getStatus(cur, cmd, flag);
496 void InsetExternal::registerEmbeddedFiles(Buffer const &,
497 EmbeddedFiles & files, ParConstIterator const & pit) const
499 files.registerFile(params_.filename.absFilename(), EmbeddedFile::AUTO, pit);
503 void InsetExternal::edit(Cursor & cur, bool)
505 InsetExternalMailer(*this).showDialog(&cur.bv());
509 bool InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
511 renderer_->metrics(mi, dim);
512 bool const changed = dim_ != dim;
518 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
520 setPosCache(pi, x, y);
521 renderer_->draw(pi, x, y);
534 RenderType getRenderType(InsetExternalParams const & p)
536 if (!external::getTemplatePtr(p) ||
537 p.filename.empty() ||
538 p.display == external::NoDisplay)
541 if (p.display == external::PreviewDisplay) {
542 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
543 return RENDERPREVIEW;
547 if (p.display == external::DefaultDisplay &&
548 lyxrc.display_graphics == graphics::NoDisplay)
550 return RENDERGRAPHIC;
554 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
556 graphics::Params gparams;
558 gparams.filename = eparams.filename;
559 gparams.scale = eparams.lyxscale;
560 if (eparams.clipdata.clip)
561 gparams.bb = eparams.clipdata.bbox;
562 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
564 switch (eparams.display) {
565 case external::DefaultDisplay:
566 gparams.display = graphics::DefaultDisplay;
568 case external::MonochromeDisplay:
569 gparams.display = graphics::MonochromeDisplay;
571 case external::GrayscaleDisplay:
572 gparams.display = graphics::GrayscaleDisplay;
574 case external::ColorDisplay:
575 gparams.display = graphics::ColorDisplay;
577 case external::NoDisplay:
578 gparams.display = graphics::NoDisplay;
583 if (gparams.display == graphics::DefaultDisplay)
584 gparams.display = lyxrc.display_graphics;
585 // Override the above if we're not using a gui
587 gparams.display = graphics::NoDisplay;
593 docstring const getScreenLabel(InsetExternalParams const & params,
594 Buffer const & buffer)
596 external::Template const * const ptr =
597 external::getTemplatePtr(params);
600 return support::bformat((_("External template %1$s is not installed")),
601 from_utf8(params.templatename()));
603 docstring gui = _(ptr->guiName);
604 return from_utf8(external::doSubstitution(params, buffer,
605 to_utf8(gui), false));
608 void add_preview_and_start_loading(RenderMonitoredPreview &,
609 InsetExternal const &,
615 InsetExternalParams const & InsetExternal::params() const
621 void InsetExternal::setParams(InsetExternalParams const & p,
622 Buffer const & buffer)
626 // Subsequent calls to the InsetExternal::Params default constructor
628 defaultTemplateName = params_.templatename();
630 switch (getRenderType(params_)) {
632 RenderButton * button_ptr = renderer_->asButton();
634 renderer_.reset(new RenderButton);
635 button_ptr = renderer_->asButton();
638 button_ptr->update(getScreenLabel(params_, buffer), true);
641 } case RENDERGRAPHIC: {
642 RenderGraphic * graphic_ptr = renderer_->asGraphic();
644 renderer_.reset(new RenderGraphic(this));
645 graphic_ptr = renderer_->asGraphic();
648 graphic_ptr->update(get_grfx_params(params_));
652 } case RENDERPREVIEW: {
653 RenderMonitoredPreview * preview_ptr =
654 renderer_->asMonitoredPreview();
656 renderer_.reset(new RenderMonitoredPreview(this));
657 preview_ptr = renderer_->asMonitoredPreview();
658 preview_ptr->fileChanged(
659 boost::bind(&InsetExternal::fileChanged, this));
662 if (preview_ptr->monitoring())
663 preview_ptr->stopMonitoring();
664 add_preview_and_start_loading(*preview_ptr, *this, buffer);
672 void InsetExternal::fileChanged() const
674 Buffer const * const buffer_ptr = LyX::cref().updateInset(this);
678 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
681 Buffer const & buffer = *buffer_ptr;
682 ptr->removePreview(buffer);
683 add_preview_and_start_loading(*ptr, *this, buffer);
687 void InsetExternal::write(Buffer const & buffer, ostream & os) const
689 params_.write(buffer, os);
693 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
695 InsetExternalParams params;
696 if (params.read(buffer, lex))
697 setParams(params, buffer);
701 int InsetExternal::latex(Buffer const & buf, odocstream & os,
702 OutputParams const & runparams) const
706 os << "\\fbox{\\ttfamily{}"
707 << from_utf8(params_.filename.outputFilename(buf.filePath()))
712 // "nice" means that the buffer is exported to LaTeX format but not
713 // run through the LaTeX compiler.
714 // If we're running through the LaTeX compiler, we should write the
715 // generated files in the buffer's temporary directory.
716 bool const external_in_tmpdir = !runparams.nice;
717 bool const dryrun = runparams.dryrun || runparams.inComment;
719 // If the template has specified a PDFLaTeX output, then we try and
721 if (runparams.flavor == OutputParams::PDFLATEX) {
722 external::Template const * const et_ptr =
723 external::getTemplatePtr(params_);
726 external::Template const & et = *et_ptr;
728 external::Template::Formats::const_iterator cit =
729 et.formats.find("PDFLaTeX");
731 if (cit != et.formats.end()) {
732 return external::writeExternal(params_, "PDFLaTeX",
734 *(runparams.exportdata),
740 return external::writeExternal(params_, "LaTeX", buf, os,
741 *(runparams.exportdata),
747 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
748 OutputParams const & runparams) const
750 os << '\n'; // output external material on a new line
751 external::writeExternal(params_, "Ascii", buf, os,
752 *(runparams.exportdata), false,
753 runparams.dryrun || runparams.inComment);
754 return PLAINTEXT_NEWLINE;
758 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
759 OutputParams const & runparams) const
761 return external::writeExternal(params_, "DocBook", buf, os,
762 *(runparams.exportdata), false,
763 runparams.dryrun || runparams.inComment);
767 void InsetExternal::validate(LaTeXFeatures & features) const
772 external::Template const * const et_ptr =
773 external::getTemplatePtr(params_);
776 external::Template const & et = *et_ptr;
779 switch (features.runparams().flavor) {
780 case OutputParams::LATEX:
783 case OutputParams::PDFLATEX:
786 case OutputParams::XML:
790 external::Template::Formats::const_iterator cit =
791 et.formats.find(format);
792 if (cit == et.formats.end())
795 // FIXME: We don't need that always
796 features.require("lyxdot");
798 vector<string>::const_iterator it = cit->second.requirements.begin();
799 vector<string>::const_iterator end = cit->second.requirements.end();
800 for (; it != end; ++it)
801 features.require(*it);
803 external::TemplateManager & etm = external::TemplateManager::get();
805 it = cit->second.preambleNames.begin();
806 end = cit->second.preambleNames.end();
807 for (; it != end; ++it) {
808 string const preamble = etm.getPreambleDefByName(*it);
809 if (!preamble.empty())
810 features.addPreambleSnippet(preamble);
821 bool preview_wanted(InsetExternalParams const & params)
823 return params.display == external::PreviewDisplay &&
824 support::isFileReadable(params.filename);
828 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
831 // We don't need to set runparams.encoding since it is not used by
833 OutputParams runparams(0);
834 runparams.flavor = OutputParams::LATEX;
835 inset.latex(buffer, os, runparams);
840 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
841 InsetExternal const & inset,
842 Buffer const & buffer)
844 InsetExternalParams const & params = inset.params();
846 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
847 preview_wanted(params)) {
848 renderer.setAbsFile(params.filename);
849 docstring const snippet = latex_string(inset, buffer);
850 renderer.addPreview(snippet, buffer);
851 renderer.startLoading(buffer);
858 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
860 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
864 if (preview_wanted(params())) {
865 ptr->setAbsFile(params_.filename);
866 docstring const snippet = latex_string(*this, ploader.buffer());
867 ptr->addPreview(snippet, ploader);
874 string const InsetExternalMailer::name_("external");
876 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
881 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
883 return params2string(inset_.params(), buffer);
887 void InsetExternalMailer::string2params(string const & in,
888 Buffer const & buffer,
889 InsetExternalParams & params)
891 params = InsetExternalParams();
895 istringstream data(in);
901 if (!lex || name != name_)
902 return print_mailer_error("InsetExternalMailer", in, 1, name_);
904 // This is part of the inset proper that is usually swallowed
905 // by Text::readInset
908 if (!lex || id != "External")
909 return print_mailer_error("InsetBoxMailer", in, 2, "External");
911 params.read(buffer, lex);
916 InsetExternalMailer::params2string(InsetExternalParams const & params,
917 Buffer const & buffer)
920 data << name_ << ' ';
921 params.write(buffer, data);
922 data << "\\end_inset\n";