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/ExternalTemplate.h"
16 #include "insets/RenderButton.h"
17 #include "insets/RenderGraphic.h"
18 #include "insets/RenderPreview.h"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
31 #include "MetricsInfo.h"
32 #include "OutputParams.h"
34 #include "frontends/alert.h"
36 #include "graphics/PreviewLoader.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/filetools.h"
40 #include "support/lstrings.h"
41 #include "support/lyxlib.h"
42 #include "support/convert.h"
43 #include "support/Translator.h"
45 #include <boost/bind.hpp>
50 using namespace lyx::support;
54 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
56 unsigned int const defaultLyxScale = 100;
58 string defaultTemplateName;
65 namespace Alert = frontend::Alert;
73 FileName const tempname = FileName::tempName("lyxext");
74 // FIXME: This is unsafe
75 tempname.removeFile();
76 // must have an extension for the converter code to work correctly.
77 tempname_ = FileName(tempname.absFilename() + ".tmp");
81 TempName::TempName(TempName const &)
83 tempname_ = TempName()();
89 tempname_.removeFile();
93 TempName & TempName::operator=(TempName const & other)
96 tempname_ = TempName()();
103 /// The translator between the Display enum and corresponding lyx string.
104 Translator<DisplayType, string> const initTranslator()
106 Translator<DisplayType, string> translator(DefaultDisplay, "default");
108 // Fill the display translator
109 translator.addPair(MonochromeDisplay, "monochrome");
110 translator.addPair(GrayscaleDisplay, "grayscale");
111 translator.addPair(ColorDisplay, "color");
112 translator.addPair(PreviewDisplay, "preview");
113 translator.addPair(NoDisplay, "none");
121 Translator<DisplayType, string> const & displayTranslator()
123 static Translator<DisplayType, string> const translator =
128 } // namespace external
131 InsetExternalParams::InsetExternalParams()
132 : display(defaultDisplayType),
133 lyxscale(defaultLyxScale),
136 if (defaultTemplateName.empty()) {
137 external::TemplateManager const & etm =
138 external::TemplateManager::get();
139 templatename_ = etm.getTemplates().begin()->first;
141 templatename_ = defaultTemplateName;
147 template <typename T>
148 void clearIfNotFound(T & data, external::TransformID value,
149 vector<external::TransformID> const & ids)
151 typedef vector<external::TransformID>::const_iterator
154 const_iterator it = ids.begin();
155 const_iterator end = ids.end();
156 it = find(it, end, value);
164 void InsetExternalParams::settemplate(string const & name)
166 templatename_ = name;
168 external::TemplateManager const & etm =
169 external::TemplateManager::get();
170 external::Template const * const et = etm.getTemplateByName(name);
172 // Be safe. Don't lose data.
175 // Ascertain which transforms the template supports.
176 // Empty all those that it doesn't.
177 vector<external::TransformID> const & ids = et->transformIds;
178 clearIfNotFound(clipdata, external::Clip, ids);
179 clearIfNotFound(extradata, external::Extra, ids);
180 clearIfNotFound(resizedata, external::Resize, ids);
181 clearIfNotFound(rotationdata, external::Rotate, ids);
185 void InsetExternalParams::write(Buffer const & buffer, ostream & os) const
188 << "\ttemplate " << templatename() << '\n';
190 if (!filename.empty()) {
191 os << "\tfilename " << filename.outputFilename(buffer.filePath()) << '\n';
192 os << "\tembed " << (filename.embedded() ? "true" : "false") << '\n';
194 if (display != defaultDisplayType)
196 << external::displayTranslator().find(display)
199 if (lyxscale != defaultLyxScale)
200 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
205 if (!clipdata.bbox.empty())
206 os << "\tboundingBox " << clipdata.bbox << '\n';
210 external::ExtraData::const_iterator it = extradata.begin();
211 external::ExtraData::const_iterator end = extradata.end();
212 for (; it != end; ++it) {
213 if (!it->second.empty())
214 os << "\textra " << it->first << " \""
215 << it->second << "\"\n";
218 if (!rotationdata.no_rotation()) {
219 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
220 if (rotationdata.origin() != external::RotationData::DEFAULT)
221 os << "\trotateOrigin "
222 << rotationdata.originString() << '\n';
225 if (!resizedata.no_resize()) {
226 double const scl = convert<double>(resizedata.scale);
227 if (!float_equal(scl, 0.0, 0.05)) {
228 if (!float_equal(scl, 100.0, 0.05))
230 << resizedata.scale << '\n';
232 if (!resizedata.width.zero())
234 << resizedata.width.asString() << '\n';
235 if (!resizedata.height.zero())
237 << resizedata.height.asString() << '\n';
239 if (resizedata.keepAspectRatio)
240 os << "\tkeepAspectRatio\n";
245 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
266 keyword_item external_tags[] = {
267 { "\\end_inset", EX_END },
268 { "boundingBox", EX_BOUNDINGBOX },
270 { "display", EX_DISPLAY},
271 { "draft", EX_DRAFT},
272 { "extra", EX_EXTRA },
273 { "filename", EX_FILENAME},
274 { "embed", EX_EMBED},
275 { "height", EX_HEIGHT },
276 { "keepAspectRatio", EX_KEEPASPECTRATIO },
277 { "lyxscale", EX_LYXSCALE},
278 { "rotateAngle", EX_ROTATEANGLE },
279 { "rotateOrigin", EX_ROTATEORIGIN },
280 { "scale", EX_SCALE },
281 { "template", EX_TEMPLATE },
282 { "width", EX_WIDTH }
285 PushPopHelper pph(lex, external_tags, EX_END);
287 bool found_end = false;
288 bool read_error = false;
294 templatename_ = lex.getString();
299 string const name = lex.getString();
300 filename.set(name, buffer.filePath());
306 filename.setEmbed(lex.getBool());
312 string const name = lex.getString();
313 display = external::displayTranslator().find(name);
319 lyxscale = lex.getInteger();
328 clipdata.bbox.xl = lex.getInteger();
330 clipdata.bbox.yb = lex.getInteger();
332 clipdata.bbox.xr = lex.getInteger();
334 clipdata.bbox.yt = lex.getInteger();
338 clipdata.clip = true;
343 string const name = lex.getString();
345 extradata.set(name, lex.getString());
351 resizedata.height = Length(lex.getString());
354 case EX_KEEPASPECTRATIO:
355 resizedata.keepAspectRatio = true;
360 rotationdata.angle = lex.getString();
363 case EX_ROTATEORIGIN:
365 rotationdata.origin(lex.getString());
370 resizedata.scale = lex.getString();
375 resizedata.width = Length(lex.getString());
383 lex.printError("ExternalInset::read: Wrong tag: $$Token");
388 if (found_end || read_error)
393 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
395 // This is a trick to make sure that the data are self-consistent.
396 settemplate(templatename_);
398 if (lyxerr.debugging(Debug::EXTERNAL)) {
399 lyxerr << "InsetExternalParams::read:\n";
400 write(buffer, lyxerr);
407 InsetExternal::InsetExternal()
408 : renderer_(new RenderButton)
412 InsetExternal::InsetExternal(InsetExternal const & other)
414 boost::signals::trackable(),
415 params_(other.params_),
416 renderer_(other.renderer_->clone(this))
420 Inset * InsetExternal::clone() const
422 return new InsetExternal(*this);
426 InsetExternal::~InsetExternal()
428 InsetExternalMailer(*this).hideDialog();
432 void InsetExternal::statusChanged() const
438 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
440 switch (cmd.action) {
442 case LFUN_EXTERNAL_EDIT: {
443 Buffer const & buffer = cur.buffer();
444 InsetExternalParams p;
445 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
446 external::editExternal(p, buffer);
450 case LFUN_INSET_MODIFY: {
451 Buffer const & buffer = cur.buffer();
452 InsetExternalParams p;
453 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
454 if (!p.filename.empty()) {
456 p.filename.enable(buffer.embedded(), &buffer);
457 } catch (ExceptionMessage const & message) {
458 Alert::error(message.title_, message.details_);
459 // do not set parameter if an error happens
463 setParams(p, buffer);
467 case LFUN_INSET_DIALOG_UPDATE:
468 InsetExternalMailer(*this).updateDialog(&cur.bv());
471 case LFUN_MOUSE_RELEASE:
472 if (!cur.selection())
473 InsetExternalMailer(*this).showDialog(&cur.bv());
477 Inset::doDispatch(cur, cmd);
482 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
483 FuncStatus & flag) const
485 switch (cmd.action) {
487 case LFUN_EXTERNAL_EDIT:
488 case LFUN_INSET_MODIFY:
489 case LFUN_INSET_DIALOG_UPDATE:
494 return Inset::getStatus(cur, cmd, flag);
499 void InsetExternal::registerEmbeddedFiles(Buffer const & buffer,
500 EmbeddedFileList & files) const
502 files.registerFile(params_.filename, this, buffer);
506 void InsetExternal::updateEmbeddedFile(Buffer const & buf,
507 EmbeddedFile const & file)
509 // when embedding is enabled, change of embedding status leads to actions
510 EmbeddedFile temp = file;
511 temp.enable(buf.embedded(), &buf);
512 // this will not be set if an exception is thorwn in enable()
513 params_.filename = temp;
517 void InsetExternal::edit(Cursor & cur, bool)
519 InsetExternalMailer(*this).showDialog(&cur.bv());
523 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
525 renderer_->metrics(mi, dim);
529 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
531 renderer_->draw(pi, x, y);
544 RenderType getRenderType(InsetExternalParams const & p)
546 if (!external::getTemplatePtr(p) ||
547 p.filename.empty() ||
548 p.display == external::NoDisplay)
551 if (p.display == external::PreviewDisplay) {
552 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
553 return RENDERPREVIEW;
557 if (p.display == external::DefaultDisplay &&
558 lyxrc.display_graphics == graphics::NoDisplay)
560 return RENDERGRAPHIC;
564 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
566 graphics::Params gparams;
568 gparams.filename = eparams.filename.availableFile();
569 gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
570 gparams.scale = eparams.lyxscale;
571 if (eparams.clipdata.clip)
572 gparams.bb = eparams.clipdata.bbox;
573 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
575 switch (eparams.display) {
576 case external::DefaultDisplay:
577 gparams.display = graphics::DefaultDisplay;
579 case external::MonochromeDisplay:
580 gparams.display = graphics::MonochromeDisplay;
582 case external::GrayscaleDisplay:
583 gparams.display = graphics::GrayscaleDisplay;
585 case external::ColorDisplay:
586 gparams.display = graphics::ColorDisplay;
588 case external::NoDisplay:
589 gparams.display = graphics::NoDisplay;
594 if (gparams.display == graphics::DefaultDisplay)
595 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
596 // Override the above if we're not using a gui
598 gparams.display = graphics::NoDisplay;
604 docstring const getScreenLabel(InsetExternalParams const & params,
605 Buffer const & buffer)
607 external::Template const * const ptr =
608 external::getTemplatePtr(params);
611 return bformat((_("External template %1$s is not installed")),
612 from_utf8(params.templatename()));
614 docstring gui = _(ptr->guiName);
615 return from_utf8(external::doSubstitution(params, buffer,
616 to_utf8(gui), false));
619 void add_preview_and_start_loading(RenderMonitoredPreview &,
620 InsetExternal const &,
626 InsetExternalParams const & InsetExternal::params() const
632 void InsetExternal::setParams(InsetExternalParams const & p,
633 Buffer const & buffer)
637 // Subsequent calls to the InsetExternal::Params default constructor
639 defaultTemplateName = params_.templatename();
641 switch (getRenderType(params_)) {
643 RenderButton * button_ptr = renderer_->asButton();
645 renderer_.reset(new RenderButton);
646 button_ptr = renderer_->asButton();
649 button_ptr->update(getScreenLabel(params_, buffer), true);
653 case RENDERGRAPHIC: {
654 RenderGraphic * graphic_ptr = renderer_->asGraphic();
656 renderer_.reset(new RenderGraphic(this));
657 graphic_ptr = renderer_->asGraphic();
660 graphic_ptr->update(get_grfx_params(params_));
665 case RENDERPREVIEW: {
666 RenderMonitoredPreview * preview_ptr =
667 renderer_->asMonitoredPreview();
669 renderer_.reset(new RenderMonitoredPreview(this));
670 preview_ptr = renderer_->asMonitoredPreview();
671 preview_ptr->fileChanged(
672 boost::bind(&InsetExternal::fileChanged, this));
675 if (preview_ptr->monitoring())
676 preview_ptr->stopMonitoring();
677 add_preview_and_start_loading(*preview_ptr, *this, buffer);
685 void InsetExternal::fileChanged() const
687 Buffer const * const buffer = updateFrontend();
691 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
694 ptr->removePreview(*buffer);
695 add_preview_and_start_loading(*ptr, *this, *buffer);
699 void InsetExternal::write(Buffer const & buffer, ostream & os) const
701 params_.write(buffer, os);
705 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
707 InsetExternalParams params;
708 if (params.read(buffer, lex)) {
709 // exception handling is not needed as long as embedded files are in place.
710 params.filename.enable(buffer.embedded(), & buffer);
711 setParams(params, buffer);
716 int InsetExternal::latex(Buffer const & buf, odocstream & os,
717 OutputParams const & runparams) const
721 os << "\\fbox{\\ttfamily{}"
722 << from_utf8(params_.filename.outputFilename(buf.filePath()))
727 // "nice" means that the buffer is exported to LaTeX format but not
728 // run through the LaTeX compiler.
729 // If we're running through the LaTeX compiler, we should write the
730 // generated files in the buffer's temporary directory.
731 bool const external_in_tmpdir = !runparams.nice;
732 bool const dryrun = runparams.dryrun || runparams.inComment;
734 // If the template has specified a PDFLaTeX output, then we try and
736 if (runparams.flavor == OutputParams::PDFLATEX) {
737 external::Template const * const et_ptr =
738 external::getTemplatePtr(params_);
741 external::Template const & et = *et_ptr;
743 external::Template::Formats::const_iterator cit =
744 et.formats.find("PDFLaTeX");
746 if (cit != et.formats.end()) {
747 return external::writeExternal(params_, "PDFLaTeX",
749 *(runparams.exportdata),
755 return external::writeExternal(params_, "LaTeX", buf, os,
756 *(runparams.exportdata),
762 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
763 OutputParams const & runparams) const
765 os << '\n'; // output external material on a new line
766 external::writeExternal(params_, "Ascii", buf, os,
767 *(runparams.exportdata), false,
768 runparams.dryrun || runparams.inComment);
769 return PLAINTEXT_NEWLINE;
773 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
774 OutputParams const & runparams) const
776 return external::writeExternal(params_, "DocBook", buf, os,
777 *(runparams.exportdata), false,
778 runparams.dryrun || runparams.inComment);
782 void InsetExternal::validate(LaTeXFeatures & features) const
787 external::Template const * const et_ptr =
788 external::getTemplatePtr(params_);
791 external::Template const & et = *et_ptr;
794 switch (features.runparams().flavor) {
795 case OutputParams::LATEX:
798 case OutputParams::PDFLATEX:
801 case OutputParams::XML:
805 external::Template::Formats::const_iterator cit =
806 et.formats.find(format);
807 if (cit == et.formats.end())
810 // FIXME: We don't need that always
811 features.require("lyxdot");
813 vector<string>::const_iterator it = cit->second.requirements.begin();
814 vector<string>::const_iterator end = cit->second.requirements.end();
815 for (; it != end; ++it)
816 features.require(*it);
818 external::TemplateManager & etm = external::TemplateManager::get();
820 it = cit->second.preambleNames.begin();
821 end = cit->second.preambleNames.end();
822 for (; it != end; ++it) {
823 string const preamble = etm.getPreambleDefByName(*it);
824 if (!preamble.empty())
825 features.addPreambleSnippet(preamble);
836 bool preview_wanted(InsetExternalParams const & params)
838 return params.display == external::PreviewDisplay &&
839 params.filename.isReadableFile();
843 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
846 // We don't need to set runparams.encoding since it is not used by
848 OutputParams runparams(0);
849 runparams.flavor = OutputParams::LATEX;
850 inset.latex(buffer, os, runparams);
855 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
856 InsetExternal const & inset,
857 Buffer const & buffer)
859 InsetExternalParams const & params = inset.params();
861 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
862 preview_wanted(params)) {
863 renderer.setAbsFile(params.filename);
864 docstring const snippet = latex_string(inset, buffer);
865 renderer.addPreview(snippet, buffer);
866 renderer.startLoading(buffer);
873 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
875 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
879 if (preview_wanted(params())) {
880 ptr->setAbsFile(params_.filename);
881 docstring const snippet = latex_string(*this, ploader.buffer());
882 ptr->addPreview(snippet, ploader);
889 string const InsetExternalMailer::name_("external");
891 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
896 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
898 return params2string(inset_.params(), buffer);
902 void InsetExternalMailer::string2params(string const & in,
903 Buffer const & buffer,
904 InsetExternalParams & params)
906 params = InsetExternalParams();
910 istringstream data(in);
916 if (!lex || name != name_)
917 return print_mailer_error("InsetExternalMailer", in, 1, name_);
919 // This is part of the inset proper that is usually swallowed
920 // by Text::readInset
923 if (!lex || id != "External")
924 return print_mailer_error("InsetBoxMailer", in, 2, "External");
926 params.read(buffer, lex);
931 InsetExternalMailer::params2string(InsetExternalParams const & params,
932 Buffer const & buffer)
935 data << name_ << ' ';
936 params.write(buffer, data);
937 data << "\\end_inset\n";