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/convert.h"
40 #include "support/debug.h"
41 #include "support/ExceptionMessage.h"
42 #include "support/filetools.h"
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45 #include "support/lyxlib.h"
46 #include "support/Translator.h"
48 #include <boost/bind.hpp>
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 InsetExternal::InsetExternal(InsetExternal const & other)
376 boost::signals::trackable(),
377 params_(other.params_),
378 renderer_(other.renderer_->clone(this))
382 InsetExternal::~InsetExternal()
384 hideDialogs("external", this);
388 void InsetExternal::statusChanged() const
394 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
396 switch (cmd.action) {
398 case LFUN_INSET_EDIT: {
399 InsetExternalParams p = params();
400 if (!cmd.argument().empty())
401 string2params(to_utf8(cmd.argument()), buffer(), p);
402 external::editExternal(p, buffer());
406 case LFUN_INSET_MODIFY: {
407 InsetExternalParams p;
408 string2params(to_utf8(cmd.argument()), buffer(), p);
413 case LFUN_INSET_DIALOG_UPDATE:
414 cur.bv().updateDialog("external",
415 params2string(params(), cur.bv().buffer()));
419 Inset::doDispatch(cur, cmd);
424 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
425 FuncStatus & flag) const
427 switch (cmd.action) {
429 case LFUN_INSET_EDIT:
430 case LFUN_INSET_MODIFY:
431 case LFUN_INSET_DIALOG_UPDATE:
432 flag.setEnabled(true);
436 return Inset::getStatus(cur, cmd, flag);
441 bool InsetExternal::showInsetDialog(BufferView * bv) const
443 bv->showDialog("external", params2string(params(), bv->buffer()),
444 const_cast<InsetExternal *>(this));
449 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
451 renderer_->metrics(mi, dim);
455 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
457 renderer_->draw(pi, x, y);
463 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
465 graphics::Params gparams;
467 gparams.filename = eparams.filename;
468 gparams.scale = eparams.lyxscale;
469 if (eparams.clipdata.clip)
470 gparams.bb = eparams.clipdata.bbox;
471 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
472 gparams.display = eparams.display;
478 docstring screenLabel(InsetExternalParams const & params,
479 Buffer const & buffer)
481 external::Template const * const ptr =
482 external::getTemplatePtr(params);
485 return bformat((_("External template %1$s is not installed")),
486 from_utf8(params.templatename()));
488 docstring gui = _(ptr->guiName);
489 return from_utf8(external::doSubstitution(params, buffer,
490 to_utf8(gui), false));
496 static bool isPreviewWanted(InsetExternalParams const & params)
498 return params.display && params.filename.isReadableFile();
502 static docstring latexString(InsetExternal const & inset)
505 // We don't need to set runparams.encoding since it is not used by
507 OutputParams runparams(0);
508 runparams.flavor = OutputParams::LATEX;
509 inset.latex(os, runparams);
514 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
515 InsetExternal const & inset,
516 Buffer const & buffer)
518 InsetExternalParams const & params = inset.params();
520 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
521 isPreviewWanted(params)) {
522 renderer.setAbsFile(params.filename);
523 docstring const snippet = latexString(inset);
524 renderer.addPreview(snippet, buffer);
525 renderer.startLoading(buffer);
530 InsetExternalParams const & InsetExternal::params() const
536 void InsetExternal::updatePreview()
542 void InsetExternal::setParams(InsetExternalParams const & p)
546 // Subsequent calls to the InsetExternal::Params default constructor
548 defaultTemplateName = params_.templatename();
550 if (!external::getTemplatePtr(params_) || params_.filename.empty()
552 || !lyxrc.display_graphics
553 || params_.preview_mode == PREVIEW_OFF
554 || (params_.preview_mode == PREVIEW_INSTANT
555 && RenderPreview::status() == LyXRC::PREVIEW_OFF)) {
556 RenderButton * button_ptr = renderer_->asButton();
558 renderer_.reset(new RenderButton);
559 button_ptr = renderer_->asButton();
561 button_ptr->update(screenLabel(params_, buffer()), true);
565 switch (params_.preview_mode) {
567 // Already taken care of above.
568 LASSERT(false, return);
570 case PREVIEW_INSTANT: {
571 RenderMonitoredPreview * preview_ptr = renderer_->asMonitoredPreview();
572 renderer_.reset(new RenderMonitoredPreview(this));
573 preview_ptr = renderer_->asMonitoredPreview();
574 preview_ptr->fileChanged(boost::bind(&InsetExternal::fileChanged, this));
575 if (preview_ptr->monitoring())
576 preview_ptr->stopMonitoring();
577 add_preview_and_start_loading(*preview_ptr, *this, buffer());
580 case PREVIEW_GRAPHICS: {
581 RenderGraphic * graphic_ptr = renderer_->asGraphic();
583 renderer_.reset(new RenderGraphic(this));
584 graphic_ptr = renderer_->asGraphic();
586 graphic_ptr->update(get_grfx_params(params_));
593 void InsetExternal::fileChanged() const
595 Buffer const * const buffer = updateFrontend();
599 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
602 ptr->removePreview(*buffer);
603 add_preview_and_start_loading(*ptr, *this, *buffer);
607 void InsetExternal::write(ostream & os) const
609 params_.write(buffer(), os);
613 void InsetExternal::read(Lexer & lex)
615 InsetExternalParams params;
616 if (params.read(buffer(), lex))
621 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
625 os << "\\fbox{\\ttfamily{}"
626 << from_utf8(params_.filename.outputFilename(buffer().filePath()))
631 // "nice" means that the buffer is exported to LaTeX format but not
632 // run through the LaTeX compiler.
633 // If we're running through the LaTeX compiler, we should write the
634 // generated files in the buffer's temporary directory.
635 bool const external_in_tmpdir = !runparams.nice;
636 bool const dryrun = runparams.dryrun || runparams.inComment;
638 // If the template has specified a PDFLaTeX output, then we try and
640 if (runparams.flavor == OutputParams::PDFLATEX) {
641 external::Template const * const et_ptr =
642 external::getTemplatePtr(params_);
645 external::Template const & et = *et_ptr;
647 external::Template::Formats::const_iterator cit =
648 et.formats.find("PDFLaTeX");
650 if (cit != et.formats.end()) {
651 return external::writeExternal(params_, "PDFLaTeX",
653 *(runparams.exportdata),
659 return external::writeExternal(params_, "LaTeX", buffer(), os,
660 *(runparams.exportdata),
666 int InsetExternal::plaintext(odocstream & os,
667 OutputParams const & runparams) const
669 os << '\n'; // output external material on a new line
670 external::writeExternal(params_, "Ascii", buffer(), os,
671 *(runparams.exportdata), false,
672 runparams.dryrun || runparams.inComment);
673 return PLAINTEXT_NEWLINE;
677 int InsetExternal::docbook(odocstream & os,
678 OutputParams const & runparams) const
680 return external::writeExternal(params_, "DocBook", buffer(), os,
681 *(runparams.exportdata), false,
682 runparams.dryrun || runparams.inComment);
686 docstring InsetExternal::xhtml(XHTMLStream & /*xs*/,
687 OutputParams const & /*rp*/) const
689 // external::writeExternal(params_, "XHTML", buffer(), os,
690 // *(runparams.exportdata), false,
691 // runparams.dryrun || runparams.inComment);
696 void InsetExternal::validate(LaTeXFeatures & features) const
701 external::Template const * const et_ptr =
702 external::getTemplatePtr(params_);
705 external::Template const & et = *et_ptr;
708 switch (features.runparams().flavor) {
709 case OutputParams::LATEX:
712 case OutputParams::PDFLATEX:
713 case OutputParams::XETEX:
716 case OutputParams::XML:
719 case OutputParams::HTML:
722 case OutputParams::TEXT:
726 external::Template::Formats::const_iterator cit =
727 et.formats.find(format);
729 if (cit == et.formats.end()) {
730 // If the template has not specified a PDFLaTeX output,
731 // we try the LaTeX format.
732 if (format == "PDFLaTeX") {
733 cit = et.formats.find("LaTeX");
734 if (cit == et.formats.end())
740 // FIXME: We don't need that always
741 features.require("lyxdot");
743 vector<string>::const_iterator it = cit->second.requirements.begin();
744 vector<string>::const_iterator end = cit->second.requirements.end();
745 for (; it != end; ++it)
746 features.require(*it);
748 external::TemplateManager & etm = external::TemplateManager::get();
750 it = cit->second.preambleNames.begin();
751 end = cit->second.preambleNames.end();
752 for (; it != end; ++it) {
753 string const preamble = etm.getPreambleDefByName(*it);
754 if (!preamble.empty())
755 features.addPreambleSnippet(preamble);
760 void InsetExternal::addPreview(DocIterator const & /*inset_pos*/,
761 graphics::PreviewLoader & ploader) const
763 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
767 if (isPreviewWanted(params())) {
768 ptr->setAbsFile(params_.filename);
769 docstring const snippet = latexString(*this);
770 ptr->addPreview(snippet, ploader);
775 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
777 return from_ascii("context-external");
781 void InsetExternal::string2params(string const & in, Buffer const & buffer,
782 InsetExternalParams & params)
784 params = InsetExternalParams();
788 istringstream data(in);
794 if (!lex || name != "external") {
795 LYXERR0("InsetExternal::string2params(" << in << ")\n"
796 "Expected arg 1 to be \"external\"\n");
800 // This is part of the inset proper that is usually swallowed
801 // by Text::readInset
804 if (!lex || id != "External") {
805 LYXERR0("InsetExternal::string2params(" << in << ")\n"
806 "Expected arg 2 to be \"External\"\n");
810 params.read(buffer, lex);
814 string InsetExternal::params2string(InsetExternalParams const & params,
815 Buffer const & buffer)
818 data << "external" << ' ';
819 params.write(buffer, data);
820 data << "\\end_inset\n";