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;
47 using std::istringstream;
49 using std::ostringstream;
54 /// The translator between the DisplayType and the corresponding lyx string.
55 extern Translator<DisplayType, string> displayTranslator;
61 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
63 unsigned int defaultLyxScale = 100;
65 /// Substitute meta-variables in string s, makeing use of params and buffer.
66 string const doSubstitution(InsetExternal::Params const & params,
67 Buffer const & buffer, string const & s);
69 /// Invoke the external editor.
70 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
75 InsetExternal::Params::Params()
76 : display(defaultDisplayType),
77 lyxscale(defaultLyxScale)
79 tempname = support::tempName(string(), "lyxext");
80 support::unlink(tempname);
81 // must have an extension for the converter code to work correctly.
86 InsetExternal::Params::~Params()
88 support::unlink(tempname);
92 InsetExternal::InsetExternal()
93 : renderer_(new ButtonRenderer)
97 InsetExternal::InsetExternal(InsetExternal const & other)
99 boost::signals::trackable(),
100 params_(other.params_),
101 renderer_(other.renderer_->clone())
103 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
105 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
110 auto_ptr<InsetBase> InsetExternal::clone() const
112 return auto_ptr<InsetBase>(new InsetExternal(*this));
116 InsetExternal::~InsetExternal()
118 InsetExternalMailer(*this).hideDialog();
122 void InsetExternal::statusChanged()
124 BufferView * bv = renderer_->view();
126 bv->updateInset(this);
130 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
132 switch (cmd.action) {
134 case LFUN_EXTERNAL_EDIT: {
135 BOOST_ASSERT(cmd.view());
137 Buffer const & buffer = *cmd.view()->buffer();
138 InsetExternal::Params p;
139 InsetExternalMailer::string2params(cmd.argument, buffer, p);
140 editExternal(p, buffer);
141 return DISPATCHED_NOUPDATE;
144 case LFUN_INSET_MODIFY: {
145 BOOST_ASSERT(cmd.view());
147 Buffer const & buffer = *cmd.view()->buffer();
148 InsetExternal::Params p;
149 InsetExternalMailer::string2params(cmd.argument, buffer, p);
150 setParams(p, buffer);
151 cmd.view()->updateInset(this);
155 case LFUN_INSET_DIALOG_UPDATE:
156 InsetExternalMailer(*this).updateDialog(cmd.view());
159 case LFUN_MOUSE_RELEASE:
160 case LFUN_INSET_EDIT:
161 InsetExternalMailer(*this).showDialog(cmd.view());
170 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
172 renderer_->metrics(mi, dim);
177 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
179 renderer_->draw(pi, x, y);
185 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
187 lyx::graphics::Params gparams;
189 gparams.filename = eparams.filename.absFilename();
190 gparams.scale = eparams.lyxscale;
191 gparams.display = eparams.display;
193 if (gparams.display == lyx::graphics::DefaultDisplay)
194 gparams.display = lyxrc.display_graphics;
196 // Override the above if we're not using a gui
197 if (!lyx_gui::use_gui)
198 gparams.display = lyx::graphics::NoDisplay;
204 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
206 ExternalTemplateManager & etm = ExternalTemplateManager::get();
207 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
208 if (templ.lyxName.empty())
214 string const getScreenLabel(InsetExternal::Params const & params,
215 Buffer const & buffer)
217 ExternalTemplate const * const ptr = getTemplatePtr(params);
219 return support::bformat(_("External template %1$s is not installed"),
220 params.templatename);
221 return doSubstitution(params, buffer, ptr->guiName);
227 InsetExternal::Params const & InsetExternal::params() const
233 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
235 // The stored params; what we would like to happen in an ideal world.
236 params_.filename = p.filename;
237 params_.templatename = p.templatename;
238 params_.display = p.display;
239 params_.lyxscale = p.lyxscale;
241 // We display the inset as a button by default.
242 bool display_button = (!getTemplatePtr(params_) ||
243 params_.filename.empty() ||
244 params_.display == lyx::graphics::NoDisplay);
246 if (display_button) {
247 ButtonRenderer * button_ptr =
248 dynamic_cast<ButtonRenderer *>(renderer_.get());
250 button_ptr = new ButtonRenderer;
251 renderer_.reset(button_ptr);
254 button_ptr->update(getScreenLabel(params_, buffer), true);
257 GraphicRenderer * graphic_ptr =
258 dynamic_cast<GraphicRenderer *>(renderer_.get());
260 graphic_ptr = new GraphicRenderer;
261 graphic_ptr->connect(
262 boost::bind(&InsetExternal::statusChanged, this));
263 renderer_.reset(graphic_ptr);
266 graphic_ptr->update(get_grfx_params(params_));
271 void InsetExternal::write(Buffer const & buffer, ostream & os) const
274 << "\ttemplate " << params_.templatename << '\n';
276 if (!params_.filename.empty())
278 << params_.filename.outputFilename(buffer.filePath())
281 if (params_.display != defaultDisplayType)
282 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
285 if (params_.lyxscale != defaultLyxScale)
286 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
290 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
300 keyword_item external_tags[] = {
301 { "\\end_inset", EX_END },
302 { "display", EX_DISPLAY},
303 { "filename", EX_FILENAME},
304 { "lyxscale", EX_LYXSCALE},
305 { "template", EX_TEMPLATE }
308 pushpophelper pph(lex, external_tags, EX_END);
310 bool found_end = false;
311 bool read_error = false;
313 InsetExternal::Params params;
318 params.templatename = lex.getString();
324 string const name = lex.getString();
325 params.filename.set(name, buffer.filePath());
331 string const name = lex.getString();
332 params.display = lyx::graphics::displayTranslator.find(name);
338 params.lyxscale = lex.getInteger();
347 lex.printError("ExternalInset::read: "
348 "Wrong tag: $$Token");
353 if (found_end || read_error)
358 lex.printError("ExternalInset::read: "
359 "Missing \\end_inset.");
362 // Replace the inset's store
363 setParams(params, buffer);
365 lyxerr[Debug::EXTERNAL]
366 << "InsetExternal::Read: "
367 << "template: '" << params_.templatename
368 << "' filename: '" << params_.filename.absFilename()
369 << "' display: '" << params_.display
370 << "' scale: '" << params_.lyxscale
375 int InsetExternal::write(string const & format,
376 Buffer const & buf, ostream & os,
377 bool external_in_tmpdir) const
379 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
382 ExternalTemplate const & et = *et_ptr;
384 ExternalTemplate::Formats::const_iterator cit =
385 et.formats.find(format);
386 if (cit == et.formats.end()) {
387 lyxerr[Debug::EXTERNAL]
388 << "External template format '" << format
389 << "' not specified in template "
390 << params_.templatename << endl;
394 updateExternal(format, buf, external_in_tmpdir);
395 string const str = doSubstitution(params_, buf, cit->second.product);
397 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
401 int InsetExternal::latex(Buffer const & buf, ostream & os,
402 LatexRunParams const & runparams) const
404 // "nice" means that the buffer is exported to LaTeX format but not
405 // run through the LaTeX compiler.
406 // If we're running through the LaTeX compiler, we should write the
407 // generated files in the bufer's temporary directory.
408 bool const external_in_tmpdir =
409 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
411 // If the template has specified a PDFLaTeX output, then we try and
413 if (runparams.flavor == LatexRunParams::PDFLATEX) {
414 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
417 ExternalTemplate const & et = *et_ptr;
419 ExternalTemplate::Formats::const_iterator cit =
420 et.formats.find("PDFLaTeX");
421 if (cit != et.formats.end())
422 return write("PDFLaTeX", buf, os, external_in_tmpdir);
425 return write("LaTeX", buf, os, external_in_tmpdir);
429 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
431 return write("Ascii", buf, os);
435 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
437 return write("LinuxDoc", buf, os);
441 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
443 return write("DocBook", buf, os);
447 void InsetExternal::validate(LaTeXFeatures & features) const
449 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
452 ExternalTemplate const & et = *et_ptr;
454 ExternalTemplate::Formats::const_iterator cit = et.formats.find("LaTeX");
455 if (cit == et.formats.end())
458 if (!cit->second.requirement.empty())
459 features.require(cit->second.requirement);
461 ExternalTemplateManager & etm = ExternalTemplateManager::get();
462 string const preamble = etm.getPreambleDefByName(cit->second.preambleName);
463 if (!preamble.empty())
464 features.addExternalPreamble(preamble);
468 void InsetExternal::updateExternal(string const & format,
470 bool external_in_tmpdir) const
472 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
475 ExternalTemplate const & et = *et_ptr;
477 if (!et.automaticProduction)
480 ExternalTemplate::Formats::const_iterator cit =
481 et.formats.find(format);
482 if (cit == et.formats.end())
485 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
486 if (outputFormat.updateResult.empty())
489 string from_format = et.inputFormat;
490 if (from_format.empty())
493 string from_file = params_.filename.absFilename();
495 if (from_format == "*") {
496 if (from_file.empty())
499 // Try and ascertain the file format from its contents.
500 from_format = support::getExtFromContents(from_file);
501 if (from_format.empty())
505 string const to_format = outputFormat.updateFormat;
506 if (to_format.empty())
509 if (!converters.isReachable(from_format, to_format)) {
510 lyxerr[Debug::EXTERNAL]
511 << "InsetExternal::updateExternal. "
512 << "Unable to convert from "
513 << from_format << " to " << to_format << endl;
517 if (external_in_tmpdir && !from_file.empty()) {
518 // We are running stuff through LaTeX
519 string const temp_file =
520 support::MakeAbsPath(params_.filename.mangledFilename(),
522 unsigned long const from_checksum = support::sum(from_file);
523 unsigned long const temp_checksum = support::sum(temp_file);
526 if (from_checksum == temp_checksum)
530 if (!support::copy(from_file, temp_file))
532 from_file = temp_file;
535 string const to_file = doSubstitution(params_, buf,
536 outputFormat.updateResult);
537 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
539 // Do we need to perform the conversion?
540 // Yes if to_file does not exist or if from_file is newer than to_file
541 if (support::compare_timestamps(from_file, abs_to_file) < 0)
544 string const to_filebase = support::ChangeExtension(to_file, string());
545 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
551 /// Substitute meta-variables in this string
552 string const doSubstitution(InsetExternal::Params const & params,
553 Buffer const & buffer, string const & s)
556 string const buffer_path = buffer.filePath();
557 string const filename = params.filename.outputFilename(buffer_path);
558 string const basename = support::ChangeExtension(filename, string());
559 string const filepath = support::OnlyPath(filename);
561 result = support::subst(s, "$$FName", filename);
562 result = support::subst(result, "$$Basename", basename);
563 result = support::subst(result, "$$FPath", filepath);
564 result = support::subst(result, "$$Tempname", params.tempname);
565 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
567 // Handle the $$Contents(filename) syntax
568 if (support::contains(result, "$$Contents(\"")) {
570 string::size_type const pos = result.find("$$Contents(\"");
571 string::size_type const end = result.find("\")", pos);
572 string const file = result.substr(pos + 12, end - (pos + 12));
575 string const filepath = support::IsFileReadable(file) ?
576 buffer.filePath() : buffer.temppath();
577 support::Path p(filepath);
579 if (support::IsFileReadable(file))
580 contents = support::GetFileContents(file);
582 result = support::subst(result,
583 ("$$Contents(\"" + file + "\")").c_str(),
591 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
593 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
596 ExternalTemplate const & et = *et_ptr;
598 if (et.editCommand.empty())
601 string const command = doSubstitution(params, buffer, et.editCommand);
603 support::Path p(buffer.filePath());
604 support::Forkedcall call;
605 if (lyxerr.debugging(Debug::EXTERNAL)) {
606 lyxerr << "Executing '" << command << "' in '"
607 << buffer.filePath() << '\'' << endl;
609 call.startscript(support::Forkedcall::DontWait, command);
614 string const InsetExternalMailer::name_("external");
616 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
621 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
623 return params2string(inset_.params(), buffer);
627 void InsetExternalMailer::string2params(string const & in,
628 Buffer const & buffer,
629 InsetExternal::Params & params)
631 params = InsetExternal::Params();
636 istringstream data(STRCONV(in));
642 string const token = lex.getString();
647 // This is part of the inset proper that is usually swallowed
648 // by Buffer::readInset
651 string const token = lex.getString();
652 if (token != "External")
658 inset.read(buffer, lex);
659 params = inset.params();
665 InsetExternalMailer::params2string(InsetExternal::Params const & params,
666 Buffer const & buffer)
669 inset.setParams(params, buffer);
671 data << name_ << ' ';
672 inset.write(buffer, data);
673 data << "\\end_inset\n";
674 return STRCONV(data.str());