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 "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"
35 #include "graphics/PreviewLoader.h"
37 #include "support/debug.h"
38 #include "support/ExceptionMessage.h"
39 #include "support/filetools.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42 #include "support/lyxlib.h"
43 #include "support/convert.h"
44 #include "support/Translator.h"
46 #include <boost/bind.hpp>
51 using namespace lyx::support;
55 lyx::external::DisplayType const defaultDisplayType = lyx::external::NoDisplay;
57 unsigned int const defaultLyxScale = 100;
59 string defaultTemplateName;
66 namespace Alert = frontend::Alert;
72 FileName const tempname = FileName::tempName("lyxext");
73 // FIXME: This is unsafe
74 tempname.removeFile();
75 // must have an extension for the converter code to work correctly.
76 tempname_ = FileName(tempname.absFilename() + ".tmp");
80 TempName::TempName(TempName const &)
82 tempname_ = TempName()();
88 tempname_.removeFile();
92 TempName & TempName::operator=(TempName const & other)
95 tempname_ = TempName()();
102 /// The translator between the Display enum and corresponding lyx string.
103 Translator<DisplayType, string> const initTranslator()
105 Translator<DisplayType, string> translator(DefaultDisplay, "default");
107 // Fill the display translator
108 translator.addPair(MonochromeDisplay, "monochrome");
109 translator.addPair(GrayscaleDisplay, "grayscale");
110 translator.addPair(ColorDisplay, "color");
111 translator.addPair(PreviewDisplay, "preview");
112 translator.addPair(NoDisplay, "none");
120 Translator<DisplayType, string> const & displayTranslator()
122 static Translator<DisplayType, string> const translator =
127 } // namespace external
130 InsetExternalParams::InsetExternalParams()
131 : display(defaultDisplayType),
132 lyxscale(defaultLyxScale),
135 if (defaultTemplateName.empty()) {
136 external::TemplateManager const & etm =
137 external::TemplateManager::get();
138 templatename_ = etm.getTemplates().begin()->first;
140 templatename_ = defaultTemplateName;
146 template <typename T>
147 void clearIfNotFound(T & data, external::TransformID value,
148 vector<external::TransformID> const & ids)
150 typedef vector<external::TransformID>::const_iterator
153 const_iterator it = ids.begin();
154 const_iterator end = ids.end();
155 it = find(it, end, value);
163 void InsetExternalParams::settemplate(string const & name)
165 templatename_ = name;
167 external::TemplateManager const & etm =
168 external::TemplateManager::get();
169 external::Template const * const et = etm.getTemplateByName(name);
171 // Be safe. Don't lose data.
174 // Ascertain which transforms the template supports.
175 // Empty all those that it doesn't.
176 vector<external::TransformID> const & ids = et->transformIds;
177 clearIfNotFound(clipdata, external::Clip, ids);
178 clearIfNotFound(extradata, external::Extra, ids);
179 clearIfNotFound(resizedata, external::Resize, ids);
180 clearIfNotFound(rotationdata, external::Rotate, ids);
184 void InsetExternalParams::write(Buffer const & buf, ostream & os) const
187 << "\ttemplate " << templatename() << '\n';
189 if (!filename.empty()) {
190 os << "\tfilename " << filename.outputFilename(buf.filePath()) << '\n';
191 os << "\tembed " << (filename.embedded() ? filename.inzipName() : "\"\"") << '\n';
193 if (display != defaultDisplayType)
195 << external::displayTranslator().find(display)
198 if (lyxscale != defaultLyxScale)
199 os << "\tlyxscale " << convert<string>(lyxscale) << '\n';
204 if (!clipdata.bbox.empty())
205 os << "\tboundingBox " << clipdata.bbox << '\n';
209 external::ExtraData::const_iterator it = extradata.begin();
210 external::ExtraData::const_iterator end = extradata.end();
211 for (; it != end; ++it) {
212 if (!it->second.empty())
213 os << "\textra " << it->first << " \""
214 << it->second << "\"\n";
217 if (!rotationdata.no_rotation()) {
218 os << "\trotateAngle " << rotationdata.adjAngle() << '\n';
219 if (rotationdata.origin() != external::RotationData::DEFAULT)
220 os << "\trotateOrigin "
221 << rotationdata.originString() << '\n';
224 if (!resizedata.no_resize()) {
225 double const scl = convert<double>(resizedata.scale);
226 if (!float_equal(scl, 0.0, 0.05)) {
227 if (!float_equal(scl, 100.0, 0.05))
229 << resizedata.scale << '\n';
231 if (!resizedata.width.zero())
233 << resizedata.width.asString() << '\n';
234 if (!resizedata.height.zero())
236 << resizedata.height.asString() << '\n';
238 if (resizedata.keepAspectRatio)
239 os << "\tkeepAspectRatio\n";
244 bool InsetExternalParams::read(Buffer const & buffer, Lexer & lex)
265 keyword_item external_tags[] = {
266 { "\\end_inset", EX_END },
267 { "boundingBox", EX_BOUNDINGBOX },
269 { "display", EX_DISPLAY},
270 { "draft", EX_DRAFT},
271 { "embed", EX_EMBED},
272 { "extra", EX_EXTRA },
273 { "filename", EX_FILENAME},
274 { "height", EX_HEIGHT },
275 { "keepAspectRatio", EX_KEEPASPECTRATIO },
276 { "lyxscale", EX_LYXSCALE},
277 { "rotateAngle", EX_ROTATEANGLE },
278 { "rotateOrigin", EX_ROTATEORIGIN },
279 { "scale", EX_SCALE },
280 { "template", EX_TEMPLATE },
281 { "width", EX_WIDTH }
284 PushPopHelper pph(lex, external_tags, EX_END);
286 bool found_end = false;
287 bool read_error = false;
293 templatename_ = lex.getString();
298 string const name = lex.getString();
299 filename.set(name, buffer.filePath());
305 string const name = lex.getString();
306 filename.setInzipName(name);
307 filename.setEmbed(!name.empty());
313 string const name = lex.getString();
314 display = external::displayTranslator().find(name);
320 lyxscale = lex.getInteger();
329 clipdata.bbox.xl = lex.getInteger();
331 clipdata.bbox.yb = lex.getInteger();
333 clipdata.bbox.xr = lex.getInteger();
335 clipdata.bbox.yt = lex.getInteger();
339 clipdata.clip = true;
344 string const name = lex.getString();
346 extradata.set(name, lex.getString());
352 resizedata.height = Length(lex.getString());
355 case EX_KEEPASPECTRATIO:
356 resizedata.keepAspectRatio = true;
361 rotationdata.angle = lex.getString();
364 case EX_ROTATEORIGIN:
366 rotationdata.origin(lex.getString());
371 resizedata.scale = lex.getString();
376 resizedata.width = Length(lex.getString());
384 lex.printError("ExternalInset::read: Wrong tag: $$Token");
389 if (found_end || read_error)
394 lex.printError("ExternalInsetParams::read: Missing \\end_inset.");
396 // This is a trick to make sure that the data are self-consistent.
397 settemplate(templatename_);
399 if (lyxerr.debugging(Debug::EXTERNAL)) {
400 lyxerr << "InsetExternalParams::read:\n";
401 write(buffer, lyxerr);
408 InsetExternal::InsetExternal()
409 : renderer_(new RenderButton)
413 InsetExternal::InsetExternal(InsetExternal const & other)
415 boost::signals::trackable(),
416 params_(other.params_),
417 renderer_(other.renderer_->clone(this))
421 InsetExternal::~InsetExternal()
423 InsetExternalMailer(*this).hideDialog();
427 void InsetExternal::statusChanged() const
433 void InsetExternal::doDispatch(Cursor & cur, FuncRequest & cmd)
435 switch (cmd.action) {
437 case LFUN_EXTERNAL_EDIT: {
438 InsetExternalParams p;
439 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
440 external::editExternal(p, buffer());
444 case LFUN_INSET_MODIFY: {
445 InsetExternalParams p;
446 InsetExternalMailer::string2params(to_utf8(cmd.argument()), buffer(), p);
447 if (!p.filename.empty()) {
449 p.filename.enable(buffer().embedded(), &buffer(), true);
450 } catch (ExceptionMessage const & message) {
451 Alert::error(message.title_, message.details_);
452 // do not set parameter if an error happens
460 case LFUN_INSET_DIALOG_UPDATE:
461 InsetExternalMailer(*this).updateDialog(&cur.bv());
464 case LFUN_MOUSE_RELEASE:
465 if (!cur.selection())
466 InsetExternalMailer(*this).showDialog(&cur.bv());
470 Inset::doDispatch(cur, cmd);
475 bool InsetExternal::getStatus(Cursor & cur, FuncRequest const & cmd,
476 FuncStatus & flag) const
478 switch (cmd.action) {
480 case LFUN_EXTERNAL_EDIT:
481 case LFUN_INSET_MODIFY:
482 case LFUN_INSET_DIALOG_UPDATE:
487 return Inset::getStatus(cur, cmd, flag);
492 void InsetExternal::registerEmbeddedFiles(EmbeddedFileList & files) const
494 files.registerFile(params_.filename, this, buffer());
498 void InsetExternal::updateEmbeddedFile(EmbeddedFile const & file)
500 params_.filename = file;
504 void InsetExternal::edit(Cursor & cur, bool, EntryDirection)
506 InsetExternalMailer(*this).showDialog(&cur.bv());
510 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
512 renderer_->metrics(mi, dim);
516 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
518 renderer_->draw(pi, x, y);
531 RenderType getRenderType(InsetExternalParams const & p)
533 if (!external::getTemplatePtr(p) ||
534 p.filename.empty() ||
535 p.display == external::NoDisplay)
538 if (p.display == external::PreviewDisplay) {
539 if (RenderPreview::status() != LyXRC::PREVIEW_OFF)
540 return RENDERPREVIEW;
544 if (p.display == external::DefaultDisplay &&
545 lyxrc.display_graphics == graphics::NoDisplay)
547 return RENDERGRAPHIC;
551 graphics::Params get_grfx_params(InsetExternalParams const & eparams)
553 graphics::Params gparams;
555 gparams.filename = eparams.filename.availableFile();
556 gparams.icon = eparams.filename.embedded() ? "pin.png" : "";
557 gparams.scale = eparams.lyxscale;
558 if (eparams.clipdata.clip)
559 gparams.bb = eparams.clipdata.bbox;
560 gparams.angle = convert<double>(eparams.rotationdata.adjAngle());
562 switch (eparams.display) {
563 case external::DefaultDisplay:
564 gparams.display = graphics::DefaultDisplay;
566 case external::MonochromeDisplay:
567 gparams.display = graphics::MonochromeDisplay;
569 case external::GrayscaleDisplay:
570 gparams.display = graphics::GrayscaleDisplay;
572 case external::ColorDisplay:
573 gparams.display = graphics::ColorDisplay;
575 case external::NoDisplay:
576 gparams.display = graphics::NoDisplay;
581 if (gparams.display == graphics::DefaultDisplay)
582 gparams.display = graphics::DisplayType(lyxrc.display_graphics);
583 // Override the above if we're not using a gui
585 gparams.display = graphics::NoDisplay;
591 docstring screenLabel(InsetExternalParams const & params,
592 Buffer const & buffer)
594 external::Template const * const ptr =
595 external::getTemplatePtr(params);
598 return bformat((_("External template %1$s is not installed")),
599 from_utf8(params.templatename()));
601 docstring gui = _(ptr->guiName);
602 return from_utf8(external::doSubstitution(params, buffer,
603 to_utf8(gui), false));
609 static bool isPreviewWanted(InsetExternalParams const & params)
611 return params.display == external::PreviewDisplay &&
612 params.filename.isReadableFile();
616 static docstring latexString(InsetExternal const & inset)
619 // We don't need to set runparams.encoding since it is not used by
621 OutputParams runparams(0);
622 runparams.flavor = OutputParams::LATEX;
623 inset.latex(os, runparams);
628 static void add_preview_and_start_loading(RenderMonitoredPreview & renderer,
629 InsetExternal const & inset,
630 Buffer const & buffer)
632 InsetExternalParams const & params = inset.params();
634 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
635 isPreviewWanted(params)) {
636 renderer.setAbsFile(params.filename);
637 docstring const snippet = latexString(inset);
638 renderer.addPreview(snippet, buffer);
639 renderer.startLoading(buffer);
644 InsetExternalParams const & InsetExternal::params() const
650 void InsetExternal::setParams(InsetExternalParams const & p)
654 // Subsequent calls to the InsetExternal::Params default constructor
656 defaultTemplateName = params_.templatename();
658 switch (getRenderType(params_)) {
660 RenderButton * button_ptr = renderer_->asButton();
662 renderer_.reset(new RenderButton);
663 button_ptr = renderer_->asButton();
666 button_ptr->update(screenLabel(params_, buffer()), true);
670 case RENDERGRAPHIC: {
671 RenderGraphic * graphic_ptr = renderer_->asGraphic();
673 renderer_.reset(new RenderGraphic(this));
674 graphic_ptr = renderer_->asGraphic();
677 graphic_ptr->update(get_grfx_params(params_));
682 case RENDERPREVIEW: {
683 RenderMonitoredPreview * preview_ptr =
684 renderer_->asMonitoredPreview();
686 renderer_.reset(new RenderMonitoredPreview(this));
687 preview_ptr = renderer_->asMonitoredPreview();
688 preview_ptr->fileChanged(
689 boost::bind(&InsetExternal::fileChanged, this));
692 if (preview_ptr->monitoring())
693 preview_ptr->stopMonitoring();
694 add_preview_and_start_loading(*preview_ptr, *this, buffer());
702 void InsetExternal::fileChanged() const
704 Buffer const * const buffer = updateFrontend();
708 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
711 ptr->removePreview(*buffer);
712 add_preview_and_start_loading(*ptr, *this, *buffer);
716 void InsetExternal::write(ostream & os) const
718 params_.write(buffer(), os);
722 void InsetExternal::read(Lexer & lex)
724 InsetExternalParams params;
725 if (params.read(buffer(), lex)) {
726 // exception handling is not needed as long as embedded files are in place.
727 params.filename.enable(buffer().embedded(), &buffer(), false);
733 int InsetExternal::latex(odocstream & os, OutputParams const & runparams) const
737 os << "\\fbox{\\ttfamily{}"
738 << from_utf8(params_.filename.outputFilename(buffer().filePath()))
743 // "nice" means that the buffer is exported to LaTeX format but not
744 // run through the LaTeX compiler.
745 // If we're running through the LaTeX compiler, we should write the
746 // generated files in the buffer's temporary directory.
747 bool const external_in_tmpdir = !runparams.nice;
748 bool const dryrun = runparams.dryrun || runparams.inComment;
750 // If the template has specified a PDFLaTeX output, then we try and
752 if (runparams.flavor == OutputParams::PDFLATEX) {
753 external::Template const * const et_ptr =
754 external::getTemplatePtr(params_);
757 external::Template const & et = *et_ptr;
759 external::Template::Formats::const_iterator cit =
760 et.formats.find("PDFLaTeX");
762 if (cit != et.formats.end()) {
763 return external::writeExternal(params_, "PDFLaTeX",
765 *(runparams.exportdata),
771 return external::writeExternal(params_, "LaTeX", buffer(), os,
772 *(runparams.exportdata),
778 int InsetExternal::plaintext(odocstream & os,
779 OutputParams const & runparams) const
781 os << '\n'; // output external material on a new line
782 external::writeExternal(params_, "Ascii", buffer(), os,
783 *(runparams.exportdata), false,
784 runparams.dryrun || runparams.inComment);
785 return PLAINTEXT_NEWLINE;
789 int InsetExternal::docbook(odocstream & os,
790 OutputParams const & runparams) const
792 return external::writeExternal(params_, "DocBook", buffer(), os,
793 *(runparams.exportdata), false,
794 runparams.dryrun || runparams.inComment);
798 void InsetExternal::validate(LaTeXFeatures & features) const
803 external::Template const * const et_ptr =
804 external::getTemplatePtr(params_);
807 external::Template const & et = *et_ptr;
810 switch (features.runparams().flavor) {
811 case OutputParams::LATEX:
814 case OutputParams::PDFLATEX:
817 case OutputParams::XML:
821 external::Template::Formats::const_iterator cit =
822 et.formats.find(format);
823 if (cit == et.formats.end())
826 // FIXME: We don't need that always
827 features.require("lyxdot");
829 vector<string>::const_iterator it = cit->second.requirements.begin();
830 vector<string>::const_iterator end = cit->second.requirements.end();
831 for (; it != end; ++it)
832 features.require(*it);
834 external::TemplateManager & etm = external::TemplateManager::get();
836 it = cit->second.preambleNames.begin();
837 end = cit->second.preambleNames.end();
838 for (; it != end; ++it) {
839 string const preamble = etm.getPreambleDefByName(*it);
840 if (!preamble.empty())
841 features.addPreambleSnippet(preamble);
850 void InsetExternal::addPreview(graphics::PreviewLoader & ploader) const
852 RenderMonitoredPreview * const ptr = renderer_->asMonitoredPreview();
856 if (isPreviewWanted(params())) {
857 ptr->setAbsFile(params_.filename);
858 docstring const snippet = latexString(*this);
859 ptr->addPreview(snippet, ploader);
866 string const InsetExternalMailer::name_("external");
868 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
873 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
875 return params2string(inset_.params(), buffer);
879 void InsetExternalMailer::string2params(string const & in,
880 Buffer const & buffer,
881 InsetExternalParams & params)
883 params = InsetExternalParams();
887 istringstream data(in);
893 if (!lex || name != name_)
894 return print_mailer_error("InsetExternalMailer", in, 1, name_);
896 // This is part of the inset proper that is usually swallowed
897 // by Text::readInset
900 if (!lex || id != "External")
901 return print_mailer_error("InsetBoxMailer", in, 2, "External");
903 params.read(buffer, lex);
908 InsetExternalMailer::params2string(InsetExternalParams const & params,
909 Buffer const & buffer)
912 data << name_ << ' ';
913 params.write(buffer, data);
914 data << "\\end_inset\n";