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;
44 namespace external = lyx::external;
49 using std::istringstream;
51 using std::ostringstream;
57 /// The translator between the DisplayType and the corresponding lyx string.
58 extern Translator<DisplayType, string> displayTranslator;
64 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
66 unsigned int defaultLyxScale = 100;
68 /// Substitute meta-variables in string s, makeing use of params and buffer.
69 string const doSubstitution(InsetExternal::Params const & params,
70 Buffer const & buffer, string const & s);
72 /// Invoke the external editor.
73 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
76 external::Template const * getTemplatePtr(string const & name)
78 external::TemplateManager const & etm =
79 external::TemplateManager::get();
80 return etm.getTemplateByName(name);
84 external::Template const * getTemplatePtr(InsetExternal::Params const & params)
86 external::TemplateManager const & etm =
87 external::TemplateManager::get();
88 return etm.getTemplateByName(params.templatename());
94 InsetExternal::TempName::TempName()
96 tempname_ = support::tempName(string(), "lyxext");
97 support::unlink(tempname_);
98 // must have an extension for the converter code to work correctly.
103 InsetExternal::TempName::TempName(InsetExternal::TempName const &)
105 tempname_ = TempName()();
109 InsetExternal::TempName::~TempName()
111 support::unlink(tempname_);
115 InsetExternal::TempName &
116 InsetExternal::TempName::operator=(InsetExternal::TempName const & other)
119 tempname_ = TempName()();
124 InsetExternal::Params::Params()
125 : display(defaultDisplayType),
126 lyxscale(defaultLyxScale)
130 void InsetExternal::Params::settemplate(string const & name)
132 templatename_ = name;
136 void InsetExternal::Params::write(Buffer const & buffer, ostream & os) const
139 << "\ttemplate " << templatename() << '\n';
141 if (!filename.empty())
143 << filename.outputFilename(buffer.filePath())
146 if (display != defaultDisplayType)
147 os << "\tdisplay " << lyx::graphics::displayTranslator.find(display)
150 if (lyxscale != defaultLyxScale)
151 os << "\tlyxscale " << tostr(lyxscale) << '\n';
155 bool InsetExternal::Params::read(Buffer const & buffer, LyXLex & lex)
165 keyword_item external_tags[] = {
166 { "\\end_inset", EX_END },
167 { "display", EX_DISPLAY},
168 { "filename", EX_FILENAME},
169 { "lyxscale", EX_LYXSCALE},
170 { "template", EX_TEMPLATE }
173 pushpophelper pph(lex, external_tags, EX_END);
175 bool found_end = false;
176 bool read_error = false;
182 templatename_ = lex.getString();
187 string const name = lex.getString();
188 filename.set(name, buffer.filePath());
194 string const name = lex.getString();
195 display = lyx::graphics::displayTranslator.find(name);
201 lyxscale = lex.getInteger();
209 lex.printError("ExternalInset::read: "
210 "Wrong tag: $$Token");
215 if (found_end || read_error)
220 lex.printError("ExternalInset::read: "
221 "Missing \\end_inset.");
224 // This is a trick to make sure that the data are self-consistent.
225 settemplate(templatename_);
227 lyxerr[Debug::EXTERNAL]
228 << "InsetExternal::Params::read: "
229 << "template: '" << templatename()
230 << "' filename: '" << filename.absFilename()
231 << "' display: '" << display
232 << "' scale: '" << lyxscale
239 InsetExternal::InsetExternal()
240 : renderer_(new ButtonRenderer)
244 InsetExternal::InsetExternal(InsetExternal const & other)
246 boost::signals::trackable(),
247 params_(other.params_),
248 renderer_(other.renderer_->clone())
250 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
252 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
257 auto_ptr<InsetBase> InsetExternal::clone() const
259 return auto_ptr<InsetBase>(new InsetExternal(*this));
263 InsetExternal::~InsetExternal()
265 InsetExternalMailer(*this).hideDialog();
269 void InsetExternal::statusChanged()
271 BufferView * bv = renderer_->view();
273 bv->updateInset(this);
277 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
279 switch (cmd.action) {
281 case LFUN_EXTERNAL_EDIT: {
282 BOOST_ASSERT(cmd.view());
284 Buffer const & buffer = *cmd.view()->buffer();
285 InsetExternal::Params p;
286 InsetExternalMailer::string2params(cmd.argument, buffer, p);
287 editExternal(p, buffer);
288 return DISPATCHED_NOUPDATE;
291 case LFUN_INSET_MODIFY: {
292 BOOST_ASSERT(cmd.view());
294 Buffer const & buffer = *cmd.view()->buffer();
295 InsetExternal::Params p;
296 InsetExternalMailer::string2params(cmd.argument, buffer, p);
297 setParams(p, buffer);
298 cmd.view()->updateInset(this);
302 case LFUN_INSET_DIALOG_UPDATE:
303 InsetExternalMailer(*this).updateDialog(cmd.view());
306 case LFUN_MOUSE_RELEASE:
307 case LFUN_INSET_EDIT:
308 InsetExternalMailer(*this).showDialog(cmd.view());
317 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
319 renderer_->metrics(mi, dim);
324 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
326 renderer_->draw(pi, x, y);
332 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
334 lyx::graphics::Params gparams;
336 gparams.filename = eparams.filename.absFilename();
337 gparams.scale = eparams.lyxscale;
338 gparams.display = eparams.display;
340 if (gparams.display == lyx::graphics::DefaultDisplay)
341 gparams.display = lyxrc.display_graphics;
343 // Override the above if we're not using a gui
344 if (!lyx_gui::use_gui)
345 gparams.display = lyx::graphics::NoDisplay;
351 string const getScreenLabel(InsetExternal::Params const & params,
352 Buffer const & buffer)
354 external::Template const * const ptr = getTemplatePtr(params);
356 return support::bformat(_("External template %1$s is not installed"),
357 params.templatename());
358 return doSubstitution(params, buffer, ptr->guiName);
364 InsetExternal::Params const & InsetExternal::params() const
370 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
372 // The stored params; what we would like to happen in an ideal world.
375 // We display the inset as a button by default.
376 bool display_button = (!getTemplatePtr(params_) ||
377 params_.filename.empty() ||
378 params_.display == lyx::graphics::NoDisplay);
380 if (display_button) {
381 ButtonRenderer * button_ptr =
382 dynamic_cast<ButtonRenderer *>(renderer_.get());
384 button_ptr = new ButtonRenderer;
385 renderer_.reset(button_ptr);
388 button_ptr->update(getScreenLabel(params_, buffer), true);
391 GraphicRenderer * graphic_ptr =
392 dynamic_cast<GraphicRenderer *>(renderer_.get());
394 graphic_ptr = new GraphicRenderer;
395 graphic_ptr->connect(
396 boost::bind(&InsetExternal::statusChanged, this));
397 renderer_.reset(graphic_ptr);
400 graphic_ptr->update(get_grfx_params(params_));
405 void InsetExternal::write(Buffer const & buffer, ostream & os) const
407 params_.write(buffer, os);
411 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
414 if (params.read(buffer, lex))
415 setParams(params, buffer);
419 int InsetExternal::write(string const & format,
420 Buffer const & buf, ostream & os,
421 bool external_in_tmpdir) const
423 external::Template const * const et_ptr = getTemplatePtr(params_);
426 external::Template const & et = *et_ptr;
428 external::Template::Formats::const_iterator cit =
429 et.formats.find(format);
430 if (cit == et.formats.end()) {
431 lyxerr[Debug::EXTERNAL]
432 << "External template format '" << format
433 << "' not specified in template "
434 << params_.templatename() << endl;
438 updateExternal(format, buf, external_in_tmpdir);
439 string const str = doSubstitution(params_, buf, cit->second.product);
441 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
445 int InsetExternal::latex(Buffer const & buf, ostream & os,
446 LatexRunParams const & runparams) const
448 // "nice" means that the buffer is exported to LaTeX format but not
449 // run through the LaTeX compiler.
450 // If we're running through the LaTeX compiler, we should write the
451 // generated files in the bufer's temporary directory.
452 bool const external_in_tmpdir =
453 lyxrc.use_tempdir && !buf.temppath().empty() && !runparams.nice;
455 // If the template has specified a PDFLaTeX output, then we try and
457 if (runparams.flavor == LatexRunParams::PDFLATEX) {
458 external::Template const * const et_ptr = getTemplatePtr(params_);
461 external::Template const & et = *et_ptr;
463 external::Template::Formats::const_iterator cit =
464 et.formats.find("PDFLaTeX");
465 if (cit != et.formats.end())
466 return write("PDFLaTeX", buf, os, external_in_tmpdir);
469 return write("LaTeX", buf, os, external_in_tmpdir);
473 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
475 return write("Ascii", buf, os);
479 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
481 return write("LinuxDoc", buf, os);
485 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
487 return write("DocBook", buf, os);
491 void InsetExternal::validate(LaTeXFeatures & features) const
493 external::Template const * const et_ptr = getTemplatePtr(params_);
496 external::Template const & et = *et_ptr;
498 external::Template::Formats::const_iterator cit = et.formats.find("LaTeX");
499 if (cit == et.formats.end())
502 if (!cit->second.requirement.empty())
503 features.require(cit->second.requirement);
505 external::TemplateManager & etm = external::TemplateManager::get();
507 vector<string>::const_iterator it = cit->second.preambleNames.begin();
508 vector<string>::const_iterator end = cit->second.preambleNames.end();
509 for (; it != end; ++it) {
510 string const preamble = etm.getPreambleDefByName(*it);
511 if (!preamble.empty())
512 features.addExternalPreamble(preamble);
517 void InsetExternal::updateExternal(string const & format,
519 bool external_in_tmpdir) const
521 external::Template const * const et_ptr = getTemplatePtr(params_);
524 external::Template const & et = *et_ptr;
526 if (!et.automaticProduction)
529 external::Template::Formats::const_iterator cit =
530 et.formats.find(format);
531 if (cit == et.formats.end())
534 external::Template::Format const & outputFormat = cit->second;
535 if (outputFormat.updateResult.empty())
538 string from_format = et.inputFormat;
539 if (from_format.empty())
542 string from_file = params_.filename.absFilename();
544 if (from_format == "*") {
545 if (from_file.empty())
548 // Try and ascertain the file format from its contents.
549 from_format = support::getExtFromContents(from_file);
550 if (from_format.empty())
554 string const to_format = outputFormat.updateFormat;
555 if (to_format.empty())
558 if (!converters.isReachable(from_format, to_format)) {
559 lyxerr[Debug::EXTERNAL]
560 << "InsetExternal::updateExternal. "
561 << "Unable to convert from "
562 << from_format << " to " << to_format << endl;
566 if (external_in_tmpdir && !from_file.empty()) {
567 // We are running stuff through LaTeX
568 string const temp_file =
569 support::MakeAbsPath(params_.filename.mangledFilename(),
571 unsigned long const from_checksum = support::sum(from_file);
572 unsigned long const temp_checksum = support::sum(temp_file);
575 if (from_checksum == temp_checksum)
579 if (!support::copy(from_file, temp_file))
581 from_file = temp_file;
584 string const to_file = doSubstitution(params_, buf,
585 outputFormat.updateResult);
586 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
588 // Do we need to perform the conversion?
589 // Yes if to_file does not exist or if from_file is newer than to_file
590 if (support::compare_timestamps(from_file, abs_to_file) < 0)
593 string const to_filebase = support::ChangeExtension(to_file, string());
594 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
600 /// Substitute meta-variables in this string
601 string const doSubstitution(InsetExternal::Params const & params,
602 Buffer const & buffer, string const & s)
605 string const buffer_path = buffer.filePath();
606 string const filename = params.filename.outputFilename(buffer_path);
607 string const basename = support::ChangeExtension(filename, string());
608 string const filepath = support::OnlyPath(filename);
610 result = support::subst(s, "$$FName", filename);
611 result = support::subst(result, "$$Basename", basename);
612 result = support::subst(result, "$$FPath", filepath);
613 result = support::subst(result, "$$Tempname", params.tempname());
614 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
616 // Handle the $$Contents(filename) syntax
617 if (support::contains(result, "$$Contents(\"")) {
619 string::size_type const pos = result.find("$$Contents(\"");
620 string::size_type const end = result.find("\")", pos);
621 string const file = result.substr(pos + 12, end - (pos + 12));
624 string const filepath = support::IsFileReadable(file) ?
625 buffer.filePath() : buffer.temppath();
626 support::Path p(filepath);
628 if (support::IsFileReadable(file))
629 contents = support::GetFileContents(file);
631 result = support::subst(result,
632 ("$$Contents(\"" + file + "\")").c_str(),
640 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
642 external::Template const * const et_ptr = getTemplatePtr(params);
645 external::Template const & et = *et_ptr;
647 if (et.editCommand.empty())
650 string const command = doSubstitution(params, buffer, et.editCommand);
652 support::Path p(buffer.filePath());
653 support::Forkedcall call;
654 if (lyxerr.debugging(Debug::EXTERNAL)) {
655 lyxerr << "Executing '" << command << "' in '"
656 << buffer.filePath() << '\'' << endl;
658 call.startscript(support::Forkedcall::DontWait, command);
663 string const InsetExternalMailer::name_("external");
665 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
670 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
672 return params2string(inset_.params(), buffer);
676 void InsetExternalMailer::string2params(string const & in,
677 Buffer const & buffer,
678 InsetExternal::Params & params)
680 params = InsetExternal::Params();
685 istringstream data(in);
691 string const token = lex.getString();
696 // This is part of the inset proper that is usually swallowed
697 // by Buffer::readInset
700 string const token = lex.getString();
701 if (token != "External")
706 params.read(buffer, lex);
712 InsetExternalMailer::params2string(InsetExternal::Params const & params,
713 Buffer const & buffer)
716 data << name_ << ' ';
717 params.write(buffer, data);
718 data << "\\end_inset\n";