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"
26 #include "support/std_sstream.h"
28 #include "frontends/lyx_gui.h"
30 #include "support/filetools.h"
31 #include "support/forkedcall.h"
32 #include "support/lstrings.h"
33 #include "support/lyxalgo.h"
34 #include "support/lyxlib.h"
35 #include "support/path.h"
36 #include "support/path_defines.h"
37 #include "support/tostr.h"
38 #include "support/translator.h"
40 #include <boost/bind.hpp>
42 namespace support = lyx::support;
46 using std::istringstream;
48 using std::ostringstream;
53 /// The translator between the DisplayType and the corresponding lyx string.
54 extern Translator<DisplayType, string> displayTranslator;
60 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
62 unsigned int defaultLyxScale = 100;
64 /// Substitute meta-variables in string s, makeing use of params and buffer.
65 string const doSubstitution(InsetExternal::Params const & params,
66 Buffer const & buffer, string const & s);
68 /// Invoke the external editor.
69 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
74 InsetExternal::Params::Params()
75 : display(defaultDisplayType),
76 lyxscale(defaultLyxScale)
78 tempname = support::tempName(string(), "lyxext");
79 support::unlink(tempname);
80 // must have an extension for the converter code to work correctly.
85 InsetExternal::Params::~Params()
87 support::unlink(tempname);
91 InsetExternal::InsetExternal()
92 : renderer_(new ButtonRenderer)
96 InsetExternal::InsetExternal(InsetExternal const & other)
98 boost::signals::trackable(),
99 params_(other.params_),
100 renderer_(other.renderer_->clone())
102 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
104 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
109 auto_ptr<InsetBase> InsetExternal::clone() const
111 return auto_ptr<InsetBase>(new InsetExternal(*this));
115 InsetExternal::~InsetExternal()
117 InsetExternalMailer(*this).hideDialog();
121 void InsetExternal::statusChanged()
123 BufferView * bv = renderer_->view();
125 bv->updateInset(this);
129 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
131 switch (cmd.action) {
133 case LFUN_EXTERNAL_EDIT: {
134 support::Assert(cmd.view());
136 Buffer const & buffer = *cmd.view()->buffer();
137 InsetExternal::Params p;
138 InsetExternalMailer::string2params(cmd.argument, buffer, p);
139 editExternal(p, buffer);
140 return DISPATCHED_NOUPDATE;
143 case LFUN_INSET_MODIFY: {
144 support::Assert(cmd.view());
146 Buffer const & buffer = *cmd.view()->buffer();
147 InsetExternal::Params p;
148 InsetExternalMailer::string2params(cmd.argument, buffer, p);
149 setParams(p, buffer);
150 cmd.view()->updateInset(this);
154 case LFUN_INSET_DIALOG_UPDATE:
155 InsetExternalMailer(*this).updateDialog(cmd.view());
158 case LFUN_MOUSE_RELEASE:
159 case LFUN_INSET_EDIT:
160 InsetExternalMailer(*this).showDialog(cmd.view());
169 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
171 renderer_->metrics(mi, dim);
176 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
178 renderer_->draw(pi, x, y);
184 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
186 lyx::graphics::Params gparams;
188 gparams.filename = eparams.filename.absFilename();
189 gparams.scale = eparams.lyxscale;
190 gparams.display = eparams.display;
192 if (gparams.display == lyx::graphics::DefaultDisplay)
193 gparams.display = lyxrc.display_graphics;
195 // Override the above if we're not using a gui
196 if (!lyx_gui::use_gui)
197 gparams.display = lyx::graphics::NoDisplay;
203 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
205 ExternalTemplateManager & etm = ExternalTemplateManager::get();
206 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
207 if (templ.lyxName.empty())
213 string const getScreenLabel(InsetExternal::Params const & params,
214 Buffer const & buffer)
216 ExternalTemplate const * const ptr = getTemplatePtr(params);
218 return support::bformat(_("External template %1$s is not installed"),
219 params.templatename);
220 return doSubstitution(params, buffer, ptr->guiName);
226 InsetExternal::Params const & InsetExternal::params() const
232 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
234 // The stored params; what we would like to happen in an ideal world.
235 params_.filename = p.filename;
236 params_.templatename = p.templatename;
237 params_.display = p.display;
238 params_.lyxscale = p.lyxscale;
240 // We display the inset as a button by default.
241 bool display_button = (!getTemplatePtr(params_) ||
242 params_.filename.empty() ||
243 params_.display == lyx::graphics::NoDisplay);
245 if (display_button) {
246 ButtonRenderer * button_ptr =
247 dynamic_cast<ButtonRenderer *>(renderer_.get());
249 button_ptr = new ButtonRenderer;
250 renderer_.reset(button_ptr);
253 button_ptr->update(getScreenLabel(params_, buffer), true);
256 GraphicRenderer * graphic_ptr =
257 dynamic_cast<GraphicRenderer *>(renderer_.get());
259 graphic_ptr = new GraphicRenderer;
260 graphic_ptr->connect(
261 boost::bind(&InsetExternal::statusChanged, this));
262 renderer_.reset(graphic_ptr);
265 graphic_ptr->update(get_grfx_params(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 pushpophelper pph(lex, 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.");
361 // Replace the inset's store
362 setParams(params, buffer);
364 lyxerr[Debug::EXTERNAL]
365 << "InsetExternal::Read: "
366 << "template: '" << params_.templatename
367 << "' filename: '" << params_.filename.absFilename()
368 << "' display: '" << params_.display
369 << "' scale: '" << params_.lyxscale
374 int InsetExternal::write(string const & format,
375 Buffer const & buf, ostream & os,
376 bool external_in_tmpdir) const
378 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
381 ExternalTemplate const & et = *et_ptr;
383 ExternalTemplate::Formats::const_iterator cit =
384 et.formats.find(format);
385 if (cit == et.formats.end()) {
386 lyxerr[Debug::EXTERNAL]
387 << "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 = et.formats.find("LaTeX");
454 if (cit == et.formats.end())
457 if (!cit->second.requirement.empty())
458 features.require(cit->second.requirement);
460 ExternalTemplateManager & etm = ExternalTemplateManager::get();
461 string const preamble = etm.getPreambleDefByName(cit->second.preambleName);
462 if (!preamble.empty())
463 features.addExternalPreamble(preamble);
467 void InsetExternal::updateExternal(string const & format,
469 bool external_in_tmpdir) const
471 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
474 ExternalTemplate const & et = *et_ptr;
476 if (!et.automaticProduction)
479 ExternalTemplate::Formats::const_iterator cit =
480 et.formats.find(format);
481 if (cit == et.formats.end())
484 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
485 if (outputFormat.updateResult.empty())
488 string from_format = et.inputFormat;
489 if (from_format.empty())
492 string from_file = params_.filename.absFilename();
494 if (from_format == "*") {
495 if (from_file.empty())
498 // Try and ascertain the file format from its contents.
499 from_format = support::getExtFromContents(from_file);
500 if (from_format.empty())
504 string const to_format = outputFormat.updateFormat;
505 if (to_format.empty())
508 if (!converters.isReachable(from_format, to_format)) {
509 lyxerr[Debug::EXTERNAL]
510 << "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 string const temp_file =
519 support::MakeAbsPath(params_.filename.mangledFilename(),
521 unsigned long const from_checksum = support::sum(from_file);
522 unsigned long const temp_checksum = support::sum(temp_file);
525 if (from_checksum == temp_checksum)
529 if (!support::copy(from_file, temp_file))
531 from_file = temp_file;
534 string const to_file = doSubstitution(params_, buf,
535 outputFormat.updateResult);
536 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
538 // Do we need to perform the conversion?
539 // Yes if to_file does not exist or if from_file is newer than to_file
540 if (support::compare_timestamps(from_file, abs_to_file) < 0)
543 string const to_filebase = support::ChangeExtension(to_file, string());
544 converters.convert(&buf, from_file, to_filebase, 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 buffer_path = buffer.filePath();
556 string const filename = params.filename.outputFilename(buffer_path);
557 string const basename = support::ChangeExtension(filename, string());
558 string const filepath = support::OnlyPath(filename);
560 result = support::subst(s, "$$FName", filename);
561 result = support::subst(result, "$$Basename", basename);
562 result = support::subst(result, "$$FPath", filepath);
563 result = support::subst(result, "$$Tempname", params.tempname);
564 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
566 // Handle the $$Contents(filename) syntax
567 if (support::contains(result, "$$Contents(\"")) {
569 string::size_type const pos = result.find("$$Contents(\"");
570 string::size_type const end = result.find("\")", pos);
571 string const file = result.substr(pos + 12, end - (pos + 12));
574 string const filepath = support::IsFileReadable(file) ?
575 buffer.filePath() : buffer.tmppath;
576 support::Path p(filepath);
578 if (support::IsFileReadable(file))
579 contents = support::GetFileContents(file);
581 result = support::subst(result,
582 ("$$Contents(\"" + file + "\")").c_str(),
590 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
592 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
595 ExternalTemplate const & et = *et_ptr;
597 if (et.editCommand.empty())
600 string const command = doSubstitution(params, buffer, et.editCommand);
602 support::Path p(buffer.filePath());
603 support::Forkedcall call;
604 if (lyxerr.debugging(Debug::EXTERNAL)) {
605 lyxerr << "Executing '" << command << "' in '"
606 << buffer.filePath() << '\'' << endl;
608 call.startscript(support::Forkedcall::DontWait, command);
613 string const InsetExternalMailer::name_("external");
615 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
620 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
622 return params2string(inset_.params(), buffer);
626 void InsetExternalMailer::string2params(string const & in,
627 Buffer const & buffer,
628 InsetExternal::Params & params)
630 params = InsetExternal::Params();
635 istringstream data(STRCONV(in));
641 string const token = lex.getString();
646 // This is part of the inset proper that is usually swallowed
647 // by Buffer::readInset
650 string const token = lex.getString();
651 if (token != "External")
657 inset.read(buffer, lex);
658 params = inset.params();
664 InsetExternalMailer::params2string(InsetExternal::Params const & params,
665 Buffer const & buffer)
668 inset.setParams(params, buffer);
670 data << name_ << ' ';
671 inset.write(buffer, data);
672 data << "\\end_inset\n";
673 return STRCONV(data.str());