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 "texstream.h"
34 #include "TocBackend.h"
36 #include "frontends/alert.h"
37 #include "frontends/Application.h"
39 #include "graphics/PreviewLoader.h"
41 #include "support/bind.h"
42 #include "support/convert.h"
43 #include "support/debug.h"
44 #include "support/ExceptionMessage.h"
45 #include "support/filetools.h"
46 #include "support/gettext.h"
47 #include "support/lassert.h"
48 #include "support/lstrings.h"
49 #include "support/lyxlib.h"
50 #include "support/TempFile.h"
56 using namespace lyx::support;
60 unsigned int const defaultLyxScale = 100;
62 string defaultTemplateName;
69 namespace Alert = frontend::Alert;
75 // must have an extension for the converter code to work correctly.
76 support::TempFile f("lyxextXXXXXX.tmp");
77 // Let f go out of scope here and delete the file ourselves in
78 // ~TempName(), since otherwise external processes would not be able
79 // to use the file on windows (bug 9925). This is not as safe as
80 // keeping a support::TempFile member would be, but the best we can do.
81 f.setAutoRemove(false);
86 TempName::TempName(TempName const & that)
94 tempname_.removeFile();
98 TempName & TempName::operator=(TempName const & other)
100 if (this != &other) {
101 tempname_.removeFile();
102 support::TempFile f("lyxextXXXXXX.tmp");
103 f.setAutoRemove(false);
104 tempname_ = f.name();
110 support::FileName TempName::operator()() const
115 } // namespace external
118 InsetExternalParams::InsetExternalParams()
120 preview_mode(PREVIEW_OFF),
121 lyxscale(defaultLyxScale),
124 if (defaultTemplateName.empty()) {
125 external::TemplateManager const & etm =
126 external::TemplateManager::get();
127 if (!etm.getTemplates().empty())
128 templatename_ = etm.getTemplates().begin()->first;
130 templatename_ = defaultTemplateName;
136 template <typename T>
137 void clearIfNotFound(T & data, external::TransformID value,
138 vector<external::TransformID> const & ids)
140 typedef vector<external::TransformID>::const_iterator
143 const_iterator it = ids.begin();
144 const_iterator end = ids.end();
145 it = find(it, end, value);
153 void InsetExternalParams::settemplate(string const & name)
155 templatename_ = name;
157 external::TemplateManager const & etm =
158 external::TemplateManager::get();
159 external::Template const * const et = etm.getTemplateByName(name);
161 // Be safe. Don't lose data.
164 // Ascertain which transforms the template supports.
165 // Empty all those that it doesn't.
166 vector<external::TransformID> const & ids = et->transformIds;
167 clearIfNotFound(clipdata, external::Clip, ids);
168 clearIfNotFound(extradata, external::Extra, ids);
169 clearIfNotFound(resizedata, external::Resize, ids);
170 clearIfNotFound(rotationdata, external::Rotate, ids);
173 preview_mode = et->preview_mode;
177 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
180 << "\ttemplate " << templatename() << '\n';
182 if (!filename.empty())
183 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
186 os << "\tdisplay false\n";
188 if (lyxscale != defaultLyxScale)
189 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
194 if (!clipdata.bbox.empty())
195 os << "\tboundingBox " << clipdata.bbox << '\n';
199 external::ExtraData::const_iterator it = extradata.begin();
200 external::ExtraData::const_iterator end = extradata.end();
201 for (; it != end; ++it) {
202 if (!it->second.empty())
203 os << "\textra " << it->first << " \""
204 << it->second << "\"\n";
207 if (!rotationdata.no_rotation()) {
208 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
209 if (rotationdata.origin() != external::RotationData::DEFAULT)
210 os << "\trotateOrigin "
211 << rotationdata.originString() << '\n';
214 if (!resizedata.no_resize()) {
215 double const scl = convert<double>(resizedata.scale);
216 if (!float_equal(scl, 0.0, 0.05)) {
217 if (!float_equal(scl, 100.0, 0.05))
219 << resizedata.scale << '\n';
221 if (!resizedata.width.zero())
223 << resizedata.width.asString() << '\n';
224 if (!resizedata.height.zero())
226 << resizedata.height.asString() << '\n';
228 if (resizedata.keepAspectRatio)
229 os << "\tkeepAspectRatio\n";
234 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
254 LexerKeyword external_tags[] = {
255 { "\\end_inset", EX_END },
256 { "boundingBox", EX_BOUNDINGBOX },
258 { "display", EX_DISPLAY},
259 { "draft", EX_DRAFT},
260 { "extra", EX_EXTRA },
261 { "filename", EX_FILENAME},
262 { "height", EX_HEIGHT },
263 { "keepAspectRatio", EX_KEEPASPECTRATIO },
264 { "lyxscale", EX_LYXSCALE},
265 { "rotateAngle", EX_ROTATEANGLE },
266 { "rotateOrigin", EX_ROTATEORIGIN },
267 { "scale", EX_SCALE },
268 { "template", EX_TEMPLATE },
269 { "width", EX_WIDTH }
272 PushPopHelper pph(lex, external_tags);
274 bool found_end = false;
275 bool read_error = false;
281 templatename_ = lex.getString();
286 string const name = lex.getString();
287 filename = buffer.getReferencedFileName(name);
293 display = lex.getString() != "false";
299 lyxscale = lex.getInteger();
308 clipdata.bbox.xl = Length(lex.getString());
310 clipdata.bbox.yb = Length(lex.getString());
312 clipdata.bbox.xr = Length(lex.getString());
314 clipdata.bbox.yt = Length(lex.getString());
318 clipdata.clip = true;
323 string const name = lex.getString();
325 extradata.set(name, lex.getString());
331 resizedata.height = Length(lex.getString());
334 case EX_KEEPASPECTRATIO:
335 resizedata.keepAspectRatio = true;
340 rotationdata.angle = lex.getString();
343 case EX_ROTATEORIGIN:
345 rotationdata.origin(lex.getString());
350 resizedata.scale = lex.getString();
355 resizedata.width = Length(lex.getString());
363 lex.printError("ExternalInset::read: Wrong tag: $$Token");
368 if (found_end || read_error)
373 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
375 // This is a trick to make sure that the data are self-consistent.
376 settemplate(templatename_);
378 if (lyxerr.debugging(Debug::EXTERNAL)) {
379 lyxerr << "InsetExternalParams::read:\n";
381 // coverity[NEGATIVE_RETURNS]
382 write(buffer, lyxerr);
391 docstring screenLabel(InsetExternalParams const & params,
392 Buffer const & buffer)
394 external::Template const * const ptr =
395 external::getTemplatePtr(params);
398 return bformat((_("External template %1$s is not installed")),
399 from_utf8(params.templatename()));
401 docstring gui = _(ptr->guiName);
404 if (params.filename.empty())
407 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
416 InsetExternal::InsetExternal(Buffer * buf)
417 : Inset(buf), renderer_(new RenderButton)
422 // Mouse hover is not copied and remains empty
423 InsetExternal::InsetExternal(InsetExternal const & other)
425 boost::signals2::trackable(),
426 params_(other.params_),
427 renderer_(other.renderer_->clone(this))
431 InsetExternal::~InsetExternal()
433 hideDialogs("external", this);
435 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
436 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
437 for (; it != end; ++it)
439 it->first->clearLastInset(this);
443 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
445 mouse_hover_[bv] = mouse_hover;
450 void InsetExternal::statusChanged() const
456 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
458 switch (cmd.action()) {
460 case LFUN_INSET_EDIT: {
461 InsetExternalParams p = params();
462 if (!cmd.argument().empty())
463 string2params(to_utf8(cmd.argument()), buffer(), p);
464 external::editExternal(p, buffer());
468 case LFUN_INSET_MODIFY: {
469 InsetExternalParams p;
470 string2params(to_utf8(cmd.argument()), buffer(), p);
476 case LFUN_INSET_DIALOG_UPDATE:
477 cur.bv().updateDialog("external",
478 params2string(params(), cur.bv().buffer()));
482 Inset::doDispatch(cur, cmd);
487 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
488 FuncStatus & flag) const
490 switch (cmd.action()) {
492 case LFUN_INSET_EDIT:
493 case LFUN_INSET_MODIFY:
494 case LFUN_INSET_DIALOG_UPDATE:
495 flag.setEnabled(true);
499 return Inset::getStatus(cur, cmd, flag);
504 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
507 DocIterator pit = cpit;
508 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
509 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
510 docstring str = screenLabel(params_, buffer());
511 toc->push_back(TocItem(pit, 0, str, output_active));
515 bool InsetExternal::showInsetDialog(BufferView * bv) const
517 bv->showDialog("external", params2string(params(), bv->buffer()),
518 const_cast<InsetExternal *>(this));
523 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
525 renderer_->metrics(mi, dim);
529 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
531 if (renderer_->asButton())
532 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
533 renderer_->draw(pi, x, y);
539 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
541 graphics::Params gparams;
543 gparams.filename = eparams.filename;
544 gparams.scale = eparams.lyxscale;
545 if (eparams.clipdata.clip)
546 gparams.bb = eparams.clipdata.bbox;
547 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
548 gparams.display = eparams.display;
556 static bool isPreviewWanted(InsetExternalParams const & params)
558 return params.display && params.filename.isReadableFile();
562 static docstring latexString(InsetExternal const & inset)
564 odocstringstream ods;
565 otexstream os(ods, false);
566 // We don't need to set runparams.encoding since it is not used by
568 OutputParams runparams(0);
569 runparams.flavor = OutputParams::LATEX;
570 inset.latex(os, runparams);
575 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
576 InsetExternal const & inset,
577 Buffer const & buffer)
579 InsetExternalParams const & params = inset.params();
581 if (RenderPreview::previewText() && isPreviewWanted(params)) {
582 renderer.setAbsFile(params.filename);
583 docstring const snippet = latexString(inset);
584 renderer.addPreview(snippet, buffer);
585 renderer.startLoading(buffer);
590 InsetExternalParams const & InsetExternal::params() const
596 void InsetExternal::updatePreview()
602 void InsetExternal::setParams(InsetExternalParams const & p)
606 // Subsequent calls to the InsetExternal::Params default constructor
608 defaultTemplateName = params_.templatename();
610 if (!external::getTemplatePtr(params_) || params_.filename.empty()
612 || !lyxrc.display_graphics
613 || params_.preview_mode == PREVIEW_OFF
614 || (params_.preview_mode == PREVIEW_INSTANT
615 && !RenderPreview::previewText())) {
616 RenderButton * button_ptr = renderer_->asButton();
618 renderer_.reset(new RenderButton);
619 button_ptr = renderer_->asButton();
621 button_ptr->update(screenLabel(params_, buffer()), true);
625 switch (params_.preview_mode) {
627 // Already taken care of above.
628 LASSERT(false, return);
630 case PREVIEW_INSTANT: {
631 renderer_.reset(new RenderMonitoredPreview(this));
632 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
633 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
634 if (preview_ptr->monitoring())
635 preview_ptr->stopMonitoring();
636 add_preview_and_start_loading(*preview_ptr, *this, buffer());
639 case PREVIEW_GRAPHICS: {
640 RenderGraphic * graphic_ptr = renderer_->asGraphic();
642 renderer_.reset(new RenderGraphic(this));
643 graphic_ptr = renderer_->asGraphic();
645 graphic_ptr->update(get_grfx_params(params_));
652 void InsetExternal::fileChanged() const
654 Buffer const * const buffer = updateFrontend();
658 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
659 LASSERT(ptr, return);
661 ptr->removePreview(*buffer);
662 add_preview_and_start_loading(*ptr, *this, *buffer);
666 void InsetExternal::write(ostream & os) const
668 params_.write(buffer(), os);
672 void InsetExternal::read(Lexer & lex)
674 InsetExternalParams params;
675 if (params.read(buffer(), lex))
680 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
684 os << "\\fbox{\\ttfamily{}"
685 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
690 // "nice" means that the buffer is exported to LaTeX format but not
691 // run through the LaTeX compiler.
692 // If we're running through the LaTeX compiler, we should write the
693 // generated files in the buffer's temporary directory.
694 bool const external_in_tmpdir = !runparams.nice;
695 bool const dryrun = runparams.dryrun || runparams.inComment;
697 // If the template has specified a PDFLaTeX output, then we try and
699 if (runparams.flavor == OutputParams::PDFLATEX) {
700 external::Template const * const et_ptr =
701 external::getTemplatePtr(params_);
704 external::Template const & et = *et_ptr;
706 external::Template::Formats::const_iterator cit =
707 et.formats.find("PDFLaTeX");
709 if (cit != et.formats.end()) {
710 external::writeExternal(params_, "PDFLaTeX",
712 *(runparams.exportdata),
719 external::writeExternal(params_, "LaTeX", buffer(), os,
720 *(runparams.exportdata),
726 int InsetExternal::plaintext(odocstringstream & os,
727 OutputParams const & runparams, size_t) const
729 // this is too slow for constant use
730 if (runparams.for_tooltip)
733 otexstream ots(os, false);
734 ots << '\n'; // output external material on a new line
735 external::writeExternal(params_, "Ascii", buffer(), ots,
736 *(runparams.exportdata), false,
737 runparams.dryrun || runparams.inComment);
738 return PLAINTEXT_NEWLINE;
742 int InsetExternal::docbook(odocstream & os,
743 OutputParams const & runparams) const
745 odocstringstream ods;
746 otexstream ots(ods, false);
747 external::writeExternal(params_, "DocBook", buffer(), ots,
748 *(runparams.exportdata), false,
749 runparams.dryrun || runparams.inComment);
751 return int(count(ods.str().begin(), ods.str().end(), '\n'));
755 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
756 OutputParams const & /*rp*/) const
758 // external::writeExternal(params_, "XHTML", buffer(), os,
759 // *(runparams.exportdata), false,
760 // runparams.dryrun || runparams.inComment);
765 void InsetExternal::validate(LaTeXFeatures & features) const
770 external::Template const * const et_ptr =
771 external::getTemplatePtr(params_);
774 external::Template const & et = *et_ptr;
777 switch (features.runparams().flavor) {
778 case OutputParams::LATEX:
779 case OutputParams::DVILUATEX:
782 case OutputParams::LUATEX:
783 case OutputParams::PDFLATEX:
784 case OutputParams::XETEX:
787 case OutputParams::XML:
790 case OutputParams::HTML:
793 case OutputParams::TEXT:
796 case OutputParams::LYX:
800 external::Template::Formats::const_iterator cit =
801 et.formats.find(format);
803 if (cit == et.formats.end()) {
804 // If the template has not specified a PDFLaTeX output,
805 // we try the LaTeX format.
806 if (format == "PDFLaTeX") {
807 cit = et.formats.find("LaTeX");
808 if (cit == et.formats.end())
814 // FIXME: We don't need that always, see InsetGraphics
815 features.require("lyxdot");
817 vector<string>::const_iterator it = cit->second.requirements.begin();
818 vector<string>::const_iterator end = cit->second.requirements.end();
819 for (; it != end; ++it)
820 features.require(*it);
822 external::TemplateManager & etm = external::TemplateManager::get();
824 it = cit->second.preambleNames.begin();
825 end = cit->second.preambleNames.end();
826 for (; it != end; ++it) {
827 string const preamble = etm.getPreambleDefByName(*it);
828 if (!preamble.empty())
829 features.addPreambleSnippet(preamble);
834 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
835 graphics::PreviewLoader & ploader) const
837 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
841 if (isPreviewWanted(params())) {
842 ptr->setAbsFile(params_.filename);
843 docstring const snippet = latexString(*this);
844 ptr->addPreview(snippet, ploader);
849 string InsetExternal::contextMenuName() const
851 return "context-external";
855 void InsetExternal::string2params(string const & in, Buffer const & buffer,
856 InsetExternalParams & params)
858 params = InsetExternalParams();
862 istringstream data(in);
868 if (!lex || name != "external") {
869 LYXERR0("InsetExternal::string2params(" << in << ")\n"
870 "Expected arg 1 to be \"external\"\n");
874 // This is part of the inset proper that is usually swallowed
875 // by Text::readInset
878 if (!lex || id != "External") {
879 LYXERR0("InsetExternal::string2params(" << in << ")\n"
880 "Expected arg 2 to be \"External\"\n");
884 params.read(buffer, lex);
888 string InsetExternal::params2string(InsetExternalParams const & params,
889 Buffer const & buffer)
892 data << "external" << ' ';
893 params.write(buffer, data);
894 data << "\\end_inset\n";