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"
21 #include "ErrorList.h"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/filetools.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/lyxalgo.h"
33 #include "support/os.h"
34 #include "support/Package.h"
39 using namespace lyx::support;
44 Template const * getTemplatePtr(InsetExternalParams const & params)
46 TemplateManager const & etm = TemplateManager::get();
47 return etm.getTemplateByName(params.templatename());
51 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
53 formats.edit(buffer, params.filename,
54 formats.getFormatFromFile(params.filename));
60 string const subst_path(string const & input,
61 string const & placeholder,
64 latex_path_extension ext = PROTECT_EXTENSION,
65 latex_path_dots dots = LEAVE_DOTS)
67 if (input.find(placeholder) == string::npos)
69 // Don't use external_path here when use_latex_path is false, as the
70 // path will be compared with another one in internal style later
71 // in Converters::move.
72 string const path2 = use_latex_path ?
73 latex_path(path, ext, dots) : path;
74 return subst(input, placeholder, path2);
80 string const doSubstitution(InsetExternalParams const & params,
81 Buffer const & buffer, string const & s,
83 bool external_in_tmpdir,
86 Buffer const * masterBuffer = buffer.masterBuffer();
87 string const parentpath = external_in_tmpdir ?
88 masterBuffer->temppath() :
90 string const filename = external_in_tmpdir ?
91 params.filename.mangledFileName() :
92 params.filename.outputFileName(parentpath);
93 string const basename = changeExtension(
94 onlyFileName(filename), string());
95 string const absname = makeAbsPath(filename, parentpath).absFileName();
98 if (what != ALL_BUT_PATHS) {
99 string const filepath = onlyPath(filename);
100 string const abspath = onlyPath(absname);
101 string const masterpath = external_in_tmpdir ?
102 masterBuffer->temppath() :
103 masterBuffer->filePath();
105 string relToMasterPath = onlyPath(
106 to_utf8(makeRelPath(from_utf8(absname),
107 from_utf8(masterpath))));
108 if (relToMasterPath == "./")
109 relToMasterPath.clear();
111 string relToParentPath = onlyPath(
112 to_utf8(makeRelPath(from_utf8(absname),
113 from_utf8(parentpath))));
114 if (relToParentPath == "./")
115 relToParentPath.clear();
117 result = subst_path(result, "$$FPath", filepath,
121 result = subst_path(result, "$$AbsPath", abspath,
125 result = subst_path(result, "$$RelPathMaster",
126 relToMasterPath, use_latex_path,
129 result = subst_path(result, "$$RelPathParent",
130 relToParentPath, use_latex_path,
133 if (FileName::isAbsolute(filename)) {
134 result = subst_path(result, "$$AbsOrRelPathMaster",
135 abspath, use_latex_path,
138 result = subst_path(result, "$$AbsOrRelPathParent",
139 abspath, use_latex_path,
143 result = subst_path(result, "$$AbsOrRelPathMaster",
144 relToMasterPath, use_latex_path,
147 result = subst_path(result, "$$AbsOrRelPathParent",
148 relToParentPath, use_latex_path,
157 result = subst_path(result, "$$FName", filename, use_latex_path,
159 result = subst_path(result, "$$Basename", basename, use_latex_path,
160 PROTECT_EXTENSION, ESCAPE_DOTS);
161 result = subst_path(result, "$$Extension",
162 '.' + getExtension(filename), use_latex_path);
163 result = subst_path(result, "$$Tempname", params.tempname().absFileName(), use_latex_path);
164 result = subst_path(result, "$$Sysdir",
165 package().system_support().absFileName(), use_latex_path);
167 // Handle the $$Contents(filename) syntax
168 if (contains(result, "$$Contents(\"")) {
169 // Since use_latex_path may be true we must extract the file
170 // name from s instead of result and do the substitutions
171 // again, this time with use_latex_path false.
172 size_t const spos = s.find("$$Contents(\"");
173 size_t const send = s.find("\")", spos);
174 string const file_template = s.substr(spos + 12, send - (spos + 12));
175 string const file = doSubstitution(params, buffer,
176 file_template, false,
177 external_in_tmpdir, what);
180 FileName const absfile(
181 makeAbsPath(file, masterBuffer->temppath()));
182 if (absfile.isReadableFile())
184 contents = to_utf8(absfile.fileContents("UTF-8"));
186 size_t const pos = result.find("$$Contents(\"");
187 size_t const end = result.find("\")", pos);
188 result.replace(pos, end + 2, contents);
197 /** update the file represented by the template.
198 If \p external_in_tmpdir == true, then the generated file is
199 placed in the buffer's temporary directory.
201 void updateExternal(InsetExternalParams const & params,
202 string const & format,
203 Buffer const & buffer,
204 ExportData & exportdata,
205 bool external_in_tmpdir,
208 Template const * const et_ptr = getTemplatePtr(params);
211 Template const & et = *et_ptr;
213 if (!et.automaticProduction)
214 return; // NOT_NEEDED
216 Template::Formats::const_iterator cit = et.formats.find(format);
217 if (cit == et.formats.end())
220 Template::Format const & outputFormat = cit->second;
221 if (outputFormat.updateResult.empty())
222 return; // NOT_NEEDED
224 string from_format = et.inputFormat;
225 if (from_format.empty())
226 return; // NOT_NEEDED
228 if (from_format == "*") {
229 if (params.filename.empty())
230 return; // NOT_NEEDED
232 // Try and ascertain the file format from its contents.
233 from_format = formats.getFormatFromFile(params.filename);
234 if (from_format.empty())
238 string const to_format = outputFormat.updateFormat;
239 if (to_format.empty())
240 return; // NOT_NEEDED
242 // The master buffer. This is useful when there are multiple levels
244 Buffer const * masterBuffer = buffer.masterBuffer();
246 // We copy the source file to the temp dir and do the conversion
247 // there if necessary
248 FileName const temp_file(
249 makeAbsPath(params.filename.mangledFileName(),
250 masterBuffer->temppath()));
251 if (!params.filename.empty() && !params.filename.isDirectory()) {
252 unsigned long const from_checksum = params.filename.checksum();
253 unsigned long const temp_checksum = temp_file.checksum();
255 if (from_checksum != temp_checksum) {
256 Mover const & mover = getMover(from_format);
257 if (!mover.copy(params.filename, temp_file)) {
258 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
259 << "Unable to copy " << params.filename << " to " << temp_file);
265 // the generated file (always in the temp dir)
266 string const to_file = doSubstitution(params, buffer,
267 outputFormat.updateResult,
269 FileName const abs_to_file(
270 makeAbsPath(to_file, masterBuffer->temppath()));
273 // Record the referenced files for the exporter.
274 // The exporter will copy them to the export dir.
275 typedef Template::Format::FileMap FileMap;
276 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
277 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
278 for (; rit != rend; ++rit) {
279 vector<string>::const_iterator fit = rit->second.begin();
280 vector<string>::const_iterator fend = rit->second.end();
281 for (; fit != fend; ++fit) {
282 FileName const source(makeAbsPath(
283 doSubstitution(params, buffer, *fit,
285 masterBuffer->temppath()));
286 // The path of the referenced file is never the
287 // temp path, but the filename may be the mangled
288 // or the real name. Therefore we substitute the
289 // paths and names separately.
290 string file = subst(*fit, "$$FName",
291 "$$FPath$$Basename$$Extension");
292 file = doSubstitution(params, buffer, file, false, false,
294 file = doSubstitution(params, buffer, file,
295 false, external_in_tmpdir,
297 // if file is a relative name, it is interpreted
298 // relative to the master document.
299 if (makeAbsPath(file, masterBuffer->filePath()) !=
300 params.filename.absFileName())
301 exportdata.addExternalFile(rit->first, source, file);
306 // Do we need to perform the conversion?
307 // Yes if to_file does not exist or if from_file is newer than to_file
308 if (compare_timestamps(temp_file, abs_to_file) < 0)
311 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
314 theConverters().convert(&buffer, temp_file, abs_to_file,
315 params.filename, from_format, to_format, el,
316 Converters::try_default | Converters::try_cache);
319 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
320 << "Unable to convert from " << from_format << " to " << to_format);
327 string const substituteCommands(InsetExternalParams const & params,
328 string const & input, string const & format);
330 string const substituteOptions(InsetExternalParams const & params,
331 string const & input, string const & format);
336 int writeExternal(InsetExternalParams const & params,
337 string const & format,
338 Buffer const & buffer, odocstream & os,
339 ExportData & exportdata,
340 bool external_in_tmpdir,
343 Template const * const et_ptr = getTemplatePtr(params);
346 Template const & et = *et_ptr;
348 Template::Formats::const_iterator cit = et.formats.find(format);
349 if (cit == et.formats.end()) {
350 LYXERR(Debug::EXTERNAL, "External template format '" << format
351 << "' not specified in template " << params.templatename());
355 if (!dryrun || contains(cit->second.product, "$$Contents"))
356 updateExternal(params, format, buffer, exportdata,
357 external_in_tmpdir, dryrun);
359 bool const use_latex_path = format == "LaTeX";
360 string str = doSubstitution(params, buffer, cit->second.product,
361 use_latex_path, external_in_tmpdir);
363 string const absname = makeAbsPath(
364 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
366 if (!external_in_tmpdir && !isValidLaTeXFileName(absname)) {
367 lyx::frontend::Alert::warning(_("Invalid filename"),
368 _("The following filename is likely to cause trouble "
369 "when running the exported file through LaTeX: ") +
373 str = substituteCommands(params, str, format);
374 str = substituteOptions(params, str, format);
376 os << from_utf8(str);
377 return int(count(str.begin(), str.end(),'\n'));
382 // Empty template, specialised below.
383 template <typename TransformType>
384 string const substituteIt(string const &,
387 Template::Format const &,
388 InsetExternalParams const &);
392 string const substituteIt<TransformCommand>(string const & input,
394 string const & /* formatname */,
395 Template::Format const & format,
396 InsetExternalParams const & params)
398 typedef map<TransformID, TransformStore> Transformers;
399 Transformers::const_iterator it = format.command_transformers.find(id);
400 if (it == format.command_transformers.end())
403 TransformStore const & store = it->second;
405 TransformCommand::ptr_type ptr;
407 ptr = store.getCommandTransformer(params.rotationdata);
408 else if (id == Resize)
409 ptr = store.getCommandTransformer(params.resizedata);
415 subst(input, ptr->front_placeholder(), ptr->front());
416 return subst(result, ptr->back_placeholder(), ptr->back());
421 string const substituteIt<TransformOption>(string const & input,
423 string const & fname,
424 Template::Format const & format,
425 InsetExternalParams const & params)
427 typedef map<TransformID, TransformStore> Transformers;
428 Transformers::const_iterator it = format.option_transformers.find(id);
429 if (it == format.option_transformers.end())
432 TransformStore const & store = it->second;
434 TransformOption::ptr_type ptr;
437 ptr = store.getOptionTransformer(params.clipdata);
440 ptr = store.getOptionTransformer(params.extradata.get(fname));
443 ptr = store.getOptionTransformer(params.rotationdata);
446 ptr = store.getOptionTransformer(params.resizedata);
453 return subst(input, ptr->placeholder(), ptr->option());
457 template <typename TransformerType>
458 string const transformIt(InsetExternalParams const & params,
459 string const & s, string const & formatname)
461 Template const * const et = getTemplatePtr(params);
462 if (!et || et->transformIds.empty())
465 Template::Formats::const_iterator fit = et->formats.find(formatname);
466 if (fit == et->formats.end())
470 Template::Format const & format = fit->second;
472 typedef vector<TransformID> TransformsIDs;
473 TransformsIDs::const_iterator it = et->transformIds.begin();
474 TransformsIDs::const_iterator end = et->transformIds.end();
475 for (; it != end; ++it) {
476 result = substituteIt<TransformerType>(result, *it, formatname,
483 string const substituteCommands(InsetExternalParams const & params,
484 string const & input, string const & format)
486 return transformIt<TransformCommand>(params, input, format);
490 string const substituteOption(InsetExternalParams const & params,
491 string const & input, string const & format)
493 string opt = transformIt<TransformOption>(params, input, format);
495 if (format == "LaTeX" || format == "PDFLaTeX")
496 return sanitizeLatexOption(opt);
497 if (format == "DocBook")
498 return sanitizeDocBookOption(opt);
503 string const substituteOptions(InsetExternalParams const & params,
504 string const & input, string const & format)
506 string output = input;
508 Template const * const et = getTemplatePtr(params);
509 if (!et || et->transformIds.empty())
512 Template::Formats::const_iterator fit = et->formats.find(format);
513 if (fit == et->formats.end() || fit->second.options.empty())
516 typedef vector<Template::Option> Options;
517 Options const & options = fit->second.options;
518 Options::const_iterator it = options.begin();
519 Options::const_iterator end = options.end();
520 for (; it != end; ++it) {
521 string const opt = substituteOption(params, it->option, format);
522 string const placeholder = "$$" + it->name;
523 output = subst(output, placeholder, opt);
531 } // namespace external