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;
52 namespace grfx = lyx::graphics;
56 grfx::DisplayType const defaultDisplayType = grfx::NoDisplay;
58 unsigned int defaultLyxScale = 100;
60 /// Substitute meta-variables in string s, makeing use of params and buffer.
61 string const doSubstitution(InsetExternal::Params const & params,
62 Buffer const * buffer, string const & s);
64 /// Invoke the external editor.
65 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
70 InsetExternal::Params::Params()
71 : display(defaultDisplayType),
72 lyxscale(defaultLyxScale)
74 tempname = tempName(string(), "lyxext");
76 // must have an extension for the converter code to work correctly.
81 InsetExternal::Params::~Params()
87 InsetExternal::InsetExternal()
88 : renderer_(new ButtonRenderer)
92 InsetExternal::InsetExternal(InsetExternal const & other)
94 boost::signals::trackable(),
95 params_(other.params_),
96 renderer_(other.renderer_->clone())
98 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
100 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
105 InsetBase * InsetExternal::clone() const
107 InsetExternal * inset = new InsetExternal(*this);
112 InsetExternal::~InsetExternal()
114 InsetExternalMailer(*this).hideDialog();
118 void InsetExternal::statusChanged()
120 BufferView * bv = renderer_->view();
122 bv->updateInset(this);
126 InsetExternal::Params const & InsetExternal::params() const
132 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
134 switch (cmd.action) {
136 case LFUN_EXTERNAL_EDIT: {
139 InsetExternal::Params p;
140 InsetExternalMailer::string2params(cmd.argument, p);
141 editExternal(p, cmd.view()->buffer());
142 return DISPATCHED_NOUPDATE;
145 case LFUN_INSET_MODIFY: {
148 InsetExternal::Params p;
149 InsetExternalMailer::string2params(cmd.argument, p);
150 setParams(p, cmd.view()->buffer()->filePath());
151 cmd.view()->updateInset(this);
155 case LFUN_INSET_DIALOG_UPDATE:
156 InsetExternalMailer(*this).updateDialog(cmd.view());
159 case LFUN_MOUSE_RELEASE:
160 case LFUN_INSET_EDIT:
161 InsetExternalMailer(*this).showDialog(cmd.view());
170 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
172 renderer_->metrics(mi, dim);
176 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
178 renderer_->draw(pi, x, y);
184 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
185 string const & filepath)
187 grfx::Params gparams;
189 if (!eparams.filename.empty()) {
190 Assert(AbsolutePath(filepath));
191 gparams.filename = MakeAbsPath(eparams.filename, filepath);
194 gparams.scale = eparams.lyxscale;
195 gparams.display = eparams.display;
197 if (gparams.display == grfx::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 = grfx::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)
220 ExternalTemplate const * const ptr = getTemplatePtr(params);
222 return bformat(_("External template %1$s is not installed"),
223 params.templatename);
224 return doSubstitution(params, 0, ptr->guiName);
230 void InsetExternal::setParams(Params const & p, string const & filepath)
232 // The stored params; what we would like to happen in an ideal world.
233 params_.filename = p.filename;
234 params_.templatename = p.templatename;
235 params_.display = p.display;
236 params_.lyxscale = p.lyxscale;
238 // We display the inset as a button by default.
239 bool display_button = (!getTemplatePtr(params_) ||
240 params_.filename.empty() ||
242 params_.display == grfx::NoDisplay);
244 if (display_button) {
245 ButtonRenderer * button_ptr =
246 dynamic_cast<ButtonRenderer *>(renderer_.get());
248 button_ptr = new ButtonRenderer;
249 renderer_.reset(button_ptr);
252 button_ptr->update(getScreenLabel(params_), true);
255 GraphicRenderer * graphic_ptr =
256 dynamic_cast<GraphicRenderer *>(renderer_.get());
258 graphic_ptr = new GraphicRenderer;
259 graphic_ptr->connect(
260 boost::bind(&InsetExternal::statusChanged, this));
261 renderer_.reset(graphic_ptr);
264 graphic_ptr->update(get_grfx_params(params_, filepath));
269 string const InsetExternal::editMessage() const
271 return getScreenLabel(params_);
275 void InsetExternal::write(Buffer const *, ostream & os) const
278 << "\ttemplate " << params_.templatename << '\n';
280 if (!params_.filename.empty())
281 os << "\tfilename " << params_.filename << '\n';
283 if (params_.display != defaultDisplayType)
284 os << "\tdisplay " << grfx::displayTranslator.find(params_.display)
287 if (params_.lyxscale != defaultLyxScale)
288 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
292 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
302 keyword_item external_tags[] = {
303 { "\\end_inset", EX_END },
304 { "display", EX_DISPLAY},
305 { "filename", EX_FILENAME},
306 { "lyxscale", EX_LYXSCALE},
307 { "template", EX_TEMPLATE }
310 lex.pushTable(external_tags, EX_END);
312 bool found_end = false;
313 bool read_error = false;
315 InsetExternal::Params params;
320 params.templatename = lex.getString();
326 string const name = lex.getString();
327 params.filename = name;
333 string const name = lex.getString();
334 params.display = grfx::displayTranslator.find(name);
340 params.lyxscale = lex.getInteger();
349 lex.printError("ExternalInset::read: "
350 "Wrong tag: $$Token");
355 if (found_end || read_error)
360 lex.printError("ExternalInset::read: "
361 "Missing \\end_inset.");
366 // Replace the inset's store
367 string const path = buffer ? buffer->filePath() : string();
368 setParams(params, path);
370 lyxerr[Debug::INFO] << "InsetExternal::Read: "
371 << "template: '" << params_.templatename
372 << "' filename: '" << params_.filename
373 << "' display: '" << params_.display
374 << "' scale: '" << params_.lyxscale
379 int InsetExternal::write(string const & format,
380 Buffer const * buf, ostream & os,
381 bool external_in_tmpdir) const
383 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
386 ExternalTemplate const & et = *et_ptr;
388 ExternalTemplate::Formats::const_iterator cit =
389 et.formats.find(format);
390 if (cit == et.formats.end()) {
391 lyxerr << "External template format '" << format
392 << "' not specified in template "
393 << params_.templatename << endl;
397 updateExternal(format, buf, external_in_tmpdir);
398 string const str = doSubstitution(params_, buf, cit->second.product);
400 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
404 int InsetExternal::latex(Buffer const * buf, ostream & os,
405 LatexRunParams const & runparams) const
407 // "nice" means that the buffer is exported to LaTeX format but not
408 // run through the LaTeX compiler.
409 // If we're running through the LaTeX compiler, we should write the
410 // generated files in the bufer's temporary directory.
411 bool const external_in_tmpdir =
412 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
414 // If the template has specified a PDFLaTeX output, then we try and
416 if (runparams.flavor == LatexRunParams::PDFLATEX) {
417 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
420 ExternalTemplate const & et = *et_ptr;
422 ExternalTemplate::Formats::const_iterator cit =
423 et.formats.find("PDFLaTeX");
424 if (cit != et.formats.end())
425 return write("PDFLaTeX", buf, os, external_in_tmpdir);
428 return write("LaTeX", buf, os, external_in_tmpdir);
432 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
434 return write("Ascii", buf, os);
438 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
440 return write("LinuxDoc", buf, os);
444 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
446 return write("DocBook", buf, os);
450 void InsetExternal::validate(LaTeXFeatures & features) const
452 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
455 ExternalTemplate const & et = *et_ptr;
457 ExternalTemplate::Formats::const_iterator cit =
458 et.formats.find("LaTeX");
460 if (cit == et.formats.end())
463 if (!cit->second.requirement.empty()) {
464 features.require(cit->second.requirement);
466 if (!cit->second.preamble.empty()) {
467 features.addExternalPreamble(cit->second.preamble + "\n");
472 void InsetExternal::updateExternal(string const & format,
474 bool external_in_tmpdir) const
476 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
479 ExternalTemplate const & et = *et_ptr;
481 if (!et.automaticProduction)
484 ExternalTemplate::Formats::const_iterator cit =
485 et.formats.find(format);
486 if (cit == et.formats.end())
489 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
490 if (outputFormat.updateResult.empty())
493 string from_format = et.inputFormat;
494 if (from_format.empty())
497 string from_file = params_.filename.empty() ?
498 string() : MakeAbsPath(params_.filename, buf->filePath());
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 basename = ChangeExtension(params.filename, string());
557 result = subst(s, "$$FName", params.filename);
558 result = subst(result, "$$Basename", basename);
559 result = subst(result, "$$FPath", filepath);
560 result = subst(result, "$$Tempname", params.tempname);
561 result = subst(result, "$$Sysdir", system_lyxdir);
563 // Handle the $$Contents(filename) syntax
564 if (contains(result, "$$Contents(\"")) {
566 string::size_type const pos = result.find("$$Contents(\"");
567 string::size_type const end = result.find("\")", pos);
568 string const file = result.substr(pos + 12, end - (pos + 12));
571 Path p(buffer->filePath());
572 if (!IsFileReadable(file))
573 Path p(buffer->tmppath);
574 if (IsFileReadable(file))
575 contents = GetFileContents(file);
577 contents = GetFileContents(file);
579 result = subst(result,
580 ("$$Contents(\"" + file + "\")").c_str(),
588 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
593 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
596 ExternalTemplate const & et = *et_ptr;
598 if (et.editCommand.empty())
601 string const command = doSubstitution(params, buffer, et.editCommand);
603 Path p(buffer->filePath());
605 if (lyxerr.debugging()) {
606 lyxerr << "Executing '" << command << "' in '"
607 << buffer->filePath() << '\'' << endl;
609 call.startscript(Forkedcall::DontWait, command);
614 string const InsetExternalMailer::name_("external");
616 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
621 string const InsetExternalMailer::inset2string() const
623 return params2string(inset_.params());
627 void InsetExternalMailer::string2params(string const & in,
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")
658 params = inset.params();
664 InsetExternalMailer::params2string(InsetExternal::Params const & params)
667 inset.setParams(params, string());
669 data << name_ << ' ';
670 inset.write(0, data);
671 data << "\\end_inset\n";
672 return STRCONV(data.str());