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 "DispatchResult.h"
24 #include "FuncStatus.h"
25 #include "FuncRequest.h"
26 #include "LaTeXFeatures.h"
28 #include "LyX.h" // use_gui
30 #include "MetricsInfo.h"
31 #include "OutputParams.h"
33 #include "graphics/PreviewLoader.h"
35 #include "support/debug.h"
36 #include "support/filetools.h"
37 #include "support/gettext.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 namespace lyx::support;
52 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
54 unsigned int const defaultLyxScale = 100;
56 string defaultTemplateName;
67 FileName const tempname = FileName::tempName("lyxext");
68 // FIXME: This is unsafe
69 tempname.removeFile();
70 // must have an extension for the converter code to work correctly.
71 tempname_ = FileName(tempname.absFilename() + ".tmp");
75 TempName::TempName(TempName const &)
77 tempname_ = TempName()();
83 tempname_.removeFile();
87 TempName & TempName::operator=(TempName const & other)
90 tempname_ = TempName()();
97 /// The translator between the Display enum and corresponding lyx string.
98 Translator<DisplayType, string> const initTranslator()
100 Translator<DisplayType, string> translator(DefaultDisplay, "default");
102 // Fill the display translator
103 translator.addPair(MonochromeDisplay, "monochrome");
104 translator.addPair(GrayscaleDisplay, "grayscale");
105 translator.addPair(ColorDisplay, "color");
106 translator.addPair(PreviewDisplay, "preview");
107 translator.addPair(NoDisplay, "none");
115 Translator<DisplayType, string> const & displayTranslator()
117 static Translator<DisplayType, string> const translator =
122 } // namespace external
125 InsetExternalParams::InsetExternalParams()
126 : display(defaultDisplayType),
127 lyxscale(defaultLyxScale),
130 if (defaultTemplateName.empty()) {
131 external::TemplateManager const & etm =
132 external::TemplateManager::get();
133 templatename_ = etm.getTemplates().begin()->first;
135 templatename_ = defaultTemplateName;
141 template <typename T>
142 void clearIfNotFound(T & data, external::TransformID value,
143 vector<external::TransformID> const & ids)
145 typedef vector<external::TransformID>::const_iterator
148 const_iterator it = ids.begin();
149 const_iterator end = ids.end();
150 it = find(it, end, value);
158 void InsetExternalParams::settemplate(string const & name)
160 templatename_ = name;
162 external::TemplateManager const & etm =
163 external::TemplateManager::get();
164 external::Template const * const et = etm.getTemplateByName(name);
166 // Be safe. Don't lose data.
169 // Ascertain which transforms the template supports.
170 // Empty all those that it doesn't.
171 vector<external::TransformID> const & ids = et->transformIds;
172 clearIfNotFound(clipdata, external::Clip, ids);
173 clearIfNotFound(extradata, external::Extra, ids);
174 clearIfNotFound(resizedata, external::Resize, ids);
175 clearIfNotFound(rotationdata, external::Rotate, ids);
179 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
182 << "\ttemplate " << templatename() << '\n';
184 if (!filename.empty()) {
185 os << "\tfilename " << filename.outputFilename(buf.filePath()) << '\n';
186 os << "\tembed " << (filename.embedded() ? filename.inzipName() : "\"\"") << '\n';
188 if (display != defaultDisplayType)
190 << external::displayTranslator().find(display)
193 if (lyxscale != defaultLyxScale)
194 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
199 if (!clipdata.bbox.empty())
200 os << "\tboundingBox " << clipdata.bbox << '\n';
204 external::ExtraData::const_iterator it = extradata.begin();
205 external::ExtraData::const_iterator end = extradata.end();
206 for (; it != end; ++it) {
207 if (!it->second.empty())
208 os << "\textra " << it->first << " \""
209 << it->second << "\"\n";
212 if (!rotationdata.no_rotation()) {
213 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
214 if (rotationdata.origin() != external::RotationData::DEFAULT)
215 os << "\trotateOrigin "
216 << rotationdata.originString() << '\n';
219 if (!resizedata.no_resize()) {
220 double const scl = convert<double>(resizedata.scale);
221 if (!float_equal(scl, 0.0, 0.05)) {
222 if (!float_equal(scl, 100.0, 0.05))
224 << resizedata.scale << '\n';
226 if (!resizedata.width.zero())
228 << resizedata.width.asString() << '\n';
229 if (!resizedata.height.zero())
231 << resizedata.height.asString() << '\n';
233 if (resizedata.keepAspectRatio)
234 os << "\tkeepAspectRatio\n";
239 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
260 keyword_item external_tags[] = {
261 { "\\end_inset", EX_END },
262 { "boundingBox", EX_BOUNDINGBOX },
264 { "display", EX_DISPLAY},
265 { "draft", EX_DRAFT},
266 { "embed", EX_EMBED},
267 { "extra", EX_EXTRA },
268 { "filename", EX_FILENAME},
269 { "height", EX_HEIGHT },
270 { "keepAspectRatio", EX_KEEPASPECTRATIO },
271 { "lyxscale", EX_LYXSCALE},
272 { "rotateAngle", EX_ROTATEANGLE },
273 { "rotateOrigin", EX_ROTATEORIGIN },
274 { "scale", EX_SCALE },
275 { "template", EX_TEMPLATE },
276 { "width", EX_WIDTH }
279 PushPopHelper pph(lex, external_tags, EX_END);
281 bool found_end = false;
282 bool read_error = false;
288 templatename_ = lex.getString();
293 string const name = lex.getString();
294 filename.set(name, buffer.filePath());
300 string const name = lex.getString();
301 filename.setInzipName(name);
302 filename.setEmbed(!name.empty());
308 string const name = lex.getString();
309 display = external::displayTranslator().find(name);
315 lyxscale = lex.getInteger();
324 clipdata.bbox.xl = lex.getInteger();
326 clipdata.bbox.yb = lex.getInteger();
328 clipdata.bbox.xr = lex.getInteger();
330 clipdata.bbox.yt = lex.getInteger();
334 clipdata.clip = true;
339 string const name = lex.getString();
341 extradata.set(name, lex.getString());
347 resizedata.height = Length(lex.getString());
350 case EX_KEEPASPECTRATIO:
351 resizedata.keepAspectRatio = true;
356 rotationdata.angle = lex.getString();
359 case EX_ROTATEORIGIN:
361 rotationdata.origin(lex.getString());
366 resizedata.scale = lex.getString();
371 resizedata.width = Length(lex.getString());
379 lex.printError("ExternalInset::read: 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(this))
416 InsetExternal::~InsetExternal()
418 InsetExternalMailer(*this).hideDialog();
422 void InsetExternal::setBuffer(Buffer & buffer)
425 params_.filename = params_.filename.copyTo(&buffer);
426 Inset::setBuffer(buffer);
430 void InsetExternal::statusChanged() const
436 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
438 switch (cmd.action) {
440 case LFUN_EXTERNAL_EDIT: {
441 InsetExternalParams p;
442 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
443 external::editExternal(p, buffer());
447 case LFUN_INSET_MODIFY: {
448 InsetExternalParams p;
449 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
454 case LFUN_INSET_DIALOG_UPDATE:
455 InsetExternalMailer(*this).updateDialog(&cur.bv());
458 case LFUN_MOUSE_RELEASE:
459 if (!cur.selection())
460 InsetExternalMailer(*this).showDialog(&cur.bv());
464 Inset::doDispatch(cur, cmd);
469 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
470 FuncStatus & flag) const
472 switch (cmd.action) {
474 case LFUN_EXTERNAL_EDIT:
475 case LFUN_INSET_MODIFY:
476 case LFUN_INSET_DIALOG_UPDATE:
481 return Inset::getStatus(cur, cmd, flag);
486 void InsetExternal::registerEmbeddedFiles(EmbeddedFileList & files) const
488 files.registerFile(params_.filename, this, buffer());
492 void InsetExternal::updateEmbeddedFile(EmbeddedFile const & file)
494 params_.filename = file;
498 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
500 InsetExternalMailer(*this).showDialog(&cur.bv());
504 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
506 renderer_->metrics(mi, dim);
510 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
512 renderer_->draw(pi, x, y);
525 RenderType getRenderType(InsetExternalParams const & p)
527 if (!external::getTemplatePtr(p) ||
528 p.filename.empty() ||
529 p.display == external::NoDisplay)
532 if (p.display == external::PreviewDisplay) {
533 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
534 return RENDERPREVIEW;
538 if (p.display == external::DefaultDisplay &&
539 lyxrc.display_graphics == graphics::NoDisplay)
541 return RENDERGRAPHIC;
545 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
547 graphics::Params gparams;
549 gparams.filename = eparams.filename.availableFile();
550 gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
551 gparams.scale = eparams.lyxscale;
552 if (eparams.clipdata.clip)
553 gparams.bb = eparams.clipdata.bbox;
554 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
556 switch (eparams.display) {
557 case external::DefaultDisplay:
558 gparams.display = graphics::DefaultDisplay;
560 case external::MonochromeDisplay:
561 gparams.display = graphics::MonochromeDisplay;
563 case external::GrayscaleDisplay:
564 gparams.display = graphics::GrayscaleDisplay;
566 case external::ColorDisplay:
567 gparams.display = graphics::ColorDisplay;
569 case external::NoDisplay:
570 gparams.display = graphics::NoDisplay;
575 if (gparams.display == graphics::DefaultDisplay)
576 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
577 // Override the above if we're not using a gui
579 gparams.display = graphics::NoDisplay;
585 docstring screenLabel(InsetExternalParams const & params,
586 Buffer const & buffer)
588 external::Template const * const ptr =
589 external::getTemplatePtr(params);
592 return bformat((_("External template %1$s is not installed")),
593 from_utf8(params.templatename()));
595 docstring gui = _(ptr->guiName);
596 return from_utf8(external::doSubstitution(params, buffer,
597 to_utf8(gui), false));
603 static bool isPreviewWanted(InsetExternalParams const & params)
605 return params.display == external::PreviewDisplay &&
606 params.filename.isReadableFile();
610 static docstring latexString(InsetExternal const & inset)
613 // We don't need to set runparams.encoding since it is not used by
615 OutputParams runparams(0);
616 runparams.flavor = OutputParams::LATEX;
617 inset.latex(os, runparams);
622 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
623 InsetExternal const & inset,
624 Buffer const & buffer)
626 InsetExternalParams const & params = inset.params();
628 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
629 isPreviewWanted(params)) {
630 renderer.setAbsFile(params.filename);
631 docstring const snippet = latexString(inset);
632 renderer.addPreview(snippet, buffer);
633 renderer.startLoading(buffer);
638 InsetExternalParams const & InsetExternal::params() const
644 void InsetExternal::setParams(InsetExternalParams const & p)
648 // Subsequent calls to the InsetExternal::Params default constructor
650 defaultTemplateName = params_.templatename();
652 switch (getRenderType(params_)) {
654 RenderButton * button_ptr = renderer_->asButton();
656 renderer_.reset(new RenderButton);
657 button_ptr = renderer_->asButton();
660 button_ptr->update(screenLabel(params_, buffer()), true);
664 case RENDERGRAPHIC: {
665 RenderGraphic * graphic_ptr = renderer_->asGraphic();
667 renderer_.reset(new RenderGraphic(this));
668 graphic_ptr = renderer_->asGraphic();
671 graphic_ptr->update(get_grfx_params(params_));
676 case RENDERPREVIEW: {
677 RenderMonitoredPreview * preview_ptr =
678 renderer_->asMonitoredPreview();
680 renderer_.reset(new RenderMonitoredPreview(this));
681 preview_ptr = renderer_->asMonitoredPreview();
682 preview_ptr->fileChanged(
683 boost::bind(&InsetExternal::fileChanged, this));
686 if (preview_ptr->monitoring())
687 preview_ptr->stopMonitoring();
688 add_preview_and_start_loading(*preview_ptr, *this, buffer());
696 void InsetExternal::fileChanged() const
698 Buffer const * const buffer = updateFrontend();
702 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
705 ptr->removePreview(*buffer);
706 add_preview_and_start_loading(*ptr, *this, *buffer);
710 void InsetExternal::write(ostream & os) const
712 params_.write(buffer(), os);
716 void InsetExternal::read(Lexer & lex)
718 InsetExternalParams params;
719 if (params.read(buffer(), lex)) {
720 // exception handling is not needed as long as embedded files are in place.
721 params.filename.enable(buffer().embedded(), &buffer(), false);
727 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
731 os << "\\fbox{\\ttfamily{}"
732 << from_utf8(params_.filename.outputFilename(buffer().filePath()))
737 // "nice" means that the buffer is exported to LaTeX format but not
738 // run through the LaTeX compiler.
739 // If we're running through the LaTeX compiler, we should write the
740 // generated files in the buffer's temporary directory.
741 bool const external_in_tmpdir = !runparams.nice;
742 bool const dryrun = runparams.dryrun || runparams.inComment;
744 // If the template has specified a PDFLaTeX output, then we try and
746 if (runparams.flavor == OutputParams::PDFLATEX) {
747 external::Template const * const et_ptr =
748 external::getTemplatePtr(params_);
751 external::Template const & et = *et_ptr;
753 external::Template::Formats::const_iterator cit =
754 et.formats.find("PDFLaTeX");
756 if (cit != et.formats.end()) {
757 return external::writeExternal(params_, "PDFLaTeX",
759 *(runparams.exportdata),
765 return external::writeExternal(params_, "LaTeX", buffer(), os,
766 *(runparams.exportdata),
772 int InsetExternal::plaintext(odocstream & os,
773 OutputParams const & runparams) const
775 os << '\n'; // output external material on a new line
776 external::writeExternal(params_, "Ascii", buffer(), os,
777 *(runparams.exportdata), false,
778 runparams.dryrun || runparams.inComment);
779 return PLAINTEXT_NEWLINE;
783 int InsetExternal::docbook(odocstream & os,
784 OutputParams const & runparams) const
786 return external::writeExternal(params_, "DocBook", buffer(), os,
787 *(runparams.exportdata), false,
788 runparams.dryrun || runparams.inComment);
792 void InsetExternal::validate(LaTeXFeatures & features) const
797 external::Template const * const et_ptr =
798 external::getTemplatePtr(params_);
801 external::Template const & et = *et_ptr;
804 switch (features.runparams().flavor) {
805 case OutputParams::LATEX:
808 case OutputParams::PDFLATEX:
811 case OutputParams::XML:
815 external::Template::Formats::const_iterator cit =
816 et.formats.find(format);
817 if (cit == et.formats.end())
820 // FIXME: We don't need that always
821 features.require("lyxdot");
823 vector<string>::const_iterator it = cit->second.requirements.begin();
824 vector<string>::const_iterator end = cit->second.requirements.end();
825 for (; it != end; ++it)
826 features.require(*it);
828 external::TemplateManager & etm = external::TemplateManager::get();
830 it = cit->second.preambleNames.begin();
831 end = cit->second.preambleNames.end();
832 for (; it != end; ++it) {
833 string const preamble = etm.getPreambleDefByName(*it);
834 if (!preamble.empty())
835 features.addPreambleSnippet(preamble);
844 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
846 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
850 if (isPreviewWanted(params())) {
851 ptr->setAbsFile(params_.filename);
852 docstring const snippet = latexString(*this);
853 ptr->addPreview(snippet, ploader);
860 string const InsetExternalMailer::name_("external");
862 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
867 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
869 return params2string(inset_.params(), buffer);
873 void InsetExternalMailer::string2params(string const & in,
874 Buffer const & buffer,
875 InsetExternalParams & params)
877 params = InsetExternalParams();
881 istringstream data(in);
887 if (!lex || name != name_)
888 return print_mailer_error("InsetExternalMailer", in, 1, name_);
890 // This is part of the inset proper that is usually swallowed
891 // by Text::readInset
894 if (!lex || id != "External")
895 return print_mailer_error("InsetBoxMailer", in, 2, "External");
897 params.read(buffer, lex);
902 InsetExternalMailer::params2string(InsetExternalParams const & params,
903 Buffer const & buffer)
906 data << name_ << ' ';
907 params.write(buffer, data);
908 data << "\\end_inset\n";