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 FileName const tempname = FileName::tempName("lyxext");
69 // FIXME: This is unsafe
70 tempname.removeFile();
71 // must have an extension for the converter code to work correctly.
72 tempname_ = 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 = 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 double const scl = convert<double>(resizedata.scale);
228 if (!float_equal(scl, 0.0, 0.05)) {
229 if (!float_equal(scl, 100.0, 0.05))
231 << resizedata.scale << '\n';
233 if (!resizedata.width.zero())
235 << resizedata.width.asString() << '\n';
236 if (!resizedata.height.zero())
238 << resizedata.height.asString() << '\n';
240 if (resizedata.keepAspectRatio)
241 os << "\tkeepAspectRatio\n";
246 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
266 keyword_item external_tags[] = {
267 { "\\end_inset", EX_END },
268 { "boundingBox", EX_BOUNDINGBOX },
270 { "display", EX_DISPLAY},
271 { "draft", EX_DRAFT},
272 { "extra", EX_EXTRA },
273 { "filename", EX_FILENAME},
274 { "height", EX_HEIGHT },
275 { "keepAspectRatio", EX_KEEPASPECTRATIO },
276 { "lyxscale", EX_LYXSCALE},
277 { "rotateAngle", EX_ROTATEANGLE },
278 { "rotateOrigin", EX_ROTATEORIGIN },
279 { "scale", EX_SCALE },
280 { "template", EX_TEMPLATE },
281 { "width", EX_WIDTH }
284 PushPopHelper pph(lex, external_tags, EX_END);
286 bool found_end = false;
287 bool read_error = false;
293 templatename_ = lex.getString();
298 string const name = lex.getString();
299 filename.set(name, buffer.filePath());
300 // maybe this file is embedded
301 EmbeddedFiles::EmbeddedFileList::const_iterator it = buffer.embeddedFiles().find(filename.toFilesystemEncoding());
302 if (it != buffer.embeddedFiles().end())
303 // using available file, embedded or external, depending on file availability and
305 filename = DocFileName(it->availableFile(&buffer));
311 string const name = lex.getString();
312 display = external::displayTranslator().find(name);
318 lyxscale = lex.getInteger();
327 clipdata.bbox.xl = lex.getInteger();
329 clipdata.bbox.yb = lex.getInteger();
331 clipdata.bbox.xr = lex.getInteger();
333 clipdata.bbox.yt = lex.getInteger();
337 clipdata.clip = true;
342 string const name = lex.getString();
344 extradata.set(name, lex.getString());
350 resizedata.height = Length(lex.getString());
353 case EX_KEEPASPECTRATIO:
354 resizedata.keepAspectRatio = true;
359 rotationdata.angle = lex.getString();
362 case EX_ROTATEORIGIN:
364 rotationdata.origin(lex.getString());
369 resizedata.scale = lex.getString();
374 resizedata.width = Length(lex.getString());
382 lex.printError("ExternalInset::read: Wrong tag: $$Token");
387 if (found_end || read_error)
392 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
394 // This is a trick to make sure that the data are self-consistent.
395 settemplate(templatename_);
397 if (lyxerr.debugging(Debug::EXTERNAL)) {
398 lyxerr << "InsetExternalParams::read:\n";
399 write(buffer, lyxerr);
406 InsetExternal::InsetExternal()
407 : renderer_(new RenderButton)
411 InsetExternal::InsetExternal(InsetExternal const & other)
413 boost::signals::trackable(),
414 params_(other.params_),
415 renderer_(other.renderer_->clone(this))
419 Inset * InsetExternal::clone() const
421 return new InsetExternal(*this);
425 InsetExternal::~InsetExternal()
427 InsetExternalMailer(*this).hideDialog();
431 void InsetExternal::statusChanged() const
437 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
439 switch (cmd.action) {
441 case LFUN_EXTERNAL_EDIT: {
442 Buffer const & buffer = cur.buffer();
443 InsetExternalParams p;
444 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
445 external::editExternal(p, buffer);
449 case LFUN_INSET_MODIFY: {
450 Buffer const & buffer = cur.buffer();
451 InsetExternalParams p;
452 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
453 setParams(p, buffer);
457 case LFUN_INSET_DIALOG_UPDATE:
458 InsetExternalMailer(*this).updateDialog(&cur.bv());
461 case LFUN_MOUSE_RELEASE:
462 if (!cur.selection())
463 InsetExternalMailer(*this).showDialog(&cur.bv());
467 Inset::doDispatch(cur, cmd);
472 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
473 FuncStatus & flag) const
475 switch (cmd.action) {
477 case LFUN_EXTERNAL_EDIT:
478 case LFUN_INSET_MODIFY:
479 case LFUN_INSET_DIALOG_UPDATE:
484 return Inset::getStatus(cur, cmd, flag);
489 void InsetExternal::registerEmbeddedFiles(Buffer const &,
490 EmbeddedFiles & files) const
492 files.registerFile(params_.filename.absFilename(), false, this);
496 void InsetExternal::edit(Cursor & cur, bool)
498 InsetExternalMailer(*this).showDialog(&cur.bv());
502 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
504 renderer_->metrics(mi, dim);
508 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
510 renderer_->draw(pi, x, y);
523 RenderType getRenderType(InsetExternalParams const & p)
525 if (!external::getTemplatePtr(p) ||
526 p.filename.empty() ||
527 p.display == external::NoDisplay)
530 if (p.display == external::PreviewDisplay) {
531 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
532 return RENDERPREVIEW;
536 if (p.display == external::DefaultDisplay &&
537 lyxrc.display_graphics == graphics::NoDisplay)
539 return RENDERGRAPHIC;
543 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
545 graphics::Params gparams;
547 gparams.filename = eparams.filename;
548 gparams.scale = eparams.lyxscale;
549 if (eparams.clipdata.clip)
550 gparams.bb = eparams.clipdata.bbox;
551 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
553 switch (eparams.display) {
554 case external::DefaultDisplay:
555 gparams.display = graphics::DefaultDisplay;
557 case external::MonochromeDisplay:
558 gparams.display = graphics::MonochromeDisplay;
560 case external::GrayscaleDisplay:
561 gparams.display = graphics::GrayscaleDisplay;
563 case external::ColorDisplay:
564 gparams.display = graphics::ColorDisplay;
566 case external::NoDisplay:
567 gparams.display = graphics::NoDisplay;
572 if (gparams.display == graphics::DefaultDisplay)
573 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
574 // Override the above if we're not using a gui
576 gparams.display = graphics::NoDisplay;
582 docstring const getScreenLabel(InsetExternalParams const & params,
583 Buffer const & buffer)
585 external::Template const * const ptr =
586 external::getTemplatePtr(params);
589 return bformat((_("External template %1$s is not installed")),
590 from_utf8(params.templatename()));
592 docstring gui = _(ptr->guiName);
593 return from_utf8(external::doSubstitution(params, buffer,
594 to_utf8(gui), false));
597 void add_preview_and_start_loading(RenderMonitoredPreview &,
598 InsetExternal const &,
604 InsetExternalParams const & InsetExternal::params() const
610 void InsetExternal::setParams(InsetExternalParams const & p,
611 Buffer const & buffer)
615 // Subsequent calls to the InsetExternal::Params default constructor
617 defaultTemplateName = params_.templatename();
619 switch (getRenderType(params_)) {
621 RenderButton * button_ptr = renderer_->asButton();
623 renderer_.reset(new RenderButton);
624 button_ptr = renderer_->asButton();
627 button_ptr->update(getScreenLabel(params_, buffer), true);
631 case RENDERGRAPHIC: {
632 RenderGraphic * graphic_ptr = renderer_->asGraphic();
634 renderer_.reset(new RenderGraphic(this));
635 graphic_ptr = renderer_->asGraphic();
638 graphic_ptr->update(get_grfx_params(params_));
643 case RENDERPREVIEW: {
644 RenderMonitoredPreview * preview_ptr =
645 renderer_->asMonitoredPreview();
647 renderer_.reset(new RenderMonitoredPreview(this));
648 preview_ptr = renderer_->asMonitoredPreview();
649 preview_ptr->fileChanged(
650 boost::bind(&InsetExternal::fileChanged, this));
653 if (preview_ptr->monitoring())
654 preview_ptr->stopMonitoring();
655 add_preview_and_start_loading(*preview_ptr, *this, buffer);
663 void InsetExternal::fileChanged() const
665 Buffer const * const buffer = updateFrontend();
669 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
672 ptr->removePreview(*buffer);
673 add_preview_and_start_loading(*ptr, *this, *buffer);
677 void InsetExternal::write(Buffer const & buffer, ostream & os) const
679 params_.write(buffer, os);
683 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
685 InsetExternalParams params;
686 if (params.read(buffer, lex))
687 setParams(params, buffer);
691 int InsetExternal::latex(Buffer const & buf, odocstream & os,
692 OutputParams const & runparams) const
696 os << "\\fbox{\\ttfamily{}"
697 << from_utf8(params_.filename.outputFilename(buf.filePath()))
702 // "nice" means that the buffer is exported to LaTeX format but not
703 // run through the LaTeX compiler.
704 // If we're running through the LaTeX compiler, we should write the
705 // generated files in the buffer's temporary directory.
706 bool const external_in_tmpdir = !runparams.nice;
707 bool const dryrun = runparams.dryrun || runparams.inComment;
709 // If the template has specified a PDFLaTeX output, then we try and
711 if (runparams.flavor == OutputParams::PDFLATEX) {
712 external::Template const * const et_ptr =
713 external::getTemplatePtr(params_);
716 external::Template const & et = *et_ptr;
718 external::Template::Formats::const_iterator cit =
719 et.formats.find("PDFLaTeX");
721 if (cit != et.formats.end()) {
722 return external::writeExternal(params_, "PDFLaTeX",
724 *(runparams.exportdata),
730 return external::writeExternal(params_, "LaTeX", buf, os,
731 *(runparams.exportdata),
737 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
738 OutputParams const & runparams) const
740 os << '\n'; // output external material on a new line
741 external::writeExternal(params_, "Ascii", buf, os,
742 *(runparams.exportdata), false,
743 runparams.dryrun || runparams.inComment);
744 return PLAINTEXT_NEWLINE;
748 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
749 OutputParams const & runparams) const
751 return external::writeExternal(params_, "DocBook", buf, os,
752 *(runparams.exportdata), false,
753 runparams.dryrun || runparams.inComment);
757 void InsetExternal::validate(LaTeXFeatures & features) const
762 external::Template const * const et_ptr =
763 external::getTemplatePtr(params_);
766 external::Template const & et = *et_ptr;
769 switch (features.runparams().flavor) {
770 case OutputParams::LATEX:
773 case OutputParams::PDFLATEX:
776 case OutputParams::XML:
780 external::Template::Formats::const_iterator cit =
781 et.formats.find(format);
782 if (cit == et.formats.end())
785 // FIXME: We don't need that always
786 features.require("lyxdot");
788 vector<string>::const_iterator it = cit->second.requirements.begin();
789 vector<string>::const_iterator end = cit->second.requirements.end();
790 for (; it != end; ++it)
791 features.require(*it);
793 external::TemplateManager & etm = external::TemplateManager::get();
795 it = cit->second.preambleNames.begin();
796 end = cit->second.preambleNames.end();
797 for (; it != end; ++it) {
798 string const preamble = etm.getPreambleDefByName(*it);
799 if (!preamble.empty())
800 features.addPreambleSnippet(preamble);
811 bool preview_wanted(InsetExternalParams const & params)
813 return params.display == external::PreviewDisplay &&
814 params.filename.isReadableFile();
818 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
821 // We don't need to set runparams.encoding since it is not used by
823 OutputParams runparams(0);
824 runparams.flavor = OutputParams::LATEX;
825 inset.latex(buffer, os, runparams);
830 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
831 InsetExternal const & inset,
832 Buffer const & buffer)
834 InsetExternalParams const & params = inset.params();
836 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
837 preview_wanted(params)) {
838 renderer.setAbsFile(params.filename);
839 docstring const snippet = latex_string(inset, buffer);
840 renderer.addPreview(snippet, buffer);
841 renderer.startLoading(buffer);
848 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
850 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
854 if (preview_wanted(params())) {
855 ptr->setAbsFile(params_.filename);
856 docstring const snippet = latex_string(*this, ploader.buffer());
857 ptr->addPreview(snippet, ploader);
864 string const InsetExternalMailer::name_("external");
866 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
871 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
873 return params2string(inset_.params(), buffer);
877 void InsetExternalMailer::string2params(string const & in,
878 Buffer const & buffer,
879 InsetExternalParams & params)
881 params = InsetExternalParams();
885 istringstream data(in);
891 if (!lex || name != name_)
892 return print_mailer_error("InsetExternalMailer", in, 1, name_);
894 // This is part of the inset proper that is usually swallowed
895 // by Text::readInset
898 if (!lex || id != "External")
899 return print_mailer_error("InsetBoxMailer", in, 2, "External");
901 params.read(buffer, lex);
906 InsetExternalMailer::params2string(InsetExternalParams const & params,
907 Buffer const & buffer)
910 data << name_ << ' ';
911 params.write(buffer, data);
912 data << "\\end_inset\n";