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 InsetExternal::InsetExternal()
134 : renderer_(new ButtonRenderer)
138 InsetExternal::InsetExternal(InsetExternal const & other)
140 boost::signals::trackable(),
141 params_(other.params_),
142 renderer_(other.renderer_->clone())
144 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
146 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
151 auto_ptr<InsetBase> InsetExternal::clone() const
153 return auto_ptr<InsetBase>(new InsetExternal(*this));
157 InsetExternal::~InsetExternal()
159 InsetExternalMailer(*this).hideDialog();
163 void InsetExternal::statusChanged()
165 BufferView * bv = renderer_->view();
167 bv->updateInset(this);
171 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
173 switch (cmd.action) {
175 case LFUN_EXTERNAL_EDIT: {
176 BOOST_ASSERT(cmd.view());
178 Buffer const & buffer = *cmd.view()->buffer();
179 InsetExternal::Params p;
180 InsetExternalMailer::string2params(cmd.argument, buffer, p);
181 editExternal(p, buffer);
182 return DISPATCHED_NOUPDATE;
185 case LFUN_INSET_MODIFY: {
186 BOOST_ASSERT(cmd.view());
188 Buffer const & buffer = *cmd.view()->buffer();
189 InsetExternal::Params p;
190 InsetExternalMailer::string2params(cmd.argument, buffer, p);
191 setParams(p, buffer);
192 cmd.view()->updateInset(this);
196 case LFUN_INSET_DIALOG_UPDATE:
197 InsetExternalMailer(*this).updateDialog(cmd.view());
200 case LFUN_MOUSE_RELEASE:
201 case LFUN_INSET_EDIT:
202 InsetExternalMailer(*this).showDialog(cmd.view());
211 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
213 renderer_->metrics(mi, dim);
218 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
220 renderer_->draw(pi, x, y);
226 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
228 lyx::graphics::Params gparams;
230 gparams.filename = eparams.filename.absFilename();
231 gparams.scale = eparams.lyxscale;
232 gparams.display = eparams.display;
234 if (gparams.display == lyx::graphics::DefaultDisplay)
235 gparams.display = lyxrc.display_graphics;
237 // Override the above if we're not using a gui
238 if (!lyx_gui::use_gui)
239 gparams.display = lyx::graphics::NoDisplay;
245 string const getScreenLabel(InsetExternal::Params const & params,
246 Buffer const & buffer)
248 ExternalTemplate const * const ptr = getTemplatePtr(params);
250 return support::bformat(_("External template %1$s is not installed"),
251 params.templatename());
252 return doSubstitution(params, buffer, ptr->guiName);
258 InsetExternal::Params const & InsetExternal::params() const
264 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
266 // The stored params; what we would like to happen in an ideal world.
269 // We display the inset as a button by default.
270 bool display_button = (!getTemplatePtr(params_) ||
271 params_.filename.empty() ||
272 params_.display == lyx::graphics::NoDisplay);
274 if (display_button) {
275 ButtonRenderer * button_ptr =
276 dynamic_cast<ButtonRenderer *>(renderer_.get());
278 button_ptr = new ButtonRenderer;
279 renderer_.reset(button_ptr);
282 button_ptr->update(getScreenLabel(params_, buffer), true);
285 GraphicRenderer * graphic_ptr =
286 dynamic_cast<GraphicRenderer *>(renderer_.get());
288 graphic_ptr = new GraphicRenderer;
289 graphic_ptr->connect(
290 boost::bind(&InsetExternal::statusChanged, this));
291 renderer_.reset(graphic_ptr);
294 graphic_ptr->update(get_grfx_params(params_));
299 void InsetExternal::write(Buffer const & buffer, ostream & os) const
302 << "\ttemplate " << params_.templatename() << '\n';
304 if (!params_.filename.empty())
306 << params_.filename.outputFilename(buffer.filePath())
309 if (params_.display != defaultDisplayType)
310 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
313 if (params_.lyxscale != defaultLyxScale)
314 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
318 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
328 keyword_item external_tags[] = {
329 { "\\end_inset", EX_END },
330 { "display", EX_DISPLAY},
331 { "filename", EX_FILENAME},
332 { "lyxscale", EX_LYXSCALE},
333 { "template", EX_TEMPLATE }
336 pushpophelper pph(lex, external_tags, EX_END);
338 bool found_end = false;
339 bool read_error = false;
341 InsetExternal::Params params;
346 params.settemplate(lex.getString());
352 string const name = lex.getString();
353 params.filename.set(name, buffer.filePath());
359 string const name = lex.getString();
360 params.display = lyx::graphics::displayTranslator.find(name);
366 params.lyxscale = lex.getInteger();
375 lex.printError("ExternalInset::read: "
376 "Wrong tag: $$Token");
381 if (found_end || read_error)
386 lex.printError("ExternalInset::read: "
387 "Missing \\end_inset.");
390 // Replace the inset's store
391 setParams(params, buffer);
393 lyxerr[Debug::EXTERNAL]
394 << "InsetExternal::Read: "
395 << "template: '" << params_.templatename()
396 << "' filename: '" << params_.filename.absFilename()
397 << "' display: '" << params_.display
398 << "' scale: '" << params_.lyxscale
403 int InsetExternal::write(string const & format,
404 Buffer const & buf, ostream & os,
405 bool external_in_tmpdir) const
407 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
410 ExternalTemplate const & et = *et_ptr;
412 ExternalTemplate::Formats::const_iterator cit =
413 et.formats.find(format);
414 if (cit == et.formats.end()) {
415 lyxerr[Debug::EXTERNAL]
416 << "External template format '" << format
417 << "' not specified in template "
418 << params_.templatename() << endl;
422 updateExternal(format, buf, external_in_tmpdir);
423 string const str = doSubstitution(params_, buf, cit->second.product);
425 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
429 int InsetExternal::latex(Buffer const & buf, ostream & os,
430 LatexRunParams const & runparams) const
432 // "nice" means that the buffer is exported to LaTeX format but not
433 // run through the LaTeX compiler.
434 // If we're running through the LaTeX compiler, we should write the
435 // generated files in the bufer's temporary directory.
436 bool const external_in_tmpdir =
437 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
439 // If the template has specified a PDFLaTeX output, then we try and
441 if (runparams.flavor == LatexRunParams::PDFLATEX) {
442 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
445 ExternalTemplate const & et = *et_ptr;
447 ExternalTemplate::Formats::const_iterator cit =
448 et.formats.find("PDFLaTeX");
449 if (cit != et.formats.end())
450 return write("PDFLaTeX", buf, os, external_in_tmpdir);
453 return write("LaTeX", buf, os, external_in_tmpdir);
457 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
459 return write("Ascii", buf, os);
463 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
465 return write("LinuxDoc", buf, os);
469 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
471 return write("DocBook", buf, os);
475 void InsetExternal::validate(LaTeXFeatures & features) const
477 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
480 ExternalTemplate const & et = *et_ptr;
482 ExternalTemplate::Formats::const_iterator cit = et.formats.find("LaTeX");
483 if (cit == et.formats.end())
486 if (!cit->second.requirement.empty())
487 features.require(cit->second.requirement);
489 ExternalTemplateManager & etm = ExternalTemplateManager::get();
491 vector<string>::const_iterator it = cit->second.preambleNames.begin();
492 vector<string>::const_iterator end = cit->second.preambleNames.end();
493 for (; it != end; ++it) {
494 string const preamble = etm.getPreambleDefByName(*it);
495 if (!preamble.empty())
496 features.addExternalPreamble(preamble);
501 void InsetExternal::updateExternal(string const & format,
503 bool external_in_tmpdir) const
505 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
508 ExternalTemplate const & et = *et_ptr;
510 if (!et.automaticProduction)
513 ExternalTemplate::Formats::const_iterator cit =
514 et.formats.find(format);
515 if (cit == et.formats.end())
518 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
519 if (outputFormat.updateResult.empty())
522 string from_format = et.inputFormat;
523 if (from_format.empty())
526 string from_file = params_.filename.absFilename();
528 if (from_format == "*") {
529 if (from_file.empty())
532 // Try and ascertain the file format from its contents.
533 from_format = support::getExtFromContents(from_file);
534 if (from_format.empty())
538 string const to_format = outputFormat.updateFormat;
539 if (to_format.empty())
542 if (!converters.isReachable(from_format, to_format)) {
543 lyxerr[Debug::EXTERNAL]
544 << "InsetExternal::updateExternal. "
545 << "Unable to convert from "
546 << from_format << " to " << to_format << endl;
550 if (external_in_tmpdir && !from_file.empty()) {
551 // We are running stuff through LaTeX
552 string const temp_file =
553 support::MakeAbsPath(params_.filename.mangledFilename(),
555 unsigned long const from_checksum = support::sum(from_file);
556 unsigned long const temp_checksum = support::sum(temp_file);
559 if (from_checksum == temp_checksum)
563 if (!support::copy(from_file, temp_file))
565 from_file = temp_file;
568 string const to_file = doSubstitution(params_, buf,
569 outputFormat.updateResult);
570 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
572 // Do we need to perform the conversion?
573 // Yes if to_file does not exist or if from_file is newer than to_file
574 if (support::compare_timestamps(from_file, abs_to_file) < 0)
577 string const to_filebase = support::ChangeExtension(to_file, string());
578 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
584 /// Substitute meta-variables in this string
585 string const doSubstitution(InsetExternal::Params const & params,
586 Buffer const & buffer, string const & s)
589 string const buffer_path = buffer.filePath();
590 string const filename = params.filename.outputFilename(buffer_path);
591 string const basename = support::ChangeExtension(filename, string());
592 string const filepath = support::OnlyPath(filename);
594 result = support::subst(s, "$$FName", filename);
595 result = support::subst(result, "$$Basename", basename);
596 result = support::subst(result, "$$FPath", filepath);
597 result = support::subst(result, "$$Tempname", params.tempname());
598 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
600 // Handle the $$Contents(filename) syntax
601 if (support::contains(result, "$$Contents(\"")) {
603 string::size_type const pos = result.find("$$Contents(\"");
604 string::size_type const end = result.find("\")", pos);
605 string const file = result.substr(pos + 12, end - (pos + 12));
608 string const filepath = support::IsFileReadable(file) ?
609 buffer.filePath() : buffer.temppath();
610 support::Path p(filepath);
612 if (support::IsFileReadable(file))
613 contents = support::GetFileContents(file);
615 result = support::subst(result,
616 ("$$Contents(\"" + file + "\")").c_str(),
624 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
626 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
629 ExternalTemplate const & et = *et_ptr;
631 if (et.editCommand.empty())
634 string const command = doSubstitution(params, buffer, et.editCommand);
636 support::Path p(buffer.filePath());
637 support::Forkedcall call;
638 if (lyxerr.debugging(Debug::EXTERNAL)) {
639 lyxerr << "Executing '" << command << "' in '"
640 << buffer.filePath() << '\'' << endl;
642 call.startscript(support::Forkedcall::DontWait, command);
647 string const InsetExternalMailer::name_("external");
649 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
654 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
656 return params2string(inset_.params(), buffer);
660 void InsetExternalMailer::string2params(string const & in,
661 Buffer const & buffer,
662 InsetExternal::Params & params)
664 params = InsetExternal::Params();
669 istringstream data(in);
675 string const token = lex.getString();
680 // This is part of the inset proper that is usually swallowed
681 // by Buffer::readInset
684 string const token = lex.getString();
685 if (token != "External")
691 inset.read(buffer, lex);
692 params = inset.params();
698 InsetExternalMailer::params2string(InsetExternal::Params const & params,
699 Buffer const & buffer)
702 inset.setParams(params, buffer);
704 data << name_ << ' ';
705 inset.write(buffer, data);
706 data << "\\end_inset\n";