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"
25 #include "texstream.h"
27 #include "frontends/alert.h"
29 #include "support/debug.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.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 theFormats().edit(buffer, params.filename,
54 theFormats().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 = theFormats().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- pos, 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 RetVal 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)
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())
238 string from_format = et.inputFormat;
239 if (from_format.empty())
242 if (from_format == "*") {
243 if (params.filename.empty())
246 // Try and ascertain the file format from its contents.
247 from_format = theFormats().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())
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 bool const isDir = params.filename.isDirectory();
264 FileName const temp_file(
265 makeAbsPath(params.filename.mangledFileName(),
266 masterBuffer->temppath()));
267 if (!params.filename.empty() && !isDir) {
268 unsigned long const from_checksum = params.filename.checksum();
269 unsigned long const temp_checksum = temp_file.checksum();
271 if (from_checksum != temp_checksum) {
272 Mover const & mover = getMover(from_format);
273 if (!mover.copy(params.filename, temp_file)) {
274 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
275 << "Unable to copy " << params.filename << " to " << temp_file);
281 // the generated file (always in the temp dir)
282 string const to_file = doSubstitution(params, buffer,
283 outputFormat.updateResult,
285 FileName const abs_to_file(
286 makeAbsPath(to_file, masterBuffer->temppath()));
289 // Record the referenced files for the exporter.
290 // The exporter will copy them to the export dir.
291 typedef Template::Format::FileMap FileMap;
292 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
293 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
294 for (; rit != rend; ++rit) {
295 vector<string>::const_iterator fit = rit->second.begin();
296 vector<string>::const_iterator fend = rit->second.end();
297 for (; fit != fend; ++fit) {
298 FileName const source(makeAbsPath(
299 doSubstitution(params, buffer, *fit,
301 masterBuffer->temppath()));
302 // The path of the referenced file is never the
303 // temp path, but the filename may be the mangled
304 // or the real name. Therefore we substitute the
305 // paths and names separately.
306 string file = subst(*fit, "$$FName",
307 "$$FPath$$Basename$$Extension");
308 file = doSubstitution(params, buffer, file, false, false,
310 file = doSubstitution(params, buffer, file,
311 false, external_in_tmpdir,
313 // if file is a relative name, it is interpreted
314 // relative to the master document.
315 if (makeAbsPath(file, masterBuffer->filePath()) !=
316 params.filename.absFileName())
317 exportdata.addExternalFile(rit->first, source, file);
322 // Do we need to perform the conversion?
323 // Yes if to_file does not exist or if from_file is newer than to_file
324 // or if from_file is a directory (bug 9925)
325 if (!isDir && compare_timestamps(temp_file, abs_to_file) < 0)
328 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
330 Converters::RetVal const success =
331 theConverters().convert(&buffer, temp_file, abs_to_file,
332 params.filename, from_format, to_format, el,
333 Converters::try_default | Converters::try_cache);
335 case Converters::SUCCESS:
337 case Converters::FAILURE:
338 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
339 << "Unable to convert from " << from_format << " to " << to_format);
341 case Converters::KILLED:
349 string const substituteCommands(InsetExternalParams const & params,
350 string const & input, string const & format);
352 string const substituteOptions(InsetExternalParams const & params,
353 string const & input, string const & format);
358 RetVal writeExternal(InsetExternalParams const & params,
359 string const & format,
360 Buffer const & buffer, otexstream & os,
361 ExportData & exportdata,
362 bool external_in_tmpdir,
365 Template const * const et_ptr = getTemplatePtr(params);
368 Template const & et = *et_ptr;
370 Template::Formats::const_iterator cit = et.formats.find(format);
371 if (cit == et.formats.end()) {
372 LYXERR(Debug::EXTERNAL, "External template format '" << format
373 << "' not specified in template " << params.templatename());
377 if (!dryrun || contains(cit->second.product, "$$Contents")) {
378 RetVal const success =
379 updateExternal(params, format, buffer, exportdata,
380 external_in_tmpdir, dryrun);
381 if (success == FAILURE || success == KILLED)
385 bool const use_latex_path = format == "LaTeX";
386 string str = doSubstitution(params, buffer, cit->second.product,
387 use_latex_path, external_in_tmpdir);
389 string const absname = makeAbsPath(
390 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
392 if (!dryrun && !external_in_tmpdir) {
393 if (!isValidLaTeXFileName(absname)) {
394 lyx::frontend::Alert::warning(_("Invalid filename"),
395 _("The following filename will cause troubles "
396 "when running the exported file through LaTeX: ") +
399 if (!isValidDVIFileName(absname)) {
400 lyx::frontend::Alert::warning(_("Problematic filename for DVI"),
401 _("The following filename can cause troubles "
402 "when running the exported file through LaTeX "
403 "and opening the resulting DVI: ") +
404 from_utf8(absname), true);
408 str = substituteCommands(params, str, format);
409 str = substituteOptions(params, str, format);
411 os << from_utf8(str);
417 // Empty template, specialised below.
418 template <typename TransformType>
419 string const substituteIt(string const &,
422 Template::Format const &,
423 InsetExternalParams const &);
427 string const substituteIt<TransformCommand>(string const & input,
429 string const & /* formatname */,
430 Template::Format const & format,
431 InsetExternalParams const & params)
433 typedef map<TransformID, TransformStore> Transformers;
434 Transformers::const_iterator it = format.command_transformers.find(id);
435 if (it == format.command_transformers.end())
438 TransformStore const & store = it->second;
440 TransformCommand::ptr_type ptr;
442 ptr = store.getCommandTransformer(params.rotationdata);
443 else if (id == Resize)
444 ptr = store.getCommandTransformer(params.resizedata);
450 subst(input, ptr->front_placeholder(), ptr->front());
451 return subst(result, ptr->back_placeholder(), ptr->back());
456 string const substituteIt<TransformOption>(string const & input,
458 string const & fname,
459 Template::Format const & format,
460 InsetExternalParams const & params)
462 typedef map<TransformID, TransformStore> Transformers;
463 Transformers::const_iterator it = format.option_transformers.find(id);
464 if (it == format.option_transformers.end())
467 TransformStore const & store = it->second;
469 TransformOption::ptr_type ptr;
472 ptr = store.getOptionTransformer(params.clipdata);
475 ptr = store.getOptionTransformer(params.extradata.get(fname));
478 ptr = store.getOptionTransformer(params.rotationdata);
481 ptr = store.getOptionTransformer(params.resizedata);
488 return subst(input, ptr->placeholder(), ptr->option());
492 template <typename TransformerType>
493 string const transformIt(InsetExternalParams const & params,
494 string const & s, string const & formatname)
496 Template const * const et = getTemplatePtr(params);
497 if (!et || et->transformIds.empty())
500 Template::Formats::const_iterator fit = et->formats.find(formatname);
501 if (fit == et->formats.end())
505 Template::Format const & format = fit->second;
507 typedef vector<TransformID> TransformsIDs;
508 TransformsIDs::const_iterator it = et->transformIds.begin();
509 TransformsIDs::const_iterator end = et->transformIds.end();
510 for (; it != end; ++it) {
511 result = substituteIt<TransformerType>(result, *it, formatname,
518 string const substituteCommands(InsetExternalParams const & params,
519 string const & input, string const & format)
521 return transformIt<TransformCommand>(params, input, format);
525 string const substituteOption(InsetExternalParams const & params,
526 string const & input, string const & format)
528 string opt = transformIt<TransformOption>(params, input, format);
530 if (format == "LaTeX" || format == "PDFLaTeX")
531 return sanitizeLatexOption(opt);
532 if (format == "DocBook")
533 return sanitizeDocBookOption(opt);
538 string const substituteOptions(InsetExternalParams const & params,
539 string const & input, string const & format)
541 string output = input;
543 Template const * const et = getTemplatePtr(params);
544 if (!et || et->transformIds.empty())
547 Template::Formats::const_iterator fit = et->formats.find(format);
548 if (fit == et->formats.end() || fit->second.options.empty())
551 typedef vector<Template::Option> Options;
552 Options const & options = fit->second.options;
553 Options::const_iterator it = options.begin();
554 Options::const_iterator end = options.end();
555 for (; it != end; ++it) {
556 string const opt = substituteOption(params, it->option, format);
557 string const placeholder = "$$" + it->name;
558 output = subst(output, placeholder, opt);
566 } // namespace external