2 * \file ExternalSupport.cpp
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
7 * \author Angus Leeming
9 * Full author contact details are available in file CREDITS.
14 #include "ExternalSupport.h"
15 #include "ExternalTemplate.h"
16 #include "ExternalTransforms.h"
17 #include "InsetExternal.h"
20 #include "Converter.h"
26 #include "support/filetools.h"
27 #include "support/Forkedcall.h"
28 #include "support/lstrings.h"
29 #include "support/lyxalgo.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/Package.h"
34 #include <boost/filesystem/operations.hpp>
40 using boost::filesystem::is_directory;
45 using support::FileName;
49 Template const * getTemplatePtr(InsetExternalParams const & params)
51 TemplateManager const & etm = TemplateManager::get();
52 return etm.getTemplateByName(params.templatename());
56 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
58 formats.edit(buffer, params.filename,
59 formats.getFormatFromFile(params.filename));
65 string const subst_path(string const & input,
66 string const & placeholder,
69 support::latex_path_extension ext = support::PROTECT_EXTENSION,
70 support::latex_path_dots dots = support::LEAVE_DOTS)
72 if (input.find(placeholder) == string::npos)
74 // Don't use external_path here when use_latex_path is false, as the
75 // path will be compared with another one in internal style later
76 // in Converters::move.
77 string const path2 = use_latex_path ?
78 support::latex_path(path, ext, dots) : path;
79 return support::subst(input, placeholder, path2);
85 string const doSubstitution(InsetExternalParams const & params,
86 Buffer const & buffer, string const & s,
88 bool external_in_tmpdir,
91 Buffer const * m_buffer = buffer.getMasterBuffer();
92 string const parentpath = external_in_tmpdir ?
93 m_buffer->temppath() :
95 string const filename = external_in_tmpdir ?
96 params.filename.mangledFilename() :
97 params.filename.outputFilename(parentpath);
98 string const basename = support::changeExtension(
99 support::onlyFilename(filename), string());
100 string const absname = support::makeAbsPath(filename, parentpath).absFilename();
103 if (what != ALL_BUT_PATHS) {
104 string const filepath = support::onlyPath(filename);
105 string const abspath = support::onlyPath(absname);
106 string const masterpath = external_in_tmpdir ?
107 m_buffer->temppath() :
108 m_buffer->filePath();
110 string relToMasterPath = support::onlyPath(
111 to_utf8(support::makeRelPath(from_utf8(absname),
112 from_utf8(masterpath))));
113 if (relToMasterPath == "./")
114 relToMasterPath.clear();
116 string relToParentPath = support::onlyPath(
117 to_utf8(support::makeRelPath(from_utf8(absname),
118 from_utf8(parentpath))));
119 if (relToParentPath == "./")
120 relToParentPath.clear();
122 result = subst_path(result, "$$FPath", filepath,
124 support::PROTECT_EXTENSION,
125 support::ESCAPE_DOTS);
126 result = subst_path(result, "$$AbsPath", abspath,
128 support::PROTECT_EXTENSION,
129 support::ESCAPE_DOTS);
130 result = subst_path(result, "$$RelPathMaster",
131 relToMasterPath, use_latex_path,
132 support::PROTECT_EXTENSION,
133 support::ESCAPE_DOTS);
134 result = subst_path(result, "$$RelPathParent",
135 relToParentPath, use_latex_path,
136 support::PROTECT_EXTENSION,
137 support::ESCAPE_DOTS);
138 if (support::absolutePath(filename)) {
139 result = subst_path(result, "$$AbsOrRelPathMaster",
140 abspath, use_latex_path,
141 support::PROTECT_EXTENSION,
142 support::ESCAPE_DOTS);
143 result = subst_path(result, "$$AbsOrRelPathParent",
144 abspath, use_latex_path,
145 support::PROTECT_EXTENSION,
146 support::ESCAPE_DOTS);
148 result = subst_path(result, "$$AbsOrRelPathMaster",
149 relToMasterPath, use_latex_path,
150 support::PROTECT_EXTENSION,
151 support::ESCAPE_DOTS);
152 result = subst_path(result, "$$AbsOrRelPathParent",
153 relToParentPath, use_latex_path,
154 support::PROTECT_EXTENSION,
155 support::ESCAPE_DOTS);
162 result = subst_path(result, "$$FName", filename, use_latex_path,
163 support::EXCLUDE_EXTENSION);
164 result = subst_path(result, "$$Basename", basename, use_latex_path,
165 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
166 result = subst_path(result, "$$Extension",
167 '.' + support::getExtension(filename), use_latex_path);
168 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
169 result = subst_path(result, "$$Sysdir",
170 support::package().system_support().absFilename(), use_latex_path);
172 // Handle the $$Contents(filename) syntax
173 if (support::contains(result, "$$Contents(\"")) {
174 // Since use_latex_path may be true we must extract the file
175 // name from s instead of result and do the substitutions
176 // again, this time with use_latex_path false.
177 string::size_type const spos = s.find("$$Contents(\"");
178 string::size_type const send = s.find("\")", spos);
179 string const file_template = s.substr(spos + 12, send - (spos + 12));
180 string const file = doSubstitution(params, buffer,
181 file_template, false,
182 external_in_tmpdir, what);
185 FileName const absfile(
186 support::makeAbsPath(file, m_buffer->temppath()));
187 if (support::isFileReadable(absfile))
188 contents = support::getFileContents(absfile);
190 string::size_type const pos = result.find("$$Contents(\"");
191 string::size_type const end = result.find("\")", pos);
192 result.replace(pos, end + 2, contents);
201 /** update the file represented by the template.
202 If \p external_in_tmpdir == true, then the generated file is
203 placed in the buffer's temporary directory.
205 void updateExternal(InsetExternalParams const & params,
206 string const & format,
207 Buffer const & buffer,
208 ExportData & exportdata,
209 bool external_in_tmpdir,
212 Template const * const et_ptr = getTemplatePtr(params);
215 Template const & et = *et_ptr;
217 if (!et.automaticProduction)
218 return; // NOT_NEEDED
220 Template::Formats::const_iterator cit = et.formats.find(format);
221 if (cit == et.formats.end())
224 Template::Format const & outputFormat = cit->second;
225 if (outputFormat.updateResult.empty())
226 return; // NOT_NEEDED
228 string from_format = et.inputFormat;
229 if (from_format.empty())
230 return; // NOT_NEEDED
232 if (from_format == "*") {
233 if (params.filename.empty())
234 return; // NOT_NEEDED
236 // Try and ascertain the file format from its contents.
237 from_format = formats.getFormatFromFile(params.filename);
238 if (from_format.empty())
243 string const to_format = outputFormat.updateFormat;
244 if (to_format.empty())
245 return; // NOT_NEEDED
247 // The master buffer. This is useful when there are multiple levels
249 Buffer const * m_buffer = buffer.getMasterBuffer();
251 // We copy the source file to the temp dir and do the conversion
252 // there if necessary
253 FileName const temp_file(
254 support::makeAbsPath(params.filename.mangledFilename(),
255 m_buffer->temppath()));
256 if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
257 unsigned long const from_checksum = support::sum(params.filename);
258 unsigned long const temp_checksum = support::sum(temp_file);
260 if (from_checksum != temp_checksum) {
261 Mover const & mover = getMover(from_format);
262 if (!mover.copy(params.filename, temp_file)) {
263 LYXERR(Debug::EXTERNAL)
264 << "external::updateExternal. "
266 << params.filename << " to " << temp_file << endl;
272 // the generated file (always in the temp dir)
273 string const to_file = doSubstitution(params, buffer,
274 outputFormat.updateResult,
276 FileName const abs_to_file(
277 support::makeAbsPath(to_file, m_buffer->temppath()));
280 // Record the referenced files for the exporter.
281 // The exporter will copy them to the export dir.
282 typedef Template::Format::FileMap FileMap;
283 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
284 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
285 for (; rit != rend; ++rit) {
286 vector<string>::const_iterator fit = rit->second.begin();
287 vector<string>::const_iterator fend = rit->second.end();
288 for (; fit != fend; ++fit) {
289 FileName const source(support::makeAbsPath(
290 doSubstitution(params, buffer, *fit,
292 m_buffer->temppath()));
293 // The path of the referenced file is never the
294 // temp path, but the filename may be the mangled
295 // or the real name. Therefore we substitute the
296 // paths and names separately.
297 string file = support::subst(*fit, "$$FName",
298 "$$FPath$$Basename$$Extension");
299 file = doSubstitution(params, buffer, file, false, false,
301 file = doSubstitution(params, buffer, file,
302 false, external_in_tmpdir,
304 // if file is a relative name, it is interpreted
305 // relative to the master document.
306 exportdata.addExternalFile(rit->first, source, file);
311 // Do we need to perform the conversion?
312 // Yes if to_file does not exist or if from_file is newer than to_file
313 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
316 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
319 theConverters().convert(&buffer, temp_file, abs_to_file,
320 params.filename, from_format, to_format, el,
321 Converters::try_default | Converters::try_cache);
324 LYXERR(Debug::EXTERNAL)
325 << "external::updateExternal. "
326 << "Unable to convert from "
327 << from_format << " to " << to_format << endl;
333 string const substituteCommands(InsetExternalParams const & params,
334 string const & input, string const & format);
336 string const substituteOptions(InsetExternalParams const & params,
337 string const & input, string const & format);
342 int writeExternal(InsetExternalParams const & params,
343 string const & format,
344 Buffer const & buffer, odocstream & os,
345 ExportData & exportdata,
346 bool external_in_tmpdir,
349 Template const * const et_ptr = getTemplatePtr(params);
352 Template const & et = *et_ptr;
354 Template::Formats::const_iterator cit = et.formats.find(format);
355 if (cit == et.formats.end()) {
356 LYXERR(Debug::EXTERNAL)
357 << "External template format '" << format
358 << "' not specified in template "
359 << params.templatename() << endl;
363 if (!dryrun || support::contains(cit->second.product, "$$Contents"))
364 updateExternal(params, format, buffer, exportdata,
365 external_in_tmpdir, dryrun);
367 bool const use_latex_path = format == "LaTeX";
368 string str = doSubstitution(params, buffer, cit->second.product,
369 use_latex_path, external_in_tmpdir);
370 str = substituteCommands(params, str, format);
371 str = substituteOptions(params, str, format);
373 os << from_utf8(str);
374 return int(lyx::count(str.begin(), str.end(),'\n'));
379 // Empty template, specialised below.
380 template <typename TransformType>
381 string const substituteIt(string const &,
384 Template::Format const &,
385 InsetExternalParams const &);
389 string const substituteIt<TransformCommand>(string const & input,
391 string const & /* formatname */,
392 Template::Format const & format,
393 InsetExternalParams const & params)
395 typedef std::map<TransformID, TransformStore> Transformers;
396 Transformers::const_iterator it = format.command_transformers.find(id);
397 if (it == format.command_transformers.end())
400 TransformStore const & store = it->second;
402 TransformCommand::ptr_type ptr;
404 ptr = store.getCommandTransformer(params.rotationdata);
405 else if (id == Resize)
406 ptr = store.getCommandTransformer(params.resizedata);
412 support::subst(input, ptr->front_placeholder(), ptr->front());
413 return support::subst(result, ptr->back_placeholder(), ptr->back());
418 string const substituteIt<TransformOption>(string const & input,
420 string const & fname,
421 Template::Format const & format,
422 InsetExternalParams const & params)
424 typedef std::map<TransformID, TransformStore> Transformers;
425 Transformers::const_iterator it = format.option_transformers.find(id);
426 if (it == format.option_transformers.end())
429 TransformStore const & store = it->second;
431 TransformOption::ptr_type ptr;
434 ptr = store.getOptionTransformer(params.clipdata);
437 ptr = store.getOptionTransformer(params.extradata.get(fname));
440 ptr = store.getOptionTransformer(params.rotationdata);
443 ptr = store.getOptionTransformer(params.resizedata);
450 return support::subst(input, ptr->placeholder(), ptr->option());
454 template <typename TransformerType>
455 string const transformIt(InsetExternalParams const & params,
456 string const & s, string const & formatname)
458 Template const * const et = getTemplatePtr(params);
459 if (!et || et->transformIds.empty())
462 Template::Formats::const_iterator fit = et->formats.find(formatname);
463 if (fit == et->formats.end())
467 Template::Format const & format = fit->second;
469 typedef vector<TransformID> TransformsIDs;
470 TransformsIDs::const_iterator it = et->transformIds.begin();
471 TransformsIDs::const_iterator end = et->transformIds.end();
472 for (; it != end; ++it) {
473 result = substituteIt<TransformerType>(result, *it, formatname,
480 string const substituteCommands(InsetExternalParams const & params,
481 string const & input, string const & format)
483 return transformIt<TransformCommand>(params, input, format);
487 string const substituteOption(InsetExternalParams const & params,
488 string const & input, string const & format)
490 string opt = transformIt<TransformOption>(params, input, format);
492 if (format == "LaTeX" || format == "PDFLaTeX")
493 return sanitizeLatexOption(opt);
494 if (format == "DocBook")
495 return sanitizeDocBookOption(opt);
500 string const substituteOptions(InsetExternalParams const & params,
501 string const & input, string const & format)
503 string output = input;
505 Template const * const et = getTemplatePtr(params);
506 if (!et || et->transformIds.empty())
509 Template::Formats::const_iterator fit = et->formats.find(format);
510 if (fit == et->formats.end() || fit->second.options.empty())
513 typedef vector<Template::Option> Options;
514 Options const & options = fit->second.options;
515 Options::const_iterator it = options.begin();
516 Options::const_iterator end = options.end();
517 for (; it != end; ++it) {
518 string const opt = substituteOption(params, it->option, format);
519 string const placeholder = "$$" + it->name;
520 output = support::subst(output, placeholder, opt);
528 } // namespace external