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"
34 #include "frontends/alert.h"
35 #include "frontends/Application.h"
37 #include "graphics/PreviewLoader.h"
39 #include "support/bind.h"
40 #include "support/convert.h"
41 #include "support/debug.h"
42 #include "support/ExceptionMessage.h"
43 #include "support/filetools.h"
44 #include "support/gettext.h"
45 #include "support/lassert.h"
46 #include "support/lstrings.h"
47 #include "support/lyxlib.h"
53 using namespace lyx::support;
57 unsigned int const defaultLyxScale = 100;
59 string defaultTemplateName;
66 namespace Alert = frontend::Alert;
72 FileName const tempname = FileName::tempName("lyxext");
73 // must have an extension for the converter code to work correctly.
74 tempname_ = FileName(tempname.absFileName() + ".tmp");
78 TempName::TempName(TempName const &)
80 tempname_ = TempName()();
86 tempname_.removeFile();
90 TempName & TempName::operator=(TempName const & other)
93 tempname_ = TempName()();
97 } // namespace external
100 InsetExternalParams::InsetExternalParams()
102 lyxscale(defaultLyxScale),
105 if (defaultTemplateName.empty()) {
106 external::TemplateManager const & etm =
107 external::TemplateManager::get();
108 if (!etm.getTemplates().empty())
109 templatename_ = etm.getTemplates().begin()->first;
111 templatename_ = defaultTemplateName;
117 template <typename T>
118 void clearIfNotFound(T & data, external::TransformID value,
119 vector<external::TransformID> const & ids)
121 typedef vector<external::TransformID>::const_iterator
124 const_iterator it = ids.begin();
125 const_iterator end = ids.end();
126 it = find(it, end, value);
134 void InsetExternalParams::settemplate(string const & name)
136 templatename_ = name;
138 external::TemplateManager const & etm =
139 external::TemplateManager::get();
140 external::Template const * const et = etm.getTemplateByName(name);
142 // Be safe. Don't lose data.
145 // Ascertain which transforms the template supports.
146 // Empty all those that it doesn't.
147 vector<external::TransformID> const & ids = et->transformIds;
148 clearIfNotFound(clipdata, external::Clip, ids);
149 clearIfNotFound(extradata, external::Extra, ids);
150 clearIfNotFound(resizedata, external::Resize, ids);
151 clearIfNotFound(rotationdata, external::Rotate, ids);
154 preview_mode = et->preview_mode;
158 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
161 << "\ttemplate " << templatename() << '\n';
163 if (!filename.empty())
164 os << "\tfilename " << filename.outputFileName(buf.filePath()) << '\n';
167 os << "\tdisplay false\n";
169 if (lyxscale != defaultLyxScale)
170 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
175 if (!clipdata.bbox.empty())
176 os << "\tboundingBox " << clipdata.bbox << '\n';
180 external::ExtraData::const_iterator it = extradata.begin();
181 external::ExtraData::const_iterator end = extradata.end();
182 for (; it != end; ++it) {
183 if (!it->second.empty())
184 os << "\textra " << it->first << " \""
185 << it->second << "\"\n";
188 if (!rotationdata.no_rotation()) {
189 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
190 if (rotationdata.origin() != external::RotationData::DEFAULT)
191 os << "\trotateOrigin "
192 << rotationdata.originString() << '\n';
195 if (!resizedata.no_resize()) {
196 double const scl = convert<double>(resizedata.scale);
197 if (!float_equal(scl, 0.0, 0.05)) {
198 if (!float_equal(scl, 100.0, 0.05))
200 << resizedata.scale << '\n';
202 if (!resizedata.width.zero())
204 << resizedata.width.asString() << '\n';
205 if (!resizedata.height.zero())
207 << resizedata.height.asString() << '\n';
209 if (resizedata.keepAspectRatio)
210 os << "\tkeepAspectRatio\n";
215 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
235 LexerKeyword external_tags[] = {
236 { "\\end_inset", EX_END },
237 { "boundingBox", EX_BOUNDINGBOX },
239 { "display", EX_DISPLAY},
240 { "draft", EX_DRAFT},
241 { "extra", EX_EXTRA },
242 { "filename", EX_FILENAME},
243 { "height", EX_HEIGHT },
244 { "keepAspectRatio", EX_KEEPASPECTRATIO },
245 { "lyxscale", EX_LYXSCALE},
246 { "rotateAngle", EX_ROTATEANGLE },
247 { "rotateOrigin", EX_ROTATEORIGIN },
248 { "scale", EX_SCALE },
249 { "template", EX_TEMPLATE },
250 { "width", EX_WIDTH }
253 PushPopHelper pph(lex, external_tags);
255 bool found_end = false;
256 bool read_error = false;
262 templatename_ = lex.getString();
267 string const name = lex.getString();
268 filename.set(name, buffer.filePath());
274 display = lex.getString() != "false";
280 lyxscale = lex.getInteger();
289 clipdata.bbox.xl = lex.getInteger();
291 clipdata.bbox.yb = lex.getInteger();
293 clipdata.bbox.xr = lex.getInteger();
295 clipdata.bbox.yt = lex.getInteger();
299 clipdata.clip = true;
304 string const name = lex.getString();
306 extradata.set(name, lex.getString());
312 resizedata.height = Length(lex.getString());
315 case EX_KEEPASPECTRATIO:
316 resizedata.keepAspectRatio = true;
321 rotationdata.angle = lex.getString();
324 case EX_ROTATEORIGIN:
326 rotationdata.origin(lex.getString());
331 resizedata.scale = lex.getString();
336 resizedata.width = Length(lex.getString());
344 lex.printError("ExternalInset::read: Wrong tag: $$Token");
349 if (found_end || read_error)
354 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
356 // This is a trick to make sure that the data are self-consistent.
357 settemplate(templatename_);
359 if (lyxerr.debugging(Debug::EXTERNAL)) {
360 lyxerr << "InsetExternalParams::read:\n";
361 write(buffer, lyxerr);
368 InsetExternal::InsetExternal(Buffer * buf)
369 : Inset(buf), renderer_(new RenderButton)
374 // Mouse hover is not copied and remains empty
375 InsetExternal::InsetExternal(InsetExternal const & other)
377 boost::signals::trackable(),
378 params_(other.params_),
379 renderer_(other.renderer_->clone(this))
383 InsetExternal::~InsetExternal()
385 hideDialogs("external", this);
387 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
388 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
389 for (; it != end; ++it)
391 it->first->clearLastInset(this);
395 bool InsetExternal::setMouseHover(BufferView const * bv, bool mouse_hover)
397 mouse_hover_[bv] = mouse_hover;
402 void InsetExternal::statusChanged() const
408 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
410 switch (cmd.action()) {
412 case LFUN_INSET_EDIT: {
413 InsetExternalParams p = params();
414 if (!cmd.argument().empty())
415 string2params(to_utf8(cmd.argument()), buffer(), p);
416 external::editExternal(p, buffer());
420 case LFUN_INSET_MODIFY: {
421 InsetExternalParams p;
422 string2params(to_utf8(cmd.argument()), buffer(), p);
428 case LFUN_INSET_DIALOG_UPDATE:
429 cur.bv().updateDialog("external",
430 params2string(params(), cur.bv().buffer()));
434 Inset::doDispatch(cur, cmd);
439 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
440 FuncStatus & flag) const
442 switch (cmd.action()) {
444 case LFUN_INSET_EDIT:
445 case LFUN_INSET_MODIFY:
446 case LFUN_INSET_DIALOG_UPDATE:
447 flag.setEnabled(true);
451 return Inset::getStatus(cur, cmd, flag);
456 bool InsetExternal::showInsetDialog(BufferView * bv) const
458 bv->showDialog("external", params2string(params(), bv->buffer()),
459 const_cast<InsetExternal *>(this));
464 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
466 renderer_->metrics(mi, dim);
470 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
472 if (renderer_->asButton())
473 renderer_->setRenderState(mouse_hover_[pi.base.bv]);
474 renderer_->draw(pi, x, y);
480 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
482 graphics::Params gparams;
484 gparams.filename = eparams.filename;
485 gparams.scale = eparams.lyxscale;
486 if (eparams.clipdata.clip)
487 gparams.bb = eparams.clipdata.bbox;
488 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
489 gparams.display = eparams.display;
495 docstring screenLabel(InsetExternalParams const & params,
496 Buffer const & buffer)
498 external::Template const * const ptr =
499 external::getTemplatePtr(params);
502 return bformat((_("External template %1$s is not installed")),
503 from_utf8(params.templatename()));
505 docstring gui = _(ptr->guiName);
506 return from_utf8(external::doSubstitution(params, buffer,
507 to_utf8(gui), false));
513 static bool isPreviewWanted(InsetExternalParams const & params)
515 return params.display && params.filename.isReadableFile();
519 static docstring latexString(InsetExternal const & inset)
522 odocstringstream ods;
523 otexstream os(ods, texrow);
524 // We don't need to set runparams.encoding since it is not used by
526 OutputParams runparams(0);
527 runparams.flavor = OutputParams::LATEX;
528 inset.latex(os, runparams);
533 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
534 InsetExternal const & inset,
535 Buffer const & buffer)
537 InsetExternalParams const & params = inset.params();
539 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
540 isPreviewWanted(params)) {
541 renderer.setAbsFile(params.filename);
542 docstring const snippet = latexString(inset);
543 renderer.addPreview(snippet, buffer);
544 renderer.startLoading(buffer);
549 InsetExternalParams const & InsetExternal::params() const
555 void InsetExternal::updatePreview()
561 void InsetExternal::setParams(InsetExternalParams const & p)
565 // Subsequent calls to the InsetExternal::Params default constructor
567 defaultTemplateName = params_.templatename();
569 if (!external::getTemplatePtr(params_) || params_.filename.empty()
571 || !lyxrc.display_graphics
572 || params_.preview_mode == PREVIEW_OFF
573 || (params_.preview_mode == PREVIEW_INSTANT
574 && RenderPreview::status() == LyXRC::PREVIEW_OFF)) {
575 RenderButton * button_ptr = renderer_->asButton();
577 renderer_.reset(new RenderButton);
578 button_ptr = renderer_->asButton();
580 button_ptr->update(screenLabel(params_, buffer()), true);
584 switch (params_.preview_mode) {
586 // Already taken care of above.
587 LASSERT(false, return);
589 case PREVIEW_INSTANT: {
590 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
591 renderer_.reset(new RenderMonitoredPreview(this));
592 preview_ptr = renderer_->asMonitoredPreview();
593 preview_ptr->fileChanged(bind(&InsetExternal::fileChanged, this));
594 if (preview_ptr->monitoring())
595 preview_ptr->stopMonitoring();
596 add_preview_and_start_loading(*preview_ptr, *this, buffer());
599 case PREVIEW_GRAPHICS: {
600 RenderGraphic * graphic_ptr = renderer_->asGraphic();
602 renderer_.reset(new RenderGraphic(this));
603 graphic_ptr = renderer_->asGraphic();
605 graphic_ptr->update(get_grfx_params(params_));
612 void InsetExternal::fileChanged() const
614 Buffer const * const buffer = updateFrontend();
618 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
621 ptr->removePreview(*buffer);
622 add_preview_and_start_loading(*ptr, *this, *buffer);
626 void InsetExternal::write(ostream & os) const
628 params_.write(buffer(), os);
632 void InsetExternal::read(Lexer & lex)
634 InsetExternalParams params;
635 if (params.read(buffer(), lex))
640 void InsetExternal::latex(otexstream & os, OutputParams const & runparams) const
644 os << "\\fbox{\\ttfamily{}"
645 << from_utf8(params_.filename.outputFileName(buffer().filePath()))
650 // "nice" means that the buffer is exported to LaTeX format but not
651 // run through the LaTeX compiler.
652 // If we're running through the LaTeX compiler, we should write the
653 // generated files in the buffer's temporary directory.
654 bool const external_in_tmpdir = !runparams.nice;
655 bool const dryrun = runparams.dryrun || runparams.inComment;
657 // If the template has specified a PDFLaTeX output, then we try and
659 if (runparams.flavor == OutputParams::PDFLATEX) {
660 external::Template const * const et_ptr =
661 external::getTemplatePtr(params_);
664 external::Template const & et = *et_ptr;
666 external::Template::Formats::const_iterator cit =
667 et.formats.find("PDFLaTeX");
669 if (cit != et.formats.end()) {
670 int l = external::writeExternal(params_, "PDFLaTeX",
672 *(runparams.exportdata),
675 os.texrow().newlines(l);
680 int l = external::writeExternal(params_, "LaTeX", buffer(), os.os(),
681 *(runparams.exportdata),
684 os.texrow().newlines(l);
688 int InsetExternal::plaintext(odocstream & os,
689 OutputParams const & runparams) const
691 os << '\n'; // output external material on a new line
692 external::writeExternal(params_, "Ascii", buffer(), os,
693 *(runparams.exportdata), false,
694 runparams.dryrun || runparams.inComment);
695 return PLAINTEXT_NEWLINE;
699 int InsetExternal::docbook(odocstream & os,
700 OutputParams const & runparams) const
702 return external::writeExternal(params_, "DocBook", buffer(), os,
703 *(runparams.exportdata), false,
704 runparams.dryrun || runparams.inComment);
708 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
709 OutputParams const & /*rp*/) const
711 // external::writeExternal(params_, "XHTML", buffer(), os,
712 // *(runparams.exportdata), false,
713 // runparams.dryrun || runparams.inComment);
718 void InsetExternal::validate(LaTeXFeatures & features) const
723 external::Template const * const et_ptr =
724 external::getTemplatePtr(params_);
727 external::Template const & et = *et_ptr;
730 switch (features.runparams().flavor) {
731 case OutputParams::LATEX:
732 case OutputParams::DVILUATEX:
735 case OutputParams::LUATEX:
736 case OutputParams::PDFLATEX:
737 case OutputParams::XETEX:
740 case OutputParams::XML:
743 case OutputParams::HTML:
746 case OutputParams::TEXT:
750 external::Template::Formats::const_iterator cit =
751 et.formats.find(format);
753 if (cit == et.formats.end()) {
754 // If the template has not specified a PDFLaTeX output,
755 // we try the LaTeX format.
756 if (format == "PDFLaTeX") {
757 cit = et.formats.find("LaTeX");
758 if (cit == et.formats.end())
764 // FIXME: We don't need that always
765 features.require("lyxdot");
767 vector<string>::const_iterator it = cit->second.requirements.begin();
768 vector<string>::const_iterator end = cit->second.requirements.end();
769 for (; it != end; ++it)
770 features.require(*it);
772 external::TemplateManager & etm = external::TemplateManager::get();
774 it = cit->second.preambleNames.begin();
775 end = cit->second.preambleNames.end();
776 for (; it != end; ++it) {
777 string const preamble = etm.getPreambleDefByName(*it);
778 if (!preamble.empty())
779 features.addPreambleSnippet(preamble);
784 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
785 graphics::PreviewLoader & ploader) const
787 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
791 if (isPreviewWanted(params())) {
792 ptr->setAbsFile(params_.filename);
793 docstring const snippet = latexString(*this);
794 ptr->addPreview(snippet, ploader);
799 docstring InsetExternal::contextMenuName() const
801 return from_ascii("context-external");
805 void InsetExternal::string2params(string const & in, Buffer const & buffer,
806 InsetExternalParams & params)
808 params = InsetExternalParams();
812 istringstream data(in);
818 if (!lex || name != "external") {
819 LYXERR0("InsetExternal::string2params(" << in << ")\n"
820 "Expected arg 1 to be \"external\"\n");
824 // This is part of the inset proper that is usually swallowed
825 // by Text::readInset
828 if (!lex || id != "External") {
829 LYXERR0("InsetExternal::string2params(" << in << ")\n"
830 "Expected arg 2 to be \"External\"\n");
834 params.read(buffer, lex);
838 string InsetExternal::params2string(InsetExternalParams const & params,
839 Buffer const & buffer)
842 data << "external" << ' ';
843 params.write(buffer, data);
844 data << "\\end_inset\n";