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"
33 #include "support/path.h"
35 #include "support/std_ostream.h"
37 namespace support = lyx::support;
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 string const file_with_path = params.filename.absFilename();
59 formats.edit(buffer, file_with_path,
60 formats.getFormatFromFile(file_with_path));
66 string const subst_path(string const & input,
67 string const & placeholder,
70 bool exclude_extension = false)
72 if (input.find(placeholder) == string::npos)
74 string const path2 = use_latex_path ?
75 support::latex_path(path, exclude_extension, use_lyxdot) :
76 support::os::external_path(path);
77 return support::subst(input, placeholder, path2);
83 string const doSubstitution(InsetExternalParams const & params,
84 Buffer const & buffer, string const & s,
86 bool external_in_tmpdir,
89 Buffer const * m_buffer = buffer.getMasterBuffer();
90 string const parentpath = external_in_tmpdir ?
91 m_buffer->temppath() :
93 string const filename = external_in_tmpdir ?
94 params.filename.mangledFilename() :
95 params.filename.outputFilename(parentpath);
96 string const basename = support::ChangeExtension(
97 support::OnlyFilename(filename), string());
98 string const absname = support::MakeAbsPath(filename, parentpath);
101 if (what != ALL_BUT_PATHS) {
102 string const filepath = support::OnlyPath(filename);
103 string const abspath = support::OnlyPath(absname);
104 string const masterpath = external_in_tmpdir ?
105 m_buffer->temppath() :
106 m_buffer->filePath();
107 string relToMasterPath = support::OnlyPath(
108 support::MakeRelPath(absname, masterpath));
109 if (relToMasterPath == "./")
110 relToMasterPath.clear();
111 string relToParentPath = support::OnlyPath(
112 support::MakeRelPath(absname, parentpath));
113 if (relToParentPath == "./")
114 relToParentPath.clear();
116 result = subst_path(result, "$$FPath", filepath, use_latex_path);
117 result = subst_path(result, "$$AbsPath", abspath, use_latex_path);
118 result = subst_path(result, "$$RelPathMaster",
119 relToMasterPath, use_latex_path);
120 result = subst_path(result, "$$RelPathParent",
121 relToParentPath, use_latex_path);
122 if (support::AbsolutePath(filename)) {
123 result = subst_path(result, "$$AbsOrRelPathMaster",
124 abspath, use_latex_path);
125 result = subst_path(result, "$$AbsOrRelPathParent",
126 abspath, use_latex_path);
128 result = subst_path(result, "$$AbsOrRelPathMaster",
129 relToMasterPath, use_latex_path);
130 result = subst_path(result, "$$AbsOrRelPathParent",
131 relToParentPath, use_latex_path);
138 result = subst_path(result, "$$FName", filename, use_latex_path, true);
139 result = subst_path(result, "$$Basename", basename, use_latex_path);
140 result = subst_path(result, "$$Extension",
141 '.' + support::GetExtension(filename), use_latex_path);
142 result = subst_path(result, "$$Tempname", params.tempname(), use_latex_path);
143 result = subst_path(result, "$$Sysdir",
144 support::package().system_support(), use_latex_path);
146 // Handle the $$Contents(filename) syntax
147 if (support::contains(result, "$$Contents(\"")) {
149 string::size_type const pos = result.find("$$Contents(\"");
150 string::size_type const end = result.find("\")", pos);
151 string const file = result.substr(pos + 12, end - (pos + 12));
154 string const filepath = support::IsFileReadable(file) ?
155 buffer.filePath() : m_buffer->temppath();
156 support::Path p(filepath);
158 if (support::IsFileReadable(file))
159 contents = support::GetFileContents(file);
161 result = support::subst(result,
162 ("$$Contents(\"" + file + "\")").c_str(),
172 /** update the file represented by the template.
173 If \p external_in_tmpdir == true, then the generated file is
174 placed in the buffer's temporary directory.
176 void updateExternal(InsetExternalParams const & params,
177 string const & format,
178 Buffer const & buffer,
179 ExportData & exportdata,
180 bool external_in_tmpdir)
182 Template const * const et_ptr = getTemplatePtr(params);
185 Template const & et = *et_ptr;
187 if (!et.automaticProduction)
188 return; // NOT_NEEDED
190 Template::Formats::const_iterator cit = et.formats.find(format);
191 if (cit == et.formats.end())
194 Template::Format const & outputFormat = cit->second;
195 if (outputFormat.updateResult.empty())
196 return; // NOT_NEEDED
198 string from_format = et.inputFormat;
199 if (from_format.empty())
200 return; // NOT_NEEDED
202 string abs_from_file = params.filename.absFilename();
204 if (from_format == "*") {
205 if (abs_from_file.empty())
206 return; // NOT_NEEDED
208 // Try and ascertain the file format from its contents.
209 from_format = formats.getFormatFromFile(abs_from_file);
210 if (from_format.empty())
215 string const to_format = outputFormat.updateFormat;
216 if (to_format.empty())
217 return; // NOT_NEEDED
219 if (!converters.isReachable(from_format, to_format)) {
220 lyxerr[Debug::EXTERNAL]
221 << "external::updateExternal. "
222 << "Unable to convert from "
223 << from_format << " to " << to_format << endl;
227 // The master buffer. This is useful when there are multiple levels
229 Buffer const * m_buffer = buffer.getMasterBuffer();
231 // We copy the source file to the temp dir and do the conversion
232 // there if necessary
233 string const temp_file =
234 support::MakeAbsPath(params.filename.mangledFilename(),
235 m_buffer->temppath());
236 if (!abs_from_file.empty()) {
237 unsigned long const from_checksum = support::sum(abs_from_file);
238 unsigned long const temp_checksum = support::sum(temp_file);
240 if (from_checksum != temp_checksum) {
241 Mover const & mover = movers(from_format);
242 if (!mover.copy(abs_from_file, temp_file)) {
243 lyxerr[Debug::EXTERNAL]
244 << "external::updateExternal. "
246 << abs_from_file << " to " << temp_file << endl;
252 // the generated file (always in the temp dir)
253 string const to_file = doSubstitution(params, buffer,
254 outputFormat.updateResult,
256 string const abs_to_file =
257 support::MakeAbsPath(to_file, m_buffer->temppath());
259 // Record the referenced files for the exporter.
260 // The exporter will copy them to the export dir.
261 typedef Template::Format::FileMap FileMap;
262 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
263 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
264 for (; rit != rend; ++rit) {
265 vector<string>::const_iterator fit = rit->second.begin();
266 vector<string>::const_iterator fend = rit->second.end();
267 for (; fit != fend; ++fit) {
268 string const source = support::MakeAbsPath(
269 doSubstitution(params, buffer, *fit,
271 m_buffer->temppath());
272 // The path of the referenced file is never the
273 // temp path, but the filename may be the mangled
274 // or the real name. Therefore we substitute the
275 // paths and names separately.
276 string file = support::subst(*fit, "$$FName",
277 "$$FPath$$Basename$$Extension");
278 file = doSubstitution(params, buffer, file, false, false,
280 file = doSubstitution(params, buffer, file,
281 false, external_in_tmpdir,
283 // if file is a relative name, it is interpreted
284 // relative to the master document.
285 exportdata.addExternalFile(rit->first, source, file);
289 // Do we need to perform the conversion?
290 // Yes if to_file does not exist or if from_file is newer than to_file
291 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
293 string const to_file_base =
294 support::ChangeExtension(to_file, string());
295 /* bool const success = */
296 converters.convert(&buffer, temp_file, to_file_base,
297 from_format, to_format, true);
302 string const substituteCommands(InsetExternalParams const & params,
303 string const & input, string const & format);
305 string const substituteOptions(InsetExternalParams const & params,
306 string const & input, string const & format);
311 int writeExternal(InsetExternalParams const & params,
312 string const & format,
313 Buffer const & buffer, ostream & os,
314 ExportData & exportdata,
315 bool external_in_tmpdir)
317 Template const * const et_ptr = getTemplatePtr(params);
320 Template const & et = *et_ptr;
322 Template::Formats::const_iterator cit = et.formats.find(format);
323 if (cit == et.formats.end()) {
324 lyxerr[Debug::EXTERNAL]
325 << "External template format '" << format
326 << "' not specified in template "
327 << params.templatename() << endl;
331 updateExternal(params, format, buffer, exportdata, external_in_tmpdir);
333 bool const use_latex_path = format == "LaTeX";
334 string str = doSubstitution(params, buffer, cit->second.product,
335 use_latex_path, external_in_tmpdir);
336 str = substituteCommands(params, str, format);
337 str = substituteOptions(params, str, format);
339 return int(lyx::count(str.begin(), str.end(),'\n'));
344 // Empty template, specialised below.
345 template <typename TransformType>
346 string const substituteIt(string const &,
349 Template::Format const &,
350 InsetExternalParams const &);
354 string const substituteIt<TransformCommand>(string const & input,
356 string const & /* formatname */,
357 Template::Format const & format,
358 InsetExternalParams const & params)
360 typedef std::map<TransformID, TransformStore> Transformers;
361 Transformers::const_iterator it = format.command_transformers.find(id);
362 if (it == format.command_transformers.end())
365 TransformStore const & store = it->second;
367 TransformCommand::ptr_type ptr;
369 ptr = store.getCommandTransformer(params.rotationdata);
370 else if (id == Resize)
371 ptr = store.getCommandTransformer(params.resizedata);
377 support::subst(input, ptr->front_placeholder(), ptr->front());
378 return support::subst(result, ptr->back_placeholder(), ptr->back());
383 string const substituteIt<TransformOption>(string const & input,
385 string const & fname,
386 Template::Format const & format,
387 InsetExternalParams const & params)
389 typedef std::map<TransformID, TransformStore> Transformers;
390 Transformers::const_iterator it = format.option_transformers.find(id);
391 if (it == format.option_transformers.end())
394 TransformStore const & store = it->second;
396 TransformOption::ptr_type ptr;
399 ptr = store.getOptionTransformer(params.clipdata);
402 ptr = store.getOptionTransformer(params.extradata.get(fname));
405 ptr = store.getOptionTransformer(params.rotationdata);
408 ptr = store.getOptionTransformer(params.resizedata);
415 return support::subst(input, ptr->placeholder(), ptr->option());
419 template <typename TransformerType>
420 string const transformIt(InsetExternalParams const & params,
421 string const & s, string const & formatname)
423 Template const * const et = getTemplatePtr(params);
424 if (!et || et->transformIds.empty())
427 Template::Formats::const_iterator fit = et->formats.find(formatname);
428 if (fit == et->formats.end())
432 Template::Format const & format = fit->second;
434 typedef vector<TransformID> TransformsIDs;
435 TransformsIDs::const_iterator it = et->transformIds.begin();
436 TransformsIDs::const_iterator end = et->transformIds.end();
437 for (; it != end; ++it) {
438 result = substituteIt<TransformerType>(result, *it, formatname,
445 string const substituteCommands(InsetExternalParams const & params,
446 string const & input, string const & format)
448 return transformIt<TransformCommand>(params, input, format);
452 string const substituteOption(InsetExternalParams const & params,
453 string const & input, string const & format)
455 string opt = transformIt<TransformOption>(params, input, format);
457 if (format == "LaTeX" || format == "PDFLaTeX")
458 return sanitizeLatexOption(opt);
459 if (format == "DocBook")
460 return sanitizeDocBookOption(opt);
461 if (format == "LinuxDoc")
462 return sanitizeLinuxDocOption(opt);
467 string const substituteOptions(InsetExternalParams const & params,
468 string const & input, string const & format)
470 string output = input;
472 Template const * const et = getTemplatePtr(params);
473 if (!et || et->transformIds.empty())
476 Template::Formats::const_iterator fit = et->formats.find(format);
477 if (fit == et->formats.end() || fit->second.options.empty())
480 typedef vector<Template::Option> Options;
481 Options const & options = fit->second.options;
482 Options::const_iterator it = options.begin();
483 Options::const_iterator end = options.end();
484 for (; it != end; ++it) {
485 string const opt = substituteOption(params, it->option, format);
486 string const placeholder = "$$" + it->name;
487 output = support::subst(output, placeholder, opt);
495 } // namespace external