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"
30 #include "frontends/lyx_gui.h"
31 #include "frontends/LyXView.h"
32 #include "frontends/Dialogs.h"
34 #include "support/FileInfo.h"
35 #include "support/filetools.h"
36 #include "support/forkedcall.h"
37 #include "support/lstrings.h"
38 #include "support/lyxalgo.h"
39 #include "support/lyxlib.h"
40 #include "support/path.h"
41 #include "support/path_defines.h"
42 #include "support/tostr.h"
43 #include "support/LAssert.h"
44 #include "support/translator.h"
46 #include <boost/bind.hpp>
51 namespace support = lyx::support;
59 /// The translator between the DisplayType and the corresponding lyx string.
60 extern Translator<DisplayType, string> displayTranslator;
66 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
68 unsigned int defaultLyxScale = 100;
70 /// Substitute meta-variables in string s, makeing use of params and buffer.
71 string const doSubstitution(InsetExternal::Params const & params,
72 Buffer const & buffer, string const & s);
74 /// Invoke the external editor.
75 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
80 InsetExternal::Params::Params()
81 : display(defaultDisplayType),
82 lyxscale(defaultLyxScale)
84 tempname = support::tempName(string(), "lyxext");
85 support::unlink(tempname);
86 // must have an extension for the converter code to work correctly.
91 InsetExternal::Params::~Params()
93 support::unlink(tempname);
97 InsetExternal::InsetExternal()
98 : renderer_(new ButtonRenderer)
102 InsetExternal::InsetExternal(InsetExternal const & other)
104 boost::signals::trackable(),
105 params_(other.params_),
106 renderer_(other.renderer_->clone())
108 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
110 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
115 auto_ptr<InsetBase> InsetExternal::clone() const
117 return auto_ptr<InsetBase>(new InsetExternal(*this));
121 InsetExternal::~InsetExternal()
123 InsetExternalMailer(*this).hideDialog();
127 void InsetExternal::statusChanged()
129 BufferView * bv = renderer_->view();
131 bv->updateInset(this);
135 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
137 switch (cmd.action) {
139 case LFUN_EXTERNAL_EDIT: {
140 support::Assert(cmd.view());
142 Buffer const & buffer = *cmd.view()->buffer();
143 InsetExternal::Params p;
144 InsetExternalMailer::string2params(cmd.argument, buffer, p);
145 editExternal(p, buffer);
146 return DISPATCHED_NOUPDATE;
149 case LFUN_INSET_MODIFY: {
150 support::Assert(cmd.view());
152 Buffer const & buffer = *cmd.view()->buffer();
153 InsetExternal::Params p;
154 InsetExternalMailer::string2params(cmd.argument, buffer, p);
155 setParams(p, buffer);
156 cmd.view()->updateInset(this);
160 case LFUN_INSET_DIALOG_UPDATE:
161 InsetExternalMailer(*this).updateDialog(cmd.view());
164 case LFUN_MOUSE_RELEASE:
165 case LFUN_INSET_EDIT:
166 InsetExternalMailer(*this).showDialog(cmd.view());
175 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
177 renderer_->metrics(mi, dim);
182 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
184 renderer_->draw(pi, x, y);
190 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
192 lyx::graphics::Params gparams;
194 gparams.filename = eparams.filename.absFilename();
195 gparams.scale = eparams.lyxscale;
196 gparams.display = eparams.display;
198 if (gparams.display == lyx::graphics::DefaultDisplay)
199 gparams.display = lyxrc.display_graphics;
201 // Override the above if we're not using a gui
202 if (!lyx_gui::use_gui)
203 gparams.display = lyx::graphics::NoDisplay;
209 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
211 ExternalTemplateManager & etm = ExternalTemplateManager::get();
212 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
213 if (templ.lyxName.empty())
219 string const getScreenLabel(InsetExternal::Params const & params,
220 Buffer const & buffer)
222 ExternalTemplate const * const ptr = getTemplatePtr(params);
224 return support::bformat(_("External template %1$s is not installed"),
225 params.templatename);
226 return doSubstitution(params, buffer, ptr->guiName);
232 InsetExternal::Params const & InsetExternal::params() const
238 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
240 // The stored params; what we would like to happen in an ideal world.
241 params_.filename = p.filename;
242 params_.templatename = p.templatename;
243 params_.display = p.display;
244 params_.lyxscale = p.lyxscale;
246 // We display the inset as a button by default.
247 bool display_button = (!getTemplatePtr(params_) ||
248 params_.filename.empty() ||
249 params_.display == lyx::graphics::NoDisplay);
251 if (display_button) {
252 ButtonRenderer * button_ptr =
253 dynamic_cast<ButtonRenderer *>(renderer_.get());
255 button_ptr = new ButtonRenderer;
256 renderer_.reset(button_ptr);
259 button_ptr->update(getScreenLabel(params_, buffer), true);
262 GraphicRenderer * graphic_ptr =
263 dynamic_cast<GraphicRenderer *>(renderer_.get());
265 graphic_ptr = new GraphicRenderer;
266 graphic_ptr->connect(
267 boost::bind(&InsetExternal::statusChanged, this));
268 renderer_.reset(graphic_ptr);
271 graphic_ptr->update(get_grfx_params(params_));
276 void InsetExternal::write(Buffer const & buffer, ostream & os) const
279 << "\ttemplate " << params_.templatename << '\n';
281 if (!params_.filename.empty())
283 << params_.filename.outputFilename(buffer.filePath())
286 if (params_.display != defaultDisplayType)
287 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
290 if (params_.lyxscale != defaultLyxScale)
291 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
295 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
305 keyword_item external_tags[] = {
306 { "\\end_inset", EX_END },
307 { "display", EX_DISPLAY},
308 { "filename", EX_FILENAME},
309 { "lyxscale", EX_LYXSCALE},
310 { "template", EX_TEMPLATE }
313 pushpophelper pph(lex, external_tags, EX_END);
315 bool found_end = false;
316 bool read_error = false;
318 InsetExternal::Params params;
323 params.templatename = lex.getString();
329 string const name = lex.getString();
330 params.filename.set(name, buffer.filePath());
336 string const name = lex.getString();
337 params.display = lyx::graphics::displayTranslator.find(name);
343 params.lyxscale = lex.getInteger();
352 lex.printError("ExternalInset::read: "
353 "Wrong tag: $$Token");
358 if (found_end || read_error)
363 lex.printError("ExternalInset::read: "
364 "Missing \\end_inset.");
367 // Replace the inset's store
368 setParams(params, buffer);
370 lyxerr[Debug::EXTERNAL]
371 << "InsetExternal::Read: "
372 << "template: '" << params_.templatename
373 << "' filename: '" << params_.filename.absFilename()
374 << "' display: '" << params_.display
375 << "' scale: '" << params_.lyxscale
380 int InsetExternal::write(string const & format,
381 Buffer const & buf, ostream & os,
382 bool external_in_tmpdir) const
384 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
387 ExternalTemplate const & et = *et_ptr;
389 ExternalTemplate::Formats::const_iterator cit =
390 et.formats.find(format);
391 if (cit == et.formats.end()) {
392 lyxerr[Debug::EXTERNAL]
393 << "External template format '" << format
394 << "' not specified in template "
395 << params_.templatename << endl;
399 updateExternal(format, buf, external_in_tmpdir);
400 string const str = doSubstitution(params_, buf, cit->second.product);
402 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
406 int InsetExternal::latex(Buffer const & buf, ostream & os,
407 LatexRunParams const & runparams) const
409 // "nice" means that the buffer is exported to LaTeX format but not
410 // run through the LaTeX compiler.
411 // If we're running through the LaTeX compiler, we should write the
412 // generated files in the bufer's temporary directory.
413 bool const external_in_tmpdir =
414 lyxrc.use_tempdir && !buf.tmppath.empty() && !runparams.nice;
416 // If the template has specified a PDFLaTeX output, then we try and
418 if (runparams.flavor == LatexRunParams::PDFLATEX) {
419 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
422 ExternalTemplate const & et = *et_ptr;
424 ExternalTemplate::Formats::const_iterator cit =
425 et.formats.find("PDFLaTeX");
426 if (cit != et.formats.end())
427 return write("PDFLaTeX", buf, os, external_in_tmpdir);
430 return write("LaTeX", buf, os, external_in_tmpdir);
434 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
436 return write("Ascii", buf, os);
440 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
442 return write("LinuxDoc", buf, os);
446 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
448 return write("DocBook", buf, os);
452 void InsetExternal::validate(LaTeXFeatures & features) const
454 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
457 ExternalTemplate const & et = *et_ptr;
459 ExternalTemplate::Formats::const_iterator cit = et.formats.find("LaTeX");
460 if (cit == et.formats.end())
463 if (!cit->second.requirement.empty())
464 features.require(cit->second.requirement);
466 ExternalTemplateManager & etm = ExternalTemplateManager::get();
467 string const preamble = etm.getPreambleDefByName(cit->second.preambleName);
468 if (!preamble.empty())
469 features.addExternalPreamble(preamble);
473 void InsetExternal::updateExternal(string const & format,
475 bool external_in_tmpdir) const
477 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
480 ExternalTemplate const & et = *et_ptr;
482 if (!et.automaticProduction)
485 ExternalTemplate::Formats::const_iterator cit =
486 et.formats.find(format);
487 if (cit == et.formats.end())
490 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
491 if (outputFormat.updateResult.empty())
494 string from_format = et.inputFormat;
495 if (from_format.empty())
498 string from_file = params_.filename.absFilename();
500 if (from_format == "*") {
501 if (from_file.empty())
504 // Try and ascertain the file format from its contents.
505 from_format = support::getExtFromContents(from_file);
506 if (from_format.empty())
510 string const to_format = outputFormat.updateFormat;
511 if (to_format.empty())
514 if (!converters.isReachable(from_format, to_format)) {
515 lyxerr[Debug::EXTERNAL]
516 << "InsetExternal::updateExternal. "
517 << "Unable to convert from "
518 << from_format << " to " << to_format << endl;
522 if (external_in_tmpdir && !from_file.empty()) {
523 // We are running stuff through LaTeX
524 string const temp_file =
525 support::MakeAbsPath(params_.filename.mangledFilename(),
527 unsigned long const from_checksum = support::sum(from_file);
528 unsigned long const temp_checksum = support::sum(temp_file);
531 if (from_checksum == temp_checksum)
535 if (!support::copy(from_file, temp_file))
537 from_file = temp_file;
540 string const to_file = doSubstitution(params_, buf,
541 outputFormat.updateResult);
542 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
544 // Do we need to perform the conversion?
545 // Yes if to_file does not exist or if from_file is newer than to_file
546 if (support::compare_timestamps(from_file, abs_to_file) < 0)
549 string const to_filebase = support::ChangeExtension(to_file, string());
550 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
556 /// Substitute meta-variables in this string
557 string const doSubstitution(InsetExternal::Params const & params,
558 Buffer const & buffer, string const & s)
561 string const buffer_path = buffer.filePath();
562 string const filename = params.filename.outputFilename(buffer_path);
563 string const basename = support::ChangeExtension(filename, string());
564 string const filepath = support::OnlyPath(filename);
566 result = support::subst(s, "$$FName", filename);
567 result = support::subst(result, "$$Basename", basename);
568 result = support::subst(result, "$$FPath", filepath);
569 result = support::subst(result, "$$Tempname", params.tempname);
570 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
572 // Handle the $$Contents(filename) syntax
573 if (support::contains(result, "$$Contents(\"")) {
575 string::size_type const pos = result.find("$$Contents(\"");
576 string::size_type const end = result.find("\")", pos);
577 string const file = result.substr(pos + 12, end - (pos + 12));
580 string const filepath = support::IsFileReadable(file) ?
581 buffer.filePath() : buffer.tmppath;
582 support::Path p(filepath);
584 if (support::IsFileReadable(file))
585 contents = support::GetFileContents(file);
587 result = support::subst(result,
588 ("$$Contents(\"" + file + "\")").c_str(),
596 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
598 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
601 ExternalTemplate const & et = *et_ptr;
603 if (et.editCommand.empty())
606 string const command = doSubstitution(params, buffer, et.editCommand);
608 support::Path p(buffer.filePath());
609 support::Forkedcall call;
610 if (lyxerr.debugging(Debug::EXTERNAL)) {
611 lyxerr << "Executing '" << command << "' in '"
612 << buffer.filePath() << '\'' << endl;
614 call.startscript(support::Forkedcall::DontWait, command);
619 string const InsetExternalMailer::name_("external");
621 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
626 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
628 return params2string(inset_.params(), buffer);
632 void InsetExternalMailer::string2params(string const & in,
633 Buffer const & buffer,
634 InsetExternal::Params & params)
636 params = InsetExternal::Params();
641 istringstream data(STRCONV(in));
647 string const token = lex.getString();
652 // This is part of the inset proper that is usually swallowed
653 // by Buffer::readInset
656 string const token = lex.getString();
657 if (token != "External")
663 inset.read(buffer, lex);
664 params = inset.params();
670 InsetExternalMailer::params2string(InsetExternal::Params const & params,
671 Buffer const & buffer)
674 inset.setParams(params, buffer);
676 data << name_ << ' ';
677 inset.write(buffer, data);
678 data << "\\end_inset\n";
679 return STRCONV(data.str());