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"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
34 #include "graphics/PreviewLoader.h"
36 #include "support/filetools.h"
37 #include "support/lstrings.h"
38 #include "support/lyxlib.h"
39 #include "support/convert.h"
40 #include "support/Translator.h"
42 #include <boost/bind.hpp>
47 using namespace lyx::support;
51 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
53 unsigned int const defaultLyxScale = 100;
55 string defaultTemplateName;
68 support::FileName const tempname(support::tempName(support::FileName(), "lyxext"));
69 // FIXME: This is unsafe
70 tempname.removeFile();
71 // must have an extension for the converter code to work correctly.
72 tempname_ = support::FileName(tempname.absFilename() + ".tmp");
76 TempName::TempName(TempName const &)
78 tempname_ = TempName()();
84 tempname_.removeFile();
88 TempName & TempName::operator=(TempName const & other)
91 tempname_ = TempName()();
98 /// The translator between the Display enum and corresponding lyx string.
99 Translator<DisplayType, string> const initTranslator()
101 Translator<DisplayType, string> translator(DefaultDisplay, "default");
103 // Fill the display translator
104 translator.addPair(MonochromeDisplay, "monochrome");
105 translator.addPair(GrayscaleDisplay, "grayscale");
106 translator.addPair(ColorDisplay, "color");
107 translator.addPair(PreviewDisplay, "preview");
108 translator.addPair(NoDisplay, "none");
116 Translator<DisplayType, string> const & displayTranslator()
118 static Translator<DisplayType, string> const translator =
123 } // namespace external
126 InsetExternalParams::InsetExternalParams()
127 : display(defaultDisplayType),
128 lyxscale(defaultLyxScale),
131 if (defaultTemplateName.empty()) {
132 external::TemplateManager const & etm =
133 external::TemplateManager::get();
134 templatename_ = etm.getTemplates().begin()->first;
136 templatename_ = defaultTemplateName;
142 template <typename T>
143 void clearIfNotFound(T & data, external::TransformID value,
144 vector<external::TransformID> const & ids)
146 typedef vector<external::TransformID>::const_iterator
149 const_iterator it = ids.begin();
150 const_iterator end = ids.end();
151 it = std::find(it, end, value);
159 void InsetExternalParams::settemplate(string const & name)
161 templatename_ = name;
163 external::TemplateManager const & etm =
164 external::TemplateManager::get();
165 external::Template const * const et = etm.getTemplateByName(name);
167 // Be safe. Don't lose data.
170 // Ascertain which transforms the template supports.
171 // Empty all those that it doesn't.
172 vector<external::TransformID> const & ids = et->transformIds;
173 clearIfNotFound(clipdata, external::Clip, ids);
174 clearIfNotFound(extradata, external::Extra, ids);
175 clearIfNotFound(resizedata, external::Resize, ids);
176 clearIfNotFound(rotationdata, external::Rotate, ids);
180 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
183 << "\ttemplate " << templatename() << '\n';
185 if (!filename.empty()) {
186 // when we save, we still use the original filename
187 EmbeddedFiles::EmbeddedFileList::const_iterator it =
188 buffer.embeddedFiles().find(filename.toFilesystemEncoding());
189 if (it != buffer.embeddedFiles().end())
190 os << "\tfilename " << DocFileName(it->absFilename()).outputFilename(buffer.filePath()) << '\n';
192 os << "\tfilename " << filename.outputFilename(buffer.filePath()) << '\n';
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, Lexer & 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());
301 // maybe this file is embedded
302 EmbeddedFiles::EmbeddedFileList::const_iterator it = buffer.embeddedFiles().find(filename.toFilesystemEncoding());
303 if (it != buffer.embeddedFiles().end())
304 // using available file, embedded or external, depending on file availability and
306 filename = DocFileName(it->availableFile(&buffer));
312 string const name = lex.getString();
313 display = external::displayTranslator().find(name);
319 lyxscale = lex.getInteger();
328 clipdata.bbox.xl = lex.getInteger();
330 clipdata.bbox.yb = lex.getInteger();
332 clipdata.bbox.xr = lex.getInteger();
334 clipdata.bbox.yt = lex.getInteger();
338 clipdata.clip = true;
343 string const name = lex.getString();
345 extradata.set(name, lex.getString());
351 resizedata.height = Length(lex.getString());
354 case EX_KEEPASPECTRATIO:
355 resizedata.keepAspectRatio = true;
360 rotationdata.angle = lex.getString();
363 case EX_ROTATEORIGIN:
365 rotationdata.origin(lex.getString());
370 resizedata.scale = lex.getString();
375 resizedata.width = Length(lex.getString());
383 lex.printError("ExternalInset::read: Wrong tag: $$Token");
388 if (found_end || read_error)
393 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
395 // This is a trick to make sure that the data are self-consistent.
396 settemplate(templatename_);
398 if (lyxerr.debugging(Debug::EXTERNAL)) {
399 lyxerr << "InsetExternalParams::read:\n";
400 write(buffer, lyxerr);
407 InsetExternal::InsetExternal()
408 : renderer_(new RenderButton)
412 InsetExternal::InsetExternal(InsetExternal const & other)
414 boost::signals::trackable(),
415 params_(other.params_),
416 renderer_(other.renderer_->clone(this))
420 Inset * InsetExternal::clone() const
422 return new InsetExternal(*this);
426 InsetExternal::~InsetExternal()
428 InsetExternalMailer(*this).hideDialog();
432 void InsetExternal::statusChanged() const
438 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
440 switch (cmd.action) {
442 case LFUN_EXTERNAL_EDIT: {
443 Buffer const & buffer = cur.buffer();
444 InsetExternalParams p;
445 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
446 external::editExternal(p, buffer);
450 case LFUN_INSET_MODIFY: {
451 Buffer const & buffer = cur.buffer();
452 InsetExternalParams p;
453 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
454 setParams(p, buffer);
458 case LFUN_INSET_DIALOG_UPDATE:
459 InsetExternalMailer(*this).updateDialog(&cur.bv());
462 case LFUN_MOUSE_RELEASE:
463 if (!cur.selection())
464 InsetExternalMailer(*this).showDialog(&cur.bv());
468 Inset::doDispatch(cur, cmd);
473 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
474 FuncStatus & flag) const
476 switch (cmd.action) {
478 case LFUN_EXTERNAL_EDIT:
479 case LFUN_INSET_MODIFY:
480 case LFUN_INSET_DIALOG_UPDATE:
485 return Inset::getStatus(cur, cmd, flag);
490 void InsetExternal::registerEmbeddedFiles(Buffer const &,
491 EmbeddedFiles & files) const
493 files.registerFile(params_.filename.absFilename(), false, this);
497 void InsetExternal::edit(Cursor & cur, bool)
499 InsetExternalMailer(*this).showDialog(&cur.bv());
503 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
505 renderer_->metrics(mi, dim);
509 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
511 renderer_->draw(pi, x, y);
524 RenderType getRenderType(InsetExternalParams const & p)
526 if (!external::getTemplatePtr(p) ||
527 p.filename.empty() ||
528 p.display == external::NoDisplay)
531 if (p.display == external::PreviewDisplay) {
532 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
533 return RENDERPREVIEW;
537 if (p.display == external::DefaultDisplay &&
538 lyxrc.display_graphics == graphics::NoDisplay)
540 return RENDERGRAPHIC;
544 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
546 graphics::Params gparams;
548 gparams.filename = eparams.filename;
549 gparams.scale = eparams.lyxscale;
550 if (eparams.clipdata.clip)
551 gparams.bb = eparams.clipdata.bbox;
552 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
554 switch (eparams.display) {
555 case external::DefaultDisplay:
556 gparams.display = graphics::DefaultDisplay;
558 case external::MonochromeDisplay:
559 gparams.display = graphics::MonochromeDisplay;
561 case external::GrayscaleDisplay:
562 gparams.display = graphics::GrayscaleDisplay;
564 case external::ColorDisplay:
565 gparams.display = graphics::ColorDisplay;
567 case external::NoDisplay:
568 gparams.display = graphics::NoDisplay;
573 if (gparams.display == graphics::DefaultDisplay)
574 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
575 // Override the above if we're not using a gui
577 gparams.display = graphics::NoDisplay;
583 docstring const getScreenLabel(InsetExternalParams const & params,
584 Buffer const & buffer)
586 external::Template const * const ptr =
587 external::getTemplatePtr(params);
590 return support::bformat((_("External template %1$s is not installed")),
591 from_utf8(params.templatename()));
593 docstring gui = _(ptr->guiName);
594 return from_utf8(external::doSubstitution(params, buffer,
595 to_utf8(gui), false));
598 void add_preview_and_start_loading(RenderMonitoredPreview &,
599 InsetExternal const &,
605 InsetExternalParams const & InsetExternal::params() const
611 void InsetExternal::setParams(InsetExternalParams const & p,
612 Buffer const & buffer)
616 // Subsequent calls to the InsetExternal::Params default constructor
618 defaultTemplateName = params_.templatename();
620 switch (getRenderType(params_)) {
622 RenderButton * button_ptr = renderer_->asButton();
624 renderer_.reset(new RenderButton);
625 button_ptr = renderer_->asButton();
628 button_ptr->update(getScreenLabel(params_, buffer), true);
632 case RENDERGRAPHIC: {
633 RenderGraphic * graphic_ptr = renderer_->asGraphic();
635 renderer_.reset(new RenderGraphic(this));
636 graphic_ptr = renderer_->asGraphic();
639 graphic_ptr->update(get_grfx_params(params_));
644 case RENDERPREVIEW: {
645 RenderMonitoredPreview * preview_ptr =
646 renderer_->asMonitoredPreview();
648 renderer_.reset(new RenderMonitoredPreview(this));
649 preview_ptr = renderer_->asMonitoredPreview();
650 preview_ptr->fileChanged(
651 boost::bind(&InsetExternal::fileChanged, this));
654 if (preview_ptr->monitoring())
655 preview_ptr->stopMonitoring();
656 add_preview_and_start_loading(*preview_ptr, *this, buffer);
664 void InsetExternal::fileChanged() const
666 Buffer const * const buffer = updateFrontend();
670 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
673 ptr->removePreview(*buffer);
674 add_preview_and_start_loading(*ptr, *this, *buffer);
678 void InsetExternal::write(Buffer const & buffer, ostream & os) const
680 params_.write(buffer, os);
684 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
686 InsetExternalParams params;
687 if (params.read(buffer, lex))
688 setParams(params, buffer);
692 int InsetExternal::latex(Buffer const & buf, odocstream & os,
693 OutputParams const & runparams) const
697 os << "\\fbox{\\ttfamily{}"
698 << from_utf8(params_.filename.outputFilename(buf.filePath()))
703 // "nice" means that the buffer is exported to LaTeX format but not
704 // run through the LaTeX compiler.
705 // If we're running through the LaTeX compiler, we should write the
706 // generated files in the buffer's temporary directory.
707 bool const external_in_tmpdir = !runparams.nice;
708 bool const dryrun = runparams.dryrun || runparams.inComment;
710 // If the template has specified a PDFLaTeX output, then we try and
712 if (runparams.flavor == OutputParams::PDFLATEX) {
713 external::Template const * const et_ptr =
714 external::getTemplatePtr(params_);
717 external::Template const & et = *et_ptr;
719 external::Template::Formats::const_iterator cit =
720 et.formats.find("PDFLaTeX");
722 if (cit != et.formats.end()) {
723 return external::writeExternal(params_, "PDFLaTeX",
725 *(runparams.exportdata),
731 return external::writeExternal(params_, "LaTeX", buf, os,
732 *(runparams.exportdata),
738 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
739 OutputParams const & runparams) const
741 os << '\n'; // output external material on a new line
742 external::writeExternal(params_, "Ascii", buf, os,
743 *(runparams.exportdata), false,
744 runparams.dryrun || runparams.inComment);
745 return PLAINTEXT_NEWLINE;
749 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
750 OutputParams const & runparams) const
752 return external::writeExternal(params_, "DocBook", buf, os,
753 *(runparams.exportdata), false,
754 runparams.dryrun || runparams.inComment);
758 void InsetExternal::validate(LaTeXFeatures & features) const
763 external::Template const * const et_ptr =
764 external::getTemplatePtr(params_);
767 external::Template const & et = *et_ptr;
770 switch (features.runparams().flavor) {
771 case OutputParams::LATEX:
774 case OutputParams::PDFLATEX:
777 case OutputParams::XML:
781 external::Template::Formats::const_iterator cit =
782 et.formats.find(format);
783 if (cit == et.formats.end())
786 // FIXME: We don't need that always
787 features.require("lyxdot");
789 vector<string>::const_iterator it = cit->second.requirements.begin();
790 vector<string>::const_iterator end = cit->second.requirements.end();
791 for (; it != end; ++it)
792 features.require(*it);
794 external::TemplateManager & etm = external::TemplateManager::get();
796 it = cit->second.preambleNames.begin();
797 end = cit->second.preambleNames.end();
798 for (; it != end; ++it) {
799 string const preamble = etm.getPreambleDefByName(*it);
800 if (!preamble.empty())
801 features.addPreambleSnippet(preamble);
812 bool preview_wanted(InsetExternalParams const & params)
814 return params.display == external::PreviewDisplay &&
815 params.filename.isReadableFile();
819 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
822 // We don't need to set runparams.encoding since it is not used by
824 OutputParams runparams(0);
825 runparams.flavor = OutputParams::LATEX;
826 inset.latex(buffer, os, runparams);
831 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
832 InsetExternal const & inset,
833 Buffer const & buffer)
835 InsetExternalParams const & params = inset.params();
837 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
838 preview_wanted(params)) {
839 renderer.setAbsFile(params.filename);
840 docstring const snippet = latex_string(inset, buffer);
841 renderer.addPreview(snippet, buffer);
842 renderer.startLoading(buffer);
849 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
851 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
855 if (preview_wanted(params())) {
856 ptr->setAbsFile(params_.filename);
857 docstring const snippet = latex_string(*this, ploader.buffer());
858 ptr->addPreview(snippet, ploader);
865 string const InsetExternalMailer::name_("external");
867 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
872 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
874 return params2string(inset_.params(), buffer);
878 void InsetExternalMailer::string2params(string const & in,
879 Buffer const & buffer,
880 InsetExternalParams & params)
882 params = InsetExternalParams();
886 istringstream data(in);
892 if (!lex || name != name_)
893 return print_mailer_error("InsetExternalMailer", in, 1, name_);
895 // This is part of the inset proper that is usually swallowed
896 // by Text::readInset
899 if (!lex || id != "External")
900 return print_mailer_error("InsetBoxMailer", in, 2, "External");
902 params.read(buffer, lex);
907 InsetExternalMailer::params2string(InsetExternalParams const & params,
908 Buffer const & buffer)
911 data << name_ << ' ';
912 params.write(buffer, data);
913 data << "\\end_inset\n";