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;
54 lyx::graphics::DisplayType const defaultDisplayType = lyx::graphics::NoDisplay;
56 unsigned int defaultLyxScale = 100;
58 /// Substitute meta-variables in string s, makeing use of params and buffer.
59 string const doSubstitution(InsetExternal::Params const & params,
60 Buffer const * buffer, string const & s);
62 /// Invoke the external editor.
63 void editExternal(InsetExternal::Params const & params, Buffer const * buffer);
68 InsetExternal::Params::Params()
69 : display(defaultDisplayType),
70 lyxscale(defaultLyxScale)
72 tempname = tempName(string(), "lyxext");
74 // must have an extension for the converter code to work correctly.
79 InsetExternal::Params::~Params()
85 InsetExternal::InsetExternal()
86 : renderer_(new ButtonRenderer)
90 InsetExternal::InsetExternal(InsetExternal const & other)
92 boost::signals::trackable(),
93 params_(other.params_),
94 renderer_(other.renderer_->clone())
96 GraphicRenderer * ptr = dynamic_cast<GraphicRenderer *>(renderer_.get());
98 ptr->connect(boost::bind(&InsetExternal::statusChanged, this));
103 InsetBase * InsetExternal::clone() const
105 InsetExternal * inset = new InsetExternal(*this);
110 InsetExternal::~InsetExternal()
112 InsetExternalMailer(*this).hideDialog();
116 void InsetExternal::statusChanged()
118 BufferView * bv = renderer_->view();
120 bv->updateInset(this);
124 InsetExternal::Params const & InsetExternal::params() const
130 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
132 switch (cmd.action) {
134 case LFUN_EXTERNAL_EDIT: {
137 InsetExternal::Params p;
138 InsetExternalMailer::string2params(cmd.argument, p);
139 editExternal(p, cmd.view()->buffer());
140 return DISPATCHED_NOUPDATE;
143 case LFUN_INSET_MODIFY: {
146 InsetExternal::Params p;
147 InsetExternalMailer::string2params(cmd.argument, p);
148 setParams(p, cmd.view()->buffer()->filePath());
149 cmd.view()->updateInset(this);
153 case LFUN_INSET_DIALOG_UPDATE:
154 InsetExternalMailer(*this).updateDialog(cmd.view());
157 case LFUN_MOUSE_RELEASE:
158 case LFUN_INSET_EDIT:
159 InsetExternalMailer(*this).showDialog(cmd.view());
168 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
170 renderer_->metrics(mi, dim);
175 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
177 renderer_->draw(pi, x, y);
183 lyx::graphics::Params get_grfx_params(InsetExternal::Params const & eparams,
184 string const & filepath)
186 lyx::graphics::Params gparams;
188 if (!eparams.filename.empty()) {
189 Assert(AbsolutePath(filepath));
190 gparams.filename = MakeAbsPath(eparams.filename, filepath);
193 gparams.scale = eparams.lyxscale;
194 gparams.display = eparams.display;
196 if (gparams.display == lyx::graphics::DefaultDisplay)
197 gparams.display = lyxrc.display_graphics;
199 // Override the above if we're not using a gui
200 if (!lyx_gui::use_gui)
201 gparams.display = lyx::graphics::NoDisplay;
207 ExternalTemplate const * getTemplatePtr(InsetExternal::Params const & params)
209 ExternalTemplateManager & etm = ExternalTemplateManager::get();
210 ExternalTemplate const & templ = etm.getTemplateByName(params.templatename);
211 if (templ.lyxName.empty())
217 string const getScreenLabel(InsetExternal::Params const & params)
219 ExternalTemplate const * const ptr = getTemplatePtr(params);
221 return bformat(_("External template %1$s is not installed"),
222 params.templatename);
223 return doSubstitution(params, 0, ptr->guiName);
229 void InsetExternal::setParams(Params const & p, string const & filepath)
231 // The stored params; what we would like to happen in an ideal world.
232 params_.filename = p.filename;
233 params_.templatename = p.templatename;
234 params_.display = p.display;
235 params_.lyxscale = p.lyxscale;
237 // We display the inset as a button by default.
238 bool display_button = (!getTemplatePtr(params_) ||
239 params_.filename.empty() ||
241 params_.display == lyx::graphics::NoDisplay);
243 if (display_button) {
244 ButtonRenderer * button_ptr =
245 dynamic_cast<ButtonRenderer *>(renderer_.get());
247 button_ptr = new ButtonRenderer;
248 renderer_.reset(button_ptr);
251 button_ptr->update(getScreenLabel(params_), true);
254 GraphicRenderer * graphic_ptr =
255 dynamic_cast<GraphicRenderer *>(renderer_.get());
257 graphic_ptr = new GraphicRenderer;
258 graphic_ptr->connect(
259 boost::bind(&InsetExternal::statusChanged, this));
260 renderer_.reset(graphic_ptr);
263 graphic_ptr->update(get_grfx_params(params_, filepath));
268 string const InsetExternal::editMessage() const
270 return getScreenLabel(params_);
274 void InsetExternal::write(Buffer const *, ostream & os) const
277 << "\ttemplate " << params_.templatename << '\n';
279 if (!params_.filename.empty())
280 os << "\tfilename " << params_.filename << '\n';
282 if (params_.display != defaultDisplayType)
283 os << "\tdisplay " << lyx::graphics::displayTranslator.find(params_.display)
286 if (params_.lyxscale != defaultLyxScale)
287 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
291 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
301 keyword_item external_tags[] = {
302 { "\\end_inset", EX_END },
303 { "display", EX_DISPLAY},
304 { "filename", EX_FILENAME},
305 { "lyxscale", EX_LYXSCALE},
306 { "template", EX_TEMPLATE }
309 lex.pushTable(external_tags, EX_END);
311 bool found_end = false;
312 bool read_error = false;
314 InsetExternal::Params params;
319 params.templatename = lex.getString();
325 string const name = lex.getString();
326 params.filename = name;
332 string const name = lex.getString();
333 params.display = lyx::graphics::displayTranslator.find(name);
339 params.lyxscale = lex.getInteger();
348 lex.printError("ExternalInset::read: "
349 "Wrong tag: $$Token");
354 if (found_end || read_error)
359 lex.printError("ExternalInset::read: "
360 "Missing \\end_inset.");
365 // Replace the inset's store
366 string const path = buffer ? buffer->filePath() : string();
367 setParams(params, path);
369 lyxerr[Debug::INFO] << "InsetExternal::Read: "
370 << "template: '" << params_.templatename
371 << "' filename: '" << params_.filename
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.empty() ?
497 string() : MakeAbsPath(params_.filename, buf->filePath());
499 if (from_format == "*") {
500 if (from_file.empty())
503 // Try and ascertain the file format from its contents.
504 from_format = 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 from_file = copyFileToDir(buf->tmppath, from_file);
523 if (from_file.empty())
527 string const to_file = doSubstitution(params_, buf,
528 outputFormat.updateResult);
530 FileInfo fi(from_file);
531 string abs_to_file = to_file;
532 if (!AbsolutePath(to_file))
533 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
534 FileInfo fi2(abs_to_file);
535 if (fi2.exist() && fi.exist() &&
536 difftime(fi2.getModificationTime(),
537 fi.getModificationTime()) >= 0) {
539 string const to_filebase = 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 basename = ChangeExtension(params.filename, string());
556 result = subst(s, "$$FName", params.filename);
557 result = subst(result, "$$Basename", basename);
558 result = subst(result, "$$FPath", filepath);
559 result = subst(result, "$$Tempname", params.tempname);
560 result = subst(result, "$$Sysdir", system_lyxdir);
562 // Handle the $$Contents(filename) syntax
563 if (contains(result, "$$Contents(\"")) {
565 string::size_type const pos = result.find("$$Contents(\"");
566 string::size_type const end = result.find("\")", pos);
567 string const file = result.substr(pos + 12, end - (pos + 12));
570 Path p(buffer->filePath());
571 if (!IsFileReadable(file))
572 Path p(buffer->tmppath);
573 if (IsFileReadable(file))
574 contents = GetFileContents(file);
576 contents = GetFileContents(file);
578 result = subst(result,
579 ("$$Contents(\"" + file + "\")").c_str(),
587 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 Path p(buffer->filePath());
604 if (lyxerr.debugging()) {
605 lyxerr << "Executing '" << command << "' in '"
606 << buffer->filePath() << '\'' << endl;
608 call.startscript(Forkedcall::DontWait, command);
613 string const InsetExternalMailer::name_("external");
615 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
620 string const InsetExternalMailer::inset2string() const
622 return params2string(inset_.params());
626 void InsetExternalMailer::string2params(string const & in,
627 InsetExternal::Params & params)
629 params = InsetExternal::Params();
634 istringstream data(STRCONV(in));
640 string const token = lex.getString();
645 // This is part of the inset proper that is usually swallowed
646 // by Buffer::readInset
649 string const token = lex.getString();
650 if (token != "External")
657 params = inset.params();
663 InsetExternalMailer::params2string(InsetExternal::Params const & params)
666 inset.setParams(params, string());
668 data << name_ << ' ';
669 inset.write(0, data);
670 data << "\\end_inset\n";
671 return STRCONV(data.str());