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"
42 #include <boost/bind.hpp>
47 using namespace lyx::support;
54 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
56 unsigned int defaultLyxScale = 100;
58 /// Substitute meta-variables in string s, makeing use of params and buffer.
59 string const doSubstitution(InsetExternal::Params const & params,
60 Buffer const * buffer, string const & s);
62 /// Invoke the external editor.
63 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
68 InsetExternal::Params::Params()
69 : display(defaultDisplayType),
70 lyxscale(defaultLyxScale)
72 tempname = tempName(string(), "lyxext");
74 // must have an extension for the converter code to work correctly.
79 InsetExternal::Params::~Params()
85 InsetExternal::InsetExternal()
86 : renderer_(new ButtonRenderer)
90 InsetExternal::InsetExternal(InsetExternal const & other)
92 boost::signals::trackable(),
93 params_(other.params_),
94 renderer_(other.renderer_->clone())
96 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
98 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
103 InsetBase * InsetExternal::clone() const
105 InsetExternal * inset = new InsetExternal(*this);
110 InsetExternal::~InsetExternal()
112 InsetExternalMailer(*this).hideDialog();
116 void InsetExternal::statusChanged()
118 BufferView * bv = renderer_->view();
120 bv->updateInset(this);
124 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
126 switch (cmd.action) {
128 case LFUN_EXTERNAL_EDIT: {
131 Buffer const & buffer = *cmd.view()->buffer();
132 InsetExternal::Params p;
133 InsetExternalMailer::string2params(cmd.argument, buffer, p);
134 editExternal(p, &buffer);
135 return DISPATCHED_NOUPDATE;
138 case LFUN_INSET_MODIFY: {
141 Buffer const & buffer = *cmd.view()->buffer();
142 InsetExternal::Params p;
143 InsetExternalMailer::string2params(cmd.argument, buffer, p);
145 cmd.view()->updateInset(this);
149 case LFUN_INSET_DIALOG_UPDATE:
150 InsetExternalMailer(*this).updateDialog(cmd.view());
153 case LFUN_MOUSE_RELEASE:
154 case LFUN_INSET_EDIT:
155 InsetExternalMailer(*this).showDialog(cmd.view());
164 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
166 renderer_->metrics(mi, dim);
171 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
173 renderer_->draw(pi, x, y);
179 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
181 lyx::graphics::Params gparams;
183 gparams.filename = eparams.filename.absFilename();
184 gparams.scale = eparams.lyxscale;
185 gparams.display = eparams.display;
187 if (gparams.display == lyx::graphics::DefaultDisplay)
188 gparams.display = lyxrc.display_graphics;
190 // Override the above if we're not using a gui
191 if (!lyx_gui::use_gui)
192 gparams.display = lyx::graphics::NoDisplay;
198 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
200 ExternalTemplateManager & etm = ExternalTemplateManager::get();
201 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
202 if (templ.lyxName.empty())
208 string const getScreenLabel(InsetExternal::Params const & params)
210 ExternalTemplate const * const ptr = getTemplatePtr(params);
212 return bformat(_("External template %1$s is not installed"),
213 params.templatename);
214 return doSubstitution(params, 0, ptr->guiName);
220 InsetExternal::Params const & InsetExternal::params() const
226 void InsetExternal::setParams(Params const & p)
228 // The stored params; what we would like to happen in an ideal world.
229 params_.filename = p.filename;
230 params_.templatename = p.templatename;
231 params_.display = p.display;
232 params_.lyxscale = p.lyxscale;
234 // We display the inset as a button by default.
235 bool display_button = (!getTemplatePtr(params_) ||
236 params_.filename.empty() ||
237 params_.display == lyx::graphics::NoDisplay);
239 if (display_button) {
240 ButtonRenderer * button_ptr =
241 dynamic_cast<ButtonRenderer *>(renderer_.get());
243 button_ptr = new ButtonRenderer;
244 renderer_.reset(button_ptr);
247 button_ptr->update(getScreenLabel(params_), true);
250 GraphicRenderer * graphic_ptr =
251 dynamic_cast<GraphicRenderer *>(renderer_.get());
253 graphic_ptr = new GraphicRenderer;
254 graphic_ptr->connect(
255 boost::bind(&InsetExternal::statusChanged, this));
256 renderer_.reset(graphic_ptr);
259 graphic_ptr->update(get_grfx_params(params_));
264 string const InsetExternal::editMessage() const
266 return getScreenLabel(params_);
270 void InsetExternal::write(Buffer const * buffer, ostream & os) const
273 << "\ttemplate " << params_.templatename << '\n';
275 if (!params_.filename.empty())
277 << params_.filename.outputFilename(buffer->filePath())
280 if (params_.display != defaultDisplayType)
281 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
284 if (params_.lyxscale != defaultLyxScale)
285 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
289 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
299 keyword_item external_tags[] = {
300 { "\\end_inset", EX_END },
301 { "display", EX_DISPLAY},
302 { "filename", EX_FILENAME},
303 { "lyxscale", EX_LYXSCALE},
304 { "template", EX_TEMPLATE }
307 lex.pushTable(external_tags, EX_END);
309 bool found_end = false;
310 bool read_error = false;
312 InsetExternal::Params params;
317 params.templatename = lex.getString();
323 string const name = lex.getString();
324 params.filename.set(name, buffer->filePath());
330 string const name = lex.getString();
331 params.display = lyx::graphics::displayTranslator.find(name);
337 params.lyxscale = lex.getInteger();
346 lex.printError("ExternalInset::read: "
347 "Wrong tag: $$Token");
352 if (found_end || read_error)
357 lex.printError("ExternalInset::read: "
358 "Missing \\end_inset.");
363 // Replace the inset's store
366 lyxerr[Debug::INFO] << "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 << "External template format '" << format
388 << "' not specified in template "
389 << params_.templatename << endl;
393 updateExternal(format, buf, external_in_tmpdir);
394 string const str = doSubstitution(params_, buf, cit->second.product);
396 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
400 int InsetExternal::latex(Buffer const * buf, ostream & os,
401 LatexRunParams const & runparams) const
403 // "nice" means that the buffer is exported to LaTeX format but not
404 // run through the LaTeX compiler.
405 // If we're running through the LaTeX compiler, we should write the
406 // generated files in the bufer's temporary directory.
407 bool const external_in_tmpdir =
408 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
410 // If the template has specified a PDFLaTeX output, then we try and
412 if (runparams.flavor == LatexRunParams::PDFLATEX) {
413 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
416 ExternalTemplate const & et = *et_ptr;
418 ExternalTemplate::Formats::const_iterator cit =
419 et.formats.find("PDFLaTeX");
420 if (cit != et.formats.end())
421 return write("PDFLaTeX", buf, os, external_in_tmpdir);
424 return write("LaTeX", buf, os, external_in_tmpdir);
428 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
430 return write("Ascii", buf, os);
434 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
436 return write("LinuxDoc", buf, os);
440 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
442 return write("DocBook", buf, os);
446 void InsetExternal::validate(LaTeXFeatures & features) const
448 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
451 ExternalTemplate const & et = *et_ptr;
453 ExternalTemplate::Formats::const_iterator cit =
454 et.formats.find("LaTeX");
456 if (cit == et.formats.end())
459 if (!cit->second.requirement.empty()) {
460 features.require(cit->second.requirement);
462 if (!cit->second.preamble.empty()) {
463 features.addExternalPreamble(cit->second.preamble + "\n");
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 = 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 << "InsetExternal::updateExternal. "
511 "Unable to convert from "
512 << from_format << " to " << to_format << endl;
516 if (external_in_tmpdir && !from_file.empty()) {
517 // We are running stuff through LaTeX
518 from_file = copyFileToDir(buf->tmppath, from_file);
519 if (from_file.empty())
523 string const to_file = doSubstitution(params_, buf,
524 outputFormat.updateResult);
526 FileInfo fi(from_file);
527 string abs_to_file = to_file;
528 if (!AbsolutePath(to_file))
529 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
530 FileInfo fi2(abs_to_file);
531 if (fi2.exist() && fi.exist() &&
532 difftime(fi2.getModificationTime(),
533 fi.getModificationTime()) >= 0) {
535 string const to_filebase = ChangeExtension(to_file, string());
536 converters.convert(buf, from_file, to_filebase,
537 from_format, to_format);
544 /// Substitute meta-variables in this string
545 string const doSubstitution(InsetExternal::Params const & params,
546 Buffer const * buffer, string const & s)
549 string const absfilename = params.filename.absFilename();
550 string const basename = ChangeExtension(absfilename, string());
553 result = subst(s, "$$FName", absfilename);
554 result = subst(result, "$$Basename", basename);
555 result = subst(result, "$$FPath", filepath);
556 result = subst(result, "$$Tempname", params.tempname);
557 result = subst(result, "$$Sysdir", system_lyxdir);
559 // Handle the $$Contents(filename) syntax
560 if (contains(result, "$$Contents(\"")) {
562 string::size_type const pos = result.find("$$Contents(\"");
563 string::size_type const end = result.find("\")", pos);
564 string const file = result.substr(pos + 12, end - (pos + 12));
567 Path p(buffer->filePath());
568 if (!IsFileReadable(file))
569 Path p(buffer->tmppath);
570 if (IsFileReadable(file))
571 contents = GetFileContents(file);
573 contents = GetFileContents(file);
575 result = subst(result,
576 ("$$Contents(\"" + file + "\")").c_str(),
584 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
589 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
592 ExternalTemplate const & et = *et_ptr;
594 if (et.editCommand.empty())
597 string const command = doSubstitution(params, buffer, et.editCommand);
599 Path p(buffer->filePath());
601 if (lyxerr.debugging()) {
602 lyxerr << "Executing '" << command << "' in '"
603 << buffer->filePath() << '\'' << endl;
605 call.startscript(Forkedcall::DontWait, command);
610 string const InsetExternalMailer::name_("external");
612 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
617 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
619 return params2string(inset_.params(), buffer);
623 void InsetExternalMailer::string2params(string const & in,
624 Buffer const & buffer,
625 InsetExternal::Params & params)
627 params = InsetExternal::Params();
632 istringstream data(STRCONV(in));
638 string const token = lex.getString();
643 // This is part of the inset proper that is usually swallowed
644 // by Buffer::readInset
647 string const token = lex.getString();
648 if (token != "External")
654 inset.read(&buffer, lex);
655 params = inset.params();
661 InsetExternalMailer::params2string(InsetExternal::Params const & params,
662 Buffer const & buffer)
665 inset.setParams(params);
667 data << name_ << ' ';
668 inset.write(&buffer, data);
669 data << "\\end_inset\n";
670 return STRCONV(data.str());