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 templatename_ = etm.getTemplates().begin()->first;
109 templatename_ = defaultTemplateName;
115 template <typename T>
116 void clearIfNotFound(T & data, external::TransformID value,
117 vector<external::TransformID> const & ids)
119 typedef vector<external::TransformID>::const_iterator
122 const_iterator it = ids.begin();
123 const_iterator end = ids.end();
124 it = find(it, end, value);
132 void InsetExternalParams::settemplate(string const & name)
134 templatename_ = name;
136 external::TemplateManager const & etm =
137 external::TemplateManager::get();
138 external::Template const * const et = etm.getTemplateByName(name);
140 // Be safe. Don't lose data.
143 // Ascertain which transforms the template supports.
144 // Empty all those that it doesn't.
145 vector<external::TransformID> const & ids = et->transformIds;
146 clearIfNotFound(clipdata, external::Clip, ids);
147 clearIfNotFound(extradata, external::Extra, ids);
148 clearIfNotFound(resizedata, external::Resize, ids);
149 clearIfNotFound(rotationdata, external::Rotate, ids);
152 preview_mode = et->preview_mode;
156 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
159 << "\ttemplate " << templatename() << '\n';
161 if (!filename.empty())
162 os << "\tfilename " << filename.outputFilename(buf.filePath()) << '\n';
165 os << "\tdisplay false\n";
167 if (lyxscale != defaultLyxScale)
168 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
173 if (!clipdata.bbox.empty())
174 os << "\tboundingBox " << clipdata.bbox << '\n';
178 external::ExtraData::const_iterator it = extradata.begin();
179 external::ExtraData::const_iterator end = extradata.end();
180 for (; it != end; ++it) {
181 if (!it->second.empty())
182 os << "\textra " << it->first << " \""
183 << it->second << "\"\n";
186 if (!rotationdata.no_rotation()) {
187 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
188 if (rotationdata.origin() != external::RotationData::DEFAULT)
189 os << "\trotateOrigin "
190 << rotationdata.originString() << '\n';
193 if (!resizedata.no_resize()) {
194 double const scl = convert<double>(resizedata.scale);
195 if (!float_equal(scl, 0.0, 0.05)) {
196 if (!float_equal(scl, 100.0, 0.05))
198 << resizedata.scale << '\n';
200 if (!resizedata.width.zero())
202 << resizedata.width.asString() << '\n';
203 if (!resizedata.height.zero())
205 << resizedata.height.asString() << '\n';
207 if (resizedata.keepAspectRatio)
208 os << "\tkeepAspectRatio\n";
213 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
233 LexerKeyword external_tags[] = {
234 { "\\end_inset", EX_END },
235 { "boundingBox", EX_BOUNDINGBOX },
237 { "display", EX_DISPLAY},
238 { "draft", EX_DRAFT},
239 { "extra", EX_EXTRA },
240 { "filename", EX_FILENAME},
241 { "height", EX_HEIGHT },
242 { "keepAspectRatio", EX_KEEPASPECTRATIO },
243 { "lyxscale", EX_LYXSCALE},
244 { "rotateAngle", EX_ROTATEANGLE },
245 { "rotateOrigin", EX_ROTATEORIGIN },
246 { "scale", EX_SCALE },
247 { "template", EX_TEMPLATE },
248 { "width", EX_WIDTH }
251 PushPopHelper pph(lex, external_tags);
253 bool found_end = false;
254 bool read_error = false;
260 templatename_ = lex.getString();
265 string const name = lex.getString();
266 filename.set(name, buffer.filePath());
272 display = lex.getString() != "false";
278 lyxscale = lex.getInteger();
287 clipdata.bbox.xl = lex.getInteger();
289 clipdata.bbox.yb = lex.getInteger();
291 clipdata.bbox.xr = lex.getInteger();
293 clipdata.bbox.yt = lex.getInteger();
297 clipdata.clip = true;
302 string const name = lex.getString();
304 extradata.set(name, lex.getString());
310 resizedata.height = Length(lex.getString());
313 case EX_KEEPASPECTRATIO:
314 resizedata.keepAspectRatio = true;
319 rotationdata.angle = lex.getString();
322 case EX_ROTATEORIGIN:
324 rotationdata.origin(lex.getString());
329 resizedata.scale = lex.getString();
334 resizedata.width = Length(lex.getString());
342 lex.printError("ExternalInset::read: Wrong tag: $$Token");
347 if (found_end || read_error)
352 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
354 // This is a trick to make sure that the data are self-consistent.
355 settemplate(templatename_);
357 if (lyxerr.debugging(Debug::EXTERNAL)) {
358 lyxerr << "InsetExternalParams::read:\n";
359 write(buffer, lyxerr);
366 InsetExternal::InsetExternal(Buffer & buf)
367 : renderer_(new RenderButton)
369 Inset::setBuffer(buf);
373 InsetExternal::InsetExternal(InsetExternal const & other)
375 boost::signals::trackable(),
376 params_(other.params_),
377 renderer_(other.renderer_->clone(this))
381 InsetExternal::~InsetExternal()
383 hideDialogs("external", this);
387 void InsetExternal::statusChanged() const
393 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
395 switch (cmd.action) {
397 case LFUN_INSET_EDIT: {
398 InsetExternalParams p = params();
399 if (!cmd.argument().empty())
400 string2params(to_utf8(cmd.argument()), buffer(), p);
401 external::editExternal(p, buffer());
405 case LFUN_INSET_MODIFY: {
406 InsetExternalParams p;
407 string2params(to_utf8(cmd.argument()), buffer(), p);
412 case LFUN_INSET_DIALOG_UPDATE:
413 cur.bv().updateDialog("external",
414 params2string(params(), cur.bv().buffer()));
417 case LFUN_MOUSE_RELEASE:
418 if (!cur.selection() && cmd.button() == mouse_button::button1)
419 cur.bv().showDialog("external",
420 params2string(params(), cur.bv().buffer()),
425 Inset::doDispatch(cur, cmd);
430 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
431 FuncStatus & flag) const
433 switch (cmd.action) {
435 case LFUN_INSET_EDIT:
436 case LFUN_INSET_MODIFY:
437 case LFUN_INSET_DIALOG_UPDATE:
438 flag.setEnabled(true);
442 return Inset::getStatus(cur, cmd, flag);
447 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
449 cur.bv().showDialog("external",
450 params2string(params(), cur.bv().buffer()),
455 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
457 renderer_->metrics(mi, dim);
461 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
463 renderer_->draw(pi, x, y);
469 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
471 graphics::Params gparams;
473 gparams.filename = eparams.filename;
474 gparams.scale = eparams.lyxscale;
475 if (eparams.clipdata.clip)
476 gparams.bb = eparams.clipdata.bbox;
477 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
478 gparams.display = eparams.display;
484 docstring screenLabel(InsetExternalParams const & params,
485 Buffer const & buffer)
487 external::Template const * const ptr =
488 external::getTemplatePtr(params);
491 return bformat((_("External template %1$s is not installed")),
492 from_utf8(params.templatename()));
494 docstring gui = _(ptr->guiName);
495 return from_utf8(external::doSubstitution(params, buffer,
496 to_utf8(gui), false));
502 static bool isPreviewWanted(InsetExternalParams const & params)
504 return params.display && params.filename.isReadableFile();
508 static docstring latexString(InsetExternal const & inset)
511 // We don't need to set runparams.encoding since it is not used by
513 OutputParams runparams(0);
514 runparams.flavor = OutputParams::LATEX;
515 inset.latex(os, runparams);
520 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
521 InsetExternal const & inset,
522 Buffer const & buffer)
524 InsetExternalParams const & params = inset.params();
526 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
527 isPreviewWanted(params)) {
528 renderer.setAbsFile(params.filename);
529 docstring const snippet = latexString(inset);
530 renderer.addPreview(snippet, buffer);
531 renderer.startLoading(buffer);
536 InsetExternalParams const & InsetExternal::params() const
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 void InsetExternal::validate(LaTeXFeatures & features) const
691 external::Template const * const et_ptr =
692 external::getTemplatePtr(params_);
695 external::Template const & et = *et_ptr;
698 switch (features.runparams().flavor) {
699 case OutputParams::LATEX:
702 case OutputParams::PDFLATEX:
705 case OutputParams::XML:
709 external::Template::Formats::const_iterator cit =
710 et.formats.find(format);
712 if (cit == et.formats.end()) {
713 // If the template has not specified a PDFLaTeX output,
714 // we try the LaTeX format.
715 if (format == "PDFLaTeX") {
716 cit = et.formats.find("LaTeX");
717 if (cit == et.formats.end())
723 // FIXME: We don't need that always
724 features.require("lyxdot");
726 vector<string>::const_iterator it = cit->second.requirements.begin();
727 vector<string>::const_iterator end = cit->second.requirements.end();
728 for (; it != end; ++it)
729 features.require(*it);
731 external::TemplateManager & etm = external::TemplateManager::get();
733 it = cit->second.preambleNames.begin();
734 end = cit->second.preambleNames.end();
735 for (; it != end; ++it) {
736 string const preamble = etm.getPreambleDefByName(*it);
737 if (!preamble.empty())
738 features.addPreambleSnippet(preamble);
743 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
745 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
749 if (isPreviewWanted(params())) {
750 ptr->setAbsFile(params_.filename);
751 docstring const snippet = latexString(*this);
752 ptr->addPreview(snippet, ploader);
757 docstring InsetExternal::contextMenu(BufferView const &, int, int) const
759 return from_ascii("context-external");
763 void InsetExternal::string2params(string const & in, Buffer const & buffer,
764 InsetExternalParams & params)
766 params = InsetExternalParams();
770 istringstream data(in);
776 if (!lex || name != "external") {
777 LYXERR0("InsetExternal::string2params(" << in << ")\n"
778 "Expected arg 1 to be \"external\"\n");
782 // This is part of the inset proper that is usually swallowed
783 // by Text::readInset
786 if (!lex || id != "External") {
787 LYXERR0("InsetExternal::string2params(" << in << ")\n"
788 "Expected arg 2 to be \"External\"\n");
792 params.read(buffer, lex);
796 string InsetExternal::params2string(InsetExternalParams const & params,
797 Buffer const & buffer)
800 data << "external" << ' ';
801 params.write(buffer, data);
802 data << "\\end_inset\n";