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/lyxalgo.h"
34 #include "support/os.h"
35 #include "support/Package.h"
40 using namespace lyx::support;
45 Template const * getTemplatePtr(InsetExternalParams const & params)
47 TemplateManager const & etm = TemplateManager::get();
48 return etm.getTemplateByName(params.templatename());
52 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
54 theFormats().edit(buffer, params.filename,
55 theFormats().getFormatFromFile(params.filename));
61 string const subst_path(string const & input,
62 string const & placeholder,
65 latex_path_extension ext = PROTECT_EXTENSION,
66 latex_path_dots dots = LEAVE_DOTS)
68 if (input.find(placeholder) == string::npos)
70 // Don't use external_path here when use_latex_path is false, as the
71 // path will be compared with another one in internal style later
72 // in Converters::move.
73 string const path2 = use_latex_path ?
74 latex_path(path, ext, dots) : path;
75 return subst(input, placeholder, path2);
81 string const doSubstitution(InsetExternalParams const & params,
82 Buffer const & buffer, string const & s,
84 bool external_in_tmpdir,
88 if (what != PATHS && contains(result, "$$pngOrjpg")) {
89 // This is for raster images and pdflatex:
90 // Since pdflatex supports both jpg and png, we choose the best format:
91 // jpg if the original file is jpg to retain the compression, else png.
92 string format = theFormats().getFormatFromFile(params.filename);
94 result = subst(result, "$$pngOrjpg", "jpg");
96 result = subst(result, "$$pngOrjpg", "png");
102 Buffer const * masterBuffer = buffer.masterBuffer();
103 string const parentpath = external_in_tmpdir ?
104 masterBuffer->temppath() :
106 string const filename = external_in_tmpdir ?
107 params.filename.mangledFileName() :
108 params.filename.outputFileName(parentpath);
109 string const basename = changeExtension(
110 onlyFileName(filename), string());
111 string const absname = makeAbsPath(filename, parentpath).absFileName();
113 if (what != ALL_BUT_PATHS) {
114 string const filepath = onlyPath(filename);
115 string const abspath = onlyPath(absname);
116 string const masterpath = external_in_tmpdir ?
117 masterBuffer->temppath() :
118 masterBuffer->filePath();
120 string relToMasterPath = onlyPath(
121 to_utf8(makeRelPath(from_utf8(absname),
122 from_utf8(masterpath))));
123 if (relToMasterPath == "./")
124 relToMasterPath.clear();
126 string relToParentPath = onlyPath(
127 to_utf8(makeRelPath(from_utf8(absname),
128 from_utf8(parentpath))));
129 if (relToParentPath == "./")
130 relToParentPath.clear();
132 result = subst_path(result, "$$FPath", filepath,
136 result = subst_path(result, "$$AbsPath", abspath,
140 result = subst_path(result, "$$RelPathMaster",
141 relToMasterPath, use_latex_path,
144 result = subst_path(result, "$$RelPathParent",
145 relToParentPath, use_latex_path,
148 if (FileName::isAbsolute(filename)) {
149 result = subst_path(result, "$$AbsOrRelPathMaster",
150 abspath, use_latex_path,
153 result = subst_path(result, "$$AbsOrRelPathParent",
154 abspath, use_latex_path,
158 result = subst_path(result, "$$AbsOrRelPathMaster",
159 relToMasterPath, use_latex_path,
162 result = subst_path(result, "$$AbsOrRelPathParent",
163 relToParentPath, use_latex_path,
172 result = subst_path(result, "$$FName", filename, use_latex_path,
174 result = subst_path(result, "$$Basename", basename, use_latex_path,
175 PROTECT_EXTENSION, ESCAPE_DOTS);
176 result = subst_path(result, "$$Extension",
177 '.' + getExtension(filename), use_latex_path);
178 result = subst_path(result, "$$Tempname", params.tempname().absFileName(), use_latex_path);
179 result = subst_path(result, "$$Sysdir",
180 package().system_support().absFileName(), use_latex_path);
182 // Handle the $$Contents(filename) syntax
183 if (contains(result, "$$Contents(\"")) {
184 // Since use_latex_path may be true we must extract the file
185 // name from s instead of result and do the substitutions
186 // again, this time with use_latex_path false.
187 size_t const spos = s.find("$$Contents(\"");
188 size_t const send = s.find("\")", spos);
189 string const file_template = s.substr(spos + 12, send - (spos + 12));
190 string const file = doSubstitution(params, buffer,
191 file_template, false,
192 external_in_tmpdir, what);
195 FileName const absfile(
196 makeAbsPath(file, masterBuffer->temppath()));
197 if (absfile.isReadableFile())
199 contents = to_utf8(absfile.fileContents("UTF-8"));
201 size_t const pos = result.find("$$Contents(\"");
202 size_t const end = result.find("\")", pos);
203 result.replace(pos, end + 2- pos, contents);
212 /** update the file represented by the template.
213 If \p external_in_tmpdir == true, then the generated file is
214 placed in the buffer's temporary directory.
216 RetVal updateExternal(InsetExternalParams const & params,
217 string const & format,
218 Buffer const & buffer,
219 ExportData & exportdata,
220 bool external_in_tmpdir,
223 Template const * const et_ptr = getTemplatePtr(params);
226 Template const & et = *et_ptr;
228 if (!et.automaticProduction)
231 Template::Formats::const_iterator cit = et.formats.find(format);
232 if (cit == et.formats.end())
235 Template::Format const & outputFormat = cit->second;
236 if (outputFormat.updateResult.empty())
239 string from_format = et.inputFormat;
240 if (from_format.empty())
243 if (from_format == "*") {
244 if (params.filename.empty())
247 // Try and ascertain the file format from its contents.
248 from_format = theFormats().getFormatFromFile(params.filename);
249 if (from_format.empty())
253 string const to_format = doSubstitution(params, buffer,
254 outputFormat.updateFormat, false, external_in_tmpdir, FORMATS);
255 if (to_format.empty())
258 // The master buffer. This is useful when there are multiple levels
260 Buffer const * masterBuffer = buffer.masterBuffer();
262 // We copy the source file to the temp dir and do the conversion
263 // there if necessary
264 bool const isDir = params.filename.isDirectory();
265 FileName const temp_file(
266 makeAbsPath(params.filename.mangledFileName(),
267 masterBuffer->temppath()));
268 if (!params.filename.empty() && !isDir) {
269 unsigned long const from_checksum = params.filename.checksum();
270 unsigned long const temp_checksum = temp_file.checksum();
272 if (from_checksum != temp_checksum) {
273 Mover const & mover = getMover(from_format);
274 if (!mover.copy(params.filename, temp_file)) {
275 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
276 << "Unable to copy " << params.filename << " to " << temp_file);
282 // the generated file (always in the temp dir)
283 string const to_file = doSubstitution(params, buffer,
284 outputFormat.updateResult,
286 FileName const abs_to_file(
287 makeAbsPath(to_file, masterBuffer->temppath()));
290 // Record the referenced files for the exporter.
291 // The exporter will copy them to the export dir.
292 typedef Template::Format::FileMap FileMap;
293 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
294 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
295 for (; rit != rend; ++rit) {
296 vector<string>::const_iterator fit = rit->second.begin();
297 vector<string>::const_iterator fend = rit->second.end();
298 for (; fit != fend; ++fit) {
299 FileName const source(makeAbsPath(
300 doSubstitution(params, buffer, *fit,
302 masterBuffer->temppath()));
303 // The path of the referenced file is never the
304 // temp path, but the filename may be the mangled
305 // or the real name. Therefore we substitute the
306 // paths and names separately.
307 string file = subst(*fit, "$$FName",
308 "$$FPath$$Basename$$Extension");
309 file = doSubstitution(params, buffer, file, false, false,
311 file = doSubstitution(params, buffer, file,
312 false, external_in_tmpdir,
314 // if file is a relative name, it is interpreted
315 // relative to the master document.
316 if (makeAbsPath(file, masterBuffer->filePath()) !=
317 params.filename.absFileName())
318 exportdata.addExternalFile(rit->first, source, file);
323 // Do we need to perform the conversion?
324 // Yes if to_file does not exist or if from_file is newer than to_file
325 // or if from_file is a directory (bug 9925)
326 if (!isDir && compare_timestamps(temp_file, abs_to_file) < 0)
329 // FIXME (Abdel 12/08/06): Is there a need to show these errors?
331 Converters::RetVal const success =
332 theConverters().convert(&buffer, temp_file, abs_to_file,
333 params.filename, from_format, to_format, el,
334 Converters::try_default | Converters::try_cache);
336 case Converters::SUCCESS:
338 case Converters::FAILURE:
339 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
340 << "Unable to convert from " << from_format << " to " << to_format);
342 case Converters::KILLED:
350 string const substituteCommands(InsetExternalParams const & params,
351 string const & input, string const & format);
353 string const substituteOptions(InsetExternalParams const & params,
354 string const & input, string const & format);
359 RetVal writeExternal(InsetExternalParams const & params,
360 string const & format,
361 Buffer const & buffer, otexstream & os,
362 ExportData & exportdata,
363 bool external_in_tmpdir,
366 Template const * const et_ptr = getTemplatePtr(params);
369 Template const & et = *et_ptr;
371 Template::Formats::const_iterator cit = et.formats.find(format);
372 if (cit == et.formats.end()) {
373 LYXERR(Debug::EXTERNAL, "External template format '" << format
374 << "' not specified in template " << params.templatename());
378 if (!dryrun || contains(cit->second.product, "$$Contents")) {
379 RetVal const success =
380 updateExternal(params, format, buffer, exportdata,
381 external_in_tmpdir, dryrun);
382 if (success == FAILURE || success == KILLED)
386 bool const use_latex_path = format == "LaTeX";
387 string str = doSubstitution(params, buffer, cit->second.product,
388 use_latex_path, external_in_tmpdir);
390 string const absname = makeAbsPath(
391 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
393 if (!dryrun && !external_in_tmpdir) {
394 if (!isValidLaTeXFileName(absname)) {
395 lyx::frontend::Alert::warning(_("Invalid filename"),
396 _("The following filename will cause troubles "
397 "when running the exported file through LaTeX: ") +
400 if (!isValidDVIFileName(absname)) {
401 lyx::frontend::Alert::warning(_("Problematic filename for DVI"),
402 _("The following filename can cause troubles "
403 "when running the exported file through LaTeX "
404 "and opening the resulting DVI: ") +
405 from_utf8(absname), true);
409 str = substituteCommands(params, str, format);
410 str = substituteOptions(params, str, format);
412 os << from_utf8(str);
418 // Empty template, specialised below.
419 template <typename TransformType>
420 string const substituteIt(string const &,
423 Template::Format const &,
424 InsetExternalParams const &);
428 string const substituteIt<TransformCommand>(string const & input,
430 string const & /* formatname */,
431 Template::Format const & format,
432 InsetExternalParams const & params)
434 typedef map<TransformID, TransformStore> Transformers;
435 Transformers::const_iterator it = format.command_transformers.find(id);
436 if (it == format.command_transformers.end())
439 TransformStore const & store = it->second;
441 TransformCommand::ptr_type ptr;
443 ptr = store.getCommandTransformer(params.rotationdata);
444 else if (id == Resize)
445 ptr = store.getCommandTransformer(params.resizedata);
451 subst(input, ptr->front_placeholder(), ptr->front());
452 return subst(result, ptr->back_placeholder(), ptr->back());
457 string const substituteIt<TransformOption>(string const & input,
459 string const & fname,
460 Template::Format const & format,
461 InsetExternalParams const & params)
463 typedef map<TransformID, TransformStore> Transformers;
464 Transformers::const_iterator it = format.option_transformers.find(id);
465 if (it == format.option_transformers.end())
468 TransformStore const & store = it->second;
470 TransformOption::ptr_type ptr;
473 ptr = store.getOptionTransformer(params.clipdata);
476 ptr = store.getOptionTransformer(params.extradata.get(fname));
479 ptr = store.getOptionTransformer(params.rotationdata);
482 ptr = store.getOptionTransformer(params.resizedata);
489 return subst(input, ptr->placeholder(), ptr->option());
493 template <typename TransformerType>
494 string const transformIt(InsetExternalParams const & params,
495 string const & s, string const & formatname)
497 Template const * const et = getTemplatePtr(params);
498 if (!et || et->transformIds.empty())
501 Template::Formats::const_iterator fit = et->formats.find(formatname);
502 if (fit == et->formats.end())
506 Template::Format const & format = fit->second;
508 typedef vector<TransformID> TransformsIDs;
509 TransformsIDs::const_iterator it = et->transformIds.begin();
510 TransformsIDs::const_iterator end = et->transformIds.end();
511 for (; it != end; ++it) {
512 result = substituteIt<TransformerType>(result, *it, formatname,
519 string const substituteCommands(InsetExternalParams const & params,
520 string const & input, string const & format)
522 return transformIt<TransformCommand>(params, input, format);
526 string const substituteOption(InsetExternalParams const & params,
527 string const & input, string const & format)
529 string opt = transformIt<TransformOption>(params, input, format);
531 if (format == "LaTeX" || format == "PDFLaTeX")
532 return sanitizeLatexOption(opt);
533 if (format == "DocBook")
534 return sanitizeDocBookOption(opt);
539 string const substituteOptions(InsetExternalParams const & params,
540 string const & input, string const & format)
542 string output = input;
544 Template const * const et = getTemplatePtr(params);
545 if (!et || et->transformIds.empty())
548 Template::Formats::const_iterator fit = et->formats.find(format);
549 if (fit == et->formats.end() || fit->second.options.empty())
552 typedef vector<Template::Option> Options;
553 Options const & options = fit->second.options;
554 Options::const_iterator it = options.begin();
555 Options::const_iterator end = options.end();
556 for (; it != end; ++it) {
557 string const opt = substituteOption(params, it->option, format);
558 string const placeholder = "$$" + it->name;
559 output = subst(output, placeholder, opt);
567 } // namespace external