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() ? filename.inzipName() : "\"\"") << '\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 string const name = lex.getString();
307 filename.setInzipName(name);
308 filename.setEmbed(!name.empty());
314 string const name = lex.getString();
315 display = external::displayTranslator().find(name);
321 lyxscale = lex.getInteger();
330 clipdata.bbox.xl = lex.getInteger();
332 clipdata.bbox.yb = lex.getInteger();
334 clipdata.bbox.xr = lex.getInteger();
336 clipdata.bbox.yt = lex.getInteger();
340 clipdata.clip = true;
345 string const name = lex.getString();
347 extradata.set(name, lex.getString());
353 resizedata.height = Length(lex.getString());
356 case EX_KEEPASPECTRATIO:
357 resizedata.keepAspectRatio = true;
362 rotationdata.angle = lex.getString();
365 case EX_ROTATEORIGIN:
367 rotationdata.origin(lex.getString());
372 resizedata.scale = lex.getString();
377 resizedata.width = Length(lex.getString());
385 lex.printError("ExternalInset::read: Wrong tag: $$Token");
390 if (found_end || read_error)
395 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
397 // This is a trick to make sure that the data are self-consistent.
398 settemplate(templatename_);
400 if (lyxerr.debugging(Debug::EXTERNAL)) {
401 lyxerr << "InsetExternalParams::read:\n";
402 write(buffer, lyxerr);
409 InsetExternal::InsetExternal()
410 : renderer_(new RenderButton)
414 InsetExternal::InsetExternal(InsetExternal const & other)
416 boost::signals::trackable(),
417 params_(other.params_),
418 renderer_(other.renderer_->clone(this))
422 Inset * InsetExternal::clone() const
424 return new InsetExternal(*this);
428 InsetExternal::~InsetExternal()
430 InsetExternalMailer(*this).hideDialog();
434 void InsetExternal::statusChanged() const
440 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
442 switch (cmd.action) {
444 case LFUN_EXTERNAL_EDIT: {
445 Buffer const & buffer = cur.buffer();
446 InsetExternalParams p;
447 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
448 external::editExternal(p, buffer);
452 case LFUN_INSET_MODIFY: {
453 Buffer const & buffer = cur.buffer();
454 InsetExternalParams p;
455 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer, p);
456 if (!p.filename.empty()) {
458 p.filename.enable(buffer.embedded(), &buffer);
459 } catch (ExceptionMessage const & message) {
460 Alert::error(message.title_, message.details_);
461 // do not set parameter if an error happens
465 setParams(p, buffer);
469 case LFUN_INSET_DIALOG_UPDATE:
470 InsetExternalMailer(*this).updateDialog(&cur.bv());
473 case LFUN_MOUSE_RELEASE:
474 if (!cur.selection())
475 InsetExternalMailer(*this).showDialog(&cur.bv());
479 Inset::doDispatch(cur, cmd);
484 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
485 FuncStatus & flag) const
487 switch (cmd.action) {
489 case LFUN_EXTERNAL_EDIT:
490 case LFUN_INSET_MODIFY:
491 case LFUN_INSET_DIALOG_UPDATE:
496 return Inset::getStatus(cur, cmd, flag);
501 void InsetExternal::registerEmbeddedFiles(Buffer const & buffer,
502 EmbeddedFileList & files) const
504 files.registerFile(params_.filename, this, buffer);
508 void InsetExternal::updateEmbeddedFile(Buffer const & buf,
509 EmbeddedFile const & file)
511 // when embedding is enabled, change of embedding status leads to actions
512 EmbeddedFile temp = file;
513 temp.enable(buf.embedded(), &buf);
514 // this will not be set if an exception is thorwn in enable()
515 params_.filename = temp;
519 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
521 InsetExternalMailer(*this).showDialog(&cur.bv());
525 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
527 renderer_->metrics(mi, dim);
531 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
533 renderer_->draw(pi, x, y);
546 RenderType getRenderType(InsetExternalParams const & p)
548 if (!external::getTemplatePtr(p) ||
549 p.filename.empty() ||
550 p.display == external::NoDisplay)
553 if (p.display == external::PreviewDisplay) {
554 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
555 return RENDERPREVIEW;
559 if (p.display == external::DefaultDisplay &&
560 lyxrc.display_graphics == graphics::NoDisplay)
562 return RENDERGRAPHIC;
566 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
568 graphics::Params gparams;
570 gparams.filename = eparams.filename.availableFile();
571 gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
572 gparams.scale = eparams.lyxscale;
573 if (eparams.clipdata.clip)
574 gparams.bb = eparams.clipdata.bbox;
575 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
577 switch (eparams.display) {
578 case external::DefaultDisplay:
579 gparams.display = graphics::DefaultDisplay;
581 case external::MonochromeDisplay:
582 gparams.display = graphics::MonochromeDisplay;
584 case external::GrayscaleDisplay:
585 gparams.display = graphics::GrayscaleDisplay;
587 case external::ColorDisplay:
588 gparams.display = graphics::ColorDisplay;
590 case external::NoDisplay:
591 gparams.display = graphics::NoDisplay;
596 if (gparams.display == graphics::DefaultDisplay)
597 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
598 // Override the above if we're not using a gui
600 gparams.display = graphics::NoDisplay;
606 docstring const getScreenLabel(InsetExternalParams const & params,
607 Buffer const & buffer)
609 external::Template const * const ptr =
610 external::getTemplatePtr(params);
613 return bformat((_("External template %1$s is not installed")),
614 from_utf8(params.templatename()));
616 docstring gui = _(ptr->guiName);
617 return from_utf8(external::doSubstitution(params, buffer,
618 to_utf8(gui), false));
621 void add_preview_and_start_loading(RenderMonitoredPreview &,
622 InsetExternal const &,
628 InsetExternalParams const & InsetExternal::params() const
634 void InsetExternal::setParams(InsetExternalParams const & p,
635 Buffer const & buffer)
639 // Subsequent calls to the InsetExternal::Params default constructor
641 defaultTemplateName = params_.templatename();
643 switch (getRenderType(params_)) {
645 RenderButton * button_ptr = renderer_->asButton();
647 renderer_.reset(new RenderButton);
648 button_ptr = renderer_->asButton();
651 button_ptr->update(getScreenLabel(params_, buffer), true);
655 case RENDERGRAPHIC: {
656 RenderGraphic * graphic_ptr = renderer_->asGraphic();
658 renderer_.reset(new RenderGraphic(this));
659 graphic_ptr = renderer_->asGraphic();
662 graphic_ptr->update(get_grfx_params(params_));
667 case RENDERPREVIEW: {
668 RenderMonitoredPreview * preview_ptr =
669 renderer_->asMonitoredPreview();
671 renderer_.reset(new RenderMonitoredPreview(this));
672 preview_ptr = renderer_->asMonitoredPreview();
673 preview_ptr->fileChanged(
674 boost::bind(&InsetExternal::fileChanged, this));
677 if (preview_ptr->monitoring())
678 preview_ptr->stopMonitoring();
679 add_preview_and_start_loading(*preview_ptr, *this, buffer);
687 void InsetExternal::fileChanged() const
689 Buffer const * const buffer = updateFrontend();
693 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
696 ptr->removePreview(*buffer);
697 add_preview_and_start_loading(*ptr, *this, *buffer);
701 void InsetExternal::write(Buffer const & buffer, ostream & os) const
703 params_.write(buffer, os);
707 void InsetExternal::read(Buffer const & buffer, Lexer & lex)
709 InsetExternalParams params;
710 if (params.read(buffer, lex)) {
711 // exception handling is not needed as long as embedded files are in place.
712 params.filename.enable(buffer.embedded(), & buffer);
713 setParams(params, buffer);
718 int InsetExternal::latex(Buffer const & buf, odocstream & os,
719 OutputParams const & runparams) const
723 os << "\\fbox{\\ttfamily{}"
724 << from_utf8(params_.filename.outputFilename(buf.filePath()))
729 // "nice" means that the buffer is exported to LaTeX format but not
730 // run through the LaTeX compiler.
731 // If we're running through the LaTeX compiler, we should write the
732 // generated files in the buffer's temporary directory.
733 bool const external_in_tmpdir = !runparams.nice;
734 bool const dryrun = runparams.dryrun || runparams.inComment;
736 // If the template has specified a PDFLaTeX output, then we try and
738 if (runparams.flavor == OutputParams::PDFLATEX) {
739 external::Template const * const et_ptr =
740 external::getTemplatePtr(params_);
743 external::Template const & et = *et_ptr;
745 external::Template::Formats::const_iterator cit =
746 et.formats.find("PDFLaTeX");
748 if (cit != et.formats.end()) {
749 return external::writeExternal(params_, "PDFLaTeX",
751 *(runparams.exportdata),
757 return external::writeExternal(params_, "LaTeX", buf, os,
758 *(runparams.exportdata),
764 int InsetExternal::plaintext(Buffer const & buf, odocstream & os,
765 OutputParams const & runparams) const
767 os << '\n'; // output external material on a new line
768 external::writeExternal(params_, "Ascii", buf, os,
769 *(runparams.exportdata), false,
770 runparams.dryrun || runparams.inComment);
771 return PLAINTEXT_NEWLINE;
775 int InsetExternal::docbook(Buffer const & buf, odocstream & os,
776 OutputParams const & runparams) const
778 return external::writeExternal(params_, "DocBook", buf, os,
779 *(runparams.exportdata), false,
780 runparams.dryrun || runparams.inComment);
784 void InsetExternal::validate(LaTeXFeatures & features) const
789 external::Template const * const et_ptr =
790 external::getTemplatePtr(params_);
793 external::Template const & et = *et_ptr;
796 switch (features.runparams().flavor) {
797 case OutputParams::LATEX:
800 case OutputParams::PDFLATEX:
803 case OutputParams::XML:
807 external::Template::Formats::const_iterator cit =
808 et.formats.find(format);
809 if (cit == et.formats.end())
812 // FIXME: We don't need that always
813 features.require("lyxdot");
815 vector<string>::const_iterator it = cit->second.requirements.begin();
816 vector<string>::const_iterator end = cit->second.requirements.end();
817 for (; it != end; ++it)
818 features.require(*it);
820 external::TemplateManager & etm = external::TemplateManager::get();
822 it = cit->second.preambleNames.begin();
823 end = cit->second.preambleNames.end();
824 for (; it != end; ++it) {
825 string const preamble = etm.getPreambleDefByName(*it);
826 if (!preamble.empty())
827 features.addPreambleSnippet(preamble);
838 bool preview_wanted(InsetExternalParams const & params)
840 return params.display == external::PreviewDisplay &&
841 params.filename.isReadableFile();
845 docstring const latex_string(InsetExternal const & inset, Buffer const & buffer)
848 // We don't need to set runparams.encoding since it is not used by
850 OutputParams runparams(0);
851 runparams.flavor = OutputParams::LATEX;
852 inset.latex(buffer, os, runparams);
857 void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
858 InsetExternal const & inset,
859 Buffer const & buffer)
861 InsetExternalParams const & params = inset.params();
863 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
864 preview_wanted(params)) {
865 renderer.setAbsFile(params.filename);
866 docstring const snippet = latex_string(inset, buffer);
867 renderer.addPreview(snippet, buffer);
868 renderer.startLoading(buffer);
875 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
877 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
881 if (preview_wanted(params())) {
882 ptr->setAbsFile(params_.filename);
883 docstring const snippet = latex_string(*this, ploader.buffer());
884 ptr->addPreview(snippet, ploader);
891 string const InsetExternalMailer::name_("external");
893 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
898 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
900 return params2string(inset_.params(), buffer);
904 void InsetExternalMailer::string2params(string const & in,
905 Buffer const & buffer,
906 InsetExternalParams & params)
908 params = InsetExternalParams();
912 istringstream data(in);
918 if (!lex || name != name_)
919 return print_mailer_error("InsetExternalMailer", in, 1, name_);
921 // This is part of the inset proper that is usually swallowed
922 // by Text::readInset
925 if (!lex || id != "External")
926 return print_mailer_error("InsetBoxMailer", in, 2, "External");
928 params.read(buffer, lex);
933 InsetExternalMailer::params2string(InsetExternalParams const & params,
934 Buffer const & buffer)
937 data << name_ << ' ';
938 params.write(buffer, data);
939 data << "\\end_inset\n";