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"
24 #include "latexrunparams.h"
27 #include "support/std_sstream.h"
29 #include "frontends/lyx_gui.h"
31 #include "support/filetools.h"
32 #include "support/forkedcall.h"
33 #include "support/lstrings.h"
34 #include "support/lyxalgo.h"
35 #include "support/lyxlib.h"
36 #include "support/path.h"
37 #include "support/path_defines.h"
38 #include "support/tostr.h"
39 #include "support/translator.h"
41 #include <boost/bind.hpp>
43 namespace support = lyx::support;
48 using std::istringstream;
50 using std::ostringstream;
56 /// The translator between the DisplayType and the corresponding lyx string.
57 extern Translator<DisplayType, string> displayTranslator;
63 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
65 unsigned int defaultLyxScale = 100;
67 /// Substitute meta-variables in string s, makeing use of params and buffer.
68 string const doSubstitution(InsetExternal::Params const & params,
69 Buffer const & buffer, string const & s);
71 /// Invoke the external editor.
72 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
75 ExternalTemplate const * getTemplatePtr(string const & name)
77 ExternalTemplateManager const & etm = ExternalTemplateManager::get();
78 return etm.getTemplateByName(name);
82 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
84 ExternalTemplateManager const & etm = ExternalTemplateManager::get();
85 return etm.getTemplateByName(params.templatename());
91 InsetExternal::TempName::TempName()
93 tempname_ = support::tempName(string(), "lyxext");
94 support::unlink(tempname_);
95 // must have an extension for the converter code to work correctly.
100 InsetExternal::TempName::TempName(InsetExternal::TempName const &)
102 tempname_ = TempName()();
106 InsetExternal::TempName::~TempName()
108 support::unlink(tempname_);
112 InsetExternal::TempName &
113 InsetExternal::TempName::operator=(InsetExternal::TempName const & other)
116 tempname_ = TempName()();
121 InsetExternal::Params::Params()
122 : display(defaultDisplayType),
123 lyxscale(defaultLyxScale)
127 void InsetExternal::Params::settemplate(string const & name)
129 templatename_ = name;
133 void InsetExternal::Params::write(Buffer const & buffer, ostream & os) const
136 << "\ttemplate " << templatename() << '\n';
138 if (!filename.empty())
140 << filename.outputFilename(buffer.filePath())
143 if (display != defaultDisplayType)
144 os << "\tdisplay " << lyx::graphics::displayTranslator.find(display)
147 if (lyxscale != defaultLyxScale)
148 os << "\tlyxscale " << tostr(lyxscale) << '\n';
152 bool InsetExternal::Params::read(Buffer const & buffer, LyXLex & lex)
162 keyword_item external_tags[] = {
163 { "\\end_inset", EX_END },
164 { "display", EX_DISPLAY},
165 { "filename", EX_FILENAME},
166 { "lyxscale", EX_LYXSCALE},
167 { "template", EX_TEMPLATE }
170 pushpophelper pph(lex, external_tags, EX_END);
172 bool found_end = false;
173 bool read_error = false;
179 templatename_ = lex.getString();
184 string const name = lex.getString();
185 filename.set(name, buffer.filePath());
191 string const name = lex.getString();
192 display = lyx::graphics::displayTranslator.find(name);
198 lyxscale = lex.getInteger();
206 lex.printError("ExternalInset::read: "
207 "Wrong tag: $$Token");
212 if (found_end || read_error)
217 lex.printError("ExternalInset::read: "
218 "Missing \\end_inset.");
221 // This is a trick to make sure that the data are self-consistent.
222 settemplate(templatename_);
224 lyxerr[Debug::EXTERNAL]
225 << "InsetExternal::Params::read: "
226 << "template: '" << templatename()
227 << "' filename: '" << filename.absFilename()
228 << "' display: '" << display
229 << "' scale: '" << lyxscale
236 InsetExternal::InsetExternal()
237 : renderer_(new ButtonRenderer)
241 InsetExternal::InsetExternal(InsetExternal const & other)
243 boost::signals::trackable(),
244 params_(other.params_),
245 renderer_(other.renderer_->clone())
247 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
249 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
254 auto_ptr<InsetBase> InsetExternal::clone() const
256 return auto_ptr<InsetBase>(new InsetExternal(*this));
260 InsetExternal::~InsetExternal()
262 InsetExternalMailer(*this).hideDialog();
266 void InsetExternal::statusChanged()
268 BufferView * bv = renderer_->view();
270 bv->updateInset(this);
274 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
276 switch (cmd.action) {
278 case LFUN_EXTERNAL_EDIT: {
279 BOOST_ASSERT(cmd.view());
281 Buffer const & buffer = *cmd.view()->buffer();
282 InsetExternal::Params p;
283 InsetExternalMailer::string2params(cmd.argument, buffer, p);
284 editExternal(p, buffer);
285 return DISPATCHED_NOUPDATE;
288 case LFUN_INSET_MODIFY: {
289 BOOST_ASSERT(cmd.view());
291 Buffer const & buffer = *cmd.view()->buffer();
292 InsetExternal::Params p;
293 InsetExternalMailer::string2params(cmd.argument, buffer, p);
294 setParams(p, buffer);
295 cmd.view()->updateInset(this);
299 case LFUN_INSET_DIALOG_UPDATE:
300 InsetExternalMailer(*this).updateDialog(cmd.view());
303 case LFUN_MOUSE_RELEASE:
304 case LFUN_INSET_EDIT:
305 InsetExternalMailer(*this).showDialog(cmd.view());
314 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
316 renderer_->metrics(mi, dim);
321 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
323 renderer_->draw(pi, x, y);
329 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
331 lyx::graphics::Params gparams;
333 gparams.filename = eparams.filename.absFilename();
334 gparams.scale = eparams.lyxscale;
335 gparams.display = eparams.display;
337 if (gparams.display == lyx::graphics::DefaultDisplay)
338 gparams.display = lyxrc.display_graphics;
340 // Override the above if we're not using a gui
341 if (!lyx_gui::use_gui)
342 gparams.display = lyx::graphics::NoDisplay;
348 string const getScreenLabel(InsetExternal::Params const & params,
349 Buffer const & buffer)
351 ExternalTemplate const * const ptr = getTemplatePtr(params);
353 return support::bformat(_("External template %1$s is not installed"),
354 params.templatename());
355 return doSubstitution(params, buffer, ptr->guiName);
361 InsetExternal::Params const & InsetExternal::params() const
367 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
369 // The stored params; what we would like to happen in an ideal world.
372 // We display the inset as a button by default.
373 bool display_button = (!getTemplatePtr(params_) ||
374 params_.filename.empty() ||
375 params_.display == lyx::graphics::NoDisplay);
377 if (display_button) {
378 ButtonRenderer * button_ptr =
379 dynamic_cast<ButtonRenderer *>(renderer_.get());
381 button_ptr = new ButtonRenderer;
382 renderer_.reset(button_ptr);
385 button_ptr->update(getScreenLabel(params_, buffer), true);
388 GraphicRenderer * graphic_ptr =
389 dynamic_cast<GraphicRenderer *>(renderer_.get());
391 graphic_ptr = new GraphicRenderer;
392 graphic_ptr->connect(
393 boost::bind(&InsetExternal::statusChanged, this));
394 renderer_.reset(graphic_ptr);
397 graphic_ptr->update(get_grfx_params(params_));
402 void InsetExternal::write(Buffer const & buffer, ostream & os) const
404 params_.write(buffer, os);
408 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
411 if (params.read(buffer, lex))
412 setParams(params, buffer);
416 int InsetExternal::write(string const & format,
417 Buffer const & buf, ostream & os,
418 bool external_in_tmpdir) const
420 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
423 ExternalTemplate const & et = *et_ptr;
425 ExternalTemplate::Formats::const_iterator cit =
426 et.formats.find(format);
427 if (cit == et.formats.end()) {
428 lyxerr[Debug::EXTERNAL]
429 << "External template format '" << format
430 << "' not specified in template "
431 << params_.templatename() << endl;
435 updateExternal(format, buf, external_in_tmpdir);
436 string const str = doSubstitution(params_, buf, cit->second.product);
438 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
442 int InsetExternal::latex(Buffer const & buf, ostream & os,
443 LatexRunParams const & runparams) const
445 // "nice" means that the buffer is exported to LaTeX format but not
446 // run through the LaTeX compiler.
447 // If we're running through the LaTeX compiler, we should write the
448 // generated files in the bufer's temporary directory.
449 bool const external_in_tmpdir =
450 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
452 // If the template has specified a PDFLaTeX output, then we try and
454 if (runparams.flavor == LatexRunParams::PDFLATEX) {
455 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
458 ExternalTemplate const & et = *et_ptr;
460 ExternalTemplate::Formats::const_iterator cit =
461 et.formats.find("PDFLaTeX");
462 if (cit != et.formats.end())
463 return write("PDFLaTeX", buf, os, external_in_tmpdir);
466 return write("LaTeX", buf, os, external_in_tmpdir);
470 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
472 return write("Ascii", buf, os);
476 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
478 return write("LinuxDoc", buf, os);
482 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
484 return write("DocBook", buf, os);
488 void InsetExternal::validate(LaTeXFeatures & features) const
490 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
493 ExternalTemplate const & et = *et_ptr;
495 ExternalTemplate::Formats::const_iterator cit = et.formats.find("LaTeX");
496 if (cit == et.formats.end())
499 if (!cit->second.requirement.empty())
500 features.require(cit->second.requirement);
502 ExternalTemplateManager & etm = ExternalTemplateManager::get();
504 vector<string>::const_iterator it = cit->second.preambleNames.begin();
505 vector<string>::const_iterator end = cit->second.preambleNames.end();
506 for (; it != end; ++it) {
507 string const preamble = etm.getPreambleDefByName(*it);
508 if (!preamble.empty())
509 features.addExternalPreamble(preamble);
514 void InsetExternal::updateExternal(string const & format,
516 bool external_in_tmpdir) const
518 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
521 ExternalTemplate const & et = *et_ptr;
523 if (!et.automaticProduction)
526 ExternalTemplate::Formats::const_iterator cit =
527 et.formats.find(format);
528 if (cit == et.formats.end())
531 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
532 if (outputFormat.updateResult.empty())
535 string from_format = et.inputFormat;
536 if (from_format.empty())
539 string from_file = params_.filename.absFilename();
541 if (from_format == "*") {
542 if (from_file.empty())
545 // Try and ascertain the file format from its contents.
546 from_format = support::getExtFromContents(from_file);
547 if (from_format.empty())
551 string const to_format = outputFormat.updateFormat;
552 if (to_format.empty())
555 if (!converters.isReachable(from_format, to_format)) {
556 lyxerr[Debug::EXTERNAL]
557 << "InsetExternal::updateExternal. "
558 << "Unable to convert from "
559 << from_format << " to " << to_format << endl;
563 if (external_in_tmpdir && !from_file.empty()) {
564 // We are running stuff through LaTeX
565 string const temp_file =
566 support::MakeAbsPath(params_.filename.mangledFilename(),
568 unsigned long const from_checksum = support::sum(from_file);
569 unsigned long const temp_checksum = support::sum(temp_file);
572 if (from_checksum == temp_checksum)
576 if (!support::copy(from_file, temp_file))
578 from_file = temp_file;
581 string const to_file = doSubstitution(params_, buf,
582 outputFormat.updateResult);
583 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
585 // Do we need to perform the conversion?
586 // Yes if to_file does not exist or if from_file is newer than to_file
587 if (support::compare_timestamps(from_file, abs_to_file) < 0)
590 string const to_filebase = support::ChangeExtension(to_file, string());
591 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
597 /// Substitute meta-variables in this string
598 string const doSubstitution(InsetExternal::Params const & params,
599 Buffer const & buffer, string const & s)
602 string const buffer_path = buffer.filePath();
603 string const filename = params.filename.outputFilename(buffer_path);
604 string const basename = support::ChangeExtension(filename, string());
605 string const filepath = support::OnlyPath(filename);
607 result = support::subst(s, "$$FName", filename);
608 result = support::subst(result, "$$Basename", basename);
609 result = support::subst(result, "$$FPath", filepath);
610 result = support::subst(result, "$$Tempname", params.tempname());
611 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
613 // Handle the $$Contents(filename) syntax
614 if (support::contains(result, "$$Contents(\"")) {
616 string::size_type const pos = result.find("$$Contents(\"");
617 string::size_type const end = result.find("\")", pos);
618 string const file = result.substr(pos + 12, end - (pos + 12));
621 string const filepath = support::IsFileReadable(file) ?
622 buffer.filePath() : buffer.temppath();
623 support::Path p(filepath);
625 if (support::IsFileReadable(file))
626 contents = support::GetFileContents(file);
628 result = support::subst(result,
629 ("$$Contents(\"" + file + "\")").c_str(),
637 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
639 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
642 ExternalTemplate const & et = *et_ptr;
644 if (et.editCommand.empty())
647 string const command = doSubstitution(params, buffer, et.editCommand);
649 support::Path p(buffer.filePath());
650 support::Forkedcall call;
651 if (lyxerr.debugging(Debug::EXTERNAL)) {
652 lyxerr << "Executing '" << command << "' in '"
653 << buffer.filePath() << '\'' << endl;
655 call.startscript(support::Forkedcall::DontWait, command);
660 string const InsetExternalMailer::name_("external");
662 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
667 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
669 return params2string(inset_.params(), buffer);
673 void InsetExternalMailer::string2params(string const & in,
674 Buffer const & buffer,
675 InsetExternal::Params & params)
677 params = InsetExternal::Params();
682 istringstream data(in);
688 string const token = lex.getString();
693 // This is part of the inset proper that is usually swallowed
694 // by Buffer::readInset
697 string const token = lex.getString();
698 if (token != "External")
703 params.read(buffer, lex);
709 InsetExternalMailer::params2string(InsetExternal::Params const & params,
710 Buffer const & buffer)
713 data << name_ << ' ';
714 params.write(buffer, data);
715 data << "\\end_inset\n";