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/lyxlib.h"
40 #include "support/path.h"
41 #include "support/path_defines.h"
42 #include "support/tostr.h"
43 #include "support/LAssert.h"
44 #include "support/translator.h"
46 #include <boost/bind.hpp>
51 namespace support = lyx::support;
59 /// The translator between the DisplayType and the corresponding lyx string.
60 extern Translator<DisplayType, string> displayTranslator;
66 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
68 unsigned int defaultLyxScale = 100;
70 /// Substitute meta-variables in string s, makeing use of params and buffer.
71 string const doSubstitution(InsetExternal::Params const & params,
72 Buffer const & buffer, string const & s);
74 /// Invoke the external editor.
75 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
80 InsetExternal::Params::Params()
81 : display(defaultDisplayType),
82 lyxscale(defaultLyxScale)
84 tempname = support::tempName(string(), "lyxext");
85 support::unlink(tempname);
86 // must have an extension for the converter code to work correctly.
91 InsetExternal::Params::~Params()
93 support::unlink(tempname);
97 InsetExternal::InsetExternal()
98 : renderer_(new ButtonRenderer)
102 InsetExternal::InsetExternal(InsetExternal const & other)
104 boost::signals::trackable(),
105 params_(other.params_),
106 renderer_(other.renderer_->clone())
108 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
110 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
115 auto_ptr<InsetBase> InsetExternal::clone() const
117 return auto_ptr<InsetBase>(new InsetExternal(*this));
121 InsetExternal::~InsetExternal()
123 InsetExternalMailer(*this).hideDialog();
127 void InsetExternal::statusChanged()
129 BufferView * bv = renderer_->view();
131 bv->updateInset(this);
135 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
137 switch (cmd.action) {
139 case LFUN_EXTERNAL_EDIT: {
140 support::Assert(cmd.view());
142 Buffer const & buffer = *cmd.view()->buffer();
143 InsetExternal::Params p;
144 InsetExternalMailer::string2params(cmd.argument, buffer, p);
145 editExternal(p, buffer);
146 return DISPATCHED_NOUPDATE;
149 case LFUN_INSET_MODIFY: {
150 support::Assert(cmd.view());
152 Buffer const & buffer = *cmd.view()->buffer();
153 InsetExternal::Params p;
154 InsetExternalMailer::string2params(cmd.argument, buffer, p);
155 setParams(p, buffer);
156 cmd.view()->updateInset(this);
160 case LFUN_INSET_DIALOG_UPDATE:
161 InsetExternalMailer(*this).updateDialog(cmd.view());
164 case LFUN_MOUSE_RELEASE:
165 case LFUN_INSET_EDIT:
166 InsetExternalMailer(*this).showDialog(cmd.view());
175 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
177 renderer_->metrics(mi, dim);
182 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
184 renderer_->draw(pi, x, y);
190 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
192 lyx::graphics::Params gparams;
194 gparams.filename = eparams.filename.absFilename();
195 gparams.scale = eparams.lyxscale;
196 gparams.display = eparams.display;
198 if (gparams.display == lyx::graphics::DefaultDisplay)
199 gparams.display = lyxrc.display_graphics;
201 // Override the above if we're not using a gui
202 if (!lyx_gui::use_gui)
203 gparams.display = lyx::graphics::NoDisplay;
209 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
211 ExternalTemplateManager & etm = ExternalTemplateManager::get();
212 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
213 if (templ.lyxName.empty())
219 string const getScreenLabel(InsetExternal::Params const & params,
220 Buffer const & buffer)
222 ExternalTemplate const * const ptr = getTemplatePtr(params);
224 return support::bformat(_("External template %1$s is not installed"),
225 params.templatename);
226 return doSubstitution(params, buffer, ptr->guiName);
232 InsetExternal::Params const & InsetExternal::params() const
238 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
240 // The stored params; what we would like to happen in an ideal world.
241 params_.filename = p.filename;
242 params_.templatename = p.templatename;
243 params_.display = p.display;
244 params_.lyxscale = p.lyxscale;
246 // We display the inset as a button by default.
247 bool display_button = (!getTemplatePtr(params_) ||
248 params_.filename.empty() ||
249 params_.display == lyx::graphics::NoDisplay);
251 if (display_button) {
252 ButtonRenderer * button_ptr =
253 dynamic_cast<ButtonRenderer *>(renderer_.get());
255 button_ptr = new ButtonRenderer;
256 renderer_.reset(button_ptr);
259 button_ptr->update(getScreenLabel(params_, buffer), true);
262 GraphicRenderer * graphic_ptr =
263 dynamic_cast<GraphicRenderer *>(renderer_.get());
265 graphic_ptr = new GraphicRenderer;
266 graphic_ptr->connect(
267 boost::bind(&InsetExternal::statusChanged, this));
268 renderer_.reset(graphic_ptr);
271 graphic_ptr->update(get_grfx_params(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 pushpophelper pph(lex, 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.");
367 // Replace the inset's store
368 setParams(params, buffer);
370 lyxerr[Debug::INFO] << "InsetExternal::Read: "
371 << "template: '" << params_.templatename
372 << "' filename: '" << params_.filename.absFilename()
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);
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.absFilename();
499 if (from_format == "*") {
500 if (from_file.empty())
503 // Try and ascertain the file format from its contents.
504 from_format = support::getExtFromContents(from_file);
505 if (from_format.empty())
509 string const to_format = outputFormat.updateFormat;
510 if (to_format.empty())
513 if (!converters.isReachable(from_format, to_format)) {
514 lyxerr << "InsetExternal::updateExternal. "
515 "Unable to convert from "
516 << from_format << " to " << to_format << endl;
520 if (external_in_tmpdir && !from_file.empty()) {
521 // We are running stuff through LaTeX
522 string const temp_file =
523 support::MakeAbsPath(params_.filename.mangledFilename(),
525 unsigned long const from_checksum = support::sum(from_file);
526 unsigned long const temp_checksum = support::sum(temp_file);
529 if (from_checksum == temp_checksum)
533 if (!support::copy(from_file, temp_file))
535 from_file = temp_file;
538 string const to_file = doSubstitution(params_, buf,
539 outputFormat.updateResult);
540 string const abs_to_file = support::MakeAbsPath(to_file, buf.filePath());
542 // Do we need to perform the conversion?
543 // Yes if to_file does not exist or if from_file is newer than to_file
544 if (support::compare_timestamps(from_file, abs_to_file) < 0)
547 string const to_filebase = support::ChangeExtension(to_file, string());
548 converters.convert(&buf, from_file, to_filebase, from_format, to_format);
554 /// Substitute meta-variables in this string
555 string const doSubstitution(InsetExternal::Params const & params,
556 Buffer const & buffer, string const & s)
559 string const buffer_path = buffer.filePath();
560 string const filename = params.filename.outputFilename(buffer_path);
561 string const basename = support::ChangeExtension(filename, string());
562 string const filepath = support::OnlyPath(filename);
564 result = support::subst(s, "$$FName", filename);
565 result = support::subst(result, "$$Basename", basename);
566 result = support::subst(result, "$$FPath", filepath);
567 result = support::subst(result, "$$Tempname", params.tempname);
568 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
570 // Handle the $$Contents(filename) syntax
571 if (support::contains(result, "$$Contents(\"")) {
573 string::size_type const pos = result.find("$$Contents(\"");
574 string::size_type const end = result.find("\")", pos);
575 string const file = result.substr(pos + 12, end - (pos + 12));
578 string const filepath = support::IsFileReadable(file) ?
579 buffer.filePath() : buffer.tmppath;
580 support::Path p(filepath);
582 if (support::IsFileReadable(file))
583 contents = support::GetFileContents(file);
585 result = support::subst(result,
586 ("$$Contents(\"" + file + "\")").c_str(),
594 void editExternal(InsetExternal::Params const & params, Buffer const & buffer)
596 ExternalTemplate const * const et_ptr = getTemplatePtr(params);
599 ExternalTemplate const & et = *et_ptr;
601 if (et.editCommand.empty())
604 string const command = doSubstitution(params, buffer, et.editCommand);
606 support::Path p(buffer.filePath());
607 support::Forkedcall call;
608 if (lyxerr.debugging()) {
609 lyxerr << "Executing '" << command << "' in '"
610 << buffer.filePath() << '\'' << endl;
612 call.startscript(support::Forkedcall::DontWait, command);
617 string const InsetExternalMailer::name_("external");
619 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
624 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
626 return params2string(inset_.params(), buffer);
630 void InsetExternalMailer::string2params(string const & in,
631 Buffer const & buffer,
632 InsetExternal::Params & params)
634 params = InsetExternal::Params();
639 istringstream data(STRCONV(in));
645 string const token = lex.getString();
650 // This is part of the inset proper that is usually swallowed
651 // by Buffer::readInset
654 string const token = lex.getString();
655 if (token != "External")
661 inset.read(buffer, lex);
662 params = inset.params();
668 InsetExternalMailer::params2string(InsetExternal::Params const & params,
669 Buffer const & buffer)
672 inset.setParams(params, buffer);
674 data << name_ << ' ';
675 inset.write(buffer, data);
676 data << "\\end_inset\n";
677 return STRCONV(data.str());