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 case LFUN_INSET_SETTINGS:
432 flag.setEnabled(true);
436 return Inset::getStatus(cur, cmd, flag);
441 bool InsetExternal::showInsetDialog(BufferView * bv) const
443 bv->showDialog("external", params2string(params(), bv->buffer()),
444 const_cast<InsetExternal *>(this));
449 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
451 renderer_->metrics(mi, dim);
455 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
457 renderer_->draw(pi, x, y);
463 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
465 graphics::Params gparams;
467 gparams.filename = eparams.filename;
468 gparams.scale = eparams.lyxscale;
469 if (eparams.clipdata.clip)
470 gparams.bb = eparams.clipdata.bbox;
471 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
472 gparams.display = eparams.display;
478 docstring screenLabel(InsetExternalParams const & params,
479 Buffer const & buffer)
481 external::Template const * const ptr =
482 external::getTemplatePtr(params);
485 return bformat((_("External template %1$s is not installed")),
486 from_utf8(params.templatename()));
488 docstring gui = _(ptr->guiName);
489 return from_utf8(external::doSubstitution(params, buffer,
490 to_utf8(gui), false));
496 static bool isPreviewWanted(InsetExternalParams const & params)
498 return params.display && params.filename.isReadableFile();
502 static docstring latexString(InsetExternal const & inset)
505 // We don't need to set runparams.encoding since it is not used by
507 OutputParams runparams(0);
508 runparams.flavor = OutputParams::LATEX;
509 inset.latex(os, runparams);
514 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
515 InsetExternal const & inset,
516 Buffer const & buffer)
518 InsetExternalParams const & params = inset.params();
520 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
521 isPreviewWanted(params)) {
522 renderer.setAbsFile(params.filename);
523 docstring const snippet = latexString(inset);
524 renderer.addPreview(snippet, buffer);
525 renderer.startLoading(buffer);
530 InsetExternalParams const & InsetExternal::params() const
536 void InsetExternal::updatePreview()
542 void InsetExternal::setParams(InsetExternalParams const & p)
546 // Subsequent calls to the InsetExternal::Params default constructor
548 defaultTemplateName = params_.templatename();
550 if (!external::getTemplatePtr(params_) || params_.filename.empty()
552 || !lyxrc.display_graphics
553 || params_.preview_mode == PREVIEW_OFF
554 || (params_.preview_mode == PREVIEW_INSTANT
555 && RenderPreview::status() == LyXRC::PREVIEW_OFF)) {
556 RenderButton * button_ptr = renderer_->asButton();
558 renderer_.reset(new RenderButton);
559 button_ptr = renderer_->asButton();
561 button_ptr->update(screenLabel(params_, buffer()), true);
565 switch (params_.preview_mode) {
567 // Already taken care of above.
568 LASSERT(false, return);
570 case PREVIEW_INSTANT: {
571 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
572 renderer_.reset(new RenderMonitoredPreview(this));
573 preview_ptr = renderer_->asMonitoredPreview();
574 preview_ptr->fileChanged(boost::bind(&InsetExternal::fileChanged, this));
575 if (preview_ptr->monitoring())
576 preview_ptr->stopMonitoring();
577 add_preview_and_start_loading(*preview_ptr, *this, buffer());
580 case PREVIEW_GRAPHICS: {
581 RenderGraphic * graphic_ptr = renderer_->asGraphic();
583 renderer_.reset(new RenderGraphic(this));
584 graphic_ptr = renderer_->asGraphic();
586 graphic_ptr->update(get_grfx_params(params_));
593 void InsetExternal::fileChanged() const
595 Buffer const * const buffer = updateFrontend();
599 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
602 ptr->removePreview(*buffer);
603 add_preview_and_start_loading(*ptr, *this, *buffer);
607 void InsetExternal::write(ostream & os) const
609 params_.write(buffer(), os);
613 void InsetExternal::read(Lexer & lex)
615 InsetExternalParams params;
616 if (params.read(buffer(), lex))
621 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
625 os << "\\fbox{\\ttfamily{}"
626 << from_utf8(params_.filename.outputFilename(buffer().filePath()))
631 // "nice" means that the buffer is exported to LaTeX format but not
632 // run through the LaTeX compiler.
633 // If we're running through the LaTeX compiler, we should write the
634 // generated files in the buffer's temporary directory.
635 bool const external_in_tmpdir = !runparams.nice;
636 bool const dryrun = runparams.dryrun || runparams.inComment;
638 // If the template has specified a PDFLaTeX output, then we try and
640 if (runparams.flavor == OutputParams::PDFLATEX) {
641 external::Template const * const et_ptr =
642 external::getTemplatePtr(params_);
645 external::Template const & et = *et_ptr;
647 external::Template::Formats::const_iterator cit =
648 et.formats.find("PDFLaTeX");
650 if (cit != et.formats.end()) {
651 return external::writeExternal(params_, "PDFLaTeX",
653 *(runparams.exportdata),
659 return external::writeExternal(params_, "LaTeX", buffer(), os,
660 *(runparams.exportdata),
666 int InsetExternal::plaintext(odocstream & os,
667 OutputParams const & runparams) const
669 os << '\n'; // output external material on a new line
670 external::writeExternal(params_, "Ascii", buffer(), os,
671 *(runparams.exportdata), false,
672 runparams.dryrun || runparams.inComment);
673 return PLAINTEXT_NEWLINE;
677 int InsetExternal::docbook(odocstream & os,
678 OutputParams const & runparams) const
680 return external::writeExternal(params_, "DocBook", buffer(), os,
681 *(runparams.exportdata), false,
682 runparams.dryrun || runparams.inComment);
686 void InsetExternal::validate(LaTeXFeatures & features) const
691 external::Template const * const et_ptr =
692 external::getTemplatePtr(params_);
695 external::Template const & et = *et_ptr;
698 switch (features.runparams().flavor) {
699 case OutputParams::LATEX:
702 case OutputParams::PDFLATEX:
703 case OutputParams::XETEX:
706 case OutputParams::XML:
710 external::Template::Formats::const_iterator cit =
711 et.formats.find(format);
713 if (cit == et.formats.end()) {
714 // If the template has not specified a PDFLaTeX output,
715 // we try the LaTeX format.
716 if (format == "PDFLaTeX") {
717 cit = et.formats.find("LaTeX");
718 if (cit == et.formats.end())
724 // FIXME: We don't need that always
725 features.require("lyxdot");
727 vector<string>::const_iterator it = cit->second.requirements.begin();
728 vector<string>::const_iterator end = cit->second.requirements.end();
729 for (; it != end; ++it)
730 features.require(*it);
732 external::TemplateManager & etm = external::TemplateManager::get();
734 it = cit->second.preambleNames.begin();
735 end = cit->second.preambleNames.end();
736 for (; it != end; ++it) {
737 string const preamble = etm.getPreambleDefByName(*it);
738 if (!preamble.empty())
739 features.addPreambleSnippet(preamble);
744 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
746 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
750 if (isPreviewWanted(params())) {
751 ptr->setAbsFile(params_.filename);
752 docstring const snippet = latexString(*this);
753 ptr->addPreview(snippet, ploader);
758 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
760 return from_ascii("context-external");
764 void InsetExternal::string2params(string const & in, Buffer const & buffer,
765 InsetExternalParams & params)
767 params = InsetExternalParams();
771 istringstream data(in);
777 if (!lex || name != "external") {
778 LYXERR0("InsetExternal::string2params(" << in << ")\n"
779 "Expected arg 1 to be \"external\"\n");
783 // This is part of the inset proper that is usually swallowed
784 // by Text::readInset
787 if (!lex || id != "External") {
788 LYXERR0("InsetExternal::string2params(" << in << ")\n"
789 "Expected arg 2 to be \"External\"\n");
793 params.read(buffer, lex);
797 string InsetExternal::params2string(InsetExternalParams const & params,
798 Buffer const & buffer)
801 data << "external" << ' ';
802 params.write(buffer, data);
803 data << "\\end_inset\n";