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"
43 Template const * getTemplatePtr(InsetExternalParams const & params)
45 TemplateManager const & etm = TemplateManager::get();
46 return etm.getTemplateByName(params.templatename());
50 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
52 string const file_with_path = params.filename.absFilename();
53 formats.edit(buffer, file_with_path,
54 formats.getFormatFromFile(file_with_path));
60 string const subst_path(string const & input,
61 string const & placeholder,
64 support::latex_path_extension ext = support::PROTECT_EXTENSION,
65 support::latex_path_dots dots = support::LEAVE_DOTS)
67 if (input.find(placeholder) == string::npos)
69 string const path2 = use_latex_path ?
70 support::latex_path(path, ext, dots) :
71 support::os::external_path(path);
72 return support::subst(input, placeholder, path2);
78 string const doSubstitution(InsetExternalParams const & params,
79 Buffer const & buffer, string const & s,
81 bool external_in_tmpdir,
84 Buffer const * m_buffer = buffer.getMasterBuffer();
85 string const parentpath = external_in_tmpdir ?
86 m_buffer->temppath() :
88 string const filename = external_in_tmpdir ?
89 params.filename.mangledFilename() :
90 params.filename.outputFilename(parentpath);
91 string const basename = support::changeExtension(
92 support::onlyFilename(filename), string());
93 string const absname = support::makeAbsPath(filename, parentpath);
96 if (what != ALL_BUT_PATHS) {
97 string const filepath = support::onlyPath(filename);
98 string const abspath = support::onlyPath(absname);
99 string const masterpath = external_in_tmpdir ?
100 m_buffer->temppath() :
101 m_buffer->filePath();
102 string relToMasterPath = support::onlyPath(
103 support::makeRelPath(absname, masterpath));
104 if (relToMasterPath == "./")
105 relToMasterPath.clear();
106 string relToParentPath = support::onlyPath(
107 support::makeRelPath(absname, parentpath));
108 if (relToParentPath == "./")
109 relToParentPath.clear();
111 result = subst_path(result, "$$FPath", filepath,
113 support::PROTECT_EXTENSION,
114 support::ESCAPE_DOTS);
115 result = subst_path(result, "$$AbsPath", abspath,
117 support::PROTECT_EXTENSION,
118 support::ESCAPE_DOTS);
119 result = subst_path(result, "$$RelPathMaster",
120 relToMasterPath, use_latex_path,
121 support::PROTECT_EXTENSION,
122 support::ESCAPE_DOTS);
123 result = subst_path(result, "$$RelPathParent",
124 relToParentPath, use_latex_path,
125 support::PROTECT_EXTENSION,
126 support::ESCAPE_DOTS);
127 if (support::absolutePath(filename)) {
128 result = subst_path(result, "$$AbsOrRelPathMaster",
129 abspath, use_latex_path,
130 support::PROTECT_EXTENSION,
131 support::ESCAPE_DOTS);
132 result = subst_path(result, "$$AbsOrRelPathParent",
133 abspath, use_latex_path,
134 support::PROTECT_EXTENSION,
135 support::ESCAPE_DOTS);
137 result = subst_path(result, "$$AbsOrRelPathMaster",
138 relToMasterPath, use_latex_path,
139 support::PROTECT_EXTENSION,
140 support::ESCAPE_DOTS);
141 result = subst_path(result, "$$AbsOrRelPathParent",
142 relToParentPath, use_latex_path,
143 support::PROTECT_EXTENSION,
144 support::ESCAPE_DOTS);
151 result = subst_path(result, "$$FName", filename, use_latex_path,
152 support::EXCLUDE_EXTENSION);
153 result = subst_path(result, "$$Basename", basename, use_latex_path,
154 support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
155 result = subst_path(result, "$$Extension",
156 '.' + support::getExtension(filename), use_latex_path);
157 result = subst_path(result, "$$Tempname", params.tempname(), use_latex_path);
158 result = subst_path(result, "$$Sysdir",
159 support::package().system_support(), use_latex_path);
161 // Handle the $$Contents(filename) syntax
162 if (support::contains(result, "$$Contents(\"")) {
164 string::size_type const pos = result.find("$$Contents(\"");
165 string::size_type const end = result.find("\")", pos);
166 string const file = result.substr(pos + 12, end - (pos + 12));
169 string const filepath = support::isFileReadable(file) ?
170 buffer.filePath() : m_buffer->temppath();
171 support::Path p(filepath);
173 if (support::isFileReadable(file))
174 contents = support::getFileContents(file);
176 result = support::subst(result,
177 ("$$Contents(\"" + file + "\")").c_str(),
187 /** update the file represented by the template.
188 If \p external_in_tmpdir == true, then the generated file is
189 placed in the buffer's temporary directory.
191 void updateExternal(InsetExternalParams const & params,
192 string const & format,
193 Buffer const & buffer,
194 ExportData & exportdata,
195 bool external_in_tmpdir)
197 Template const * const et_ptr = getTemplatePtr(params);
200 Template const & et = *et_ptr;
202 if (!et.automaticProduction)
203 return; // NOT_NEEDED
205 Template::Formats::const_iterator cit = et.formats.find(format);
206 if (cit == et.formats.end())
209 Template::Format const & outputFormat = cit->second;
210 if (outputFormat.updateResult.empty())
211 return; // NOT_NEEDED
213 string from_format = et.inputFormat;
214 if (from_format.empty())
215 return; // NOT_NEEDED
217 string abs_from_file = params.filename.absFilename();
219 if (from_format == "*") {
220 if (abs_from_file.empty())
221 return; // NOT_NEEDED
223 // Try and ascertain the file format from its contents.
224 from_format = formats.getFormatFromFile(abs_from_file);
225 if (from_format.empty())
230 string const to_format = outputFormat.updateFormat;
231 if (to_format.empty())
232 return; // NOT_NEEDED
234 if (!converters.isReachable(from_format, to_format)) {
235 lyxerr[Debug::EXTERNAL]
236 << "external::updateExternal. "
237 << "Unable to convert from "
238 << from_format << " to " << to_format << endl;
242 // The master buffer. This is useful when there are multiple levels
244 Buffer const * m_buffer = buffer.getMasterBuffer();
246 // We copy the source file to the temp dir and do the conversion
247 // there if necessary
248 string const temp_file =
249 support::makeAbsPath(params.filename.mangledFilename(),
250 m_buffer->temppath());
251 if (!abs_from_file.empty()) {
252 unsigned long const from_checksum = support::sum(abs_from_file);
253 unsigned long const temp_checksum = support::sum(temp_file);
255 if (from_checksum != temp_checksum) {
256 Mover const & mover = movers(from_format);
257 if (!mover.copy(abs_from_file, temp_file)) {
258 lyxerr[Debug::EXTERNAL]
259 << "external::updateExternal. "
261 << abs_from_file << " to " << temp_file << endl;
267 // the generated file (always in the temp dir)
268 string const to_file = doSubstitution(params, buffer,
269 outputFormat.updateResult,
271 string const abs_to_file =
272 support::makeAbsPath(to_file, m_buffer->temppath());
274 // Record the referenced files for the exporter.
275 // The exporter will copy them to the export dir.
276 typedef Template::Format::FileMap FileMap;
277 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
278 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
279 for (; rit != rend; ++rit) {
280 vector<string>::const_iterator fit = rit->second.begin();
281 vector<string>::const_iterator fend = rit->second.end();
282 for (; fit != fend; ++fit) {
283 string const source = support::makeAbsPath(
284 doSubstitution(params, buffer, *fit,
286 m_buffer->temppath());
287 // The path of the referenced file is never the
288 // temp path, but the filename may be the mangled
289 // or the real name. Therefore we substitute the
290 // paths and names separately.
291 string file = support::subst(*fit, "$$FName",
292 "$$FPath$$Basename$$Extension");
293 file = doSubstitution(params, buffer, file, false, false,
295 file = doSubstitution(params, buffer, file,
296 false, external_in_tmpdir,
298 // if file is a relative name, it is interpreted
299 // relative to the master document.
300 exportdata.addExternalFile(rit->first, source, file);
304 // Do we need to perform the conversion?
305 // Yes if to_file does not exist or if from_file is newer than to_file
306 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
309 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
311 /* bool const success = */
312 converters.convert(&buffer, temp_file, abs_to_file,
313 abs_from_file, from_format, to_format, el,
314 Converters::try_default | Converters::try_cache);
319 string const substituteCommands(InsetExternalParams const & params,
320 string const & input, string const & format);
322 string const substituteOptions(InsetExternalParams const & params,
323 string const & input, string const & format);
328 int writeExternal(InsetExternalParams const & params,
329 string const & format,
330 Buffer const & buffer, odocstream & os,
331 ExportData & exportdata,
332 bool external_in_tmpdir,
333 bool external_in_comment)
335 Template const * const et_ptr = getTemplatePtr(params);
338 Template const & et = *et_ptr;
340 Template::Formats::const_iterator cit = et.formats.find(format);
341 if (cit == et.formats.end()) {
342 lyxerr[Debug::EXTERNAL]
343 << "External template format '" << format
344 << "' not specified in template "
345 << params.templatename() << endl;
349 if (!external_in_comment)
350 updateExternal(params, format, buffer, exportdata,
353 bool const use_latex_path = format == "LaTeX";
354 string str = doSubstitution(params, buffer, cit->second.product,
355 use_latex_path, external_in_tmpdir);
356 str = substituteCommands(params, str, format);
357 str = substituteOptions(params, str, format);
359 os << from_utf8(str);
360 return int(lyx::count(str.begin(), str.end(),'\n'));
365 // Empty template, specialised below.
366 template <typename TransformType>
367 string const substituteIt(string const &,
370 Template::Format const &,
371 InsetExternalParams const &);
375 string const substituteIt<TransformCommand>(string const & input,
377 string const & /* formatname */,
378 Template::Format const & format,
379 InsetExternalParams const & params)
381 typedef std::map<TransformID, TransformStore> Transformers;
382 Transformers::const_iterator it = format.command_transformers.find(id);
383 if (it == format.command_transformers.end())
386 TransformStore const & store = it->second;
388 TransformCommand::ptr_type ptr;
390 ptr = store.getCommandTransformer(params.rotationdata);
391 else if (id == Resize)
392 ptr = store.getCommandTransformer(params.resizedata);
398 support::subst(input, ptr->front_placeholder(), ptr->front());
399 return support::subst(result, ptr->back_placeholder(), ptr->back());
404 string const substituteIt<TransformOption>(string const & input,
406 string const & fname,
407 Template::Format const & format,
408 InsetExternalParams const & params)
410 typedef std::map<TransformID, TransformStore> Transformers;
411 Transformers::const_iterator it = format.option_transformers.find(id);
412 if (it == format.option_transformers.end())
415 TransformStore const & store = it->second;
417 TransformOption::ptr_type ptr;
420 ptr = store.getOptionTransformer(params.clipdata);
423 ptr = store.getOptionTransformer(params.extradata.get(fname));
426 ptr = store.getOptionTransformer(params.rotationdata);
429 ptr = store.getOptionTransformer(params.resizedata);
436 return support::subst(input, ptr->placeholder(), ptr->option());
440 template <typename TransformerType>
441 string const transformIt(InsetExternalParams const & params,
442 string const & s, string const & formatname)
444 Template const * const et = getTemplatePtr(params);
445 if (!et || et->transformIds.empty())
448 Template::Formats::const_iterator fit = et->formats.find(formatname);
449 if (fit == et->formats.end())
453 Template::Format const & format = fit->second;
455 typedef vector<TransformID> TransformsIDs;
456 TransformsIDs::const_iterator it = et->transformIds.begin();
457 TransformsIDs::const_iterator end = et->transformIds.end();
458 for (; it != end; ++it) {
459 result = substituteIt<TransformerType>(result, *it, formatname,
466 string const substituteCommands(InsetExternalParams const & params,
467 string const & input, string const & format)
469 return transformIt<TransformCommand>(params, input, format);
473 string const substituteOption(InsetExternalParams const & params,
474 string const & input, string const & format)
476 string opt = transformIt<TransformOption>(params, input, format);
478 if (format == "LaTeX" || format == "PDFLaTeX")
479 return sanitizeLatexOption(opt);
480 if (format == "DocBook")
481 return sanitizeDocBookOption(opt);
486 string const substituteOptions(InsetExternalParams const & params,
487 string const & input, string const & format)
489 string output = input;
491 Template const * const et = getTemplatePtr(params);
492 if (!et || et->transformIds.empty())
495 Template::Formats::const_iterator fit = et->formats.find(format);
496 if (fit == et->formats.end() || fit->second.options.empty())
499 typedef vector<Template::Option> Options;
500 Options const & options = fit->second.options;
501 Options::const_iterator it = options.begin();
502 Options::const_iterator end = options.end();
503 for (; it != end; ++it) {
504 string const opt = substituteOption(params, it->option, format);
505 string const placeholder = "$$" + it->name;
506 output = support::subst(output, placeholder, opt);
514 } // namespace external