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/path_defines.h"
41 #include "support/tostr.h"
42 #include "support/LAssert.h"
43 #include "support/translator.h"
45 #include <boost/bind.hpp>
50 using namespace lyx::support;
58 /// The translator between the DisplayType and the corresponding lyx string.
59 extern Translator<DisplayType, string> displayTranslator;
65 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
67 unsigned int defaultLyxScale = 100;
69 /// Substitute meta-variables in string s, makeing use of params and buffer.
70 string const doSubstitution(InsetExternal::Params const & params,
71 Buffer const * buffer, string const & s);
73 /// Invoke the external editor.
74 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
79 InsetExternal::Params::Params()
80 : display(defaultDisplayType),
81 lyxscale(defaultLyxScale)
83 tempname = tempName(string(), "lyxext");
85 // must have an extension for the converter code to work correctly.
90 InsetExternal::Params::~Params()
96 InsetExternal::InsetExternal()
97 : renderer_(new ButtonRenderer)
101 InsetExternal::InsetExternal(InsetExternal const & other)
103 boost::signals::trackable(),
104 params_(other.params_),
105 renderer_(other.renderer_->clone())
107 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
109 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
114 auto_ptr<InsetBase> InsetExternal::clone() const
116 return auto_ptr<InsetBase>(new InsetExternal(*this));
120 InsetExternal::~InsetExternal()
122 InsetExternalMailer(*this).hideDialog();
126 void InsetExternal::statusChanged()
128 BufferView * bv = renderer_->view();
130 bv->updateInset(this);
134 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
136 switch (cmd.action) {
138 case LFUN_EXTERNAL_EDIT: {
141 Buffer const & buffer = *cmd.view()->buffer();
142 InsetExternal::Params p;
143 InsetExternalMailer::string2params(cmd.argument, buffer, p);
144 editExternal(p, &buffer);
145 return DISPATCHED_NOUPDATE;
148 case LFUN_INSET_MODIFY: {
151 Buffer const * buffer = cmd.view()->buffer();
152 InsetExternal::Params p;
153 InsetExternalMailer::string2params(cmd.argument, *buffer, p);
154 setParams(p, buffer);
155 cmd.view()->updateInset(this);
159 case LFUN_INSET_DIALOG_UPDATE:
160 InsetExternalMailer(*this).updateDialog(cmd.view());
163 case LFUN_MOUSE_RELEASE:
164 case LFUN_INSET_EDIT:
165 InsetExternalMailer(*this).showDialog(cmd.view());
174 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
176 renderer_->metrics(mi, dim);
181 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
183 renderer_->draw(pi, x, y);
189 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
191 lyx::graphics::Params gparams;
193 gparams.filename = eparams.filename.absFilename();
194 gparams.scale = eparams.lyxscale;
195 gparams.display = eparams.display;
197 if (gparams.display == lyx::graphics::DefaultDisplay)
198 gparams.display = lyxrc.display_graphics;
200 // Override the above if we're not using a gui
201 if (!lyx_gui::use_gui)
202 gparams.display = lyx::graphics::NoDisplay;
208 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
210 ExternalTemplateManager & etm = ExternalTemplateManager::get();
211 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
212 if (templ.lyxName.empty())
218 string const getScreenLabel(InsetExternal::Params const & params,
219 Buffer const * buffer)
221 ExternalTemplate const * const ptr = getTemplatePtr(params);
223 return bformat(_("External template %1$s is not installed"),
224 params.templatename);
225 return doSubstitution(params, buffer, ptr->guiName);
231 InsetExternal::Params const & InsetExternal::params() const
237 void InsetExternal::setParams(Params const & p, Buffer const * buffer)
239 // The stored params; what we would like to happen in an ideal world.
240 params_.filename = p.filename;
241 params_.templatename = p.templatename;
242 params_.display = p.display;
243 params_.lyxscale = p.lyxscale;
245 // We display the inset as a button by default.
246 bool display_button = (!getTemplatePtr(params_) ||
247 params_.filename.empty() ||
248 params_.display == lyx::graphics::NoDisplay);
250 if (display_button) {
251 ButtonRenderer * button_ptr =
252 dynamic_cast<ButtonRenderer *>(renderer_.get());
254 button_ptr = new ButtonRenderer;
255 renderer_.reset(button_ptr);
258 button_ptr->update(getScreenLabel(params_, buffer), true);
261 GraphicRenderer * graphic_ptr =
262 dynamic_cast<GraphicRenderer *>(renderer_.get());
264 graphic_ptr = new GraphicRenderer;
265 graphic_ptr->connect(
266 boost::bind(&InsetExternal::statusChanged, this));
267 renderer_.reset(graphic_ptr);
270 graphic_ptr->update(get_grfx_params(params_));
275 void InsetExternal::write(Buffer const * buffer, ostream & os) const
278 << "\ttemplate " << params_.templatename << '\n';
280 if (!params_.filename.empty())
282 << params_.filename.outputFilename(buffer->filePath())
285 if (params_.display != defaultDisplayType)
286 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
289 if (params_.lyxscale != defaultLyxScale)
290 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
294 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
304 keyword_item external_tags[] = {
305 { "\\end_inset", EX_END },
306 { "display", EX_DISPLAY},
307 { "filename", EX_FILENAME},
308 { "lyxscale", EX_LYXSCALE},
309 { "template", EX_TEMPLATE }
312 lex.pushTable(external_tags, EX_END);
314 bool found_end = false;
315 bool read_error = false;
317 InsetExternal::Params params;
322 params.templatename = lex.getString();
328 string const name = lex.getString();
329 params.filename.set(name, buffer->filePath());
335 string const name = lex.getString();
336 params.display = lyx::graphics::displayTranslator.find(name);
342 params.lyxscale = lex.getInteger();
351 lex.printError("ExternalInset::read: "
352 "Wrong tag: $$Token");
357 if (found_end || read_error)
362 lex.printError("ExternalInset::read: "
363 "Missing \\end_inset.");
368 // Replace the inset's store
369 setParams(params, buffer);
371 lyxerr[Debug::INFO] << "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 << "External template format '" << format
393 << "' not specified in template "
394 << params_.templatename << endl;
398 updateExternal(format, buf, external_in_tmpdir);
399 string const str = doSubstitution(params_, buf, cit->second.product);
401 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
405 int InsetExternal::latex(Buffer const * buf, ostream & os,
406 LatexRunParams const & runparams) const
408 // "nice" means that the buffer is exported to LaTeX format but not
409 // run through the LaTeX compiler.
410 // If we're running through the LaTeX compiler, we should write the
411 // generated files in the bufer's temporary directory.
412 bool const external_in_tmpdir =
413 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
415 // If the template has specified a PDFLaTeX output, then we try and
417 if (runparams.flavor == LatexRunParams::PDFLATEX) {
418 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
421 ExternalTemplate const & et = *et_ptr;
423 ExternalTemplate::Formats::const_iterator cit =
424 et.formats.find("PDFLaTeX");
425 if (cit != et.formats.end())
426 return write("PDFLaTeX", buf, os, external_in_tmpdir);
429 return write("LaTeX", buf, os, external_in_tmpdir);
433 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
435 return write("Ascii", buf, os);
439 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
441 return write("LinuxDoc", buf, os);
445 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
447 return write("DocBook", buf, os);
451 void InsetExternal::validate(LaTeXFeatures & features) const
453 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
456 ExternalTemplate const & et = *et_ptr;
458 ExternalTemplate::Formats::const_iterator cit =
459 et.formats.find("LaTeX");
461 if (cit == et.formats.end())
464 if (!cit->second.requirement.empty()) {
465 features.require(cit->second.requirement);
467 if (!cit->second.preamble.empty()) {
468 features.addExternalPreamble(cit->second.preamble + "\n");
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 = 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 << "InsetExternal::updateExternal. "
516 "Unable to convert from "
517 << from_format << " to " << to_format << endl;
521 if (external_in_tmpdir && !from_file.empty()) {
522 // We are running stuff through LaTeX
523 from_file = copyFileToDir(buf->tmppath, from_file);
524 if (from_file.empty())
528 string const to_file = doSubstitution(params_, buf,
529 outputFormat.updateResult);
531 FileInfo fi(from_file);
532 string abs_to_file = to_file;
533 if (!AbsolutePath(to_file))
534 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
535 FileInfo fi2(abs_to_file);
536 if (fi2.exist() && fi.exist() &&
537 difftime(fi2.getModificationTime(),
538 fi.getModificationTime()) >= 0) {
540 string const to_filebase = ChangeExtension(to_file, string());
541 converters.convert(buf, from_file, to_filebase,
542 from_format, to_format);
549 /// Substitute meta-variables in this string
550 string const doSubstitution(InsetExternal::Params const & params,
551 Buffer const * buffer, string const & s)
554 string const buffer_path = buffer ? buffer->filePath() : string();
555 string const filename = params.filename.outputFilename(buffer_path);
556 string const basename = ChangeExtension(filename, string());
557 string const filepath = OnlyPath(filename);
559 result = subst(s, "$$FName", filename);
560 result = subst(result, "$$Basename", basename);
561 result = subst(result, "$$FPath", filepath);
562 result = subst(result, "$$Tempname", params.tempname);
563 result = subst(result, "$$Sysdir", system_lyxdir());
565 // Handle the $$Contents(filename) syntax
566 if (contains(result, "$$Contents(\"")) {
568 string::size_type const pos = result.find("$$Contents(\"");
569 string::size_type const end = result.find("\")", pos);
570 string const file = result.substr(pos + 12, end - (pos + 12));
573 Path p(buffer->filePath());
574 if (!IsFileReadable(file))
575 Path p(buffer->tmppath);
576 if (IsFileReadable(file))
577 contents = GetFileContents(file);
579 contents = GetFileContents(file);
581 result = subst(result,
582 ("$$Contents(\"" + file + "\")").c_str(),
590 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
595 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
598 ExternalTemplate const & et = *et_ptr;
600 if (et.editCommand.empty())
603 string const command = doSubstitution(params, buffer, et.editCommand);
605 Path p(buffer->filePath());
607 if (lyxerr.debugging()) {
608 lyxerr << "Executing '" << command << "' in '"
609 << buffer->filePath() << '\'' << endl;
611 call.startscript(Forkedcall::DontWait, command);
616 string const InsetExternalMailer::name_("external");
618 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
623 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
625 return params2string(inset_.params(), buffer);
629 void InsetExternalMailer::string2params(string const & in,
630 Buffer const & buffer,
631 InsetExternal::Params & params)
633 params = InsetExternal::Params();
638 istringstream data(STRCONV(in));
644 string const token = lex.getString();
649 // This is part of the inset proper that is usually swallowed
650 // by Buffer::readInset
653 string const token = lex.getString();
654 if (token != "External")
660 inset.read(&buffer, lex);
661 params = inset.params();
667 InsetExternalMailer::params2string(InsetExternal::Params const & params,
668 Buffer const & buffer)
671 inset.setParams(params, &buffer);
673 data << name_ << ' ';
674 inset.write(&buffer, data);
675 data << "\\end_inset\n";
676 return STRCONV(data.str());