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/path.h"
40 #include "support/tostr.h"
41 #include "support/LAssert.h"
42 #include "support/translator.h"
44 #include <boost/bind.hpp>
49 using namespace lyx::support;
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);
78 InsetExternal::Params::Params()
79 : display(defaultDisplayType),
80 lyxscale(defaultLyxScale)
82 tempname = tempName(string(), "lyxext");
84 // must have an extension for the converter code to work correctly.
89 InsetExternal::Params::~Params()
95 InsetExternal::InsetExternal()
96 : renderer_(new ButtonRenderer)
100 InsetExternal::InsetExternal(InsetExternal const & other)
102 boost::signals::trackable(),
103 params_(other.params_),
104 renderer_(other.renderer_->clone())
106 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
108 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
113 auto_ptr<InsetBase> InsetExternal::clone() const
115 return auto_ptr<InsetBase>(new InsetExternal(*this));
119 InsetExternal::~InsetExternal()
121 InsetExternalMailer(*this).hideDialog();
125 void InsetExternal::statusChanged()
127 BufferView * bv = renderer_->view();
129 bv->updateInset(this);
133 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
135 switch (cmd.action) {
137 case LFUN_EXTERNAL_EDIT: {
140 Buffer const & buffer = *cmd.view()->buffer();
141 InsetExternal::Params p;
142 InsetExternalMailer::string2params(cmd.argument, buffer, p);
143 editExternal(p, &buffer);
144 return DISPATCHED_NOUPDATE;
147 case LFUN_INSET_MODIFY: {
150 Buffer const * buffer = cmd.view()->buffer();
151 InsetExternal::Params p;
152 InsetExternalMailer::string2params(cmd.argument, *buffer, p);
153 setParams(p, buffer);
154 cmd.view()->updateInset(this);
158 case LFUN_INSET_DIALOG_UPDATE:
159 InsetExternalMailer(*this).updateDialog(cmd.view());
162 case LFUN_MOUSE_RELEASE:
163 case LFUN_INSET_EDIT:
164 InsetExternalMailer(*this).showDialog(cmd.view());
173 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
175 renderer_->metrics(mi, dim);
180 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
182 renderer_->draw(pi, x, y);
188 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
190 lyx::graphics::Params gparams;
192 gparams.filename = eparams.filename.absFilename();
193 gparams.scale = eparams.lyxscale;
194 gparams.display = eparams.display;
196 if (gparams.display == lyx::graphics::DefaultDisplay)
197 gparams.display = lyxrc.display_graphics;
199 // Override the above if we're not using a gui
200 if (!lyx_gui::use_gui)
201 gparams.display = lyx::graphics::NoDisplay;
207 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
209 ExternalTemplateManager & etm = ExternalTemplateManager::get();
210 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
211 if (templ.lyxName.empty())
217 string const getScreenLabel(InsetExternal::Params const & params,
218 Buffer const * buffer)
220 ExternalTemplate const * const ptr = getTemplatePtr(params);
222 return bformat(_("External template %1$s is not installed"),
223 params.templatename);
224 return doSubstitution(params, buffer, ptr->guiName);
230 InsetExternal::Params const & InsetExternal::params() const
236 void InsetExternal::setParams(Params const & p, Buffer const * buffer)
238 // The stored params; what we would like to happen in an ideal world.
239 params_.filename = p.filename;
240 params_.templatename = p.templatename;
241 params_.display = p.display;
242 params_.lyxscale = p.lyxscale;
244 // We display the inset as a button by default.
245 bool display_button = (!getTemplatePtr(params_) ||
246 params_.filename.empty() ||
247 params_.display == lyx::graphics::NoDisplay);
249 if (display_button) {
250 ButtonRenderer * button_ptr =
251 dynamic_cast<ButtonRenderer *>(renderer_.get());
253 button_ptr = new ButtonRenderer;
254 renderer_.reset(button_ptr);
257 button_ptr->update(getScreenLabel(params_, buffer), true);
260 GraphicRenderer * graphic_ptr =
261 dynamic_cast<GraphicRenderer *>(renderer_.get());
263 graphic_ptr = new GraphicRenderer;
264 graphic_ptr->connect(
265 boost::bind(&InsetExternal::statusChanged, this));
266 renderer_.reset(graphic_ptr);
269 graphic_ptr->update(get_grfx_params(params_));
274 void InsetExternal::write(Buffer const * buffer, ostream & os) const
277 << "\ttemplate " << params_.templatename << '\n';
279 if (!params_.filename.empty())
281 << params_.filename.outputFilename(buffer->filePath())
284 if (params_.display != defaultDisplayType)
285 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
288 if (params_.lyxscale != defaultLyxScale)
289 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
293 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
303 keyword_item external_tags[] = {
304 { "\\end_inset", EX_END },
305 { "display", EX_DISPLAY},
306 { "filename", EX_FILENAME},
307 { "lyxscale", EX_LYXSCALE},
308 { "template", EX_TEMPLATE }
311 lex.pushTable(external_tags, EX_END);
313 bool found_end = false;
314 bool read_error = false;
316 InsetExternal::Params params;
321 params.templatename = lex.getString();
327 string const name = lex.getString();
328 params.filename.set(name, buffer->filePath());
334 string const name = lex.getString();
335 params.display = lyx::graphics::displayTranslator.find(name);
341 params.lyxscale = lex.getInteger();
350 lex.printError("ExternalInset::read: "
351 "Wrong tag: $$Token");
356 if (found_end || read_error)
361 lex.printError("ExternalInset::read: "
362 "Missing \\end_inset.");
367 // Replace the inset's store
368 setParams(params, buffer);
370 lyxerr[Debug::INFO] << "InsetExternal::Read: "
371 << "template: '" << params_.templatename
372 << "' filename: '" << params_.filename.absFilename()
373 << "' display: '" << params_.display
374 << "' scale: '" << params_.lyxscale
379 int InsetExternal::write(string const & format,
380 Buffer const * buf, ostream & os,
381 bool external_in_tmpdir) const
383 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
386 ExternalTemplate const & et = *et_ptr;
388 ExternalTemplate::Formats::const_iterator cit =
389 et.formats.find(format);
390 if (cit == et.formats.end()) {
391 lyxerr << "External template format '" << format
392 << "' not specified in template "
393 << params_.templatename << endl;
397 updateExternal(format, buf, external_in_tmpdir);
398 string const str = doSubstitution(params_, buf, cit->second.product);
400 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
404 int InsetExternal::latex(Buffer const * buf, ostream & os,
405 LatexRunParams const & runparams) const
407 // "nice" means that the buffer is exported to LaTeX format but not
408 // run through the LaTeX compiler.
409 // If we're running through the LaTeX compiler, we should write the
410 // generated files in the bufer's temporary directory.
411 bool const external_in_tmpdir =
412 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
414 // If the template has specified a PDFLaTeX output, then we try and
416 if (runparams.flavor == LatexRunParams::PDFLATEX) {
417 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
420 ExternalTemplate const & et = *et_ptr;
422 ExternalTemplate::Formats::const_iterator cit =
423 et.formats.find("PDFLaTeX");
424 if (cit != et.formats.end())
425 return write("PDFLaTeX", buf, os, external_in_tmpdir);
428 return write("LaTeX", buf, os, external_in_tmpdir);
432 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
434 return write("Ascii", buf, os);
438 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
440 return write("LinuxDoc", buf, os);
444 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
446 return write("DocBook", buf, os);
450 void InsetExternal::validate(LaTeXFeatures & features) const
452 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
455 ExternalTemplate const & et = *et_ptr;
457 ExternalTemplate::Formats::const_iterator cit =
458 et.formats.find("LaTeX");
460 if (cit == et.formats.end())
463 if (!cit->second.requirement.empty()) {
464 features.require(cit->second.requirement);
466 if (!cit->second.preamble.empty()) {
467 features.addExternalPreamble(cit->second.preamble + "\n");
472 void InsetExternal::updateExternal(string const & format,
474 bool external_in_tmpdir) const
476 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
479 ExternalTemplate const & et = *et_ptr;
481 if (!et.automaticProduction)
484 ExternalTemplate::Formats::const_iterator cit =
485 et.formats.find(format);
486 if (cit == et.formats.end())
489 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
490 if (outputFormat.updateResult.empty())
493 string from_format = et.inputFormat;
494 if (from_format.empty())
497 string from_file = params_.filename.absFilename();
499 if (from_format == "*") {
500 if (from_file.empty())
503 // Try and ascertain the file format from its contents.
504 from_format = getExtFromContents(from_file);
505 if (from_format.empty())
509 string const to_format = outputFormat.updateFormat;
510 if (to_format.empty())
513 if (!converters.isReachable(from_format, to_format)) {
514 lyxerr << "InsetExternal::updateExternal. "
515 "Unable to convert from "
516 << from_format << " to " << to_format << endl;
520 if (external_in_tmpdir && !from_file.empty()) {
521 // We are running stuff through LaTeX
522 from_file = copyFileToDir(buf->tmppath, from_file);
523 if (from_file.empty())
527 string const to_file = doSubstitution(params_, buf,
528 outputFormat.updateResult);
530 FileInfo fi(from_file);
531 string abs_to_file = to_file;
532 if (!AbsolutePath(to_file))
533 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
534 FileInfo fi2(abs_to_file);
535 if (fi2.exist() && fi.exist() &&
536 difftime(fi2.getModificationTime(),
537 fi.getModificationTime()) >= 0) {
539 string const to_filebase = ChangeExtension(to_file, string());
540 converters.convert(buf, from_file, to_filebase,
541 from_format, to_format);
548 /// Substitute meta-variables in this string
549 string const doSubstitution(InsetExternal::Params const & params,
550 Buffer const * buffer, string const & s)
553 string const buffer_path = buffer ? buffer->filePath() : string();
554 string const filename = params.filename.outputFilename(buffer_path);
555 string const basename = ChangeExtension(filename, string());
556 string const filepath = OnlyPath(filename);
558 result = subst(s, "$$FName", filename);
559 result = subst(result, "$$Basename", basename);
560 result = subst(result, "$$FPath", filepath);
561 result = subst(result, "$$Tempname", params.tempname);
562 result = subst(result, "$$Sysdir", system_lyxdir);
564 // Handle the $$Contents(filename) syntax
565 if (contains(result, "$$Contents(\"")) {
567 string::size_type const pos = result.find("$$Contents(\"");
568 string::size_type const end = result.find("\")", pos);
569 string const file = result.substr(pos + 12, end - (pos + 12));
572 Path p(buffer->filePath());
573 if (!IsFileReadable(file))
574 Path p(buffer->tmppath);
575 if (IsFileReadable(file))
576 contents = GetFileContents(file);
578 contents = GetFileContents(file);
580 result = subst(result,
581 ("$$Contents(\"" + file + "\")").c_str(),
589 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
594 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
597 ExternalTemplate const & et = *et_ptr;
599 if (et.editCommand.empty())
602 string const command = doSubstitution(params, buffer, et.editCommand);
604 Path p(buffer->filePath());
606 if (lyxerr.debugging()) {
607 lyxerr << "Executing '" << command << "' in '"
608 << buffer->filePath() << '\'' << endl;
610 call.startscript(Forkedcall::DontWait, command);
615 string const InsetExternalMailer::name_("external");
617 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
622 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
624 return params2string(inset_.params(), buffer);
628 void InsetExternalMailer::string2params(string const & in,
629 Buffer const & buffer,
630 InsetExternal::Params & params)
632 params = InsetExternal::Params();
637 istringstream data(STRCONV(in));
643 string const token = lex.getString();
648 // This is part of the inset proper that is usually swallowed
649 // by Buffer::readInset
652 string const token = lex.getString();
653 if (token != "External")
659 inset.read(&buffer, lex);
660 params = inset.params();
666 InsetExternalMailer::params2string(InsetExternal::Params const & params,
667 Buffer const & buffer)
670 inset.setParams(params, &buffer);
672 data << name_ << ' ';
673 inset.write(&buffer, data);
674 data << "\\end_inset\n";
675 return STRCONV(data.str());