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();
111 string const origabsname = makeAbsPath(params.filename.outputFileName(parentpath),
112 parentpath).absFileName();
114 if (what != ALL_BUT_PATHS) {
115 string const filepath = onlyPath(filename);
116 string const abspath = onlyPath(absname);
117 string const masterpath = external_in_tmpdir ?
118 masterBuffer->temppath() :
119 masterBuffer->filePath();
121 string relToMasterPath = onlyPath(
122 to_utf8(makeRelPath(from_utf8(absname),
123 from_utf8(masterpath))));
124 if (relToMasterPath == "./")
125 relToMasterPath.clear();
127 string relToParentPath = onlyPath(
128 to_utf8(makeRelPath(from_utf8(absname),
129 from_utf8(parentpath))));
130 if (relToParentPath == "./")
131 relToParentPath.clear();
133 result = subst_path(result, "$$FPath", filepath,
137 result = subst_path(result, "$$AbsPath", abspath,
141 result = subst_path(result, "$$OrigAbsName", origabsname,
145 result = subst_path(result, "$$RelPathMaster",
146 relToMasterPath, use_latex_path,
149 result = subst_path(result, "$$RelPathParent",
150 relToParentPath, use_latex_path,
153 if (FileName::isAbsolute(filename)) {
154 result = subst_path(result, "$$AbsOrRelPathMaster",
155 abspath, use_latex_path,
158 result = subst_path(result, "$$AbsOrRelPathParent",
159 abspath, use_latex_path,
163 result = subst_path(result, "$$AbsOrRelPathMaster",
164 relToMasterPath, use_latex_path,
167 result = subst_path(result, "$$AbsOrRelPathParent",
168 relToParentPath, use_latex_path,
177 result = subst_path(result, "$$FName", filename, use_latex_path,
179 result = subst_path(result, "$$Basename", basename, use_latex_path,
180 PROTECT_EXTENSION, ESCAPE_DOTS);
181 result = subst_path(result, "$$Extension",
182 '.' + getExtension(filename), use_latex_path);
183 result = subst_path(result, "$$Tempname", params.tempname().absFileName(), use_latex_path);
184 result = subst_path(result, "$$Sysdir",
185 package().system_support().absFileName(), use_latex_path);
187 // Handle the $$Contents(filename) syntax
188 if (contains(result, "$$Contents(\"")) {
189 // Since use_latex_path may be true we must extract the file
190 // name from s instead of result and do the substitutions
191 // again, this time with use_latex_path false.
192 size_t const spos = s.find("$$Contents(\"");
193 size_t const send = s.find("\")", spos);
194 string const file_template = s.substr(spos + 12, send - (spos + 12));
195 string const file = doSubstitution(params, buffer,
196 file_template, false,
197 external_in_tmpdir, what);
200 FileName const absfile(
201 makeAbsPath(file, masterBuffer->temppath()));
202 if (absfile.isReadableFile())
204 contents = to_utf8(absfile.fileContents("UTF-8"));
206 size_t const pos = result.find("$$Contents(\"");
207 size_t const end = result.find("\")", pos);
208 result.replace(pos, end + 2- pos, contents);
217 /** update the file represented by the template.
218 If \p external_in_tmpdir == true, then the generated file is
219 placed in the buffer's temporary directory.
221 RetVal updateExternal(InsetExternalParams const & params,
222 string const & format,
223 Buffer const & buffer,
224 ExportData & exportdata,
225 bool external_in_tmpdir,
228 Template const * const et_ptr = getTemplatePtr(params);
231 Template const & et = *et_ptr;
233 if (!et.automaticProduction)
236 Template::Formats::const_iterator cit = et.formats.find(format);
237 if (cit == et.formats.end())
240 Template::Format const & outputFormat = cit->second;
241 if (outputFormat.updateResult.empty())
244 string from_format = et.inputFormat;
245 if (from_format.empty())
248 if (from_format == "*") {
249 if (params.filename.empty())
252 // Try and ascertain the file format from its contents.
253 from_format = theFormats().getFormatFromFile(params.filename);
254 if (from_format.empty())
258 string const to_format = doSubstitution(params, buffer,
259 outputFormat.updateFormat, false, external_in_tmpdir, FORMATS);
260 if (to_format.empty())
263 // The master buffer. This is useful when there are multiple levels
265 Buffer const * masterBuffer = buffer.masterBuffer();
267 // We copy the source file to the temp dir and do the conversion
268 // there if necessary
269 bool const isDir = params.filename.isDirectory();
270 FileName const temp_file(
271 makeAbsPath(params.filename.mangledFileName(),
272 masterBuffer->temppath()));
273 if (!params.filename.empty() && !isDir) {
274 unsigned long const from_checksum = params.filename.checksum();
275 unsigned long const temp_checksum = temp_file.checksum();
277 if (from_checksum != temp_checksum) {
278 Mover const & mover = getMover(from_format);
279 if (!mover.copy(params.filename, temp_file)) {
280 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
281 << "Unable to copy " << params.filename << " to " << temp_file);
287 // the generated file (always in the temp dir)
288 string const to_file = doSubstitution(params, buffer,
289 outputFormat.updateResult,
291 FileName const abs_to_file(
292 makeAbsPath(to_file, masterBuffer->temppath()));
295 // Record the referenced files for the exporter.
296 // The exporter will copy them to the export dir.
297 typedef Template::Format::FileMap FileMap;
298 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
299 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
300 for (; rit != rend; ++rit) {
301 vector<string>::const_iterator fit = rit->second.begin();
302 vector<string>::const_iterator fend = rit->second.end();
303 for (; fit != fend; ++fit) {
304 FileName const source(makeAbsPath(
305 doSubstitution(params, buffer, *fit,
307 masterBuffer->temppath()));
308 // The path of the referenced file is never the
309 // temp path, but the filename may be the mangled
310 // or the real name. Therefore we substitute the
311 // paths and names separately.
312 string file = subst(*fit, "$$FName",
313 "$$FPath$$Basename$$Extension");
314 file = doSubstitution(params, buffer, file, false, false,
316 file = doSubstitution(params, buffer, file,
317 false, external_in_tmpdir,
319 // if file is a relative name, it is interpreted
320 // relative to the master document.
321 if (makeAbsPath(file, masterBuffer->filePath()) !=
322 params.filename.absFileName())
323 exportdata.addExternalFile(rit->first, source, file);
328 // Do we need to perform the conversion?
329 // Yes if to_file does not exist or if from_file is newer than to_file
330 // or if from_file is a directory (bug 9925)
331 if (!isDir && compare_timestamps(temp_file, abs_to_file) < 0)
334 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
336 Converters::RetVal const success =
337 theConverters().convert(&buffer, temp_file, abs_to_file,
338 params.filename, from_format, to_format, el,
339 Converters::try_default | Converters::try_cache);
341 case Converters::SUCCESS:
343 case Converters::FAILURE:
344 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
345 << "Unable to convert from " << from_format << " to " << to_format);
347 case Converters::KILLED:
355 string const substituteCommands(InsetExternalParams const & params,
356 string const & input, string const & format);
358 string const substituteOptions(InsetExternalParams const & params,
359 string const & input, string const & format);
364 RetVal writeExternal(InsetExternalParams const & params,
365 string const & format,
366 Buffer const & buffer, otexstream & os,
367 ExportData & exportdata,
368 bool external_in_tmpdir,
371 Template const * const et_ptr = getTemplatePtr(params);
374 Template const & et = *et_ptr;
376 Template::Formats::const_iterator cit = et.formats.find(format);
377 if (cit == et.formats.end()) {
378 LYXERR(Debug::EXTERNAL, "External template format '" << format
379 << "' not specified in template " << params.templatename());
383 if (!dryrun || contains(cit->second.product, "$$Contents")) {
384 RetVal const success =
385 updateExternal(params, format, buffer, exportdata,
386 external_in_tmpdir, dryrun);
387 if (success == FAILURE || success == KILLED)
391 bool const use_latex_path = format == "LaTeX";
392 string str = doSubstitution(params, buffer, cit->second.product,
393 use_latex_path, external_in_tmpdir);
395 string const absname = makeAbsPath(
396 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
398 if (!dryrun && !external_in_tmpdir) {
399 if (!isValidLaTeXFileName(absname)) {
400 lyx::frontend::Alert::warning(_("Invalid filename"),
401 _("The following filename will cause troubles "
402 "when running the exported file through LaTeX: ") +
405 if (!isValidDVIFileName(absname)) {
406 lyx::frontend::Alert::warning(_("Problematic filename for DVI"),
407 _("The following filename can cause troubles "
408 "when running the exported file through LaTeX "
409 "and opening the resulting DVI: ") +
410 from_utf8(absname), true);
414 str = substituteCommands(params, str, format);
415 str = substituteOptions(params, str, format);
417 os << from_utf8(str);
423 // Empty template, specialised below.
424 template <typename TransformType>
425 string const substituteIt(string const &,
428 Template::Format const &,
429 InsetExternalParams const &);
433 string const substituteIt<TransformCommand>(string const & input,
435 string const & /* formatname */,
436 Template::Format const & format,
437 InsetExternalParams const & params)
439 typedef map<TransformID, TransformStore> Transformers;
440 Transformers::const_iterator it = format.command_transformers.find(id);
441 if (it == format.command_transformers.end())
444 TransformStore const & store = it->second;
446 TransformCommand::ptr_type ptr;
448 ptr = store.getCommandTransformer(params.rotationdata);
449 else if (id == Resize)
450 ptr = store.getCommandTransformer(params.resizedata);
456 subst(input, ptr->front_placeholder(), ptr->front());
457 return subst(result, ptr->back_placeholder(), ptr->back());
462 string const substituteIt<TransformOption>(string const & input,
464 string const & fname,
465 Template::Format const & format,
466 InsetExternalParams const & params)
468 typedef map<TransformID, TransformStore> Transformers;
469 Transformers::const_iterator it = format.option_transformers.find(id);
470 if (it == format.option_transformers.end())
473 TransformStore const & store = it->second;
475 TransformOption::ptr_type ptr;
478 ptr = store.getOptionTransformer(params.clipdata);
481 ptr = store.getOptionTransformer(params.extradata.get(fname));
484 ptr = store.getOptionTransformer(params.rotationdata);
487 ptr = store.getOptionTransformer(params.resizedata);
496 return subst(input, ptr->placeholder(), ptr->option());
500 template <typename TransformerType>
501 string const transformIt(InsetExternalParams const & params,
502 string const & s, string const & formatname)
504 Template const * const et = getTemplatePtr(params);
505 if (!et || et->transformIds.empty())
508 Template::Formats::const_iterator fit = et->formats.find(formatname);
509 if (fit == et->formats.end())
513 Template::Format const & format = fit->second;
515 typedef vector<TransformID> TransformsIDs;
516 TransformsIDs::const_iterator it = et->transformIds.begin();
517 TransformsIDs::const_iterator end = et->transformIds.end();
518 for (; it != end; ++it) {
519 result = substituteIt<TransformerType>(result, *it, formatname,
526 string const substituteCommands(InsetExternalParams const & params,
527 string const & input, string const & format)
529 return transformIt<TransformCommand>(params, input, format);
533 string const substituteOption(InsetExternalParams const & params,
534 string const & input, string const & format)
536 string opt = transformIt<TransformOption>(params, input, format);
538 if (format == "LaTeX" || format == "PDFLaTeX")
539 return sanitizeLatexOption(opt);
540 if (format == "DocBook")
541 return sanitizeDocBookOption(opt);
546 string const substituteOptions(InsetExternalParams const & params,
547 string const & input, string const & format)
549 string output = input;
551 Template const * const et = getTemplatePtr(params);
552 if (!et || et->transformIds.empty())
555 Template::Formats::const_iterator fit = et->formats.find(format);
556 if (fit == et->formats.end() || fit->second.options.empty())
559 typedef vector<Template::Option> Options;
560 Options const & options = fit->second.options;
561 Options::const_iterator it = options.begin();
562 Options::const_iterator end = options.end();
563 for (; it != end; ++it) {
564 string const opt = substituteOption(params, it->option, format);
565 string const placeholder = "$$" + it->name;
566 output = subst(output, placeholder, opt);
574 } // namespace external