2 * \file insetexternal.C
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/renderers.h"
17 #include "BufferView.h"
18 #include "converter.h"
20 #include "ExternalTemplate.h"
21 #include "funcrequest.h"
23 #include "LaTeXFeatures.h"
26 #include "support/std_sstream.h"
28 #include "frontends/lyx_gui.h"
30 #include "support/filetools.h"
31 #include "support/forkedcall.h"
32 #include "support/lstrings.h"
33 #include "support/lyxalgo.h"
34 #include "support/lyxlib.h"
35 #include "support/path.h"
36 #include "support/path_defines.h"
37 #include "support/tostr.h"
38 #include "support/translator.h"
40 #include <boost/bind.hpp>
42 namespace support = lyx::support;
51 /// The translator between the DisplayType and the corresponding lyx string.
52 extern Translator<DisplayType, string> displayTranslator;
58 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
60 unsigned int defaultLyxScale = 100;
62 /// Substitute meta-variables in string s, makeing use of params and buffer.
63 string const doSubstitution(InsetExternal::Params const & params,
64 Buffer const & buffer, string const & s);
66 /// Invoke the external editor.
67 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
72 InsetExternal::Params::Params()
73 : display(defaultDisplayType),
74 lyxscale(defaultLyxScale)
76 tempname = support::tempName(string(), "lyxext");
77 support::unlink(tempname);
78 // must have an extension for the converter code to work correctly.
83 InsetExternal::Params::~Params()
85 support::unlink(tempname);
89 InsetExternal::InsetExternal()
90 : renderer_(new ButtonRenderer)
94 InsetExternal::InsetExternal(InsetExternal const & other)
96 boost::signals::trackable(),
97 params_(other.params_),
98 renderer_(other.renderer_->clone())
100 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
102 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
107 auto_ptr<InsetBase> InsetExternal::clone() const
109 return auto_ptr<InsetBase>(new InsetExternal(*this));
113 InsetExternal::~InsetExternal()
115 InsetExternalMailer(*this).hideDialog();
119 void InsetExternal::statusChanged()
121 BufferView * bv = renderer_->view();
123 bv->updateInset(this);
127 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
129 switch (cmd.action) {
131 case LFUN_EXTERNAL_EDIT: {
132 support::Assert(cmd.view());
134 Buffer const & buffer = *cmd.view()->buffer();
135 InsetExternal::Params p;
136 InsetExternalMailer::string2params(cmd.argument, buffer, p);
137 editExternal(p, buffer);
138 return DISPATCHED_NOUPDATE;
141 case LFUN_INSET_MODIFY: {
142 support::Assert(cmd.view());
144 Buffer const & buffer = *cmd.view()->buffer();
145 InsetExternal::Params p;
146 InsetExternalMailer::string2params(cmd.argument, buffer, p);
147 setParams(p, buffer);
148 cmd.view()->updateInset(this);
152 case LFUN_INSET_DIALOG_UPDATE:
153 InsetExternalMailer(*this).updateDialog(cmd.view());
156 case LFUN_MOUSE_RELEASE:
157 case LFUN_INSET_EDIT:
158 InsetExternalMailer(*this).showDialog(cmd.view());
167 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
169 renderer_->metrics(mi, dim);
174 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
176 renderer_->draw(pi, x, y);
182 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
184 lyx::graphics::Params gparams;
186 gparams.filename = eparams.filename.absFilename();
187 gparams.scale = eparams.lyxscale;
188 gparams.display = eparams.display;
190 if (gparams.display == lyx::graphics::DefaultDisplay)
191 gparams.display = lyxrc.display_graphics;
193 // Override the above if we're not using a gui
194 if (!lyx_gui::use_gui)
195 gparams.display = lyx::graphics::NoDisplay;
201 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
203 ExternalTemplateManager & etm = ExternalTemplateManager::get();
204 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
205 if (templ.lyxName.empty())
211 string const getScreenLabel(InsetExternal::Params const & params,
212 Buffer const & buffer)
214 ExternalTemplate const * const ptr = getTemplatePtr(params);
216 return support::bformat(_("External template %1$s is not installed"),
217 params.templatename);
218 return doSubstitution(params, buffer, ptr->guiName);
224 InsetExternal::Params const & InsetExternal::params() const
230 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
232 // The stored params; what we would like to happen in an ideal world.
233 params_.filename = p.filename;
234 params_.templatename = p.templatename;
235 params_.display = p.display;
236 params_.lyxscale = p.lyxscale;
238 // We display the inset as a button by default.
239 bool display_button = (!getTemplatePtr(params_) ||
240 params_.filename.empty() ||
241 params_.display == lyx::graphics::NoDisplay);
243 if (display_button) {
244 ButtonRenderer * button_ptr =
245 dynamic_cast<ButtonRenderer *>(renderer_.get());
247 button_ptr = new ButtonRenderer;
248 renderer_.reset(button_ptr);
251 button_ptr->update(getScreenLabel(params_, buffer), true);
254 GraphicRenderer * graphic_ptr =
255 dynamic_cast<GraphicRenderer *>(renderer_.get());
257 graphic_ptr = new GraphicRenderer;
258 graphic_ptr->connect(
259 boost::bind(&InsetExternal::statusChanged, this));
260 renderer_.reset(graphic_ptr);
263 graphic_ptr->update(get_grfx_params(params_));
268 void InsetExternal::write(Buffer const & buffer, ostream & os) const
271 << "\ttemplate " << params_.templatename << '\n';
273 if (!params_.filename.empty())
275 << params_.filename.outputFilename(buffer.filePath())
278 if (params_.display != defaultDisplayType)
279 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
282 if (params_.lyxscale != defaultLyxScale)
283 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
287 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
297 keyword_item external_tags[] = {
298 { "\\end_inset", EX_END },
299 { "display", EX_DISPLAY},
300 { "filename", EX_FILENAME},
301 { "lyxscale", EX_LYXSCALE},
302 { "template", EX_TEMPLATE }
305 pushpophelper pph(lex, external_tags, EX_END);
307 bool found_end = false;
308 bool read_error = false;
310 InsetExternal::Params params;
315 params.templatename = lex.getString();
321 string const name = lex.getString();
322 params.filename.set(name, buffer.filePath());
328 string const name = lex.getString();
329 params.display = lyx::graphics::displayTranslator.find(name);
335 params.lyxscale = lex.getInteger();
344 lex.printError("ExternalInset::read: "
345 "Wrong tag: $$Token");
350 if (found_end || read_error)
355 lex.printError("ExternalInset::read: "
356 "Missing \\end_inset.");
359 // Replace the inset's store
360 setParams(params, buffer);
362 lyxerr[Debug::EXTERNAL]
363 << "InsetExternal::Read: "
364 << "template: '" << params_.templatename
365 << "' filename: '" << params_.filename.absFilename()
366 << "' display: '" << params_.display
367 << "' scale: '" << params_.lyxscale
372 int InsetExternal::write(string const & format,
373 Buffer const & buf, ostream & os,
374 bool external_in_tmpdir) const
376 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
379 ExternalTemplate const & et = *et_ptr;
381 ExternalTemplate::Formats::const_iterator cit =
382 et.formats.find(format);
383 if (cit == et.formats.end()) {
384 lyxerr[Debug::EXTERNAL]
385 << "External template format '" << format
386 << "' not specified in template "
387 << params_.templatename << endl;
391 updateExternal(format, buf, external_in_tmpdir);
392 string const str = doSubstitution(params_, buf, cit->second.product);
394 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
398 int InsetExternal::latex(Buffer const & buf, ostream & os,
399 LatexRunParams const & runparams) const
401 // "nice" means that the buffer is exported to LaTeX format but not
402 // run through the LaTeX compiler.
403 // If we're running through the LaTeX compiler, we should write the
404 // generated files in the bufer's temporary directory.
405 bool const external_in_tmpdir =
406 lyxrc.use_tempdir && !buf.tmppath.empty() && !runparams.nice;
408 // If the template has specified a PDFLaTeX output, then we try and
410 if (runparams.flavor == LatexRunParams::PDFLATEX) {
411 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
414 ExternalTemplate const & et = *et_ptr;
416 ExternalTemplate::Formats::const_iterator cit =
417 et.formats.find("PDFLaTeX");
418 if (cit != et.formats.end())
419 return write("PDFLaTeX", buf, os, external_in_tmpdir);
422 return write("LaTeX", buf, os, external_in_tmpdir);
426 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
428 return write("Ascii", buf, os);
432 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
434 return write("LinuxDoc", buf, os);
438 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
440 return write("DocBook", buf, os);
444 void InsetExternal::validate(LaTeXFeatures & features) const
446 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
449 ExternalTemplate const & et = *et_ptr;
451 ExternalTemplate::Formats::const_iterator cit = et.formats.find("LaTeX");
452 if (cit == et.formats.end())
455 if (!cit->second.requirement.empty())
456 features.require(cit->second.requirement);
458 ExternalTemplateManager & etm = ExternalTemplateManager::get();
459 string const preamble = etm.getPreambleDefByName(cit->second.preambleName);
460 if (!preamble.empty())
461 features.addExternalPreamble(preamble);
465 void InsetExternal::updateExternal(string const & format,
467 bool external_in_tmpdir) const
469 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
472 ExternalTemplate const & et = *et_ptr;
474 if (!et.automaticProduction)
477 ExternalTemplate::Formats::const_iterator cit =
478 et.formats.find(format);
479 if (cit == et.formats.end())
482 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
483 if (outputFormat.updateResult.empty())
486 string from_format = et.inputFormat;
487 if (from_format.empty())
490 string from_file = params_.filename.absFilename();
492 if (from_format == "*") {
493 if (from_file.empty())
496 // Try and ascertain the file format from its contents.
497 from_format = support::getExtFromContents(from_file);
498 if (from_format.empty())
502 string const to_format = outputFormat.updateFormat;
503 if (to_format.empty())
506 if (!converters.isReachable(from_format, to_format)) {
507 lyxerr[Debug::EXTERNAL]
508 << "InsetExternal::updateExternal. "
509 << "Unable to convert from "
510 << from_format << " to " << to_format << endl;
514 if (external_in_tmpdir && !from_file.empty()) {
515 // We are running stuff through LaTeX
516 string const temp_file =
517 support::MakeAbsPath(params_.filename.mangledFilename(),
519 unsigned long const from_checksum = support::sum(from_file);
520 unsigned long const temp_checksum = support::sum(temp_file);
523 if (from_checksum == temp_checksum)
527 if (!support::copy(from_file, temp_file))
529 from_file = temp_file;
532 string const to_file = doSubstitution(params_, buf,
533 outputFormat.updateResult);
534 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
536 // Do we need to perform the conversion?
537 // Yes if to_file does not exist or if from_file is newer than to_file
538 if (support::compare_timestamps(from_file, abs_to_file) < 0)
541 string const to_filebase = support::ChangeExtension(to_file, string());
542 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
548 /// Substitute meta-variables in this string
549 string const doSubstitution(InsetExternal::Params const & params,
550 Buffer const & buffer, string const & s)
553 string const buffer_path = buffer.filePath();
554 string const filename = params.filename.outputFilename(buffer_path);
555 string const basename = support::ChangeExtension(filename, string());
556 string const filepath = support::OnlyPath(filename);
558 result = support::subst(s, "$$FName", filename);
559 result = support::subst(result, "$$Basename", basename);
560 result = support::subst(result, "$$FPath", filepath);
561 result = support::subst(result, "$$Tempname", params.tempname);
562 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
564 // Handle the $$Contents(filename) syntax
565 if (support::contains(result, "$$Contents(\"")) {
567 string::size_type const pos = result.find("$$Contents(\"");
568 string::size_type const end = result.find("\")", pos);
569 string const file = result.substr(pos + 12, end - (pos + 12));
572 string const filepath = support::IsFileReadable(file) ?
573 buffer.filePath() : buffer.tmppath;
574 support::Path p(filepath);
576 if (support::IsFileReadable(file))
577 contents = support::GetFileContents(file);
579 result = support::subst(result,
580 ("$$Contents(\"" + file + "\")").c_str(),
588 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
590 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
593 ExternalTemplate const & et = *et_ptr;
595 if (et.editCommand.empty())
598 string const command = doSubstitution(params, buffer, et.editCommand);
600 support::Path p(buffer.filePath());
601 support::Forkedcall call;
602 if (lyxerr.debugging(Debug::EXTERNAL)) {
603 lyxerr << "Executing '" << command << "' in '"
604 << buffer.filePath() << '\'' << endl;
606 call.startscript(support::Forkedcall::DontWait, command);
611 string const InsetExternalMailer::name_("external");
613 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
618 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
620 return params2string(inset_.params(), buffer);
624 void InsetExternalMailer::string2params(string const & in,
625 Buffer const & buffer,
626 InsetExternal::Params & params)
628 params = InsetExternal::Params();
633 istringstream data(STRCONV(in));
639 string const token = lex.getString();
644 // This is part of the inset proper that is usually swallowed
645 // by Buffer::readInset
648 string const token = lex.getString();
649 if (token != "External")
655 inset.read(buffer, lex);
656 params = inset.params();
662 InsetExternalMailer::params2string(InsetExternal::Params const & params,
663 Buffer const & buffer)
666 inset.setParams(params, buffer);
668 data << name_ << ' ';
669 inset.write(buffer, data);
670 data << "\\end_inset\n";
671 return STRCONV(data.str());