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";
379 write(buffer, lyxerr);
388 docstring screenLabel(InsetExternalParams const & params,
389 Buffer const & buffer)
391 external::Template const * const ptr =
392 external::getTemplatePtr(params);
395 return bformat((_("External template %1$s is not installed")),
396 from_utf8(params.templatename()));
398 docstring gui = _(ptr->guiName);
401 if (params.filename.empty())
404 gui += from_utf8(params.filename.relFileName(buffer.filePath()));
413 InsetExternal::InsetExternal(Buffer * buf)
414 : Inset(buf), renderer_(new RenderButton)
419 // Mouse hover is not copied and remains empty
420 InsetExternal::InsetExternal(InsetExternal const & other)
422 boost::signals::trackable(),
423 params_(other.params_),
424 renderer_(other.renderer_->clone(this))
428 InsetExternal::~InsetExternal()
430 hideDialogs("external", this);
432 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
433 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
434 for (; it != end; ++it)
436 it->first->clearLastInset(this);
440 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover) const
442 mouse_hover_[bv] = mouse_hover;
447 void InsetExternal::statusChanged() const
453 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
455 switch (cmd.action()) {
457 case LFUN_INSET_EDIT: {
458 InsetExternalParams p = params();
459 if (!cmd.argument().empty())
460 string2params(to_utf8(cmd.argument()), buffer(), p);
461 external::editExternal(p, buffer());
465 case LFUN_INSET_MODIFY: {
466 InsetExternalParams p;
467 string2params(to_utf8(cmd.argument()), buffer(), p);
473 case LFUN_INSET_DIALOG_UPDATE:
474 cur.bv().updateDialog("external",
475 params2string(params(), cur.bv().buffer()));
479 Inset::doDispatch(cur, cmd);
484 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
485 FuncStatus & flag) const
487 switch (cmd.action()) {
489 case LFUN_INSET_EDIT:
490 case LFUN_INSET_MODIFY:
491 case LFUN_INSET_DIALOG_UPDATE:
492 flag.setEnabled(true);
496 return Inset::getStatus(cur, cmd, flag);
501 void InsetExternal::addToToc(DocIterator const & cpit, bool output_active,
504 DocIterator pit = cpit;
505 pit.push_back(CursorSlice(const_cast<InsetExternal &>(*this)));
506 shared_ptr<Toc> toc = buffer().tocBackend().toc("external");
507 docstring str = screenLabel(params_, buffer());
508 toc->push_back(TocItem(pit, 0, str, output_active));
512 bool InsetExternal::showInsetDialog(BufferView * bv) const
514 bv->showDialog("external", params2string(params(), bv->buffer()),
515 const_cast<InsetExternal *>(this));
520 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
522 renderer_->metrics(mi, dim);
526 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
528 if (renderer_->asButton())
529 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
530 renderer_->draw(pi, x, y);
536 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
538 graphics::Params gparams;
540 gparams.filename = eparams.filename;
541 gparams.scale = eparams.lyxscale;
542 if (eparams.clipdata.clip)
543 gparams.bb = eparams.clipdata.bbox;
544 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
545 gparams.display = eparams.display;
553 static bool isPreviewWanted(InsetExternalParams const & params)
555 return params.display && params.filename.isReadableFile();
559 static docstring latexString(InsetExternal const & inset)
562 odocstringstream ods;
563 otexstream os(ods, texrow);
564 // We don't need to set runparams.encoding since it is not used by
566 OutputParams runparams(0);
567 runparams.flavor = OutputParams::LATEX;
568 inset.latex(os, runparams);
573 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
574 InsetExternal const & inset,
575 Buffer const & buffer)
577 InsetExternalParams const & params = inset.params();
579 if (RenderPreview::previewText() && isPreviewWanted(params)) {
580 renderer.setAbsFile(params.filename);
581 docstring const snippet = latexString(inset);
582 renderer.addPreview(snippet, buffer);
583 renderer.startLoading(buffer);
588 InsetExternalParams const & InsetExternal::params() const
594 void InsetExternal::updatePreview()
600 void InsetExternal::setParams(InsetExternalParams const & p)
604 // Subsequent calls to the InsetExternal::Params default constructor
606 defaultTemplateName = params_.templatename();
608 if (!external::getTemplatePtr(params_) || params_.filename.empty()
610 || !lyxrc.display_graphics
611 || params_.preview_mode == PREVIEW_OFF
612 || (params_.preview_mode == PREVIEW_INSTANT
613 && !RenderPreview::previewText())) {
614 RenderButton * button_ptr = renderer_->asButton();
616 renderer_.reset(new RenderButton);
617 button_ptr = renderer_->asButton();
619 button_ptr->update(screenLabel(params_, buffer()), true);
623 switch (params_.preview_mode) {
625 // Already taken care of above.
626 LASSERT(false, return);
628 case PREVIEW_INSTANT: {
629 renderer_.reset(new RenderMonitoredPreview(this));
630 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
631 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
632 if (preview_ptr->monitoring())
633 preview_ptr->stopMonitoring();
634 add_preview_and_start_loading(*preview_ptr, *this, buffer());
637 case PREVIEW_GRAPHICS: {
638 RenderGraphic * graphic_ptr = renderer_->asGraphic();
640 renderer_.reset(new RenderGraphic(this));
641 graphic_ptr = renderer_->asGraphic();
643 graphic_ptr->update(get_grfx_params(params_));
650 void InsetExternal::fileChanged() const
652 Buffer const * const buffer = updateFrontend();
656 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
657 LASSERT(ptr, return);
659 ptr->removePreview(*buffer);
660 add_preview_and_start_loading(*ptr, *this, *buffer);
664 void InsetExternal::write(ostream & os) const
666 params_.write(buffer(), os);
670 void InsetExternal::read(Lexer & lex)
672 InsetExternalParams params;
673 if (params.read(buffer(), lex))
678 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
682 os << "\\fbox{\\ttfamily{}"
683 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
688 // "nice" means that the buffer is exported to LaTeX format but not
689 // run through the LaTeX compiler.
690 // If we're running through the LaTeX compiler, we should write the
691 // generated files in the buffer's temporary directory.
692 bool const external_in_tmpdir = !runparams.nice;
693 bool const dryrun = runparams.dryrun || runparams.inComment;
695 // If the template has specified a PDFLaTeX output, then we try and
697 if (runparams.flavor == OutputParams::PDFLATEX) {
698 external::Template const * const et_ptr =
699 external::getTemplatePtr(params_);
702 external::Template const & et = *et_ptr;
704 external::Template::Formats::const_iterator cit =
705 et.formats.find("PDFLaTeX");
707 if (cit != et.formats.end()) {
708 external::writeExternal(params_, "PDFLaTeX",
710 *(runparams.exportdata),
717 external::writeExternal(params_, "LaTeX", buffer(), os,
718 *(runparams.exportdata),
724 int InsetExternal::plaintext(odocstringstream & os,
725 OutputParams const & runparams, size_t) const
727 // this is too slow for constant use
728 if (runparams.for_tooltip)
732 otexstream ots(os, texrow);
733 ots << '\n'; // output external material on a new line
734 external::writeExternal(params_, "Ascii", buffer(), ots,
735 *(runparams.exportdata), false,
736 runparams.dryrun || runparams.inComment);
737 return PLAINTEXT_NEWLINE;
741 int InsetExternal::docbook(odocstream & os,
742 OutputParams const & runparams) const
745 odocstringstream ods;
746 otexstream ots(ods, texrow);
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";