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/path_defines.h"
41 #include "support/tostr.h"
42 #include "support/LAssert.h"
43 #include "support/translator.h"
45 #include <boost/bind.hpp>
50 namespace support = lyx::support;
58 /// The translator between the DisplayType and the corresponding lyx string.
59 extern Translator<DisplayType, string> displayTranslator;
65 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
67 unsigned int defaultLyxScale = 100;
69 /// Substitute meta-variables in string s, makeing use of params and buffer.
70 string const doSubstitution(InsetExternal::Params const & params,
71 Buffer const & buffer, string const & s);
73 /// Invoke the external editor.
74 void editExternal(InsetExternal::Params const & params, Buffer const & buffer);
79 InsetExternal::Params::Params()
80 : display(defaultDisplayType),
81 lyxscale(defaultLyxScale)
83 tempname = support::tempName(string(), "lyxext");
84 support::unlink(tempname);
85 // must have an extension for the converter code to work correctly.
90 InsetExternal::Params::~Params()
92 support::unlink(tempname);
96 InsetExternal::InsetExternal()
97 : renderer_(new ButtonRenderer)
101 InsetExternal::InsetExternal(InsetExternal const & other)
103 boost::signals::trackable(),
104 params_(other.params_),
105 renderer_(other.renderer_->clone())
107 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
109 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
114 auto_ptr<InsetBase> InsetExternal::clone() const
116 return auto_ptr<InsetBase>(new InsetExternal(*this));
120 InsetExternal::~InsetExternal()
122 InsetExternalMailer(*this).hideDialog();
126 void InsetExternal::statusChanged()
128 BufferView * bv = renderer_->view();
130 bv->updateInset(this);
134 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
136 switch (cmd.action) {
138 case LFUN_EXTERNAL_EDIT: {
139 support::Assert(cmd.view());
141 Buffer const & buffer = *cmd.view()->buffer();
142 InsetExternal::Params p;
143 InsetExternalMailer::string2params(cmd.argument, buffer, p);
144 editExternal(p, buffer);
145 return DISPATCHED_NOUPDATE;
148 case LFUN_INSET_MODIFY: {
149 support::Assert(cmd.view());
151 Buffer const & buffer = *cmd.view()->buffer();
152 InsetExternal::Params p;
153 InsetExternalMailer::string2params(cmd.argument, buffer, p);
154 setParams(p, buffer);
155 cmd.view()->updateInset(this);
159 case LFUN_INSET_DIALOG_UPDATE:
160 InsetExternalMailer(*this).updateDialog(cmd.view());
163 case LFUN_MOUSE_RELEASE:
164 case LFUN_INSET_EDIT:
165 InsetExternalMailer(*this).showDialog(cmd.view());
174 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
176 renderer_->metrics(mi, dim);
181 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
183 renderer_->draw(pi, x, y);
189 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams)
191 lyx::graphics::Params gparams;
193 gparams.filename = eparams.filename.absFilename();
194 gparams.scale = eparams.lyxscale;
195 gparams.display = eparams.display;
197 if (gparams.display == lyx::graphics::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 = lyx::graphics::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,
219 Buffer const & buffer)
221 ExternalTemplate const * const ptr = getTemplatePtr(params);
223 return support::bformat(_("External template %1$s is not installed"),
224 params.templatename);
225 return doSubstitution(params, buffer, ptr->guiName);
231 InsetExternal::Params const & InsetExternal::params() const
237 void InsetExternal::setParams(Params const & p, Buffer const & buffer)
239 // The stored params; what we would like to happen in an ideal world.
240 params_.filename = p.filename;
241 params_.templatename = p.templatename;
242 params_.display = p.display;
243 params_.lyxscale = p.lyxscale;
245 // We display the inset as a button by default.
246 bool display_button = (!getTemplatePtr(params_) ||
247 params_.filename.empty() ||
248 params_.display == lyx::graphics::NoDisplay);
250 if (display_button) {
251 ButtonRenderer * button_ptr =
252 dynamic_cast<ButtonRenderer *>(renderer_.get());
254 button_ptr = new ButtonRenderer;
255 renderer_.reset(button_ptr);
258 button_ptr->update(getScreenLabel(params_, buffer), true);
261 GraphicRenderer * graphic_ptr =
262 dynamic_cast<GraphicRenderer *>(renderer_.get());
264 graphic_ptr = new GraphicRenderer;
265 graphic_ptr->connect(
266 boost::bind(&InsetExternal::statusChanged, this));
267 renderer_.reset(graphic_ptr);
270 graphic_ptr->update(get_grfx_params(params_));
275 void InsetExternal::write(Buffer const & buffer, ostream & os) const
278 << "\ttemplate " << params_.templatename << '\n';
280 if (!params_.filename.empty())
282 << params_.filename.outputFilename(buffer.filePath())
285 if (params_.display != defaultDisplayType)
286 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
289 if (params_.lyxscale != defaultLyxScale)
290 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
294 void InsetExternal::read(Buffer const & buffer, LyXLex & lex)
304 keyword_item external_tags[] = {
305 { "\\end_inset", EX_END },
306 { "display", EX_DISPLAY},
307 { "filename", EX_FILENAME},
308 { "lyxscale", EX_LYXSCALE},
309 { "template", EX_TEMPLATE }
312 pushpophelper pph(lex, external_tags, EX_END);
314 bool found_end = false;
315 bool read_error = false;
317 InsetExternal::Params params;
322 params.templatename = lex.getString();
328 string const name = lex.getString();
329 params.filename.set(name, buffer.filePath());
335 string const name = lex.getString();
336 params.display = lyx::graphics::displayTranslator.find(name);
342 params.lyxscale = lex.getInteger();
351 lex.printError("ExternalInset::read: "
352 "Wrong tag: $$Token");
357 if (found_end || read_error)
362 lex.printError("ExternalInset::read: "
363 "Missing \\end_inset.");
366 // Replace the inset's store
367 setParams(params, buffer);
369 lyxerr[Debug::INFO] << "InsetExternal::Read: "
370 << "template: '" << params_.templatename
371 << "' filename: '" << params_.filename.absFilename()
372 << "' display: '" << params_.display
373 << "' scale: '" << params_.lyxscale
378 int InsetExternal::write(string const & format,
379 Buffer const & buf, ostream & os,
380 bool external_in_tmpdir) const
382 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
385 ExternalTemplate const & et = *et_ptr;
387 ExternalTemplate::Formats::const_iterator cit =
388 et.formats.find(format);
389 if (cit == et.formats.end()) {
390 lyxerr << "External template format '" << format
391 << "' not specified in template "
392 << params_.templatename << endl;
396 updateExternal(format, buf, external_in_tmpdir);
397 string const str = doSubstitution(params_, buf, cit->second.product);
399 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
403 int InsetExternal::latex(Buffer const & buf, ostream & os,
404 LatexRunParams const & runparams) const
406 // "nice" means that the buffer is exported to LaTeX format but not
407 // run through the LaTeX compiler.
408 // If we're running through the LaTeX compiler, we should write the
409 // generated files in the bufer's temporary directory.
410 bool const external_in_tmpdir =
411 lyxrc.use_tempdir && !buf.tmppath.empty() && !runparams.nice;
413 // If the template has specified a PDFLaTeX output, then we try and
415 if (runparams.flavor == LatexRunParams::PDFLATEX) {
416 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
419 ExternalTemplate const & et = *et_ptr;
421 ExternalTemplate::Formats::const_iterator cit =
422 et.formats.find("PDFLaTeX");
423 if (cit != et.formats.end())
424 return write("PDFLaTeX", buf, os, external_in_tmpdir);
427 return write("LaTeX", buf, os, external_in_tmpdir);
431 int InsetExternal::ascii(Buffer const & buf, ostream & os, int) const
433 return write("Ascii", buf, os);
437 int InsetExternal::linuxdoc(Buffer const & buf, ostream & os) const
439 return write("LinuxDoc", buf, os);
443 int InsetExternal::docbook(Buffer const & buf, ostream & os, bool) const
445 return write("DocBook", buf, os);
449 void InsetExternal::validate(LaTeXFeatures & features) const
451 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
454 ExternalTemplate const & et = *et_ptr;
456 ExternalTemplate::Formats::const_iterator cit =
457 et.formats.find("LaTeX");
459 if (cit == et.formats.end())
462 if (!cit->second.requirement.empty()) {
463 features.require(cit->second.requirement);
465 if (!cit->second.preamble.empty()) {
466 features.addExternalPreamble(cit->second.preamble + "\n");
471 void InsetExternal::updateExternal(string const & format,
473 bool external_in_tmpdir) const
475 ExternalTemplate const * const et_ptr = getTemplatePtr(params_);
478 ExternalTemplate const & et = *et_ptr;
480 if (!et.automaticProduction)
483 ExternalTemplate::Formats::const_iterator cit =
484 et.formats.find(format);
485 if (cit == et.formats.end())
488 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
489 if (outputFormat.updateResult.empty())
492 string from_format = et.inputFormat;
493 if (from_format.empty())
496 string from_file = params_.filename.absFilename();
498 if (from_format == "*") {
499 if (from_file.empty())
502 // Try and ascertain the file format from its contents.
503 from_format = support::getExtFromContents(from_file);
504 if (from_format.empty())
508 string const to_format = outputFormat.updateFormat;
509 if (to_format.empty())
512 if (!converters.isReachable(from_format, to_format)) {
513 lyxerr << "InsetExternal::updateExternal. "
514 "Unable to convert from "
515 << from_format << " to " << to_format << endl;
519 if (external_in_tmpdir && !from_file.empty()) {
520 // We are running stuff through LaTeX
521 from_file = support::copyFileToDir(buf.tmppath, from_file);
522 if (from_file.empty())
526 string const to_file = doSubstitution(params_, buf,
527 outputFormat.updateResult);
529 support::FileInfo fi(from_file);
530 string abs_to_file = to_file;
531 if (!support::AbsolutePath(to_file))
532 abs_to_file = support::MakeAbsPath(to_file,
533 support::OnlyPath(from_file));
534 support::FileInfo fi2(abs_to_file);
535 if (fi2.exist() && fi.exist() &&
536 difftime(fi2.getModificationTime(),
537 fi.getModificationTime()) >= 0) {
539 string const to_filebase = support::ChangeExtension(to_file, string());
540 converters.convert(&buf, from_file, to_filebase,
541 from_format, to_format);
548 /// Substitute meta-variables in this string
549 string const doSubstitution(InsetExternal::Params const & params,
550 Buffer const & buffer, string const & s)
553 string const buffer_path = buffer.filePath();
554 string const filename = params.filename.outputFilename(buffer_path);
555 string const basename = support::ChangeExtension(filename, string());
556 string const filepath = support::OnlyPath(filename);
558 result = support::subst(s, "$$FName", filename);
559 result = support::subst(result, "$$Basename", basename);
560 result = support::subst(result, "$$FPath", filepath);
561 result = support::subst(result, "$$Tempname", params.tempname);
562 result = support::subst(result, "$$Sysdir", support::system_lyxdir());
564 // Handle the $$Contents(filename) syntax
565 if (support::contains(result, "$$Contents(\"")) {
567 string::size_type const pos = result.find("$$Contents(\"");
568 string::size_type const end = result.find("\")", pos);
569 string const file = result.substr(pos + 12, end - (pos + 12));
572 string const filepath = support::IsFileReadable(file) ?
573 buffer.filePath() : buffer.tmppath;
574 support::Path p(filepath);
576 if (support::IsFileReadable(file))
577 contents = support::GetFileContents(file);
579 result = support::subst(result,
580 ("$$Contents(\"" + file + "\")").c_str(),
588 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 support::Path p(buffer.filePath());
601 support::Forkedcall call;
602 if (lyxerr.debugging()) {
603 lyxerr << "Executing '" << command << "' in '"
604 << buffer.filePath() << '\'' << endl;
606 call.startscript(support::Forkedcall::DontWait, command);
611 string const InsetExternalMailer::name_("external");
613 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
618 string const InsetExternalMailer::inset2string(Buffer const & buffer) const
620 return params2string(inset_.params(), buffer);
624 void InsetExternalMailer::string2params(string const & in,
625 Buffer const & buffer,
626 InsetExternal::Params & params)
628 params = InsetExternal::Params();
633 istringstream data(STRCONV(in));
639 string const token = lex.getString();
644 // This is part of the inset proper that is usually swallowed
645 // by Buffer::readInset
648 string const token = lex.getString();
649 if (token != "External")
655 inset.read(buffer, lex);
656 params = inset.params();
662 InsetExternalMailer::params2string(InsetExternal::Params const & params,
663 Buffer const & buffer)
666 inset.setParams(params, buffer);
668 data << name_ << ' ';
669 inset.write(buffer, data);
670 data << "\\end_inset\n";
671 return STRCONV(data.str());