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"
33 #include "frontends/alert.h"
34 #include "frontends/Application.h"
36 #include "graphics/PreviewLoader.h"
38 #include "support/convert.h"
39 #include "support/debug.h"
40 #include "support/ExceptionMessage.h"
41 #include "support/filetools.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/lyxlib.h"
45 #include "support/Translator.h"
47 #include <boost/bind.hpp>
52 using namespace lyx::support;
56 unsigned int const defaultLyxScale = 100;
58 string defaultTemplateName;
65 namespace Alert = frontend::Alert;
71 FileName const tempname = FileName::tempName("lyxext");
72 // must have an extension for the converter code to work correctly.
73 tempname_ = FileName(tempname.absFilename() + ".tmp");
77 TempName::TempName(TempName const &)
79 tempname_ = TempName()();
85 tempname_.removeFile();
89 TempName & TempName::operator=(TempName const & other)
92 tempname_ = TempName()();
96 } // namespace external
99 InsetExternalParams::InsetExternalParams()
101 lyxscale(defaultLyxScale),
104 if (defaultTemplateName.empty()) {
105 external::TemplateManager const & etm =
106 external::TemplateManager::get();
107 if (!etm.getTemplates().empty())
108 templatename_ = etm.getTemplates().begin()->first;
110 templatename_ = defaultTemplateName;
116 template <typename T>
117 void clearIfNotFound(T & data, external::TransformID value,
118 vector<external::TransformID> const & ids)
120 typedef vector<external::TransformID>::const_iterator
123 const_iterator it = ids.begin();
124 const_iterator end = ids.end();
125 it = find(it, end, value);
133 void InsetExternalParams::settemplate(string const & name)
135 templatename_ = name;
137 external::TemplateManager const & etm =
138 external::TemplateManager::get();
139 external::Template const * const et = etm.getTemplateByName(name);
141 // Be safe. Don't lose data.
144 // Ascertain which transforms the template supports.
145 // Empty all those that it doesn't.
146 vector<external::TransformID> const & ids = et->transformIds;
147 clearIfNotFound(clipdata, external::Clip, ids);
148 clearIfNotFound(extradata, external::Extra, ids);
149 clearIfNotFound(resizedata, external::Resize, ids);
150 clearIfNotFound(rotationdata, external::Rotate, ids);
153 preview_mode = et->preview_mode;
157 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
160 << "\ttemplate " << templatename() << '\n';
162 if (!filename.empty())
163 os << "\tfilename " << filename.outputFilename(buf.filePath()) << '\n';
166 os << "\tdisplay false\n";
168 if (lyxscale != defaultLyxScale)
169 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
174 if (!clipdata.bbox.empty())
175 os << "\tboundingBox " << clipdata.bbox << '\n';
179 external::ExtraData::const_iterator it = extradata.begin();
180 external::ExtraData::const_iterator end = extradata.end();
181 for (; it != end; ++it) {
182 if (!it->second.empty())
183 os << "\textra " << it->first << " \""
184 << it->second << "\"\n";
187 if (!rotationdata.no_rotation()) {
188 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
189 if (rotationdata.origin() != external::RotationData::DEFAULT)
190 os << "\trotateOrigin "
191 << rotationdata.originString() << '\n';
194 if (!resizedata.no_resize()) {
195 double const scl = convert<double>(resizedata.scale);
196 if (!float_equal(scl, 0.0, 0.05)) {
197 if (!float_equal(scl, 100.0, 0.05))
199 << resizedata.scale << '\n';
201 if (!resizedata.width.zero())
203 << resizedata.width.asString() << '\n';
204 if (!resizedata.height.zero())
206 << resizedata.height.asString() << '\n';
208 if (resizedata.keepAspectRatio)
209 os << "\tkeepAspectRatio\n";
214 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
234 LexerKeyword external_tags[] = {
235 { "\\end_inset", EX_END },
236 { "boundingBox", EX_BOUNDINGBOX },
238 { "display", EX_DISPLAY},
239 { "draft", EX_DRAFT},
240 { "extra", EX_EXTRA },
241 { "filename", EX_FILENAME},
242 { "height", EX_HEIGHT },
243 { "keepAspectRatio", EX_KEEPASPECTRATIO },
244 { "lyxscale", EX_LYXSCALE},
245 { "rotateAngle", EX_ROTATEANGLE },
246 { "rotateOrigin", EX_ROTATEORIGIN },
247 { "scale", EX_SCALE },
248 { "template", EX_TEMPLATE },
249 { "width", EX_WIDTH }
252 PushPopHelper pph(lex, external_tags);
254 bool found_end = false;
255 bool read_error = false;
261 templatename_ = lex.getString();
266 string const name = lex.getString();
267 filename.set(name, buffer.filePath());
273 display = lex.getString() != "false";
279 lyxscale = lex.getInteger();
288 clipdata.bbox.xl = lex.getInteger();
290 clipdata.bbox.yb = lex.getInteger();
292 clipdata.bbox.xr = lex.getInteger();
294 clipdata.bbox.yt = lex.getInteger();
298 clipdata.clip = true;
303 string const name = lex.getString();
305 extradata.set(name, lex.getString());
311 resizedata.height = Length(lex.getString());
314 case EX_KEEPASPECTRATIO:
315 resizedata.keepAspectRatio = true;
320 rotationdata.angle = lex.getString();
323 case EX_ROTATEORIGIN:
325 rotationdata.origin(lex.getString());
330 resizedata.scale = lex.getString();
335 resizedata.width = Length(lex.getString());
343 lex.printError("ExternalInset::read: Wrong tag: $$Token");
348 if (found_end || read_error)
353 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
355 // This is a trick to make sure that the data are self-consistent.
356 settemplate(templatename_);
358 if (lyxerr.debugging(Debug::EXTERNAL)) {
359 lyxerr << "InsetExternalParams::read:\n";
360 write(buffer, lyxerr);
367 InsetExternal::InsetExternal(Buffer & buf)
368 : renderer_(new RenderButton)
370 Inset::setBuffer(buf);
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(odocstream & /*os*/,
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:
720 external::Template::Formats::const_iterator cit =
721 et.formats.find(format);
723 if (cit == et.formats.end()) {
724 // If the template has not specified a PDFLaTeX output,
725 // we try the LaTeX format.
726 if (format == "PDFLaTeX") {
727 cit = et.formats.find("LaTeX");
728 if (cit == et.formats.end())
734 // FIXME: We don't need that always
735 features.require("lyxdot");
737 vector<string>::const_iterator it = cit->second.requirements.begin();
738 vector<string>::const_iterator end = cit->second.requirements.end();
739 for (; it != end; ++it)
740 features.require(*it);
742 external::TemplateManager & etm = external::TemplateManager::get();
744 it = cit->second.preambleNames.begin();
745 end = cit->second.preambleNames.end();
746 for (; it != end; ++it) {
747 string const preamble = etm.getPreambleDefByName(*it);
748 if (!preamble.empty())
749 features.addPreambleSnippet(preamble);
754 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
756 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
760 if (isPreviewWanted(params())) {
761 ptr->setAbsFile(params_.filename);
762 docstring const snippet = latexString(*this);
763 ptr->addPreview(snippet, ploader);
768 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
770 return from_ascii("context-external");
774 void InsetExternal::string2params(string const & in, Buffer const & buffer,
775 InsetExternalParams & params)
777 params = InsetExternalParams();
781 istringstream data(in);
787 if (!lex || name != "external") {
788 LYXERR0("InsetExternal::string2params(" << in << ")\n"
789 "Expected arg 1 to be \"external\"\n");
793 // This is part of the inset proper that is usually swallowed
794 // by Text::readInset
797 if (!lex || id != "External") {
798 LYXERR0("InsetExternal::string2params(" << in << ")\n"
799 "Expected arg 2 to be \"External\"\n");
803 params.read(buffer, lex);
807 string InsetExternal::params2string(InsetExternalParams const & params,
808 Buffer const & buffer)
811 data << "external" << ' ';
812 params.write(buffer, data);
813 data << "\\end_inset\n";