2 * \file ExternalSupport.C
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"
26 #include "support/filetools.h"
27 #include "support/forkedcall.h"
28 #include "support/lstrings.h"
29 #include "support/lyxalgo.h"
30 #include "support/lyxlib.h"
31 #include "support/package.h"
32 #include "support/path.h"
34 #include "support/std_ostream.h"
36 namespace support = lyx::support;
48 Template const * getTemplatePtr(InsetExternalParams const & params)
50 TemplateManager const & etm = TemplateManager::get();
51 return etm.getTemplateByName(params.templatename());
55 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
57 string const file_with_path = params.filename.absFilename();
58 formats.edit(buffer, file_with_path,
59 formats.getFormatFromFile(file_with_path));
63 string const doSubstitution(InsetExternalParams const & params,
64 Buffer const & buffer, string const & s,
65 bool external_in_tmpdir)
67 Buffer const * m_buffer = buffer.getMasterBuffer();
68 string const parentpath = external_in_tmpdir ?
69 m_buffer->temppath() :
71 string const filename = external_in_tmpdir ?
72 params.filename.mangledFilename() :
73 params.filename.outputFilename(parentpath);
75 string const basename = support::ChangeExtension(
76 support::OnlyFilename(filename), string());
77 string const absname = support::MakeAbsPath(filename, parentpath);
78 string const filepath = support::OnlyPath(filename);
79 string const abspath = support::OnlyPath(absname);
80 string const masterpath = external_in_tmpdir ?
81 m_buffer->temppath() :
83 string relToMasterPath = support::OnlyPath(
84 support::MakeRelPath(absname, masterpath));
85 if (relToMasterPath == "./")
86 relToMasterPath.clear();
87 string relToParentPath = support::OnlyPath(
88 support::MakeRelPath(absname, parentpath));
89 if (relToParentPath == "./")
90 relToParentPath.clear();
92 result = support::subst(s, "$$FName", filename);
93 result = support::subst(result, "$$Basename", basename);
94 result = support::subst(result, "$$Extension",
95 '.' + support::GetExtension(filename));
96 result = support::subst(result, "$$FPath", filepath);
97 result = support::subst(result, "$$AbsPath", abspath);
98 result = support::subst(result, "$$RelPathMaster", relToMasterPath);
99 result = support::subst(result, "$$RelPathParent", relToParentPath);
100 if (support::AbsolutePath(filename)) {
101 result = support::subst(result, "$$AbsOrRelPathMaster",
103 result = support::subst(result, "$$AbsOrRelPathParent",
106 result = support::subst(result, "$$AbsOrRelPathMaster",
108 result = support::subst(result, "$$AbsOrRelPathParent",
111 result = support::subst(result, "$$Tempname", params.tempname());
112 result = support::subst(result, "$$Sysdir",
113 support::package().system_support());
115 // Handle the $$Contents(filename) syntax
116 if (support::contains(result, "$$Contents(\"")) {
118 string::size_type const pos = result.find("$$Contents(\"");
119 string::size_type const end = result.find("\")", pos);
120 string const file = result.substr(pos + 12, end - (pos + 12));
123 string const filepath = support::IsFileReadable(file) ?
124 buffer.filePath() : m_buffer->temppath();
125 support::Path p(filepath);
127 if (support::IsFileReadable(file))
128 contents = support::GetFileContents(file);
130 result = support::subst(result,
131 ("$$Contents(\"" + file + "\")").c_str(),
141 /** update the file represented by the template.
142 If \param external_in_tmpdir == true, then the generated file is
143 place in the buffer's temporary directory.
145 void updateExternal(InsetExternalParams const & params,
146 string const & format,
147 Buffer const & buffer,
148 ExportData & exportdata,
149 bool external_in_tmpdir)
151 Template const * const et_ptr = getTemplatePtr(params);
154 Template const & et = *et_ptr;
156 if (!et.automaticProduction)
157 return; // NOT_NEEDED
159 Template::Formats::const_iterator cit = et.formats.find(format);
160 if (cit == et.formats.end())
163 Template::Format const & outputFormat = cit->second;
164 if (outputFormat.updateResult.empty())
165 return; // NOT_NEEDED
167 string from_format = et.inputFormat;
168 if (from_format.empty())
169 return; // NOT_NEEDED
171 string abs_from_file = params.filename.absFilename();
173 if (from_format == "*") {
174 if (abs_from_file.empty())
175 return; // NOT_NEEDED
177 // Try and ascertain the file format from its contents.
178 from_format = formats.getFormatFromFile(abs_from_file);
179 if (from_format.empty())
184 string const to_format = outputFormat.updateFormat;
185 if (to_format.empty())
186 return; // NOT_NEEDED
188 if (!converters.isReachable(from_format, to_format)) {
189 lyxerr[Debug::EXTERNAL]
190 << "external::updateExternal. "
191 << "Unable to convert from "
192 << from_format << " to " << to_format << endl;
196 // The master buffer. This is useful when there are multiple levels
198 Buffer const * m_buffer = buffer.getMasterBuffer();
200 // We copy the source file to the temp dir and do the conversion
201 // there if necessary
202 string const temp_file =
203 support::MakeAbsPath(params.filename.mangledFilename(),
204 m_buffer->temppath());
205 if (!abs_from_file.empty()) {
206 unsigned long const from_checksum = support::sum(abs_from_file);
207 unsigned long const temp_checksum = support::sum(temp_file);
209 if (from_checksum != temp_checksum) {
210 Mover const & mover = movers(from_format);
211 if (!mover.copy(abs_from_file, temp_file)) {
212 lyxerr[Debug::EXTERNAL]
213 << "external::updateExternal. "
215 << abs_from_file << " to " << temp_file << endl;
221 // the generated file (always in the temp dir)
222 string const to_file = doSubstitution(params, buffer,
223 outputFormat.updateResult,
225 string const abs_to_file =
226 support::MakeAbsPath(to_file, m_buffer->temppath());
228 // Record the referenced files for the exporter.
229 // The exporter will copy them to the export dir.
230 typedef Template::Format::FileMap FileMap;
231 FileMap::const_iterator rit = outputFormat.referencedFiles.begin();
232 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
233 for (; rit != rend; ++rit) {
234 vector<string>::const_iterator fit = rit->second.begin();
235 vector<string>::const_iterator fend = rit->second.end();
236 for (; fit != fend; ++fit) {
237 string const source = support::MakeAbsPath(
238 doSubstitution(params, buffer, *fit,
240 m_buffer->temppath());
241 string const file = doSubstitution(params, buffer,
244 // if file is a relative name, it is interpreted
245 // relative to the master document.
246 exportdata.addExternalFile(rit->first, source, file);
250 // Do we need to perform the conversion?
251 // Yes if to_file does not exist or if from_file is newer than to_file
252 if (support::compare_timestamps(temp_file, abs_to_file) < 0)
254 string const to_file_base =
255 support::ChangeExtension(to_file, string());
256 /* bool const success = */
257 converters.convert(&buffer, temp_file, to_file_base,
258 from_format, to_format);
263 string const substituteCommands(InsetExternalParams const & params,
264 string const & input, string const & format);
266 string const substituteOptions(InsetExternalParams const & params,
267 string const & input, string const & format);
272 int writeExternal(InsetExternalParams const & params,
273 string const & format,
274 Buffer const & buffer, ostream & os,
275 ExportData & exportdata,
276 bool external_in_tmpdir)
278 Template const * const et_ptr = getTemplatePtr(params);
281 Template const & et = *et_ptr;
283 Template::Formats::const_iterator cit = et.formats.find(format);
284 if (cit == et.formats.end()) {
285 lyxerr[Debug::EXTERNAL]
286 << "External template format '" << format
287 << "' not specified in template "
288 << params.templatename() << endl;
292 updateExternal(params, format, buffer, exportdata, external_in_tmpdir);
294 string str = doSubstitution(params, buffer, cit->second.product,
296 str = substituteCommands(params, str, format);
297 str = substituteOptions(params, str, format);
299 return int(lyx::count(str.begin(), str.end(),'\n') + 1);
304 // Empty template, specialised below.
305 template <typename TransformType>
306 string const substituteIt(string const &,
309 Template::Format const &,
310 InsetExternalParams const &);
314 string const substituteIt<TransformCommand>(string const & input,
316 string const & /* formatname */,
317 Template::Format const & format,
318 InsetExternalParams const & params)
320 typedef std::map<TransformID, TransformStore> Transformers;
321 Transformers::const_iterator it = format.command_transformers.find(id);
322 if (it == format.command_transformers.end())
325 TransformStore const & store = it->second;
327 TransformCommand::ptr_type ptr;
329 ptr = store.getCommandTransformer(params.rotationdata);
330 else if (id == Resize)
331 ptr = store.getCommandTransformer(params.resizedata);
337 support::subst(input, ptr->front_placeholder(), ptr->front());
338 return support::subst(result, ptr->back_placeholder(), ptr->back());
343 string const substituteIt<TransformOption>(string const & input,
345 string const & fname,
346 Template::Format const & format,
347 InsetExternalParams const & params)
349 typedef std::map<TransformID, TransformStore> Transformers;
350 Transformers::const_iterator it = format.option_transformers.find(id);
351 if (it == format.option_transformers.end())
354 TransformStore const & store = it->second;
356 TransformOption::ptr_type ptr;
359 ptr = store.getOptionTransformer(params.clipdata);
362 ptr = store.getOptionTransformer(params.extradata.get(fname));
365 ptr = store.getOptionTransformer(params.rotationdata);
368 ptr = store.getOptionTransformer(params.resizedata);
375 return support::subst(input, ptr->placeholder(), ptr->option());
379 template <typename TransformerType>
380 string const transformIt(InsetExternalParams const & params,
381 string const & s, string const & formatname)
383 Template const * const et = getTemplatePtr(params);
384 if (!et || et->transformIds.empty())
387 Template::Formats::const_iterator fit = et->formats.find(formatname);
388 if (fit == et->formats.end())
392 Template::Format const & format = fit->second;
394 typedef vector<TransformID> TransformsIDs;
395 TransformsIDs::const_iterator it = et->transformIds.begin();
396 TransformsIDs::const_iterator end = et->transformIds.end();
397 for (; it != end; ++it) {
398 result = substituteIt<TransformerType>(result, *it, formatname,
405 string const substituteCommands(InsetExternalParams const & params,
406 string const & input, string const & format)
408 return transformIt<TransformCommand>(params, input, format);
412 string const substituteOption(InsetExternalParams const & params,
413 string const & input, string const & format)
415 string opt = transformIt<TransformOption>(params, input, format);
417 if (format == "LaTeX" || format == "PDFLaTeX")
418 return sanitizeLatexOption(opt);
419 if (format == "DocBook")
420 return sanitizeDocBookOption(opt);
421 if (format == "LinuxDoc")
422 return sanitizeLinuxDocOption(opt);
427 string const substituteOptions(InsetExternalParams const & params,
428 string const & input, string const & format)
430 string output = input;
432 Template const * const et = getTemplatePtr(params);
433 if (!et || et->transformIds.empty())
436 Template::Formats::const_iterator fit = et->formats.find(format);
437 if (fit == et->formats.end() || fit->second.options.empty())
440 typedef vector<Template::Option> Options;
441 Options const & options = fit->second.options;
442 Options::const_iterator it = options.begin();
443 Options::const_iterator end = options.end();
444 for (; it != end; ++it) {
445 string const opt = substituteOption(params, it->option, format);
446 string const placeholder = "$$" + it->name;
447 output = support::subst(output, placeholder, opt);
455 } // namespace external