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/graphicinset.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 GraphicInset)
87 renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
88 params_.templ = ExternalTemplateManager::get().getTemplates().begin()->second;
92 InsetExternal::InsetExternal(InsetExternal const & other)
94 boost::signals::trackable(),
95 params_(other.params_),
96 renderer_(new GraphicInset(*other.renderer_))
98 renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
102 Inset * 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;
207 void InsetExternal::setParams(Params const & p, string const & filepath)
209 params_.filename = p.filename;
210 params_.templ = p.templ;
211 params_.display = p.display;
212 params_.lyxscale = p.lyxscale;
214 // Update the display using the new parameters.
215 if (params_.filename.empty() || !filepath.empty())
216 renderer_->update(get_grfx_params(params_, filepath));
217 string const msg = doSubstitution(params_, 0, params_.templ.guiName);
218 renderer_->setNoDisplayMessage(msg);
222 string const InsetExternal::editMessage() const
224 return doSubstitution(params_, 0, params_.templ.guiName);
228 void InsetExternal::write(Buffer const *, ostream & os) const
231 << "\ttemplate " << params_.templ.lyxName << '\n';
233 if (!params_.filename.empty())
234 os << "\tfilename " << params_.filename << '\n';
236 if (params_.display != defaultDisplayType)
237 os << "\tdisplay " << grfx::displayTranslator.find(params_.display)
240 if (params_.lyxscale != defaultLyxScale)
241 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
245 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
255 keyword_item external_tags[] = {
256 { "\\end_inset", EX_END },
257 { "display", EX_DISPLAY},
258 { "filename", EX_FILENAME},
259 { "lyxscale", EX_LYXSCALE},
260 { "template", EX_TEMPLATE }
263 lex.pushTable(external_tags, EX_END);
265 bool found_end = false;
266 bool read_error = false;
268 InsetExternal::Params params;
273 string const name = lex.getString();
274 ExternalTemplateManager & etm =
275 ExternalTemplateManager::get();
276 params.templ = etm.getTemplateByName(name);
282 string const name = lex.getString();
283 params.filename = name;
289 string const name = lex.getString();
290 params.display = grfx::displayTranslator.find(name);
296 params.lyxscale = lex.getInteger();
305 lex.printError("ExternalInset::read: "
306 "Wrong tag: $$Token");
311 if (found_end || read_error)
316 lex.printError("ExternalInset::read: "
317 "Missing \\end_inset.");
322 // Replace the inset's store
325 lyxerr[Debug::INFO] << "InsetExternal::Read: "
326 << "template: '" << params_.templ.lyxName
327 << "' filename: '" << params_.filename
328 << "' display: '" << params_.display
329 << "' scale: '" << params_.lyxscale
332 // Update the display using the new parameters.
334 renderer_->update(get_grfx_params(params_, buffer->filePath()));
335 string const msg = doSubstitution(params_, 0, params_.templ.guiName);
336 renderer_->setNoDisplayMessage(msg);
340 int InsetExternal::write(string const & format,
341 Buffer const * buf, ostream & os,
342 bool external_in_tmpdir) const
344 ExternalTemplate const & et = params_.templ;
345 ExternalTemplate::Formats::const_iterator cit =
346 et.formats.find(format);
347 if (cit == et.formats.end()) {
348 lyxerr << "External template format '" << format
349 << "' not specified in template "
350 << params_.templ.lyxName << endl;
354 updateExternal(format, buf, external_in_tmpdir);
355 string const str = doSubstitution(params_, buf, cit->second.product);
357 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
361 int InsetExternal::latex(Buffer const * buf, ostream & os,
362 LatexRunParams const & runparams) const
364 // "nice" means that the buffer is exported to LaTeX format but not
365 // run through the LaTeX compiler.
366 // If we're running through the LaTeX compiler, we should write the
367 // generated files in the bufer's temporary directory.
368 bool const external_in_tmpdir =
369 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
371 // If the template has specified a PDFLaTeX output, then we try and
373 if (runparams.flavor == LatexRunParams::PDFLATEX) {
374 ExternalTemplate const & et = params_.templ;
375 ExternalTemplate::Formats::const_iterator cit =
376 et.formats.find("PDFLaTeX");
377 if (cit != et.formats.end())
378 return write("PDFLaTeX", buf, os, external_in_tmpdir);
381 return write("LaTeX", buf, os, external_in_tmpdir);
385 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
387 return write("Ascii", buf, os);
391 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
393 return write("LinuxDoc", buf, os);
397 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
399 return write("DocBook", buf, os);
403 void InsetExternal::validate(LaTeXFeatures & features) const
405 ExternalTemplate const & et = params_.templ;
406 ExternalTemplate::Formats::const_iterator cit =
407 et.formats.find("LaTeX");
409 if (cit == et.formats.end())
412 if (!cit->second.requirement.empty()) {
413 features.require(cit->second.requirement);
415 if (!cit->second.preamble.empty()) {
416 features.addExternalPreamble(cit->second.preamble + "\n");
421 void InsetExternal::updateExternal(string const & format,
423 bool external_in_tmpdir) const
425 ExternalTemplate const & et = params_.templ;
426 if (!et.automaticProduction)
429 ExternalTemplate::Formats::const_iterator cit =
430 et.formats.find(format);
431 if (cit == et.formats.end())
434 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
435 if (outputFormat.updateResult.empty())
438 string from_format = et.inputFormat;
439 if (from_format.empty())
442 string from_file = params_.filename.empty() ?
443 string() : MakeAbsPath(params_.filename, buf->filePath());
445 if (from_format == "*") {
446 if (from_file.empty())
449 // Try and ascertain the file format from its contents.
450 from_format = getExtFromContents(from_file);
451 if (from_format.empty())
455 string const to_format = outputFormat.updateFormat;
456 if (to_format.empty())
459 if (!converters.isReachable(from_format, to_format)) {
460 lyxerr << "InsetExternal::updateExternal. "
461 "Unable to convert from "
462 << from_format << " to " << to_format << endl;
466 if (external_in_tmpdir && !from_file.empty()) {
467 // We are running stuff through LaTeX
468 from_file = copyFileToDir(buf->tmppath, from_file);
469 if (from_file.empty())
473 string const to_file = doSubstitution(params_, buf,
474 outputFormat.updateResult);
476 FileInfo fi(from_file);
477 string abs_to_file = to_file;
478 if (!AbsolutePath(to_file))
479 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
480 FileInfo fi2(abs_to_file);
481 if (fi2.exist() && fi.exist() &&
482 difftime(fi2.getModificationTime(),
483 fi.getModificationTime()) >= 0) {
485 string const to_filebase = ChangeExtension(to_file, string());
486 converters.convert(buf, from_file, to_filebase,
487 from_format, to_format);
494 /// Substitute meta-variables in this string
495 string const doSubstitution(InsetExternal::Params const & params,
496 Buffer const * buffer, string const & s)
499 string const basename = ChangeExtension(params.filename, string());
502 result = subst(s, "$$FName", params.filename);
503 result = subst(result, "$$Basename", basename);
504 result = subst(result, "$$FPath", filepath);
505 result = subst(result, "$$Tempname", params.tempname);
506 result = subst(result, "$$Sysdir", system_lyxdir);
508 // Handle the $$Contents(filename) syntax
509 if (contains(result, "$$Contents(\"")) {
511 string::size_type const pos = result.find("$$Contents(\"");
512 string::size_type const end = result.find("\")", pos);
513 string const file = result.substr(pos + 12, end - (pos + 12));
516 Path p(buffer->filePath());
517 if (!IsFileReadable(file))
518 Path p(buffer->tmppath);
519 if (IsFileReadable(file))
520 contents = GetFileContents(file);
522 contents = GetFileContents(file);
524 result = subst(result,
525 ("$$Contents(\"" + file + "\")").c_str(),
533 void editExternal(InsetExternal::Params const & params, Buffer const * buffer)
538 ExternalTemplate const & et = params.templ;
539 if (et.editCommand.empty())
542 string const command = doSubstitution(params, buffer, et.editCommand);
544 Path p(buffer->filePath());
546 if (lyxerr.debugging()) {
547 lyxerr << "Executing '" << command << "' in '"
548 << buffer->filePath() << '\'' << endl;
550 call.startscript(Forkedcall::DontWait, command);
555 string const InsetExternalMailer::name_("external");
557 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
562 string const InsetExternalMailer::inset2string() const
564 return params2string(inset_.params());
568 void InsetExternalMailer::string2params(string const & in,
569 InsetExternal::Params & params)
571 params = InsetExternal::Params();
576 istringstream data(STRCONV(in));
582 string const token = lex.getString();
587 // This is part of the inset proper that is usually swallowed
588 // by Buffer::readInset
591 string const token = lex.getString();
592 if (token != "External")
599 params = inset.params();
605 InsetExternalMailer::params2string(InsetExternal::Params const & params)
608 inset.setParams(params, string());
610 data << name_ << ' ';
611 inset.write(0, data);
612 data << "\\end_inset\n";
613 return STRCONV(data.str());