2 * \file ExternalSupport.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
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"
41 using support::FileName;
45 Template const * getTemplatePtr(InsetExternalParams const & params)
47 TemplateManager const & etm = TemplateManager::get();
48 return etm.getTemplateByName(params.templatename());
52 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
54 formats.edit(buffer, params.filename,
55 formats.getFormatFromFile(params.filename));
61 string const subst_path(string const & input,
62 string const & placeholder,
65 support::latex_path_extension ext = support::PROTECT_EXTENSION,
66 support::latex_path_dots dots = support::LEAVE_DOTS)
68 if (input.find(placeholder) == string::npos)
70 string const path2 = use_latex_path ?
71 support::latex_path(path, ext, dots) :
72 support::os::external_path(path);
73 return support::subst(input, placeholder, path2);
79 string const doSubstitution(InsetExternalParams const & params,
80 Buffer const & buffer, string const & s,
82 bool external_in_tmpdir,
85 Buffer const * m_buffer = buffer.getMasterBuffer();
86 string const parentpath = external_in_tmpdir ?
87 m_buffer->temppath() :
89 string const filename = external_in_tmpdir ?
90 params.filename.mangledFilename() :
91 params.filename.outputFilename(parentpath);
92 string const basename = support::changeExtension(
93 support::onlyFilename(filename), string());
94 string const absname = support::makeAbsPath(filename, parentpath);
97 if (what != ALL_BUT_PATHS) {
98 string const filepath = support::onlyPath(filename);
99 string const abspath = support::onlyPath(absname);
100 string const masterpath = external_in_tmpdir ?
101 m_buffer->temppath() :
102 m_buffer->filePath();
103 string relToMasterPath = support::onlyPath(
104 support::makeRelPath(absname, masterpath));
105 if (relToMasterPath == "./")
106 relToMasterPath.clear();
107 string relToParentPath = support::onlyPath(
108 support::makeRelPath(absname, parentpath));
109 if (relToParentPath == "./")
110 relToParentPath.clear();
112 result = subst_path(result, "$$FPath", filepath,
114 support::PROTECT_EXTENSION,
115 support::ESCAPE_DOTS);
116 result = subst_path(result, "$$AbsPath", abspath,
118 support::PROTECT_EXTENSION,
119 support::ESCAPE_DOTS);
120 result = subst_path(result, "$$RelPathMaster",
121 relToMasterPath, use_latex_path,
122 support::PROTECT_EXTENSION,
123 support::ESCAPE_DOTS);
124 result = subst_path(result, "$$RelPathParent",
125 relToParentPath, use_latex_path,
126 support::PROTECT_EXTENSION,
127 support::ESCAPE_DOTS);
128 if (support::absolutePath(filename)) {
129 result = subst_path(result, "$$AbsOrRelPathMaster",
130 abspath, use_latex_path,
131 support::PROTECT_EXTENSION,
132 support::ESCAPE_DOTS);
133 result = subst_path(result, "$$AbsOrRelPathParent",
134 abspath, use_latex_path,
135 support::PROTECT_EXTENSION,
136 support::ESCAPE_DOTS);
138 result = subst_path(result, "$$AbsOrRelPathMaster",
139 relToMasterPath, use_latex_path,
140 support::PROTECT_EXTENSION,
141 support::ESCAPE_DOTS);
142 result = subst_path(result, "$$AbsOrRelPathParent",
143 relToParentPath, use_latex_path,
144 support::PROTECT_EXTENSION,
145 support::ESCAPE_DOTS);
152 result = subst_path(result, "$$FName", filename, use_latex_path,
153 support::EXCLUDE_EXTENSION);
154 result = subst_path(result, "$$Basename", basename, use_latex_path,
155 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
156 result = subst_path(result, "$$Extension",
157 '.' + support::getExtension(filename), use_latex_path);
158 result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
159 result = subst_path(result, "$$Sysdir",
160 support::package().system_support(), use_latex_path);
162 // Handle the $$Contents(filename) syntax
163 if (support::contains(result, "$$Contents(\"")) {
165 string::size_type const pos = result.find("$$Contents(\"");
166 string::size_type const end = result.find("\")", pos);
167 string const file = result.substr(pos + 12, end - (pos + 12));
170 FileName const absfile = FileName(
171 support::makeAbsPath(file, m_buffer->temppath()));
172 if (support::isFileReadable(absfile))
173 contents = support::getFileContents(absfile);
175 result = support::subst(result,
176 ("$$Contents(\"" + file + "\")").c_str(),
186 /** update the file represented by the template.
187 If \p external_in_tmpdir == true, then the generated file is
188 placed in the buffer's temporary directory.
190 void updateExternal(InsetExternalParams const & params,
191 string const & format,
192 Buffer const & buffer,
193 ExportData & exportdata,
194 bool external_in_tmpdir)
196 Template const * const et_ptr = getTemplatePtr(params);
199 Template const & et = *et_ptr;
201 if (!et.automaticProduction)
202 return; // NOT_NEEDED
204 Template::Formats::const_iterator cit = et.formats.find(format);
205 if (cit == et.formats.end())
208 Template::Format const & outputFormat = cit->second;
209 if (outputFormat.updateResult.empty())
210 return; // NOT_NEEDED
212 string from_format = et.inputFormat;
213 if (from_format.empty())
214 return; // NOT_NEEDED
216 if (from_format == "*") {
217 if (params.filename.empty())
218 return; // NOT_NEEDED
220 // Try and ascertain the file format from its contents.
221 from_format = formats.getFormatFromFile(params.filename);
222 if (from_format.empty())
227 string const to_format = outputFormat.updateFormat;
228 if (to_format.empty())
229 return; // NOT_NEEDED
231 if (!converters.isReachable(from_format, to_format)) {
232 lyxerr[Debug::EXTERNAL]
233 << "external::updateExternal. "
234 << "Unable to convert from "
235 << from_format << " to " << to_format << endl;
239 // The master buffer. This is useful when there are multiple levels
241 Buffer const * m_buffer = buffer.getMasterBuffer();
243 // We copy the source file to the temp dir and do the conversion
244 // there if necessary
245 FileName const temp_file = FileName(
246 support::makeAbsPath(params.filename.mangledFilename(),
247 m_buffer->temppath()));
248 if (!params.filename.empty()) {
249 unsigned long const from_checksum = support::sum(params.filename);
250 unsigned long const temp_checksum = support::sum(temp_file);
252 if (from_checksum != temp_checksum) {
253 Mover const & mover = movers(from_format);
254 if (!mover.copy(params.filename, temp_file)) {
255 lyxerr[Debug::EXTERNAL]
256 << "external::updateExternal. "
258 << params.filename << " to " << temp_file << endl;
264 // the generated file (always in the temp dir)
265 string const to_file = doSubstitution(params, buffer,
266 outputFormat.updateResult,
268 FileName const abs_to_file = FileName(
269 support::makeAbsPath(to_file, m_buffer->temppath()));
271 // Record the referenced files for the exporter.
272 // The exporter will copy them to the export dir.
273 typedef Template::Format::FileMap FileMap;
274 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
275 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
276 for (; rit != rend; ++rit) {
277 vector<string>::const_iterator fit = rit->second.begin();
278 vector<string>::const_iterator fend = rit->second.end();
279 for (; fit != fend; ++fit) {
280 FileName const source(support::makeAbsPath(
281 doSubstitution(params, buffer, *fit,
283 m_buffer->temppath()));
284 // The path of the referenced file is never the
285 // temp path, but the filename may be the mangled
286 // or the real name. Therefore we substitute the
287 // paths and names separately.
288 string file = support::subst(*fit, "$$FName",
289 "$$FPath$$Basename$$Extension");
290 file = doSubstitution(params, buffer, file, false, false,
292 file = doSubstitution(params, buffer, file,
293 false, external_in_tmpdir,
295 // if file is a relative name, it is interpreted
296 // relative to the master document.
297 exportdata.addExternalFile(rit->first, source, file);
301 // Do we need to perform the conversion?
302 // Yes if to_file does not exist or if from_file is newer than to_file
303 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
306 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
308 /* bool const success = */
309 converters.convert(&buffer, temp_file, abs_to_file,
310 params.filename, from_format, to_format, el,
311 Converters::try_default | Converters::try_cache);
316 string const substituteCommands(InsetExternalParams const & params,
317 string const & input, string const & format);
319 string const substituteOptions(InsetExternalParams const & params,
320 string const & input, string const & format);
325 int writeExternal(InsetExternalParams const & params,
326 string const & format,
327 Buffer const & buffer, odocstream & os,
328 ExportData & exportdata,
329 bool external_in_tmpdir,
330 bool external_in_comment)
332 Template const * const et_ptr = getTemplatePtr(params);
335 Template const & et = *et_ptr;
337 Template::Formats::const_iterator cit = et.formats.find(format);
338 if (cit == et.formats.end()) {
339 lyxerr[Debug::EXTERNAL]
340 << "External template format '" << format
341 << "' not specified in template "
342 << params.templatename() << endl;
346 if (!external_in_comment)
347 updateExternal(params, format, buffer, exportdata,
350 bool const use_latex_path = format == "LaTeX";
351 string str = doSubstitution(params, buffer, cit->second.product,
352 use_latex_path, external_in_tmpdir);
353 str = substituteCommands(params, str, format);
354 str = substituteOptions(params, str, format);
356 os << from_utf8(str);
357 return int(lyx::count(str.begin(), str.end(),'\n'));
362 // Empty template, specialised below.
363 template <typename TransformType>
364 string const substituteIt(string const &,
367 Template::Format const &,
368 InsetExternalParams const &);
372 string const substituteIt<TransformCommand>(string const & input,
374 string const & /* formatname */,
375 Template::Format const & format,
376 InsetExternalParams const & params)
378 typedef std::map<TransformID, TransformStore> Transformers;
379 Transformers::const_iterator it = format.command_transformers.find(id);
380 if (it == format.command_transformers.end())
383 TransformStore const & store = it->second;
385 TransformCommand::ptr_type ptr;
387 ptr = store.getCommandTransformer(params.rotationdata);
388 else if (id == Resize)
389 ptr = store.getCommandTransformer(params.resizedata);
395 support::subst(input, ptr->front_placeholder(), ptr->front());
396 return support::subst(result, ptr->back_placeholder(), ptr->back());
401 string const substituteIt<TransformOption>(string const & input,
403 string const & fname,
404 Template::Format const & format,
405 InsetExternalParams const & params)
407 typedef std::map<TransformID, TransformStore> Transformers;
408 Transformers::const_iterator it = format.option_transformers.find(id);
409 if (it == format.option_transformers.end())
412 TransformStore const & store = it->second;
414 TransformOption::ptr_type ptr;
417 ptr = store.getOptionTransformer(params.clipdata);
420 ptr = store.getOptionTransformer(params.extradata.get(fname));
423 ptr = store.getOptionTransformer(params.rotationdata);
426 ptr = store.getOptionTransformer(params.resizedata);
433 return support::subst(input, ptr->placeholder(), ptr->option());
437 template <typename TransformerType>
438 string const transformIt(InsetExternalParams const & params,
439 string const & s, string const & formatname)
441 Template const * const et = getTemplatePtr(params);
442 if (!et || et->transformIds.empty())
445 Template::Formats::const_iterator fit = et->formats.find(formatname);
446 if (fit == et->formats.end())
450 Template::Format const & format = fit->second;
452 typedef vector<TransformID> TransformsIDs;
453 TransformsIDs::const_iterator it = et->transformIds.begin();
454 TransformsIDs::const_iterator end = et->transformIds.end();
455 for (; it != end; ++it) {
456 result = substituteIt<TransformerType>(result, *it, formatname,
463 string const substituteCommands(InsetExternalParams const & params,
464 string const & input, string const & format)
466 return transformIt<TransformCommand>(params, input, format);
470 string const substituteOption(InsetExternalParams const & params,
471 string const & input, string const & format)
473 string opt = transformIt<TransformOption>(params, input, format);
475 if (format == "LaTeX" || format == "PDFLaTeX")
476 return sanitizeLatexOption(opt);
477 if (format == "DocBook")
478 return sanitizeDocBookOption(opt);
483 string const substituteOptions(InsetExternalParams const & params,
484 string const & input, string const & format)
486 string output = input;
488 Template const * const et = getTemplatePtr(params);
489 if (!et || et->transformIds.empty())
492 Template::Formats::const_iterator fit = et->formats.find(format);
493 if (fit == et->formats.end() || fit->second.options.empty())
496 typedef vector<Template::Option> Options;
497 Options const & options = fit->second.options;
498 Options::const_iterator it = options.begin();
499 Options::const_iterator end = options.end();
500 for (; it != end; ++it) {
501 string const opt = substituteOption(params, it->option, format);
502 string const placeholder = "$$" + it->name;
503 output = support::subst(output, placeholder, opt);
511 } // namespace external