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 preview_mode(PREVIEW_OFF),
120 lyxscale(defaultLyxScale),
123 if (defaultTemplateName.empty()) {
124 external::TemplateManager const & etm =
125 external::TemplateManager::get();
126 if (!etm.getTemplates().empty())
127 templatename_ = etm.getTemplates().begin()->first;
129 templatename_ = defaultTemplateName;
135 template <typename T>
136 void clearIfNotFound(T & data, external::TransformID value,
137 vector<external::TransformID> const & ids)
139 typedef vector<external::TransformID>::const_iterator
142 const_iterator it = ids.begin();
143 const_iterator end = ids.end();
144 it = find(it, end, value);
152 void InsetExternalParams::settemplate(string const & name)
154 templatename_ = name;
156 external::TemplateManager const & etm =
157 external::TemplateManager::get();
158 external::Template const * const et = etm.getTemplateByName(name);
160 // Be safe. Don't lose data.
163 // Ascertain which transforms the template supports.
164 // Empty all those that it doesn't.
165 vector<external::TransformID> const & ids = et->transformIds;
166 clearIfNotFound(clipdata, external::Clip, ids);
167 clearIfNotFound(extradata, external::Extra, ids);
168 clearIfNotFound(resizedata, external::Resize, ids);
169 clearIfNotFound(rotationdata, external::Rotate, ids);
172 preview_mode = et->preview_mode;
176 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
179 << "\ttemplate " << templatename() << '\n';
181 if (!filename.empty())
182 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
185 os << "\tdisplay false\n";
187 if (lyxscale != defaultLyxScale)
188 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
193 if (!clipdata.bbox.empty())
194 os << "\tboundingBox " << clipdata.bbox << '\n';
198 external::ExtraData::const_iterator it = extradata.begin();
199 external::ExtraData::const_iterator end = extradata.end();
200 for (; it != end; ++it) {
201 if (!it->second.empty())
202 os << "\textra " << it->first << " \""
203 << it->second << "\"\n";
206 if (!rotationdata.no_rotation()) {
207 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
208 if (rotationdata.origin() != external::RotationData::DEFAULT)
209 os << "\trotateOrigin "
210 << rotationdata.originString() << '\n';
213 if (!resizedata.no_resize()) {
214 double const scl = convert<double>(resizedata.scale);
215 if (!float_equal(scl, 0.0, 0.05)) {
216 if (!float_equal(scl, 100.0, 0.05))
218 << resizedata.scale << '\n';
220 if (!resizedata.width.zero())
222 << resizedata.width.asString() << '\n';
223 if (!resizedata.height.zero())
225 << resizedata.height.asString() << '\n';
227 if (resizedata.keepAspectRatio)
228 os << "\tkeepAspectRatio\n";
233 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
253 LexerKeyword external_tags[] = {
254 { "\\end_inset", EX_END },
255 { "boundingBox", EX_BOUNDINGBOX },
257 { "display", EX_DISPLAY},
258 { "draft", EX_DRAFT},
259 { "extra", EX_EXTRA },
260 { "filename", EX_FILENAME},
261 { "height", EX_HEIGHT },
262 { "keepAspectRatio", EX_KEEPASPECTRATIO },
263 { "lyxscale", EX_LYXSCALE},
264 { "rotateAngle", EX_ROTATEANGLE },
265 { "rotateOrigin", EX_ROTATEORIGIN },
266 { "scale", EX_SCALE },
267 { "template", EX_TEMPLATE },
268 { "width", EX_WIDTH }
271 PushPopHelper pph(lex, external_tags);
273 bool found_end = false;
274 bool read_error = false;
280 templatename_ = lex.getString();
285 string const name = lex.getString();
286 filename = buffer.getReferencedFileName(name);
292 display = lex.getString() != "false";
298 lyxscale = lex.getInteger();
307 clipdata.bbox.xl = Length(lex.getString());
309 clipdata.bbox.yb = Length(lex.getString());
311 clipdata.bbox.xr = Length(lex.getString());
313 clipdata.bbox.yt = Length(lex.getString());
317 clipdata.clip = true;
322 string const name = lex.getString();
324 extradata.set(name, lex.getString());
330 resizedata.height = Length(lex.getString());
333 case EX_KEEPASPECTRATIO:
334 resizedata.keepAspectRatio = true;
339 rotationdata.angle = lex.getString();
342 case EX_ROTATEORIGIN:
344 rotationdata.origin(lex.getString());
349 resizedata.scale = lex.getString();
354 resizedata.width = Length(lex.getString());
362 lex.printError("ExternalInset::read: Wrong tag: $$Token");
367 if (found_end || read_error)
372 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
374 // This is a trick to make sure that the data are self-consistent.
375 settemplate(templatename_);
377 if (lyxerr.debugging(Debug::EXTERNAL)) {
378 lyxerr << "InsetExternalParams::read:\n";
380 // coverity[NEGATIVE_RETURNS]
381 write(buffer, lyxerr);
390 docstring screenLabel(InsetExternalParams const & params,
391 Buffer const & buffer)
393 external::Template const * const ptr =
394 external::getTemplatePtr(params);
397 return bformat((_("External template %1$s is not installed")),
398 from_utf8(params.templatename()));
400 docstring gui = _(ptr->guiName);
403 if (params.filename.empty())
406 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
415 InsetExternal::InsetExternal(Buffer * buf)
416 : Inset(buf), renderer_(new RenderButton)
421 // Mouse hover is not copied and remains empty
422 InsetExternal::InsetExternal(InsetExternal const & other)
424 boost::signals2::trackable(),
425 params_(other.params_),
426 renderer_(other.renderer_->clone(this))
430 InsetExternal::~InsetExternal()
432 hideDialogs("external", this);
434 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
435 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
436 for (; it != end; ++it)
438 it->first->clearLastInset(this);
442 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
444 mouse_hover_[bv] = mouse_hover;
449 void InsetExternal::statusChanged() const
455 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
457 switch (cmd.action()) {
459 case LFUN_INSET_EDIT: {
460 InsetExternalParams p = params();
461 if (!cmd.argument().empty())
462 string2params(to_utf8(cmd.argument()), buffer(), p);
463 external::editExternal(p, buffer());
467 case LFUN_INSET_MODIFY: {
468 InsetExternalParams p;
469 string2params(to_utf8(cmd.argument()), buffer(), p);
475 case LFUN_INSET_DIALOG_UPDATE:
476 cur.bv().updateDialog("external",
477 params2string(params(), cur.bv().buffer()));
481 Inset::doDispatch(cur, cmd);
486 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
487 FuncStatus & flag) const
489 switch (cmd.action()) {
491 case LFUN_INSET_EDIT:
492 case LFUN_INSET_MODIFY:
493 case LFUN_INSET_DIALOG_UPDATE:
494 flag.setEnabled(true);
498 return Inset::getStatus(cur, cmd, flag);
503 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
506 DocIterator pit = cpit;
507 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
508 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
509 docstring str = screenLabel(params_, buffer());
510 toc->push_back(TocItem(pit, 0, str, output_active));
514 bool InsetExternal::showInsetDialog(BufferView * bv) const
516 bv->showDialog("external", params2string(params(), bv->buffer()),
517 const_cast<InsetExternal *>(this));
522 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
524 renderer_->metrics(mi, dim);
528 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
530 if (renderer_->asButton())
531 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
532 renderer_->draw(pi, x, y);
538 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
540 graphics::Params gparams;
542 gparams.filename = eparams.filename;
543 gparams.scale = eparams.lyxscale;
544 if (eparams.clipdata.clip)
545 gparams.bb = eparams.clipdata.bbox;
546 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
547 gparams.display = eparams.display;
555 static bool isPreviewWanted(InsetExternalParams const & params)
557 return params.display && params.filename.isReadableFile();
561 static docstring latexString(InsetExternal const & inset)
564 odocstringstream ods;
565 otexstream os(ods, texrow);
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)
734 otexstream ots(os, texrow);
735 ots << '\n'; // output external material on a new line
736 external::writeExternal(params_, "Ascii", buffer(), ots,
737 *(runparams.exportdata), false,
738 runparams.dryrun || runparams.inComment);
739 return PLAINTEXT_NEWLINE;
743 int InsetExternal::docbook(odocstream & os,
744 OutputParams const & runparams) const
747 odocstringstream ods;
748 otexstream ots(ods, texrow);
749 external::writeExternal(params_, "DocBook", buffer(), ots,
750 *(runparams.exportdata), false,
751 runparams.dryrun || runparams.inComment);
753 return int(count(ods.str().begin(), ods.str().end(), '\n'));
757 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
758 OutputParams const & /*rp*/) const
760 // external::writeExternal(params_, "XHTML", buffer(), os,
761 // *(runparams.exportdata), false,
762 // runparams.dryrun || runparams.inComment);
767 void InsetExternal::validate(LaTeXFeatures & features) const
772 external::Template const * const et_ptr =
773 external::getTemplatePtr(params_);
776 external::Template const & et = *et_ptr;
779 switch (features.runparams().flavor) {
780 case OutputParams::LATEX:
781 case OutputParams::DVILUATEX:
784 case OutputParams::LUATEX:
785 case OutputParams::PDFLATEX:
786 case OutputParams::XETEX:
789 case OutputParams::XML:
792 case OutputParams::HTML:
795 case OutputParams::TEXT:
798 case OutputParams::LYX:
802 external::Template::Formats::const_iterator cit =
803 et.formats.find(format);
805 if (cit == et.formats.end()) {
806 // If the template has not specified a PDFLaTeX output,
807 // we try the LaTeX format.
808 if (format == "PDFLaTeX") {
809 cit = et.formats.find("LaTeX");
810 if (cit == et.formats.end())
816 // FIXME: We don't need that always, see InsetGraphics
817 features.require("lyxdot");
819 vector<string>::const_iterator it = cit->second.requirements.begin();
820 vector<string>::const_iterator end = cit->second.requirements.end();
821 for (; it != end; ++it)
822 features.require(*it);
824 external::TemplateManager & etm = external::TemplateManager::get();
826 it = cit->second.preambleNames.begin();
827 end = cit->second.preambleNames.end();
828 for (; it != end; ++it) {
829 string const preamble = etm.getPreambleDefByName(*it);
830 if (!preamble.empty())
831 features.addPreambleSnippet(preamble);
836 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
837 graphics::PreviewLoader & ploader) const
839 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
843 if (isPreviewWanted(params())) {
844 ptr->setAbsFile(params_.filename);
845 docstring const snippet = latexString(*this);
846 ptr->addPreview(snippet, ploader);
851 string InsetExternal::contextMenuName() const
853 return "context-external";
857 void InsetExternal::string2params(string const & in, Buffer const & buffer,
858 InsetExternalParams & params)
860 params = InsetExternalParams();
864 istringstream data(in);
870 if (!lex || name != "external") {
871 LYXERR0("InsetExternal::string2params(" << in << ")\n"
872 "Expected arg 1 to be \"external\"\n");
876 // This is part of the inset proper that is usually swallowed
877 // by Text::readInset
880 if (!lex || id != "External") {
881 LYXERR0("InsetExternal::string2params(" << in << ")\n"
882 "Expected arg 2 to be \"External\"\n");
886 params.read(buffer, lex);
890 string InsetExternal::params2string(InsetExternalParams const & params,
891 Buffer const & buffer)
894 data << "external" << ' ';
895 params.write(buffer, data);
896 data << "\\end_inset\n";