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,
87 if (what != PATHS && contains(result, "$$pngOrjpg")) {
88 // This is for raster images and pdflatex:
89 // Since pdflatex supports both jpg and png, we choose the best format:
90 // jpg if the original file is jpg to retain the compression, else png.
91 string format = formats.getFormatFromFile(params.filename);
93 result = subst(result, "$$pngOrjpg", "jpg");
95 result = subst(result, "$$pngOrjpg", "png");
101 Buffer const * masterBuffer = buffer.masterBuffer();
102 string const parentpath = external_in_tmpdir ?
103 masterBuffer->temppath() :
105 string const filename = external_in_tmpdir ?
106 params.filename.mangledFileName() :
107 params.filename.outputFileName(parentpath);
108 string const basename = changeExtension(
109 onlyFileName(filename), string());
110 string const absname = makeAbsPath(filename, parentpath).absFileName();
112 if (what != ALL_BUT_PATHS) {
113 string const filepath = onlyPath(filename);
114 string const abspath = onlyPath(absname);
115 string const masterpath = external_in_tmpdir ?
116 masterBuffer->temppath() :
117 masterBuffer->filePath();
119 string relToMasterPath = onlyPath(
120 to_utf8(makeRelPath(from_utf8(absname),
121 from_utf8(masterpath))));
122 if (relToMasterPath == "./")
123 relToMasterPath.clear();
125 string relToParentPath = onlyPath(
126 to_utf8(makeRelPath(from_utf8(absname),
127 from_utf8(parentpath))));
128 if (relToParentPath == "./")
129 relToParentPath.clear();
131 result = subst_path(result, "$$FPath", filepath,
135 result = subst_path(result, "$$AbsPath", abspath,
139 result = subst_path(result, "$$RelPathMaster",
140 relToMasterPath, use_latex_path,
143 result = subst_path(result, "$$RelPathParent",
144 relToParentPath, use_latex_path,
147 if (FileName::isAbsolute(filename)) {
148 result = subst_path(result, "$$AbsOrRelPathMaster",
149 abspath, use_latex_path,
152 result = subst_path(result, "$$AbsOrRelPathParent",
153 abspath, use_latex_path,
157 result = subst_path(result, "$$AbsOrRelPathMaster",
158 relToMasterPath, use_latex_path,
161 result = subst_path(result, "$$AbsOrRelPathParent",
162 relToParentPath, use_latex_path,
171 result = subst_path(result, "$$FName", filename, use_latex_path,
173 result = subst_path(result, "$$Basename", basename, use_latex_path,
174 PROTECT_EXTENSION, ESCAPE_DOTS);
175 result = subst_path(result, "$$Extension",
176 '.' + getExtension(filename), use_latex_path);
177 result = subst_path(result, "$$Tempname", params.tempname().absFileName(), use_latex_path);
178 result = subst_path(result, "$$Sysdir",
179 package().system_support().absFileName(), use_latex_path);
181 // Handle the $$Contents(filename) syntax
182 if (contains(result, "$$Contents(\"")) {
183 // Since use_latex_path may be true we must extract the file
184 // name from s instead of result and do the substitutions
185 // again, this time with use_latex_path false.
186 size_t const spos = s.find("$$Contents(\"");
187 size_t const send = s.find("\")", spos);
188 string const file_template = s.substr(spos + 12, send - (spos + 12));
189 string const file = doSubstitution(params, buffer,
190 file_template, false,
191 external_in_tmpdir, what);
194 FileName const absfile(
195 makeAbsPath(file, masterBuffer->temppath()));
196 if (absfile.isReadableFile())
198 contents = to_utf8(absfile.fileContents("UTF-8"));
200 size_t const pos = result.find("$$Contents(\"");
201 size_t const end = result.find("\")", pos);
202 result.replace(pos, end + 2, contents);
211 /** update the file represented by the template.
212 If \p external_in_tmpdir == true, then the generated file is
213 placed in the buffer's temporary directory.
215 void updateExternal(InsetExternalParams const & params,
216 string const & format,
217 Buffer const & buffer,
218 ExportData & exportdata,
219 bool external_in_tmpdir,
222 Template const * const et_ptr = getTemplatePtr(params);
225 Template const & et = *et_ptr;
227 if (!et.automaticProduction)
228 return; // NOT_NEEDED
230 Template::Formats::const_iterator cit = et.formats.find(format);
231 if (cit == et.formats.end())
234 Template::Format const & outputFormat = cit->second;
235 if (outputFormat.updateResult.empty())
236 return; // NOT_NEEDED
238 string from_format = et.inputFormat;
239 if (from_format.empty())
240 return; // NOT_NEEDED
242 if (from_format == "*") {
243 if (params.filename.empty())
244 return; // NOT_NEEDED
246 // Try and ascertain the file format from its contents.
247 from_format = formats.getFormatFromFile(params.filename);
248 if (from_format.empty())
252 string const to_format = doSubstitution(params, buffer,
253 outputFormat.updateFormat, false, external_in_tmpdir, FORMATS);
254 if (to_format.empty())
255 return; // NOT_NEEDED
257 // The master buffer. This is useful when there are multiple levels
259 Buffer const * masterBuffer = buffer.masterBuffer();
261 // We copy the source file to the temp dir and do the conversion
262 // there if necessary
263 FileName const temp_file(
264 makeAbsPath(params.filename.mangledFileName(),
265 masterBuffer->temppath()));
266 if (!params.filename.empty() && !params.filename.isDirectory()) {
267 unsigned long const from_checksum = params.filename.checksum();
268 unsigned long const temp_checksum = temp_file.checksum();
270 if (from_checksum != temp_checksum) {
271 Mover const & mover = getMover(from_format);
272 if (!mover.copy(params.filename, temp_file)) {
273 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
274 << "Unable to copy " << params.filename << " to " << temp_file);
280 // the generated file (always in the temp dir)
281 string const to_file = doSubstitution(params, buffer,
282 outputFormat.updateResult,
284 FileName const abs_to_file(
285 makeAbsPath(to_file, masterBuffer->temppath()));
288 // Record the referenced files for the exporter.
289 // The exporter will copy them to the export dir.
290 typedef Template::Format::FileMap FileMap;
291 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
292 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
293 for (; rit != rend; ++rit) {
294 vector<string>::const_iterator fit = rit->second.begin();
295 vector<string>::const_iterator fend = rit->second.end();
296 for (; fit != fend; ++fit) {
297 FileName const source(makeAbsPath(
298 doSubstitution(params, buffer, *fit,
300 masterBuffer->temppath()));
301 // The path of the referenced file is never the
302 // temp path, but the filename may be the mangled
303 // or the real name. Therefore we substitute the
304 // paths and names separately.
305 string file = subst(*fit, "$$FName",
306 "$$FPath$$Basename$$Extension");
307 file = doSubstitution(params, buffer, file, false, false,
309 file = doSubstitution(params, buffer, file,
310 false, external_in_tmpdir,
312 // if file is a relative name, it is interpreted
313 // relative to the master document.
314 if (makeAbsPath(file, masterBuffer->filePath()) !=
315 params.filename.absFileName())
316 exportdata.addExternalFile(rit->first, source, file);
321 // Do we need to perform the conversion?
322 // Yes if to_file does not exist or if from_file is newer than to_file
323 if (compare_timestamps(temp_file, abs_to_file) < 0)
326 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
329 theConverters().convert(&buffer, temp_file, abs_to_file,
330 params.filename, from_format, to_format, el,
331 Converters::try_default | Converters::try_cache);
334 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
335 << "Unable to convert from " << from_format << " to " << to_format);
342 string const substituteCommands(InsetExternalParams const & params,
343 string const & input, string const & format);
345 string const substituteOptions(InsetExternalParams const & params,
346 string const & input, string const & format);
351 void writeExternal(InsetExternalParams const & params,
352 string const & format,
353 Buffer const & buffer, otexstream & os,
354 ExportData & exportdata,
355 bool external_in_tmpdir,
358 Template const * const et_ptr = getTemplatePtr(params);
361 Template const & et = *et_ptr;
363 Template::Formats::const_iterator cit = et.formats.find(format);
364 if (cit == et.formats.end()) {
365 LYXERR(Debug::EXTERNAL, "External template format '" << format
366 << "' not specified in template " << params.templatename());
370 if (!dryrun || contains(cit->second.product, "$$Contents"))
371 updateExternal(params, format, buffer, exportdata,
372 external_in_tmpdir, dryrun);
374 bool const use_latex_path = format == "LaTeX";
375 string str = doSubstitution(params, buffer, cit->second.product,
376 use_latex_path, external_in_tmpdir);
378 string const absname = makeAbsPath(
379 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
381 if (!dryrun && !external_in_tmpdir) {
382 if (!isValidLaTeXFileName(absname)) {
383 lyx::frontend::Alert::warning(_("Invalid filename"),
384 _("The following filename will cause troubles "
385 "when running the exported file through LaTeX: ") +
388 if (!isValidDVIFileName(absname)) {
389 lyx::frontend::Alert::warning(_("Problematic filename for DVI"),
390 _("The following filename can cause troubles "
391 "when running the exported file through LaTeX "
392 "and opening the resulting DVI: ") +
393 from_utf8(absname), true);
397 str = substituteCommands(params, str, format);
398 str = substituteOptions(params, str, format);
400 os << from_utf8(str);
406 // Empty template, specialised below.
407 template <typename TransformType>
408 string const substituteIt(string const &,
411 Template::Format const &,
412 InsetExternalParams const &);
416 string const substituteIt<TransformCommand>(string const & input,
418 string const & /* formatname */,
419 Template::Format const & format,
420 InsetExternalParams const & params)
422 typedef map<TransformID, TransformStore> Transformers;
423 Transformers::const_iterator it = format.command_transformers.find(id);
424 if (it == format.command_transformers.end())
427 TransformStore const & store = it->second;
429 TransformCommand::ptr_type ptr;
431 ptr = store.getCommandTransformer(params.rotationdata);
432 else if (id == Resize)
433 ptr = store.getCommandTransformer(params.resizedata);
439 subst(input, ptr->front_placeholder(), ptr->front());
440 return subst(result, ptr->back_placeholder(), ptr->back());
445 string const substituteIt<TransformOption>(string const & input,
447 string const & fname,
448 Template::Format const & format,
449 InsetExternalParams const & params)
451 typedef map<TransformID, TransformStore> Transformers;
452 Transformers::const_iterator it = format.option_transformers.find(id);
453 if (it == format.option_transformers.end())
456 TransformStore const & store = it->second;
458 TransformOption::ptr_type ptr;
461 ptr = store.getOptionTransformer(params.clipdata);
464 ptr = store.getOptionTransformer(params.extradata.get(fname));
467 ptr = store.getOptionTransformer(params.rotationdata);
470 ptr = store.getOptionTransformer(params.resizedata);
477 return subst(input, ptr->placeholder(), ptr->option());
481 template <typename TransformerType>
482 string const transformIt(InsetExternalParams const & params,
483 string const & s, string const & formatname)
485 Template const * const et = getTemplatePtr(params);
486 if (!et || et->transformIds.empty())
489 Template::Formats::const_iterator fit = et->formats.find(formatname);
490 if (fit == et->formats.end())
494 Template::Format const & format = fit->second;
496 typedef vector<TransformID> TransformsIDs;
497 TransformsIDs::const_iterator it = et->transformIds.begin();
498 TransformsIDs::const_iterator end = et->transformIds.end();
499 for (; it != end; ++it) {
500 result = substituteIt<TransformerType>(result, *it, formatname,
507 string const substituteCommands(InsetExternalParams const & params,
508 string const & input, string const & format)
510 return transformIt<TransformCommand>(params, input, format);
514 string const substituteOption(InsetExternalParams const & params,
515 string const & input, string const & format)
517 string opt = transformIt<TransformOption>(params, input, format);
519 if (format == "LaTeX" || format == "PDFLaTeX")
520 return sanitizeLatexOption(opt);
521 if (format == "DocBook")
522 return sanitizeDocBookOption(opt);
527 string const substituteOptions(InsetExternalParams const & params,
528 string const & input, string const & format)
530 string output = input;
532 Template const * const et = getTemplatePtr(params);
533 if (!et || et->transformIds.empty())
536 Template::Formats::const_iterator fit = et->formats.find(format);
537 if (fit == et->formats.end() || fit->second.options.empty())
540 typedef vector<Template::Option> Options;
541 Options const & options = fit->second.options;
542 Options::const_iterator it = options.begin();
543 Options::const_iterator end = options.end();
544 for (; it != end; ++it) {
545 string const opt = substituteOption(params, it->option, format);
546 string const placeholder = "$$" + it->name;
547 output = subst(output, placeholder, opt);
555 } // namespace external