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"
32 #include "output_latex.h"
34 #include "frontends/alert.h"
35 #include "frontends/Application.h"
37 #include "graphics/PreviewLoader.h"
39 #include "support/bind.h"
40 #include "support/convert.h"
41 #include "support/debug.h"
42 #include "support/ExceptionMessage.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lassert.h"
46 #include "support/lstrings.h"
47 #include "support/lyxlib.h"
48 #include "support/TempFile.h"
54 using namespace lyx::support;
58 unsigned int const defaultLyxScale = 100;
60 string defaultTemplateName;
67 namespace Alert = frontend::Alert;
71 TempName::TempName() : tempfile_(new support::TempFile("lyxextXXXXXX.tmp"))
73 // must have an extension for the converter code to work correctly.
77 TempName::TempName(TempName const & that) : tempfile_(0)
89 TempName & TempName::operator=(TempName const & other)
93 tempfile_ = new support::TempFile("lyxextXXXXXX.tmp");
99 support::FileName TempName::operator()() const
101 return tempfile_->name();
104 } // namespace external
107 InsetExternalParams::InsetExternalParams()
109 lyxscale(defaultLyxScale),
112 if (defaultTemplateName.empty()) {
113 external::TemplateManager const & etm =
114 external::TemplateManager::get();
115 if (!etm.getTemplates().empty())
116 templatename_ = etm.getTemplates().begin()->first;
118 templatename_ = defaultTemplateName;
124 template <typename T>
125 void clearIfNotFound(T & data, external::TransformID value,
126 vector<external::TransformID> const & ids)
128 typedef vector<external::TransformID>::const_iterator
131 const_iterator it = ids.begin();
132 const_iterator end = ids.end();
133 it = find(it, end, value);
141 void InsetExternalParams::settemplate(string const & name)
143 templatename_ = name;
145 external::TemplateManager const & etm =
146 external::TemplateManager::get();
147 external::Template const * const et = etm.getTemplateByName(name);
149 // Be safe. Don't lose data.
152 // Ascertain which transforms the template supports.
153 // Empty all those that it doesn't.
154 vector<external::TransformID> const & ids = et->transformIds;
155 clearIfNotFound(clipdata, external::Clip, ids);
156 clearIfNotFound(extradata, external::Extra, ids);
157 clearIfNotFound(resizedata, external::Resize, ids);
158 clearIfNotFound(rotationdata, external::Rotate, ids);
161 preview_mode = et->preview_mode;
165 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
168 << "\ttemplate " << templatename() << '\n';
170 if (!filename.empty())
171 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
174 os << "\tdisplay false\n";
176 if (lyxscale != defaultLyxScale)
177 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
182 if (!clipdata.bbox.empty())
183 os << "\tboundingBox " << clipdata.bbox << '\n';
187 external::ExtraData::const_iterator it = extradata.begin();
188 external::ExtraData::const_iterator end = extradata.end();
189 for (; it != end; ++it) {
190 if (!it->second.empty())
191 os << "\textra " << it->first << " \""
192 << it->second << "\"\n";
195 if (!rotationdata.no_rotation()) {
196 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
197 if (rotationdata.origin() != external::RotationData::DEFAULT)
198 os << "\trotateOrigin "
199 << rotationdata.originString() << '\n';
202 if (!resizedata.no_resize()) {
203 double const scl = convert<double>(resizedata.scale);
204 if (!float_equal(scl, 0.0, 0.05)) {
205 if (!float_equal(scl, 100.0, 0.05))
207 << resizedata.scale << '\n';
209 if (!resizedata.width.zero())
211 << resizedata.width.asString() << '\n';
212 if (!resizedata.height.zero())
214 << resizedata.height.asString() << '\n';
216 if (resizedata.keepAspectRatio)
217 os << "\tkeepAspectRatio\n";
222 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
242 LexerKeyword external_tags[] = {
243 { "\\end_inset", EX_END },
244 { "boundingBox", EX_BOUNDINGBOX },
246 { "display", EX_DISPLAY},
247 { "draft", EX_DRAFT},
248 { "extra", EX_EXTRA },
249 { "filename", EX_FILENAME},
250 { "height", EX_HEIGHT },
251 { "keepAspectRatio", EX_KEEPASPECTRATIO },
252 { "lyxscale", EX_LYXSCALE},
253 { "rotateAngle", EX_ROTATEANGLE },
254 { "rotateOrigin", EX_ROTATEORIGIN },
255 { "scale", EX_SCALE },
256 { "template", EX_TEMPLATE },
257 { "width", EX_WIDTH }
260 PushPopHelper pph(lex, external_tags);
262 bool found_end = false;
263 bool read_error = false;
269 templatename_ = lex.getString();
274 string const name = lex.getString();
275 filename.set(name, buffer.originFilePath());
281 display = lex.getString() != "false";
287 lyxscale = lex.getInteger();
296 clipdata.bbox.xl = Length(lex.getString());
298 clipdata.bbox.yb = Length(lex.getString());
300 clipdata.bbox.xr = Length(lex.getString());
302 clipdata.bbox.yt = Length(lex.getString());
306 clipdata.clip = true;
311 string const name = lex.getString();
313 extradata.set(name, lex.getString());
319 resizedata.height = Length(lex.getString());
322 case EX_KEEPASPECTRATIO:
323 resizedata.keepAspectRatio = true;
328 rotationdata.angle = lex.getString();
331 case EX_ROTATEORIGIN:
333 rotationdata.origin(lex.getString());
338 resizedata.scale = lex.getString();
343 resizedata.width = Length(lex.getString());
351 lex.printError("ExternalInset::read: Wrong tag: $$Token");
356 if (found_end || read_error)
361 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
363 // This is a trick to make sure that the data are self-consistent.
364 settemplate(templatename_);
366 if (lyxerr.debugging(Debug::EXTERNAL)) {
367 lyxerr << "InsetExternalParams::read:\n";
368 write(buffer, lyxerr);
375 InsetExternal::InsetExternal(Buffer * buf)
376 : Inset(buf), renderer_(new RenderButton)
381 // Mouse hover is not copied and remains empty
382 InsetExternal::InsetExternal(InsetExternal const & other)
384 boost::signals::trackable(),
385 params_(other.params_),
386 renderer_(other.renderer_->clone(this))
390 InsetExternal::~InsetExternal()
392 hideDialogs("external", this);
394 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
395 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
396 for (; it != end; ++it)
398 it->first->clearLastInset(this);
402 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
404 mouse_hover_[bv] = mouse_hover;
409 void InsetExternal::statusChanged() const
415 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
417 switch (cmd.action()) {
419 case LFUN_INSET_EDIT: {
420 InsetExternalParams p = params();
421 if (!cmd.argument().empty())
422 string2params(to_utf8(cmd.argument()), buffer(), p);
423 external::editExternal(p, buffer());
427 case LFUN_INSET_MODIFY: {
428 InsetExternalParams p;
429 string2params(to_utf8(cmd.argument()), buffer(), p);
435 case LFUN_INSET_DIALOG_UPDATE:
436 cur.bv().updateDialog("external",
437 params2string(params(), cur.bv().buffer()));
441 Inset::doDispatch(cur, cmd);
446 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
447 FuncStatus & flag) const
449 switch (cmd.action()) {
451 case LFUN_INSET_EDIT:
452 case LFUN_INSET_MODIFY:
453 case LFUN_INSET_DIALOG_UPDATE:
454 flag.setEnabled(true);
458 return Inset::getStatus(cur, cmd, flag);
463 bool InsetExternal::showInsetDialog(BufferView * bv) const
465 bv->showDialog("external", params2string(params(), bv->buffer()),
466 const_cast<InsetExternal *>(this));
471 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
473 renderer_->metrics(mi, dim);
477 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
479 if (renderer_->asButton())
480 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
481 renderer_->draw(pi, x, y);
487 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
489 graphics::Params gparams;
491 gparams.filename = eparams.filename;
492 gparams.scale = eparams.lyxscale;
493 if (eparams.clipdata.clip)
494 gparams.bb = eparams.clipdata.bbox;
495 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
496 gparams.display = eparams.display;
502 docstring screenLabel(InsetExternalParams const & params,
503 Buffer const & buffer)
505 external::Template const * const ptr =
506 external::getTemplatePtr(params);
509 return bformat((_("External template %1$s is not installed")),
510 from_utf8(params.templatename()));
512 docstring gui = _(ptr->guiName);
515 if (params.filename.empty())
518 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
526 static bool isPreviewWanted(InsetExternalParams const & params)
528 return params.display && params.filename.isReadableFile();
532 static docstring latexString(InsetExternal const & inset)
535 odocstringstream ods;
536 otexstream os(ods, texrow);
537 // We don't need to set runparams.encoding since it is not used by
539 OutputParams runparams(0);
540 runparams.flavor = OutputParams::LATEX;
541 inset.latex(os, runparams);
546 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
547 InsetExternal const & inset,
548 Buffer const & buffer)
550 InsetExternalParams const & params = inset.params();
552 if (RenderPreview::previewText() && isPreviewWanted(params)) {
553 renderer.setAbsFile(params.filename);
554 docstring const snippet = latexString(inset);
555 renderer.addPreview(snippet, buffer);
556 renderer.startLoading(buffer);
561 InsetExternalParams const & InsetExternal::params() const
567 void InsetExternal::updatePreview()
573 void InsetExternal::setParams(InsetExternalParams const & p)
577 // Subsequent calls to the InsetExternal::Params default constructor
579 defaultTemplateName = params_.templatename();
581 if (!external::getTemplatePtr(params_) || params_.filename.empty()
583 || !lyxrc.display_graphics
584 || params_.preview_mode == PREVIEW_OFF
585 || (params_.preview_mode == PREVIEW_INSTANT
586 && !RenderPreview::previewText())) {
587 RenderButton * button_ptr = renderer_->asButton();
589 renderer_.reset(new RenderButton);
590 button_ptr = renderer_->asButton();
592 button_ptr->update(screenLabel(params_, buffer()), true);
596 switch (params_.preview_mode) {
598 // Already taken care of above.
599 LASSERT(false, return);
601 case PREVIEW_INSTANT: {
602 //FIXME: why is the value below immediately forgotten?
603 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
604 renderer_.reset(new RenderMonitoredPreview(this));
605 preview_ptr = renderer_->asMonitoredPreview();
606 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
607 if (preview_ptr->monitoring())
608 preview_ptr->stopMonitoring();
609 add_preview_and_start_loading(*preview_ptr, *this, buffer());
612 case PREVIEW_GRAPHICS: {
613 RenderGraphic * graphic_ptr = renderer_->asGraphic();
615 renderer_.reset(new RenderGraphic(this));
616 graphic_ptr = renderer_->asGraphic();
618 graphic_ptr->update(get_grfx_params(params_));
625 void InsetExternal::fileChanged() const
627 Buffer const * const buffer = updateFrontend();
631 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
632 LASSERT(ptr, return);
634 ptr->removePreview(*buffer);
635 add_preview_and_start_loading(*ptr, *this, *buffer);
639 void InsetExternal::write(ostream & os) const
641 params_.write(buffer(), os);
645 void InsetExternal::read(Lexer & lex)
647 InsetExternalParams params;
648 if (params.read(buffer(), lex))
653 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
657 os << "\\fbox{\\ttfamily{}"
658 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
663 // "nice" means that the buffer is exported to LaTeX format but not
664 // run through the LaTeX compiler.
665 // If we're running through the LaTeX compiler, we should write the
666 // generated files in the buffer's temporary directory.
667 bool const external_in_tmpdir = !runparams.nice;
668 bool const dryrun = runparams.dryrun || runparams.inComment;
670 // If the template has specified a PDFLaTeX output, then we try and
672 if (runparams.flavor == OutputParams::PDFLATEX) {
673 external::Template const * const et_ptr =
674 external::getTemplatePtr(params_);
677 external::Template const & et = *et_ptr;
679 external::Template::Formats::const_iterator cit =
680 et.formats.find("PDFLaTeX");
682 if (cit != et.formats.end()) {
683 external::writeExternal(params_, "PDFLaTeX",
685 *(runparams.exportdata),
692 external::writeExternal(params_, "LaTeX", buffer(), os,
693 *(runparams.exportdata),
699 int InsetExternal::plaintext(odocstringstream & os,
700 OutputParams const & runparams, size_t) const
702 // this is too slow for constant use
703 if (runparams.for_tooltip)
707 otexstream ots(os, texrow);
708 ots << '\n'; // output external material on a new line
709 external::writeExternal(params_, "Ascii", buffer(), ots,
710 *(runparams.exportdata), false,
711 runparams.dryrun || runparams.inComment);
712 return PLAINTEXT_NEWLINE;
716 int InsetExternal::docbook(odocstream & os,
717 OutputParams const & runparams) const
720 odocstringstream ods;
721 otexstream ots(ods, texrow);
722 external::writeExternal(params_, "DocBook", buffer(), ots,
723 *(runparams.exportdata), false,
724 runparams.dryrun || runparams.inComment);
726 return int(count(ods.str().begin(), ods.str().end(), '\n'));
730 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
731 OutputParams const & /*rp*/) const
733 // external::writeExternal(params_, "XHTML", buffer(), os,
734 // *(runparams.exportdata), false,
735 // runparams.dryrun || runparams.inComment);
740 void InsetExternal::validate(LaTeXFeatures & features) const
745 external::Template const * const et_ptr =
746 external::getTemplatePtr(params_);
749 external::Template const & et = *et_ptr;
752 switch (features.runparams().flavor) {
753 case OutputParams::LATEX:
754 case OutputParams::DVILUATEX:
757 case OutputParams::LUATEX:
758 case OutputParams::PDFLATEX:
759 case OutputParams::XETEX:
762 case OutputParams::XML:
765 case OutputParams::HTML:
768 case OutputParams::TEXT:
771 case OutputParams::LYX:
775 external::Template::Formats::const_iterator cit =
776 et.formats.find(format);
778 if (cit == et.formats.end()) {
779 // If the template has not specified a PDFLaTeX output,
780 // we try the LaTeX format.
781 if (format == "PDFLaTeX") {
782 cit = et.formats.find("LaTeX");
783 if (cit == et.formats.end())
789 // FIXME: We don't need that always, see InsetGraphics
790 features.require("lyxdot");
792 vector<string>::const_iterator it = cit->second.requirements.begin();
793 vector<string>::const_iterator end = cit->second.requirements.end();
794 for (; it != end; ++it)
795 features.require(*it);
797 external::TemplateManager & etm = external::TemplateManager::get();
799 it = cit->second.preambleNames.begin();
800 end = cit->second.preambleNames.end();
801 for (; it != end; ++it) {
802 string const preamble = etm.getPreambleDefByName(*it);
803 if (!preamble.empty())
804 features.addPreambleSnippet(preamble);
809 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
810 graphics::PreviewLoader & ploader) const
812 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
816 if (isPreviewWanted(params())) {
817 ptr->setAbsFile(params_.filename);
818 docstring const snippet = latexString(*this);
819 ptr->addPreview(snippet, ploader);
824 string InsetExternal::contextMenuName() const
826 return "context-external";
830 void InsetExternal::string2params(string const & in, Buffer const & buffer,
831 InsetExternalParams & params)
833 params = InsetExternalParams();
837 istringstream data(in);
843 if (!lex || name != "external") {
844 LYXERR0("InsetExternal::string2params(" << in << ")\n"
845 "Expected arg 1 to be \"external\"\n");
849 // This is part of the inset proper that is usually swallowed
850 // by Text::readInset
853 if (!lex || id != "External") {
854 LYXERR0("InsetExternal::string2params(" << in << ")\n"
855 "Expected arg 2 to be \"External\"\n");
859 params.read(buffer, lex);
863 string InsetExternal::params2string(InsetExternalParams const & params,
864 Buffer const & buffer)
867 data << "external" << ' ';
868 params.write(buffer, data);
869 data << "\\end_inset\n";