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 BufferView * InsetExternal::view() const
266 return renderer_->view();
270 string const InsetExternal::editMessage() const
272 return getScreenLabel(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 lex.pushTable(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.");
369 // Replace the inset's store
372 lyxerr[Debug::INFO] << "InsetExternal::Read: "
373 << "template: '" << params_.templatename
374 << "' filename: '" << params_.filename.absFilename()
375 << "' display: '" << params_.display
376 << "' scale: '" << params_.lyxscale
381 int InsetExternal::write(string const & format,
382 Buffer const * buf, ostream & os,
383 bool external_in_tmpdir) const
385 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
388 ExternalTemplate const & et = *et_ptr;
390 ExternalTemplate::Formats::const_iterator cit =
391 et.formats.find(format);
392 if (cit == et.formats.end()) {
393 lyxerr << "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 =
460 et.formats.find("LaTeX");
462 if (cit == et.formats.end())
465 if (!cit->second.requirement.empty()) {
466 features.require(cit->second.requirement);
468 if (!cit->second.preamble.empty()) {
469 features.addExternalPreamble(cit->second.preamble + "\n");
474 void InsetExternal::updateExternal(string const & format,
476 bool external_in_tmpdir) const
478 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
481 ExternalTemplate const & et = *et_ptr;
483 if (!et.automaticProduction)
486 ExternalTemplate::Formats::const_iterator cit =
487 et.formats.find(format);
488 if (cit == et.formats.end())
491 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
492 if (outputFormat.updateResult.empty())
495 string from_format = et.inputFormat;
496 if (from_format.empty())
499 string from_file = params_.filename.absFilename();
501 if (from_format == "*") {
502 if (from_file.empty())
505 // Try and ascertain the file format from its contents.
506 from_format = getExtFromContents(from_file);
507 if (from_format.empty())
511 string const to_format = outputFormat.updateFormat;
512 if (to_format.empty())
515 if (!converters.isReachable(from_format, to_format)) {
516 lyxerr << "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 from_file = copyFileToDir(buf->tmppath, from_file);
525 if (from_file.empty())
529 string const to_file = doSubstitution(params_, buf,
530 outputFormat.updateResult);
532 FileInfo fi(from_file);
533 string abs_to_file = to_file;
534 if (!AbsolutePath(to_file))
535 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
536 FileInfo fi2(abs_to_file);
537 if (fi2.exist() && fi.exist() &&
538 difftime(fi2.getModificationTime(),
539 fi.getModificationTime()) >= 0) {
541 string const to_filebase = ChangeExtension(to_file, string());
542 converters.convert(buf, from_file, to_filebase,
543 from_format, to_format);
550 /// Substitute meta-variables in this string
551 string const doSubstitution(InsetExternal::Params const & params,
552 Buffer const * buffer, string const & s)
555 string const absfilename = params.filename.absFilename();
556 string const basename = ChangeExtension(absfilename, string());
559 result = subst(s, "$$FName", absfilename);
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() const
625 BufferView * bv = inset_.view();
628 return params2string(inset_.params(), bv->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);
676 data << name_ << ' ';
677 inset.write(buffer, data);
678 data << "\\end_inset\n";
679 return STRCONV(data.str());