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;
60 InsetExternal::Params::Params()
61 : display(defaultDisplayType),
62 lyxscale(defaultLyxScale)
66 InsetExternal::InsetExternal()
67 : renderer_(new GraphicInset)
69 renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
70 params_.templ = ExternalTemplateManager::get().getTemplates().begin()->second;
74 InsetExternal::InsetExternal(InsetExternal const & other)
76 boost::signals::trackable(),
77 params_(other.params_),
78 renderer_(new GraphicInset(*other.renderer_))
80 renderer_->connect(boost::bind(&InsetExternal::statusChanged, this));
84 Inset * InsetExternal::clone() const
86 InsetExternal * inset = new InsetExternal(*this);
91 InsetExternal::~InsetExternal()
93 if (!tempname_.empty())
94 lyx::unlink(tempname_);
95 InsetExternalMailer(*this).hideDialog();
99 void InsetExternal::statusChanged()
101 BufferView * bv = renderer_->view();
103 bv->updateInset(this);
107 InsetExternal::Params const & InsetExternal::params() const
113 dispatch_result InsetExternal::localDispatch(FuncRequest const & cmd)
115 switch (cmd.action) {
117 case LFUN_INSET_MODIFY: {
118 InsetExternal::Params p;
119 InsetExternalMailer::string2params(cmd.argument, p);
120 setParams(p, cmd.view()->buffer()->filePath());
121 cmd.view()->updateInset(this);
125 case LFUN_INSET_DIALOG_UPDATE:
126 InsetExternalMailer(*this).updateDialog(cmd.view());
129 case LFUN_MOUSE_RELEASE:
130 case LFUN_INSET_EDIT:
131 InsetExternalMailer(*this).showDialog(cmd.view());
140 void InsetExternal::cache(BufferView * bv) const
146 void InsetExternal::metrics(MetricsInfo & mi, Dimension & dim) const
148 renderer_->metrics(mi, dim);
152 void InsetExternal::draw(PainterInfo & pi, int x, int y) const
154 renderer_->draw(pi, x, y);
160 grfx::Params get_grfx_params(InsetExternal::Params const & eparams,
161 string const & filepath)
163 grfx::Params gparams;
165 if (!eparams.filename.empty()) {
166 lyx::Assert(AbsolutePath(filepath));
167 gparams.filename = MakeAbsPath(eparams.filename, filepath);
170 gparams.scale = eparams.lyxscale;
171 gparams.display = eparams.display;
173 if (gparams.display == grfx::DefaultDisplay)
174 gparams.display = lyxrc.display_graphics;
176 // Override the above if we're not using a gui
177 if (!lyx_gui::use_gui)
178 gparams.display = grfx::NoDisplay;
186 void InsetExternal::setParams(Params const & p, string const & filepath)
188 params_.filename = p.filename;
189 params_.templ = p.templ;
190 params_.display = p.display;
191 params_.lyxscale = p.lyxscale;
193 // Update the display using the new parameters.
194 if (params_.filename.empty() || !filepath.empty())
195 renderer_->update(get_grfx_params(params_, filepath));
196 string const msg = doSubstitution(0, params_.templ.guiName);
197 renderer_->setNoDisplayMessage(msg);
201 string const InsetExternal::editMessage() const
203 return doSubstitution(0, params_.templ.guiName);
207 void InsetExternal::write(Buffer const *, ostream & os) const
210 << "\ttemplate " << params_.templ.lyxName << '\n';
212 if (!params_.filename.empty())
213 os << "\tfilename " << params_.filename << '\n';
215 if (params_.display != defaultDisplayType)
216 os << "\tdisplay " << grfx::displayTranslator.find(params_.display)
219 if (params_.lyxscale != defaultLyxScale)
220 os << "\tlyxscale " << tostr(params_.lyxscale) << '\n';
224 void InsetExternal::read(Buffer const * buffer, LyXLex & lex)
234 keyword_item external_tags[] = {
235 { "\\end_inset", EX_END },
236 { "display", EX_DISPLAY},
237 { "filename", EX_FILENAME},
238 { "lyxscale", EX_LYXSCALE},
239 { "template", EX_TEMPLATE }
242 lex.pushTable(external_tags, EX_END);
244 bool found_end = false;
245 bool read_error = false;
247 InsetExternal::Params params;
252 string const name = lex.getString();
253 ExternalTemplateManager & etm =
254 ExternalTemplateManager::get();
255 params.templ = etm.getTemplateByName(name);
261 string const name = lex.getString();
262 params.filename = name;
268 string const name = lex.getString();
269 params.display = grfx::displayTranslator.find(name);
275 params.lyxscale = lex.getInteger();
284 lex.printError("ExternalInset::read: "
285 "Wrong tag: $$Token");
290 if (found_end || read_error)
295 lex.printError("ExternalInset::read: "
296 "Missing \\end_inset.");
301 // Replace the inset's store
304 lyxerr[Debug::INFO] << "InsetExternal::Read: "
305 << "template: '" << params_.templ.lyxName
306 << "' filename: '" << params_.filename
307 << "' display: '" << params_.display
308 << "' scale: '" << params_.lyxscale
311 // Update the display using the new parameters.
313 renderer_->update(get_grfx_params(params_, buffer->filePath()));
314 string const msg = doSubstitution(0, params_.templ.guiName);
315 renderer_->setNoDisplayMessage(msg);
319 int InsetExternal::write(string const & format,
320 Buffer const * buf, ostream & os,
321 bool external_in_tmpdir) const
323 ExternalTemplate const & et = params_.templ;
324 ExternalTemplate::Formats::const_iterator cit =
325 et.formats.find(format);
326 if (cit == et.formats.end()) {
327 lyxerr << "External template format '" << format
328 << "' not specified in template "
329 << params_.templ.lyxName << endl;
333 updateExternal(format, buf, external_in_tmpdir);
334 string const str = doSubstitution(buf, cit->second.product);
336 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
340 int InsetExternal::latex(Buffer const * buf, ostream & os,
341 LatexRunParams const & runparams) const
343 // "nice" means that the buffer is exported to LaTeX format but not
344 // run through the LaTeX compiler.
345 // If we're running through the LaTeX compiler, we should write the
346 // generated files in the bufer's temporary directory.
347 bool const external_in_tmpdir =
348 lyxrc.use_tempdir && !buf->tmppath.empty() && !runparams.nice;
350 // If the template has specified a PDFLaTeX output, then we try and
352 if (runparams.flavor == LatexRunParams::PDFLATEX) {
353 ExternalTemplate const & et = params_.templ;
354 ExternalTemplate::Formats::const_iterator cit =
355 et.formats.find("PDFLaTeX");
356 if (cit != et.formats.end())
357 return write("PDFLaTeX", buf, os, external_in_tmpdir);
360 return write("LaTeX", buf, os, external_in_tmpdir);
364 int InsetExternal::ascii(Buffer const * buf, ostream & os, int) const
366 return write("Ascii", buf, os);
370 int InsetExternal::linuxdoc(Buffer const * buf, ostream & os) const
372 return write("LinuxDoc", buf, os);
376 int InsetExternal::docbook(Buffer const * buf, ostream & os, bool) const
378 return write("DocBook", buf, os);
382 void InsetExternal::validate(LaTeXFeatures & features) const
384 ExternalTemplate const & et = params_.templ;
385 ExternalTemplate::Formats::const_iterator cit =
386 et.formats.find("LaTeX");
388 if (cit == et.formats.end())
391 if (!cit->second.requirement.empty()) {
392 features.require(cit->second.requirement);
394 if (!cit->second.preamble.empty()) {
395 features.addExternalPreamble(cit->second.preamble + "\n");
400 string const InsetExternal::doSubstitution(Buffer const * buffer,
401 string const & s) const
404 string const basename = ChangeExtension(params_.filename, string());
406 bool external_in_tmpdir = false;
407 if (buffer && !buffer->tmppath.empty() && !buffer->niceFile) {
408 filepath = buffer->filePath();
409 if (lyxrc.use_tempdir)
410 external_in_tmpdir = true;
412 if (tempname_.empty()) {
413 string const path = external_in_tmpdir ? buffer->tmppath : string();
414 tempname_ = lyx::tempName(path, "lyxext");
415 lyx::unlink(tempname_);
416 // must have an extension for the converter code to work correctly.
419 result = subst(s, "$$FName", params_.filename);
420 result = subst(result, "$$Basename", basename);
421 result = subst(result, "$$FPath", filepath);
422 result = subst(result, "$$Tempname", tempname_);
423 result = subst(result, "$$Sysdir", system_lyxdir);
425 // Handle the $$Contents(filename) syntax
426 if (contains(result, "$$Contents(\"")) {
428 string::size_type const pos = result.find("$$Contents(\"");
429 string::size_type const end = result.find("\")", pos);
430 string const file = result.substr(pos + 12, end - (pos + 12));
433 Path p(buffer->filePath());
434 if (!IsFileReadable(file))
435 Path p(buffer->tmppath);
436 if (IsFileReadable(file))
437 contents = GetFileContents(file);
439 contents = GetFileContents(file);
441 result = subst(result,
442 ("$$Contents(\"" + file + "\")").c_str(),
450 void InsetExternal::updateExternal(string const & format,
452 bool external_in_tmpdir) const
454 ExternalTemplate const & et = params_.templ;
455 if (!et.automaticProduction)
458 ExternalTemplate::Formats::const_iterator cit =
459 et.formats.find(format);
460 if (cit == et.formats.end())
463 ExternalTemplate::FormatTemplate const & outputFormat = cit->second;
464 if (outputFormat.updateResult.empty())
467 string from_format = et.inputFormat;
468 if (from_format.empty())
471 string from_file = params_.filename.empty() ?
472 string() : MakeAbsPath(params_.filename, buf->filePath());
474 if (from_format == "*") {
475 if (from_file.empty())
478 // Try and ascertain the file format from its contents.
479 from_format = getExtFromContents(from_file);
480 if (from_format.empty())
484 string const to_format = outputFormat.updateFormat;
485 if (to_format.empty())
488 if (!converters.isReachable(from_format, to_format)) {
489 lyxerr << "InsetExternal::updateExternal. "
490 "Unable to convert from "
491 << from_format << " to " << to_format << endl;
495 if (external_in_tmpdir && !from_file.empty()) {
496 // We are running stuff through LaTeX
497 from_file = copyFileToDir(buf->tmppath, from_file);
498 if (from_file.empty())
502 string const to_file = doSubstitution(buf, outputFormat.updateResult);
504 FileInfo fi(from_file);
505 string abs_to_file = to_file;
506 if (!AbsolutePath(to_file))
507 abs_to_file = MakeAbsPath(to_file, OnlyPath(from_file));
508 FileInfo fi2(abs_to_file);
509 if (fi2.exist() && fi.exist() &&
510 difftime(fi2.getModificationTime(),
511 fi.getModificationTime()) >= 0) {
513 string const to_filebase = ChangeExtension(to_file, string());
514 converters.convert(buf, from_file, to_filebase,
515 from_format, to_format);
520 void InsetExternal::editExternal() const
522 ExternalTemplate const & et = params_.templ;
523 if (et.editCommand.empty())
526 BufferView const * bv = renderer_->view();
527 Buffer const * buffer = bv ? bv->buffer() : 0;
531 string const command = doSubstitution(buffer, et.editCommand);
533 Path p(buffer->filePath());
535 if (lyxerr.debugging()) {
536 lyxerr << "Executing '" << command << "' in '"
537 << buffer->filePath() << '\'' << endl;
539 call.startscript(Forkedcall::DontWait, command);
543 string const InsetExternalMailer::name_("external");
545 InsetExternalMailer::InsetExternalMailer(InsetExternal & inset)
550 string const InsetExternalMailer::inset2string() const
552 return params2string(inset_.params());
556 void InsetExternalMailer::string2params(string const & in,
557 InsetExternal::Params & params)
559 params = InsetExternal::Params();
564 istringstream data(STRCONV(in));
570 string const token = lex.getString();
575 // This is part of the inset proper that is usually swallowed
576 // by Buffer::readInset
579 string const token = lex.getString();
580 if (token != "External")
587 params = inset.params();
593 InsetExternalMailer::params2string(InsetExternal::Params const & params)
596 inset.setParams(params, string());
598 data << name_ << ' ';
599 inset.write(0, data);
600 data << "\\end_inset\n";
601 return STRCONV(data.str());