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;
72 TempName::TempName() : tempfile_(new support::TempFile("lyxextXXXXXX.tmp"))
74 // must have an extension for the converter code to work correctly.
78 TempName::TempName(TempName const & that) : tempfile_(0)
90 TempName & TempName::operator=(TempName const & other)
94 tempfile_ = new support::TempFile("lyxextXXXXXX.tmp");
100 support::FileName TempName::operator()() const
102 return tempfile_->name();
105 } // namespace external
108 InsetExternalParams::InsetExternalParams()
110 lyxscale(defaultLyxScale),
113 if (defaultTemplateName.empty()) {
114 external::TemplateManager const & etm =
115 external::TemplateManager::get();
116 if (!etm.getTemplates().empty())
117 templatename_ = etm.getTemplates().begin()->first;
119 templatename_ = defaultTemplateName;
125 template <typename T>
126 void clearIfNotFound(T & data, external::TransformID value,
127 vector<external::TransformID> const & ids)
129 typedef vector<external::TransformID>::const_iterator
132 const_iterator it = ids.begin();
133 const_iterator end = ids.end();
134 it = find(it, end, value);
142 void InsetExternalParams::settemplate(string const & name)
144 templatename_ = name;
146 external::TemplateManager const & etm =
147 external::TemplateManager::get();
148 external::Template const * const et = etm.getTemplateByName(name);
150 // Be safe. Don't lose data.
153 // Ascertain which transforms the template supports.
154 // Empty all those that it doesn't.
155 vector<external::TransformID> const & ids = et->transformIds;
156 clearIfNotFound(clipdata, external::Clip, ids);
157 clearIfNotFound(extradata, external::Extra, ids);
158 clearIfNotFound(resizedata, external::Resize, ids);
159 clearIfNotFound(rotationdata, external::Rotate, ids);
162 preview_mode = et->preview_mode;
166 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
169 << "\ttemplate " << templatename() << '\n';
171 if (!filename.empty())
172 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
175 os << "\tdisplay false\n";
177 if (lyxscale != defaultLyxScale)
178 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
183 if (!clipdata.bbox.empty())
184 os << "\tboundingBox " << clipdata.bbox << '\n';
188 external::ExtraData::const_iterator it = extradata.begin();
189 external::ExtraData::const_iterator end = extradata.end();
190 for (; it != end; ++it) {
191 if (!it->second.empty())
192 os << "\textra " << it->first << " \""
193 << it->second << "\"\n";
196 if (!rotationdata.no_rotation()) {
197 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
198 if (rotationdata.origin() != external::RotationData::DEFAULT)
199 os << "\trotateOrigin "
200 << rotationdata.originString() << '\n';
203 if (!resizedata.no_resize()) {
204 double const scl = convert<double>(resizedata.scale);
205 if (!float_equal(scl, 0.0, 0.05)) {
206 if (!float_equal(scl, 100.0, 0.05))
208 << resizedata.scale << '\n';
210 if (!resizedata.width.zero())
212 << resizedata.width.asString() << '\n';
213 if (!resizedata.height.zero())
215 << resizedata.height.asString() << '\n';
217 if (resizedata.keepAspectRatio)
218 os << "\tkeepAspectRatio\n";
223 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
243 LexerKeyword external_tags[] = {
244 { "\\end_inset", EX_END },
245 { "boundingBox", EX_BOUNDINGBOX },
247 { "display", EX_DISPLAY},
248 { "draft", EX_DRAFT},
249 { "extra", EX_EXTRA },
250 { "filename", EX_FILENAME},
251 { "height", EX_HEIGHT },
252 { "keepAspectRatio", EX_KEEPASPECTRATIO },
253 { "lyxscale", EX_LYXSCALE},
254 { "rotateAngle", EX_ROTATEANGLE },
255 { "rotateOrigin", EX_ROTATEORIGIN },
256 { "scale", EX_SCALE },
257 { "template", EX_TEMPLATE },
258 { "width", EX_WIDTH }
261 PushPopHelper pph(lex, external_tags);
263 bool found_end = false;
264 bool read_error = false;
270 templatename_ = lex.getString();
275 string const name = lex.getString();
276 filename.set(name, buffer.originFilePath());
282 display = lex.getString() != "false";
288 lyxscale = lex.getInteger();
297 clipdata.bbox.xl = Length(lex.getString());
299 clipdata.bbox.yb = Length(lex.getString());
301 clipdata.bbox.xr = Length(lex.getString());
303 clipdata.bbox.yt = Length(lex.getString());
307 clipdata.clip = true;
312 string const name = lex.getString();
314 extradata.set(name, lex.getString());
320 resizedata.height = Length(lex.getString());
323 case EX_KEEPASPECTRATIO:
324 resizedata.keepAspectRatio = true;
329 rotationdata.angle = lex.getString();
332 case EX_ROTATEORIGIN:
334 rotationdata.origin(lex.getString());
339 resizedata.scale = lex.getString();
344 resizedata.width = Length(lex.getString());
352 lex.printError("ExternalInset::read: Wrong tag: $$Token");
357 if (found_end || read_error)
362 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
364 // This is a trick to make sure that the data are self-consistent.
365 settemplate(templatename_);
367 if (lyxerr.debugging(Debug::EXTERNAL)) {
368 lyxerr << "InsetExternalParams::read:\n";
369 write(buffer, lyxerr);
378 docstring screenLabel(InsetExternalParams const & params,
379 Buffer const & buffer)
381 external::Template const * const ptr =
382 external::getTemplatePtr(params);
385 return bformat((_("External template %1$s is not installed")),
386 from_utf8(params.templatename()));
388 docstring gui = _(ptr->guiName);
391 if (params.filename.empty())
394 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
403 InsetExternal::InsetExternal(Buffer * buf)
404 : Inset(buf), renderer_(new RenderButton)
409 // Mouse hover is not copied and remains empty
410 InsetExternal::InsetExternal(InsetExternal const & other)
412 boost::signals::trackable(),
413 params_(other.params_),
414 renderer_(other.renderer_->clone(this))
418 InsetExternal::~InsetExternal()
420 hideDialogs("external", this);
422 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
423 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
424 for (; it != end; ++it)
426 it->first->clearLastInset(this);
430 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
432 mouse_hover_[bv] = mouse_hover;
437 void InsetExternal::statusChanged() const
443 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
445 switch (cmd.action()) {
447 case LFUN_INSET_EDIT: {
448 InsetExternalParams p = params();
449 if (!cmd.argument().empty())
450 string2params(to_utf8(cmd.argument()), buffer(), p);
451 external::editExternal(p, buffer());
455 case LFUN_INSET_MODIFY: {
456 InsetExternalParams p;
457 string2params(to_utf8(cmd.argument()), buffer(), p);
463 case LFUN_INSET_DIALOG_UPDATE:
464 cur.bv().updateDialog("external",
465 params2string(params(), cur.bv().buffer()));
469 Inset::doDispatch(cur, cmd);
474 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
475 FuncStatus & flag) const
477 switch (cmd.action()) {
479 case LFUN_INSET_EDIT:
480 case LFUN_INSET_MODIFY:
481 case LFUN_INSET_DIALOG_UPDATE:
482 flag.setEnabled(true);
486 return Inset::getStatus(cur, cmd, flag);
491 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
494 DocIterator pit = cpit;
495 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
496 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
497 docstring str = screenLabel(params_, buffer());
498 toc->push_back(TocItem(pit, 0, str, output_active));
502 bool InsetExternal::showInsetDialog(BufferView * bv) const
504 bv->showDialog("external", params2string(params(), bv->buffer()),
505 const_cast<InsetExternal *>(this));
510 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
512 renderer_->metrics(mi, dim);
516 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
518 if (renderer_->asButton())
519 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
520 renderer_->draw(pi, x, y);
526 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
528 graphics::Params gparams;
530 gparams.filename = eparams.filename;
531 gparams.scale = eparams.lyxscale;
532 if (eparams.clipdata.clip)
533 gparams.bb = eparams.clipdata.bbox;
534 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
535 gparams.display = eparams.display;
543 static bool isPreviewWanted(InsetExternalParams const & params)
545 return params.display && params.filename.isReadableFile();
549 static docstring latexString(InsetExternal const & inset)
552 odocstringstream ods;
553 otexstream os(ods, texrow);
554 // We don't need to set runparams.encoding since it is not used by
556 OutputParams runparams(0);
557 runparams.flavor = OutputParams::LATEX;
558 inset.latex(os, runparams);
563 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
564 InsetExternal const & inset,
565 Buffer const & buffer)
567 InsetExternalParams const & params = inset.params();
569 if (RenderPreview::previewText() && isPreviewWanted(params)) {
570 renderer.setAbsFile(params.filename);
571 docstring const snippet = latexString(inset);
572 renderer.addPreview(snippet, buffer);
573 renderer.startLoading(buffer);
578 InsetExternalParams const & InsetExternal::params() const
584 void InsetExternal::updatePreview()
590 void InsetExternal::setParams(InsetExternalParams const & p)
594 // Subsequent calls to the InsetExternal::Params default constructor
596 defaultTemplateName = params_.templatename();
598 if (!external::getTemplatePtr(params_) || params_.filename.empty()
600 || !lyxrc.display_graphics
601 || params_.preview_mode == PREVIEW_OFF
602 || (params_.preview_mode == PREVIEW_INSTANT
603 && !RenderPreview::previewText())) {
604 RenderButton * button_ptr = renderer_->asButton();
606 renderer_.reset(new RenderButton);
607 button_ptr = renderer_->asButton();
609 button_ptr->update(screenLabel(params_, buffer()), true);
613 switch (params_.preview_mode) {
615 // Already taken care of above.
616 LASSERT(false, return);
618 case PREVIEW_INSTANT: {
619 //FIXME: why is the value below immediately forgotten?
620 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
621 renderer_.reset(new RenderMonitoredPreview(this));
622 preview_ptr = renderer_->asMonitoredPreview();
623 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
624 if (preview_ptr->monitoring())
625 preview_ptr->stopMonitoring();
626 add_preview_and_start_loading(*preview_ptr, *this, buffer());
629 case PREVIEW_GRAPHICS: {
630 RenderGraphic * graphic_ptr = renderer_->asGraphic();
632 renderer_.reset(new RenderGraphic(this));
633 graphic_ptr = renderer_->asGraphic();
635 graphic_ptr->update(get_grfx_params(params_));
642 void InsetExternal::fileChanged() const
644 Buffer const * const buffer = updateFrontend();
648 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
649 LASSERT(ptr, return);
651 ptr->removePreview(*buffer);
652 add_preview_and_start_loading(*ptr, *this, *buffer);
656 void InsetExternal::write(ostream & os) const
658 params_.write(buffer(), os);
662 void InsetExternal::read(Lexer & lex)
664 InsetExternalParams params;
665 if (params.read(buffer(), lex))
670 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
674 os << "\\fbox{\\ttfamily{}"
675 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
680 // "nice" means that the buffer is exported to LaTeX format but not
681 // run through the LaTeX compiler.
682 // If we're running through the LaTeX compiler, we should write the
683 // generated files in the buffer's temporary directory.
684 bool const external_in_tmpdir = !runparams.nice;
685 bool const dryrun = runparams.dryrun || runparams.inComment;
687 // If the template has specified a PDFLaTeX output, then we try and
689 if (runparams.flavor == OutputParams::PDFLATEX) {
690 external::Template const * const et_ptr =
691 external::getTemplatePtr(params_);
694 external::Template const & et = *et_ptr;
696 external::Template::Formats::const_iterator cit =
697 et.formats.find("PDFLaTeX");
699 if (cit != et.formats.end()) {
700 external::writeExternal(params_, "PDFLaTeX",
702 *(runparams.exportdata),
709 external::writeExternal(params_, "LaTeX", buffer(), os,
710 *(runparams.exportdata),
716 int InsetExternal::plaintext(odocstringstream & os,
717 OutputParams const & runparams, size_t) const
719 // this is too slow for constant use
720 if (runparams.for_tooltip)
724 otexstream ots(os, texrow);
725 ots << '\n'; // output external material on a new line
726 external::writeExternal(params_, "Ascii", buffer(), ots,
727 *(runparams.exportdata), false,
728 runparams.dryrun || runparams.inComment);
729 return PLAINTEXT_NEWLINE;
733 int InsetExternal::docbook(odocstream & os,
734 OutputParams const & runparams) const
737 odocstringstream ods;
738 otexstream ots(ods, texrow);
739 external::writeExternal(params_, "DocBook", buffer(), ots,
740 *(runparams.exportdata), false,
741 runparams.dryrun || runparams.inComment);
743 return int(count(ods.str().begin(), ods.str().end(), '\n'));
747 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
748 OutputParams const & /*rp*/) const
750 // external::writeExternal(params_, "XHTML", buffer(), os,
751 // *(runparams.exportdata), false,
752 // runparams.dryrun || runparams.inComment);
757 void InsetExternal::validate(LaTeXFeatures & features) const
762 external::Template const * const et_ptr =
763 external::getTemplatePtr(params_);
766 external::Template const & et = *et_ptr;
769 switch (features.runparams().flavor) {
770 case OutputParams::LATEX:
771 case OutputParams::DVILUATEX:
774 case OutputParams::LUATEX:
775 case OutputParams::PDFLATEX:
776 case OutputParams::XETEX:
779 case OutputParams::XML:
782 case OutputParams::HTML:
785 case OutputParams::TEXT:
788 case OutputParams::LYX:
792 external::Template::Formats::const_iterator cit =
793 et.formats.find(format);
795 if (cit == et.formats.end()) {
796 // If the template has not specified a PDFLaTeX output,
797 // we try the LaTeX format.
798 if (format == "PDFLaTeX") {
799 cit = et.formats.find("LaTeX");
800 if (cit == et.formats.end())
806 // FIXME: We don't need that always, see InsetGraphics
807 features.require("lyxdot");
809 vector<string>::const_iterator it = cit->second.requirements.begin();
810 vector<string>::const_iterator end = cit->second.requirements.end();
811 for (; it != end; ++it)
812 features.require(*it);
814 external::TemplateManager & etm = external::TemplateManager::get();
816 it = cit->second.preambleNames.begin();
817 end = cit->second.preambleNames.end();
818 for (; it != end; ++it) {
819 string const preamble = etm.getPreambleDefByName(*it);
820 if (!preamble.empty())
821 features.addPreambleSnippet(preamble);
826 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
827 graphics::PreviewLoader & ploader) const
829 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
833 if (isPreviewWanted(params())) {
834 ptr->setAbsFile(params_.filename);
835 docstring const snippet = latexString(*this);
836 ptr->addPreview(snippet, ploader);
841 string InsetExternal::contextMenuName() const
843 return "context-external";
847 void InsetExternal::string2params(string const & in, Buffer const & buffer,
848 InsetExternalParams & params)
850 params = InsetExternalParams();
854 istringstream data(in);
860 if (!lex || name != "external") {
861 LYXERR0("InsetExternal::string2params(" << in << ")\n"
862 "Expected arg 1 to be \"external\"\n");
866 // This is part of the inset proper that is usually swallowed
867 // by Text::readInset
870 if (!lex || id != "External") {
871 LYXERR0("InsetExternal::string2params(" << in << ")\n"
872 "Expected arg 2 to be \"External\"\n");
876 params.read(buffer, lex);
880 string InsetExternal::params2string(InsetExternalParams const & params,
881 Buffer const & buffer)
884 data << "external" << ' ';
885 params.write(buffer, data);
886 data << "\\end_inset\n";