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/RenderButton.h"
16 #include "insets/RenderGraphic.h"
17 #include "insets/RenderPreview.h"
20 #include "BufferView.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 "frontends/alert.h"
34 #include "frontends/Application.h"
36 #include "graphics/PreviewLoader.h"
38 #include "support/convert.h"
39 #include "support/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/filetools.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/lyxlib.h"
45 #include "support/Translator.h"
47 #include <boost/bind.hpp>
52 using namespace lyx::support;
56 unsigned int const defaultLyxScale = 100;
58 string defaultTemplateName;
65 namespace Alert = frontend::Alert;
71 FileName const tempname = FileName::tempName("lyxext");
72 // must have an extension for the converter code to work correctly.
73 tempname_ = FileName(tempname.absFilename() + ".tmp");
77 TempName::TempName(TempName const &)
79 tempname_ = TempName()();
85 tempname_.removeFile();
89 TempName & TempName::operator=(TempName const & other)
92 tempname_ = TempName()();
96 } // namespace external
99 InsetExternalParams::InsetExternalParams()
101 lyxscale(defaultLyxScale),
104 if (defaultTemplateName.empty()) {
105 external::TemplateManager const & etm =
106 external::TemplateManager::get();
107 templatename_ = etm.getTemplates().begin()->first;
109 templatename_ = defaultTemplateName;
115 template <typename T>
116 void clearIfNotFound(T & data, external::TransformID value,
117 vector<external::TransformID> const & ids)
119 typedef vector<external::TransformID>::const_iterator
122 const_iterator it = ids.begin();
123 const_iterator end = ids.end();
124 it = find(it, end, value);
132 void InsetExternalParams::settemplate(string const & name)
134 templatename_ = name;
136 external::TemplateManager const & etm =
137 external::TemplateManager::get();
138 external::Template const * const et = etm.getTemplateByName(name);
140 // Be safe. Don't lose data.
143 // Ascertain which transforms the template supports.
144 // Empty all those that it doesn't.
145 vector<external::TransformID> const & ids = et->transformIds;
146 clearIfNotFound(clipdata, external::Clip, ids);
147 clearIfNotFound(extradata, external::Extra, ids);
148 clearIfNotFound(resizedata, external::Resize, ids);
149 clearIfNotFound(rotationdata, external::Rotate, ids);
152 preview_mode = et->preview_mode;
156 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
159 << "\ttemplate " << templatename() << '\n';
161 if (!filename.empty())
162 os << "\tfilename " << filename.outputFilename(buf.filePath()) << '\n';
165 os << "\tdisplay false\n";
167 if (lyxscale != defaultLyxScale)
168 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
173 if (!clipdata.bbox.empty())
174 os << "\tboundingBox " << clipdata.bbox << '\n';
178 external::ExtraData::const_iterator it = extradata.begin();
179 external::ExtraData::const_iterator end = extradata.end();
180 for (; it != end; ++it) {
181 if (!it->second.empty())
182 os << "\textra " << it->first << " \""
183 << it->second << "\"\n";
186 if (!rotationdata.no_rotation()) {
187 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
188 if (rotationdata.origin() != external::RotationData::DEFAULT)
189 os << "\trotateOrigin "
190 << rotationdata.originString() << '\n';
193 if (!resizedata.no_resize()) {
194 double const scl = convert<double>(resizedata.scale);
195 if (!float_equal(scl, 0.0, 0.05)) {
196 if (!float_equal(scl, 100.0, 0.05))
198 << resizedata.scale << '\n';
200 if (!resizedata.width.zero())
202 << resizedata.width.asString() << '\n';
203 if (!resizedata.height.zero())
205 << resizedata.height.asString() << '\n';
207 if (resizedata.keepAspectRatio)
208 os << "\tkeepAspectRatio\n";
213 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
233 LexerKeyword external_tags[] = {
234 { "\\end_inset", EX_END },
235 { "boundingBox", EX_BOUNDINGBOX },
237 { "display", EX_DISPLAY},
238 { "draft", EX_DRAFT},
239 { "extra", EX_EXTRA },
240 { "filename", EX_FILENAME},
241 { "height", EX_HEIGHT },
242 { "keepAspectRatio", EX_KEEPASPECTRATIO },
243 { "lyxscale", EX_LYXSCALE},
244 { "rotateAngle", EX_ROTATEANGLE },
245 { "rotateOrigin", EX_ROTATEORIGIN },
246 { "scale", EX_SCALE },
247 { "template", EX_TEMPLATE },
248 { "width", EX_WIDTH }
251 PushPopHelper pph(lex, external_tags);
253 bool found_end = false;
254 bool read_error = false;
260 templatename_ = lex.getString();
265 string const name = lex.getString();
266 filename.set(name, buffer.filePath());
272 display = lex.getString() != "false";
278 lyxscale = lex.getInteger();
287 clipdata.bbox.xl = lex.getInteger();
289 clipdata.bbox.yb = lex.getInteger();
291 clipdata.bbox.xr = lex.getInteger();
293 clipdata.bbox.yt = lex.getInteger();
297 clipdata.clip = true;
302 string const name = lex.getString();
304 extradata.set(name, lex.getString());
310 resizedata.height = Length(lex.getString());
313 case EX_KEEPASPECTRATIO:
314 resizedata.keepAspectRatio = true;
319 rotationdata.angle = lex.getString();
322 case EX_ROTATEORIGIN:
324 rotationdata.origin(lex.getString());
329 resizedata.scale = lex.getString();
334 resizedata.width = Length(lex.getString());
342 lex.printError("ExternalInset::read: Wrong tag: $$Token");
347 if (found_end || read_error)
352 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
354 // This is a trick to make sure that the data are self-consistent.
355 settemplate(templatename_);
357 if (lyxerr.debugging(Debug::EXTERNAL)) {
358 lyxerr << "InsetExternalParams::read:\n";
359 write(buffer, lyxerr);
366 InsetExternal::InsetExternal(Buffer & buf)
367 : renderer_(new RenderButton)
369 Inset::setBuffer(buf);
373 InsetExternal::InsetExternal(InsetExternal const & other)
375 boost::signals::trackable(),
376 params_(other.params_),
377 renderer_(other.renderer_->clone(this))
381 InsetExternal::~InsetExternal()
383 hideDialogs("external", this);
387 void InsetExternal::statusChanged() const
393 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
395 switch (cmd.action) {
397 case LFUN_INSET_EDIT: {
398 InsetExternalParams p = params();
399 if (!cmd.argument().empty())
400 string2params(to_utf8(cmd.argument()), buffer(), p);
401 external::editExternal(p, buffer());
405 case LFUN_INSET_MODIFY: {
406 InsetExternalParams p;
407 string2params(to_utf8(cmd.argument()), buffer(), p);
412 case LFUN_INSET_DIALOG_UPDATE:
413 cur.bv().updateDialog("external",
414 params2string(params(), cur.bv().buffer()));
418 Inset::doDispatch(cur, cmd);
423 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
424 FuncStatus & flag) const
426 switch (cmd.action) {
428 case LFUN_INSET_EDIT:
429 case LFUN_INSET_MODIFY:
430 case LFUN_INSET_DIALOG_UPDATE:
431 flag.setEnabled(true);
435 return Inset::getStatus(cur, cmd, flag);
440 bool InsetExternal::showInsetDialog(BufferView * bv) const
442 bv->showDialog("external", params2string(params(), bv->buffer()),
443 const_cast<InsetExternal *>(this));
448 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
450 renderer_->metrics(mi, dim);
454 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
456 renderer_->draw(pi, x, y);
462 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
464 graphics::Params gparams;
466 gparams.filename = eparams.filename;
467 gparams.scale = eparams.lyxscale;
468 if (eparams.clipdata.clip)
469 gparams.bb = eparams.clipdata.bbox;
470 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
471 gparams.display = eparams.display;
477 docstring screenLabel(InsetExternalParams const & params,
478 Buffer const & buffer)
480 external::Template const * const ptr =
481 external::getTemplatePtr(params);
484 return bformat((_("External template %1$s is not installed")),
485 from_utf8(params.templatename()));
487 docstring gui = _(ptr->guiName);
488 return from_utf8(external::doSubstitution(params, buffer,
489 to_utf8(gui), false));
495 static bool isPreviewWanted(InsetExternalParams const & params)
497 return params.display && params.filename.isReadableFile();
501 static docstring latexString(InsetExternal const & inset)
504 // We don't need to set runparams.encoding since it is not used by
506 OutputParams runparams(0);
507 runparams.flavor = OutputParams::LATEX;
508 inset.latex(os, runparams);
513 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
514 InsetExternal const & inset,
515 Buffer const & buffer)
517 InsetExternalParams const & params = inset.params();
519 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
520 isPreviewWanted(params)) {
521 renderer.setAbsFile(params.filename);
522 docstring const snippet = latexString(inset);
523 renderer.addPreview(snippet, buffer);
524 renderer.startLoading(buffer);
529 InsetExternalParams const & InsetExternal::params() const
535 void InsetExternal::updatePreview()
541 void InsetExternal::setParams(InsetExternalParams const & p)
545 // Subsequent calls to the InsetExternal::Params default constructor
547 defaultTemplateName = params_.templatename();
549 if (!external::getTemplatePtr(params_) || params_.filename.empty()
551 || !lyxrc.display_graphics
552 || params_.preview_mode == PREVIEW_OFF
553 || (params_.preview_mode == PREVIEW_INSTANT
554 && RenderPreview::status() == LyXRC::PREVIEW_OFF)) {
555 RenderButton * button_ptr = renderer_->asButton();
557 renderer_.reset(new RenderButton);
558 button_ptr = renderer_->asButton();
560 button_ptr->update(screenLabel(params_, buffer()), true);
564 switch (params_.preview_mode) {
566 // Already taken care of above.
567 LASSERT(false, return);
569 case PREVIEW_INSTANT: {
570 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
571 renderer_.reset(new RenderMonitoredPreview(this));
572 preview_ptr = renderer_->asMonitoredPreview();
573 preview_ptr->fileChanged(boost::bind(&InsetExternal::fileChanged, this));
574 if (preview_ptr->monitoring())
575 preview_ptr->stopMonitoring();
576 add_preview_and_start_loading(*preview_ptr, *this, buffer());
579 case PREVIEW_GRAPHICS: {
580 RenderGraphic * graphic_ptr = renderer_->asGraphic();
582 renderer_.reset(new RenderGraphic(this));
583 graphic_ptr = renderer_->asGraphic();
585 graphic_ptr->update(get_grfx_params(params_));
592 void InsetExternal::fileChanged() const
594 Buffer const * const buffer = updateFrontend();
598 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
601 ptr->removePreview(*buffer);
602 add_preview_and_start_loading(*ptr, *this, *buffer);
606 void InsetExternal::write(ostream & os) const
608 params_.write(buffer(), os);
612 void InsetExternal::read(Lexer & lex)
614 InsetExternalParams params;
615 if (params.read(buffer(), lex))
620 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
624 os << "\\fbox{\\ttfamily{}"
625 << from_utf8(params_.filename.outputFilename(buffer().filePath()))
630 // "nice" means that the buffer is exported to LaTeX format but not
631 // run through the LaTeX compiler.
632 // If we're running through the LaTeX compiler, we should write the
633 // generated files in the buffer's temporary directory.
634 bool const external_in_tmpdir = !runparams.nice;
635 bool const dryrun = runparams.dryrun || runparams.inComment;
637 // If the template has specified a PDFLaTeX output, then we try and
639 if (runparams.flavor == OutputParams::PDFLATEX) {
640 external::Template const * const et_ptr =
641 external::getTemplatePtr(params_);
644 external::Template const & et = *et_ptr;
646 external::Template::Formats::const_iterator cit =
647 et.formats.find("PDFLaTeX");
649 if (cit != et.formats.end()) {
650 return external::writeExternal(params_, "PDFLaTeX",
652 *(runparams.exportdata),
658 return external::writeExternal(params_, "LaTeX", buffer(), os,
659 *(runparams.exportdata),
665 int InsetExternal::plaintext(odocstream & os,
666 OutputParams const & runparams) const
668 os << '\n'; // output external material on a new line
669 external::writeExternal(params_, "Ascii", buffer(), os,
670 *(runparams.exportdata), false,
671 runparams.dryrun || runparams.inComment);
672 return PLAINTEXT_NEWLINE;
676 int InsetExternal::docbook(odocstream & os,
677 OutputParams const & runparams) const
679 return external::writeExternal(params_, "DocBook", buffer(), os,
680 *(runparams.exportdata), false,
681 runparams.dryrun || runparams.inComment);
685 docstring InsetExternal::xhtml(odocstream & os,
686 OutputParams const & rp) const {
687 // external::writeExternal(params_, "XHTML", buffer(), os,
688 // *(runparams.exportdata), false,
689 // runparams.dryrun || runparams.inComment);
694 void InsetExternal::validate(LaTeXFeatures & features) const
699 external::Template const * const et_ptr =
700 external::getTemplatePtr(params_);
703 external::Template const & et = *et_ptr;
706 switch (features.runparams().flavor) {
707 case OutputParams::LATEX:
710 case OutputParams::PDFLATEX:
711 case OutputParams::XETEX:
714 case OutputParams::XML:
718 external::Template::Formats::const_iterator cit =
719 et.formats.find(format);
721 if (cit == et.formats.end()) {
722 // If the template has not specified a PDFLaTeX output,
723 // we try the LaTeX format.
724 if (format == "PDFLaTeX") {
725 cit = et.formats.find("LaTeX");
726 if (cit == et.formats.end())
732 // FIXME: We don't need that always
733 features.require("lyxdot");
735 vector<string>::const_iterator it = cit->second.requirements.begin();
736 vector<string>::const_iterator end = cit->second.requirements.end();
737 for (; it != end; ++it)
738 features.require(*it);
740 external::TemplateManager & etm = external::TemplateManager::get();
742 it = cit->second.preambleNames.begin();
743 end = cit->second.preambleNames.end();
744 for (; it != end; ++it) {
745 string const preamble = etm.getPreambleDefByName(*it);
746 if (!preamble.empty())
747 features.addPreambleSnippet(preamble);
752 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
754 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
758 if (isPreviewWanted(params())) {
759 ptr->setAbsFile(params_.filename);
760 docstring const snippet = latexString(*this);
761 ptr->addPreview(snippet, ploader);
766 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
768 return from_ascii("context-external");
772 void InsetExternal::string2params(string const & in, Buffer const & buffer,
773 InsetExternalParams & params)
775 params = InsetExternalParams();
779 istringstream data(in);
785 if (!lex || name != "external") {
786 LYXERR0("InsetExternal::string2params(" << in << ")\n"
787 "Expected arg 1 to be \"external\"\n");
791 // This is part of the inset proper that is usually swallowed
792 // by Text::readInset
795 if (!lex || id != "External") {
796 LYXERR0("InsetExternal::string2params(" << in << ")\n"
797 "Expected arg 2 to be \"External\"\n");
801 params.read(buffer, lex);
805 string InsetExternal::params2string(InsetExternalParams const & params,
806 Buffer const & buffer)
809 data << "external" << ' ';
810 params.write(buffer, data);
811 data << "\\end_inset\n";