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>
53 grfx::DisplayType const defaultDisplayType = grfx::NoDisplay;
55 unsigned int defaultLyxScale = 100;
57 /// Substitute meta-variables in string s, makeing use of params and buffer.
58 string const doSubstitution(InsetExternal::Params const & params,
59 Buffer const * buffer, string const & s);
61 /// Invoke the external editor.
62 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
67 InsetExternal::Params::Params()
68 : display(defaultDisplayType),
69 lyxscale(defaultLyxScale)
71 tempname = lyx::tempName(string(), "lyxext");
72 lyx::unlink(tempname);
73 // must have an extension for the converter code to work correctly.
78 InsetExternal::Params::~Params()
80 lyx::unlink(tempname);
84 InsetExternal::InsetExternal()
85 : renderer_(new ButtonRenderer)
89 InsetExternal::InsetExternal(InsetExternal const & other)
91 boost::signals::trackable(),
92 params_(other.params_),
93 renderer_(other.renderer_->clone())
95 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
97 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
102 InsetBase * InsetExternal::clone() const
104 InsetExternal * inset = new InsetExternal(*this);
109 InsetExternal::~InsetExternal()
111 InsetExternalMailer(*this).hideDialog();
115 void InsetExternal::statusChanged()
117 BufferView * bv = renderer_->view();
119 bv->updateInset(this);
123 InsetExternal::Params const & InsetExternal::params() const
129 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
131 switch (cmd.action) {
133 case LFUN_EXTERNAL_EDIT: {
134 lyx::Assert(cmd.view());
136 InsetExternal::Params p;
137 InsetExternalMailer::string2params(cmd.argument, p);
138 editExternal(p, cmd.view()->buffer());
139 return DISPATCHED_NOUPDATE;
142 case LFUN_INSET_MODIFY: {
143 lyx::Assert(cmd.view());
145 InsetExternal::Params p;
146 InsetExternalMailer::string2params(cmd.argument, p);
147 setParams(p, cmd.view()->buffer()->filePath());
148 cmd.view()->updateInset(this);
152 case LFUN_INSET_DIALOG_UPDATE:
153 InsetExternalMailer(*this).updateDialog(cmd.view());
156 case LFUN_MOUSE_RELEASE:
157 case LFUN_INSET_EDIT:
158 InsetExternalMailer(*this).showDialog(cmd.view());
167 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
169 renderer_->metrics(mi, dim);
173 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
175 renderer_->draw(pi, x, y);
181 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
182 string const & filepath)
184 grfx::Params gparams;
186 if (!eparams.filename.empty()) {
187 lyx::Assert(AbsolutePath(filepath));
188 gparams.filename = MakeAbsPath(eparams.filename, filepath);
191 gparams.scale = eparams.lyxscale;
192 gparams.display = eparams.display;
194 if (gparams.display == grfx::DefaultDisplay)
195 gparams.display = lyxrc.display_graphics;
197 // Override the above if we're not using a gui
198 if (!lyx_gui::use_gui)
199 gparams.display = grfx::NoDisplay;
205 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
207 ExternalTemplateManager & etm = ExternalTemplateManager::get();
208 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
209 if (templ.lyxName.empty())
215 string const getScreenLabel(InsetExternal::Params const & params)
217 ExternalTemplate const * const ptr = getTemplatePtr(params);
219 return bformat(_("External template %1$s is not installed"),
220 params.templatename);
221 return doSubstitution(params, 0, ptr->guiName);
227 void InsetExternal::setParams(Params const & p, string const & filepath)
229 // The stored params; what we would like to happen in an ideal world.
230 params_.filename = p.filename;
231 params_.templatename = p.templatename;
232 params_.display = p.display;
233 params_.lyxscale = p.lyxscale;
235 // We display the inset as a button by default.
236 bool display_button = (!getTemplatePtr(params_) ||
237 params_.filename.empty() ||
239 params_.display == grfx::NoDisplay);
241 if (display_button) {
242 ButtonRenderer * button_ptr =
243 dynamic_cast<ButtonRenderer *>(renderer_.get());
245 button_ptr = new ButtonRenderer;
246 renderer_.reset(button_ptr);
249 button_ptr->update(getScreenLabel(params_), true);
252 GraphicRenderer * graphic_ptr =
253 dynamic_cast<GraphicRenderer *>(renderer_.get());
255 graphic_ptr = new GraphicRenderer;
256 graphic_ptr->connect(
257 boost::bind(&InsetExternal::statusChanged, this));
258 renderer_.reset(graphic_ptr);
261 graphic_ptr->update(get_grfx_params(params_, filepath));
266 string const InsetExternal::editMessage() const
268 return getScreenLabel(params_);
272 void InsetExternal::write(Buffer const *, ostream & os) const
275 << "\ttemplate " << params_.templatename << '\n';
277 if (!params_.filename.empty())
278 os << "\tfilename " << params_.filename << '\n';
280 if (params_.display != defaultDisplayType)
281 os << "\tdisplay " << grfx::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 = name;
330 string const name = lex.getString();
331 params.display = grfx::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
364 string const path = buffer ? buffer->filePath() : string();
365 setParams(params, path);
367 lyxerr[Debug::INFO] << "InsetExternal::Read: "
368 << "template: '" << params_.templatename
369 << "' filename: '" << params_.filename
370 << "' display: '" << params_.display
371 << "' scale: '" << params_.lyxscale
376 int InsetExternal::write(string const & format,
377 Buffer const * buf, ostream & os,
378 bool external_in_tmpdir) const
380 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
383 ExternalTemplate const & et = *et_ptr;
385 ExternalTemplate::Formats::const_iterator cit =
386 et.formats.find(format);
387 if (cit == et.formats.end()) {
388 lyxerr << "External template format '" << format
389 << "' not specified in template "
390 << params_.templatename << endl;
394 updateExternal(format, buf, external_in_tmpdir);
395 string const str = doSubstitution(params_, buf, cit->second.product);
397 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
401 int InsetExternal::latex(Buffer const * buf, ostream & os,
402 LatexRunParams const & runparams) const
404 // "nice" means that the buffer is exported to LaTeX format but not
405 // run through the LaTeX compiler.
406 // If we're running through the LaTeX compiler, we should write the
407 // generated files in the bufer's temporary directory.
408 bool const external_in_tmpdir =
409 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
411 // If the template has specified a PDFLaTeX output, then we try and
413 if (runparams.flavor == LatexRunParams::PDFLATEX) {
414 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
417 ExternalTemplate const & et = *et_ptr;
419 ExternalTemplate::Formats::const_iterator cit =
420 et.formats.find("PDFLaTeX");
421 if (cit != et.formats.end())
422 return write("PDFLaTeX", buf, os, external_in_tmpdir);
425 return write("LaTeX", buf, os, external_in_tmpdir);
429 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
431 return write("Ascii", buf, os);
435 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
437 return write("LinuxDoc", buf, os);
441 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
443 return write("DocBook", buf, os);
447 void InsetExternal::validate(LaTeXFeatures & features) const
449 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
452 ExternalTemplate const & et = *et_ptr;
454 ExternalTemplate::Formats::const_iterator cit =
455 et.formats.find("LaTeX");
457 if (cit == et.formats.end())
460 if (!cit->second.requirement.empty()) {
461 features.require(cit->second.requirement);
463 if (!cit->second.preamble.empty()) {
464 features.addExternalPreamble(cit->second.preamble + "\n");
469 void InsetExternal::updateExternal(string const & format,
471 bool external_in_tmpdir) const
473 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
476 ExternalTemplate const & et = *et_ptr;
478 if (!et.automaticProduction)
481 ExternalTemplate::Formats::const_iterator cit =
482 et.formats.find(format);
483 if (cit == et.formats.end())
486 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
487 if (outputFormat.updateResult.empty())
490 string from_format = et.inputFormat;
491 if (from_format.empty())
494 string from_file = params_.filename.empty() ?
495 string() : MakeAbsPath(params_.filename, buf->filePath());
497 if (from_format == "*") {
498 if (from_file.empty())
501 // Try and ascertain the file format from its contents.
502 from_format = getExtFromContents(from_file);
503 if (from_format.empty())
507 string const to_format = outputFormat.updateFormat;
508 if (to_format.empty())
511 if (!converters.isReachable(from_format, to_format)) {
512 lyxerr << "InsetExternal::updateExternal. "
513 "Unable to convert from "
514 << from_format << " to " << to_format << endl;
518 if (external_in_tmpdir && !from_file.empty()) {
519 // We are running stuff through LaTeX
520 from_file = copyFileToDir(buf->tmppath, from_file);
521 if (from_file.empty())
525 string const to_file = doSubstitution(params_, buf,
526 outputFormat.updateResult);
528 FileInfo fi(from_file);
529 string abs_to_file = to_file;
530 if (!AbsolutePath(to_file))
531 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
532 FileInfo fi2(abs_to_file);
533 if (fi2.exist() && fi.exist() &&
534 difftime(fi2.getModificationTime(),
535 fi.getModificationTime()) >= 0) {
537 string const to_filebase = ChangeExtension(to_file, string());
538 converters.convert(buf, from_file, to_filebase,
539 from_format, to_format);
546 /// Substitute meta-variables in this string
547 string const doSubstitution(InsetExternal::Params const & params,
548 Buffer const * buffer, string const & s)
551 string const basename = ChangeExtension(params.filename, string());
554 result = subst(s, "$$FName", params.filename);
555 result = subst(result, "$$Basename", basename);
556 result = subst(result, "$$FPath", filepath);
557 result = subst(result, "$$Tempname", params.tempname);
558 result = subst(result, "$$Sysdir", system_lyxdir);
560 // Handle the $$Contents(filename) syntax
561 if (contains(result, "$$Contents(\"")) {
563 string::size_type const pos = result.find("$$Contents(\"");
564 string::size_type const end = result.find("\")", pos);
565 string const file = result.substr(pos + 12, end - (pos + 12));
568 Path p(buffer->filePath());
569 if (!IsFileReadable(file))
570 Path p(buffer->tmppath);
571 if (IsFileReadable(file))
572 contents = GetFileContents(file);
574 contents = GetFileContents(file);
576 result = subst(result,
577 ("$$Contents(\"" + file + "\")").c_str(),
585 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
590 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
593 ExternalTemplate const & et = *et_ptr;
595 if (et.editCommand.empty())
598 string const command = doSubstitution(params, buffer, et.editCommand);
600 Path p(buffer->filePath());
602 if (lyxerr.debugging()) {
603 lyxerr << "Executing '" << command << "' in '"
604 << buffer->filePath() << '\'' << endl;
606 call.startscript(Forkedcall::DontWait, command);
611 string const InsetExternalMailer::name_("external");
613 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
618 string const InsetExternalMailer::inset2string() const
620 return params2string(inset_.params());
624 void InsetExternalMailer::string2params(string const & in,
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")
655 params = inset.params();
661 InsetExternalMailer::params2string(InsetExternal::Params const & params)
664 inset.setParams(params, string());
666 data << name_ << ' ';
667 inset.write(0, data);
668 data << "\\end_inset\n";
669 return STRCONV(data.str());