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"
33 #include "TocBackend.h"
35 #include "frontends/alert.h"
36 #include "frontends/Application.h"
38 #include "graphics/PreviewLoader.h"
40 #include "support/bind.h"
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/filetools.h"
45 #include "support/gettext.h"
46 #include "support/lassert.h"
47 #include "support/lstrings.h"
48 #include "support/lyxlib.h"
49 #include "support/TempFile.h"
55 using namespace lyx::support;
59 unsigned int const defaultLyxScale = 100;
61 string defaultTemplateName;
68 namespace Alert = frontend::Alert;
74 // must have an extension for the converter code to work correctly.
75 support::TempFile f("lyxextXXXXXX.tmp");
76 // Let f go out of scope here and delete the file ourselves in
77 // ~TempName(), since otherwise external processes would not be able
78 // to use the file on windows (bug 9925). This is not as safe as
79 // keeping a support::TempFile member would be, but the best we can do.
80 f.setAutoRemove(false);
85 TempName::TempName(TempName const & that)
93 tempname_.removeFile();
97 TempName & TempName::operator=(TempName const & other)
100 tempname_.removeFile();
101 support::TempFile f("lyxextXXXXXX.tmp");
102 f.setAutoRemove(false);
103 tempname_ = f.name();
109 support::FileName TempName::operator()() const
114 } // namespace external
117 InsetExternalParams::InsetExternalParams()
119 lyxscale(defaultLyxScale),
122 if (defaultTemplateName.empty()) {
123 external::TemplateManager const & etm =
124 external::TemplateManager::get();
125 if (!etm.getTemplates().empty())
126 templatename_ = etm.getTemplates().begin()->first;
128 templatename_ = defaultTemplateName;
134 template <typename T>
135 void clearIfNotFound(T & data, external::TransformID value,
136 vector<external::TransformID> const & ids)
138 typedef vector<external::TransformID>::const_iterator
141 const_iterator it = ids.begin();
142 const_iterator end = ids.end();
143 it = find(it, end, value);
151 void InsetExternalParams::settemplate(string const & name)
153 templatename_ = name;
155 external::TemplateManager const & etm =
156 external::TemplateManager::get();
157 external::Template const * const et = etm.getTemplateByName(name);
159 // Be safe. Don't lose data.
162 // Ascertain which transforms the template supports.
163 // Empty all those that it doesn't.
164 vector<external::TransformID> const & ids = et->transformIds;
165 clearIfNotFound(clipdata, external::Clip, ids);
166 clearIfNotFound(extradata, external::Extra, ids);
167 clearIfNotFound(resizedata, external::Resize, ids);
168 clearIfNotFound(rotationdata, external::Rotate, ids);
171 preview_mode = et->preview_mode;
175 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
178 << "\ttemplate " << templatename() << '\n';
180 if (!filename.empty())
181 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
184 os << "\tdisplay false\n";
186 if (lyxscale != defaultLyxScale)
187 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
192 if (!clipdata.bbox.empty())
193 os << "\tboundingBox " << clipdata.bbox << '\n';
197 external::ExtraData::const_iterator it = extradata.begin();
198 external::ExtraData::const_iterator end = extradata.end();
199 for (; it != end; ++it) {
200 if (!it->second.empty())
201 os << "\textra " << it->first << " \""
202 << it->second << "\"\n";
205 if (!rotationdata.no_rotation()) {
206 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
207 if (rotationdata.origin() != external::RotationData::DEFAULT)
208 os << "\trotateOrigin "
209 << rotationdata.originString() << '\n';
212 if (!resizedata.no_resize()) {
213 double const scl = convert<double>(resizedata.scale);
214 if (!float_equal(scl, 0.0, 0.05)) {
215 if (!float_equal(scl, 100.0, 0.05))
217 << resizedata.scale << '\n';
219 if (!resizedata.width.zero())
221 << resizedata.width.asString() << '\n';
222 if (!resizedata.height.zero())
224 << resizedata.height.asString() << '\n';
226 if (resizedata.keepAspectRatio)
227 os << "\tkeepAspectRatio\n";
232 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
252 LexerKeyword external_tags[] = {
253 { "\\end_inset", EX_END },
254 { "boundingBox", EX_BOUNDINGBOX },
256 { "display", EX_DISPLAY},
257 { "draft", EX_DRAFT},
258 { "extra", EX_EXTRA },
259 { "filename", EX_FILENAME},
260 { "height", EX_HEIGHT },
261 { "keepAspectRatio", EX_KEEPASPECTRATIO },
262 { "lyxscale", EX_LYXSCALE},
263 { "rotateAngle", EX_ROTATEANGLE },
264 { "rotateOrigin", EX_ROTATEORIGIN },
265 { "scale", EX_SCALE },
266 { "template", EX_TEMPLATE },
267 { "width", EX_WIDTH }
270 PushPopHelper pph(lex, external_tags);
272 bool found_end = false;
273 bool read_error = false;
279 templatename_ = lex.getString();
284 string const name = lex.getString();
285 filename = buffer.getReferencedFileName(name);
291 display = lex.getString() != "false";
297 lyxscale = lex.getInteger();
306 clipdata.bbox.xl = Length(lex.getString());
308 clipdata.bbox.yb = Length(lex.getString());
310 clipdata.bbox.xr = Length(lex.getString());
312 clipdata.bbox.yt = Length(lex.getString());
316 clipdata.clip = true;
321 string const name = lex.getString();
323 extradata.set(name, lex.getString());
329 resizedata.height = Length(lex.getString());
332 case EX_KEEPASPECTRATIO:
333 resizedata.keepAspectRatio = true;
338 rotationdata.angle = lex.getString();
341 case EX_ROTATEORIGIN:
343 rotationdata.origin(lex.getString());
348 resizedata.scale = lex.getString();
353 resizedata.width = Length(lex.getString());
361 lex.printError("ExternalInset::read: Wrong tag: $$Token");
366 if (found_end || read_error)
371 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
373 // This is a trick to make sure that the data are self-consistent.
374 settemplate(templatename_);
376 if (lyxerr.debugging(Debug::EXTERNAL)) {
377 lyxerr << "InsetExternalParams::read:\n";
378 write(buffer, lyxerr);
387 docstring screenLabel(InsetExternalParams const & params,
388 Buffer const & buffer)
390 external::Template const * const ptr =
391 external::getTemplatePtr(params);
394 return bformat((_("External template %1$s is not installed")),
395 from_utf8(params.templatename()));
397 docstring gui = _(ptr->guiName);
400 if (params.filename.empty())
403 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
412 InsetExternal::InsetExternal(Buffer * buf)
413 : Inset(buf), renderer_(new RenderButton)
418 // Mouse hover is not copied and remains empty
419 InsetExternal::InsetExternal(InsetExternal const & other)
421 boost::signals::trackable(),
422 params_(other.params_),
423 renderer_(other.renderer_->clone(this))
427 InsetExternal::~InsetExternal()
429 hideDialogs("external", this);
431 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
432 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
433 for (; it != end; ++it)
435 it->first->clearLastInset(this);
439 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
441 mouse_hover_[bv] = mouse_hover;
446 void InsetExternal::statusChanged() const
452 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
454 switch (cmd.action()) {
456 case LFUN_INSET_EDIT: {
457 InsetExternalParams p = params();
458 if (!cmd.argument().empty())
459 string2params(to_utf8(cmd.argument()), buffer(), p);
460 external::editExternal(p, buffer());
464 case LFUN_INSET_MODIFY: {
465 InsetExternalParams p;
466 string2params(to_utf8(cmd.argument()), buffer(), p);
472 case LFUN_INSET_DIALOG_UPDATE:
473 cur.bv().updateDialog("external",
474 params2string(params(), cur.bv().buffer()));
478 Inset::doDispatch(cur, cmd);
483 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
484 FuncStatus & flag) const
486 switch (cmd.action()) {
488 case LFUN_INSET_EDIT:
489 case LFUN_INSET_MODIFY:
490 case LFUN_INSET_DIALOG_UPDATE:
491 flag.setEnabled(true);
495 return Inset::getStatus(cur, cmd, flag);
500 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
503 DocIterator pit = cpit;
504 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
505 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
506 docstring str = screenLabel(params_, buffer());
507 toc->push_back(TocItem(pit, 0, str, output_active));
511 bool InsetExternal::showInsetDialog(BufferView * bv) const
513 bv->showDialog("external", params2string(params(), bv->buffer()),
514 const_cast<InsetExternal *>(this));
519 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
521 renderer_->metrics(mi, dim);
525 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
527 if (renderer_->asButton())
528 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
529 renderer_->draw(pi, x, y);
535 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
537 graphics::Params gparams;
539 gparams.filename = eparams.filename;
540 gparams.scale = eparams.lyxscale;
541 if (eparams.clipdata.clip)
542 gparams.bb = eparams.clipdata.bbox;
543 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
544 gparams.display = eparams.display;
552 static bool isPreviewWanted(InsetExternalParams const & params)
554 return params.display && params.filename.isReadableFile();
558 static docstring latexString(InsetExternal const & inset)
561 odocstringstream ods;
562 otexstream os(ods, texrow);
563 // We don't need to set runparams.encoding since it is not used by
565 OutputParams runparams(0);
566 runparams.flavor = OutputParams::LATEX;
567 inset.latex(os, runparams);
572 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
573 InsetExternal const & inset,
574 Buffer const & buffer)
576 InsetExternalParams const & params = inset.params();
578 if (RenderPreview::previewText() && isPreviewWanted(params)) {
579 renderer.setAbsFile(params.filename);
580 docstring const snippet = latexString(inset);
581 renderer.addPreview(snippet, buffer);
582 renderer.startLoading(buffer);
587 InsetExternalParams const & InsetExternal::params() const
593 void InsetExternal::updatePreview()
599 void InsetExternal::setParams(InsetExternalParams const & p)
603 // Subsequent calls to the InsetExternal::Params default constructor
605 defaultTemplateName = params_.templatename();
607 if (!external::getTemplatePtr(params_) || params_.filename.empty()
609 || !lyxrc.display_graphics
610 || params_.preview_mode == PREVIEW_OFF
611 || (params_.preview_mode == PREVIEW_INSTANT
612 && !RenderPreview::previewText())) {
613 RenderButton * button_ptr = renderer_->asButton();
615 renderer_.reset(new RenderButton);
616 button_ptr = renderer_->asButton();
618 button_ptr->update(screenLabel(params_, buffer()), true);
622 switch (params_.preview_mode) {
624 // Already taken care of above.
625 LASSERT(false, return);
627 case PREVIEW_INSTANT: {
628 renderer_.reset(new RenderMonitoredPreview(this));
629 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
630 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
631 if (preview_ptr->monitoring())
632 preview_ptr->stopMonitoring();
633 add_preview_and_start_loading(*preview_ptr, *this, buffer());
636 case PREVIEW_GRAPHICS: {
637 RenderGraphic * graphic_ptr = renderer_->asGraphic();
639 renderer_.reset(new RenderGraphic(this));
640 graphic_ptr = renderer_->asGraphic();
642 graphic_ptr->update(get_grfx_params(params_));
649 void InsetExternal::fileChanged() const
651 Buffer const * const buffer = updateFrontend();
655 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
656 LASSERT(ptr, return);
658 ptr->removePreview(*buffer);
659 add_preview_and_start_loading(*ptr, *this, *buffer);
663 void InsetExternal::write(ostream & os) const
665 params_.write(buffer(), os);
669 void InsetExternal::read(Lexer & lex)
671 InsetExternalParams params;
672 if (params.read(buffer(), lex))
677 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
681 os << "\\fbox{\\ttfamily{}"
682 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
687 // "nice" means that the buffer is exported to LaTeX format but not
688 // run through the LaTeX compiler.
689 // If we're running through the LaTeX compiler, we should write the
690 // generated files in the buffer's temporary directory.
691 bool const external_in_tmpdir = !runparams.nice;
692 bool const dryrun = runparams.dryrun || runparams.inComment;
694 // If the template has specified a PDFLaTeX output, then we try and
696 if (runparams.flavor == OutputParams::PDFLATEX) {
697 external::Template const * const et_ptr =
698 external::getTemplatePtr(params_);
701 external::Template const & et = *et_ptr;
703 external::Template::Formats::const_iterator cit =
704 et.formats.find("PDFLaTeX");
706 if (cit != et.formats.end()) {
707 external::writeExternal(params_, "PDFLaTeX",
709 *(runparams.exportdata),
716 external::writeExternal(params_, "LaTeX", buffer(), os,
717 *(runparams.exportdata),
723 int InsetExternal::plaintext(odocstringstream & os,
724 OutputParams const & runparams, size_t) const
726 // this is too slow for constant use
727 if (runparams.for_tooltip)
731 otexstream ots(os, texrow);
732 ots << '\n'; // output external material on a new line
733 external::writeExternal(params_, "Ascii", buffer(), ots,
734 *(runparams.exportdata), false,
735 runparams.dryrun || runparams.inComment);
736 return PLAINTEXT_NEWLINE;
740 int InsetExternal::docbook(odocstream & os,
741 OutputParams const & runparams) const
744 odocstringstream ods;
745 otexstream ots(ods, texrow);
746 external::writeExternal(params_, "DocBook", buffer(), ots,
747 *(runparams.exportdata), false,
748 runparams.dryrun || runparams.inComment);
750 return int(count(ods.str().begin(), ods.str().end(), '\n'));
754 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
755 OutputParams const & /*rp*/) const
757 // external::writeExternal(params_, "XHTML", buffer(), os,
758 // *(runparams.exportdata), false,
759 // runparams.dryrun || runparams.inComment);
764 void InsetExternal::validate(LaTeXFeatures & features) const
769 external::Template const * const et_ptr =
770 external::getTemplatePtr(params_);
773 external::Template const & et = *et_ptr;
776 switch (features.runparams().flavor) {
777 case OutputParams::LATEX:
778 case OutputParams::DVILUATEX:
781 case OutputParams::LUATEX:
782 case OutputParams::PDFLATEX:
783 case OutputParams::XETEX:
786 case OutputParams::XML:
789 case OutputParams::HTML:
792 case OutputParams::TEXT:
795 case OutputParams::LYX:
799 external::Template::Formats::const_iterator cit =
800 et.formats.find(format);
802 if (cit == et.formats.end()) {
803 // If the template has not specified a PDFLaTeX output,
804 // we try the LaTeX format.
805 if (format == "PDFLaTeX") {
806 cit = et.formats.find("LaTeX");
807 if (cit == et.formats.end())
813 // FIXME: We don't need that always, see InsetGraphics
814 features.require("lyxdot");
816 vector<string>::const_iterator it = cit->second.requirements.begin();
817 vector<string>::const_iterator end = cit->second.requirements.end();
818 for (; it != end; ++it)
819 features.require(*it);
821 external::TemplateManager & etm = external::TemplateManager::get();
823 it = cit->second.preambleNames.begin();
824 end = cit->second.preambleNames.end();
825 for (; it != end; ++it) {
826 string const preamble = etm.getPreambleDefByName(*it);
827 if (!preamble.empty())
828 features.addPreambleSnippet(preamble);
833 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
834 graphics::PreviewLoader & ploader) const
836 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
840 if (isPreviewWanted(params())) {
841 ptr->setAbsFile(params_.filename);
842 docstring const snippet = latexString(*this);
843 ptr->addPreview(snippet, ploader);
848 string InsetExternal::contextMenuName() const
850 return "context-external";
854 void InsetExternal::string2params(string const & in, Buffer const & buffer,
855 InsetExternalParams & params)
857 params = InsetExternalParams();
861 istringstream data(in);
867 if (!lex || name != "external") {
868 LYXERR0("InsetExternal::string2params(" << in << ")\n"
869 "Expected arg 1 to be \"external\"\n");
873 // This is part of the inset proper that is usually swallowed
874 // by Text::readInset
877 if (!lex || id != "External") {
878 LYXERR0("InsetExternal::string2params(" << in << ")\n"
879 "Expected arg 2 to be \"External\"\n");
883 params.read(buffer, lex);
887 string InsetExternal::params2string(InsetExternalParams const & params,
888 Buffer const & buffer)
891 data << "external" << ' ';
892 params.write(buffer, data);
893 data << "\\end_inset\n";