]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
The package reworking.
[lyx.git] / src / insets / ExternalSupport.C
1 /**
2  * \file ExternalSupport.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup Nielsen
7  * \author Angus Leeming
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "ExternalSupport.h"
15 #include "ExternalTemplate.h"
16 #include "ExternalTransforms.h"
17 #include "insetexternal.h"
18
19 #include "buffer.h"
20 #include "converter.h"
21 #include "debug.h"
22 #include "exporter.h"
23 #include "format.h"
24 #include "mover.h"
25
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"
33
34 #include "support/std_ostream.h"
35
36 namespace support = lyx::support;
37
38 using std::endl;
39
40 using std::ostream;
41 using std::string;
42 using std::vector;
43
44
45 namespace lyx {
46 namespace external {
47
48 Template const * getTemplatePtr(InsetExternalParams const & params)
49 {
50         TemplateManager const & etm = TemplateManager::get();
51         return etm.getTemplateByName(params.templatename());
52 }
53
54
55 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
56 {
57         string const file_with_path = params.filename.absFilename();
58         formats.edit(buffer, file_with_path,
59                      formats.getFormatFromFile(file_with_path));
60 }
61
62
63 string const doSubstitution(InsetExternalParams const & params,
64                             Buffer const & buffer, string const & s,
65                             bool external_in_tmpdir)
66 {
67         Buffer const * m_buffer = buffer.getMasterBuffer();
68         string const parentpath = external_in_tmpdir ?
69                 m_buffer->temppath() :
70                 buffer.filePath();
71         string const filename = external_in_tmpdir ?
72                 params.filename.mangledFilename() :
73                 params.filename.outputFilename(parentpath);
74         string result;
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() :
82                 m_buffer->filePath();
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();
91
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",
102                                         abspath);
103                 result = support::subst(result, "$$AbsOrRelPathParent",
104                                         abspath);
105         } else {
106                 result = support::subst(result, "$$AbsOrRelPathMaster",
107                                         relToMasterPath);
108                 result = support::subst(result, "$$AbsOrRelPathParent",
109                                         relToParentPath);
110         }
111         result = support::subst(result, "$$Tempname", params.tempname());
112         result = support::subst(result, "$$Sysdir",
113                                 support::package().system_support());
114
115         // Handle the $$Contents(filename) syntax
116         if (support::contains(result, "$$Contents(\"")) {
117
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));
121                 string contents;
122
123                 string const filepath = support::IsFileReadable(file) ?
124                         buffer.filePath() : m_buffer->temppath();
125                 support::Path p(filepath);
126
127                 if (support::IsFileReadable(file))
128                         contents = support::GetFileContents(file);
129
130                 result = support::subst(result,
131                                         ("$$Contents(\"" + file + "\")").c_str(),
132                                         contents);
133         }
134
135         return result;
136 }
137
138
139 namespace {
140
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.
144 */
145 void updateExternal(InsetExternalParams const & params,
146                     string const & format,
147                     Buffer const & buffer,
148                     ExportData & exportdata,
149                     bool external_in_tmpdir)
150 {
151         Template const * const et_ptr = getTemplatePtr(params);
152         if (!et_ptr)
153                 return; // FAILURE
154         Template const & et = *et_ptr;
155
156         if (!et.automaticProduction)
157                 return; // NOT_NEEDED
158
159         Template::Formats::const_iterator cit = et.formats.find(format);
160         if (cit == et.formats.end())
161                 return; // FAILURE
162
163         Template::Format const & outputFormat = cit->second;
164         if (outputFormat.updateResult.empty())
165                 return; // NOT_NEEDED
166
167         string from_format = et.inputFormat;
168         if (from_format.empty())
169                 return; // NOT_NEEDED
170
171         string abs_from_file = params.filename.absFilename();
172
173         if (from_format == "*") {
174                 if (abs_from_file.empty())
175                         return; // NOT_NEEDED
176
177                 // Try and ascertain the file format from its contents.
178                 from_format = formats.getFormatFromFile(abs_from_file);
179                 if (from_format.empty())
180                         return; // FAILURE
181
182         }
183
184         string const to_format = outputFormat.updateFormat;
185         if (to_format.empty())
186                 return; // NOT_NEEDED
187
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;
193                 return; // FAILURE
194         }
195
196         // The master buffer. This is useful when there are multiple levels
197         // of include files
198         Buffer const * m_buffer = buffer.getMasterBuffer();
199
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);
208
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. "
214                                         << "Unable to copy "
215                                         << abs_from_file << " to " << temp_file << endl;
216                                 return; // FAILURE
217                         }
218                 }
219         }
220
221         // the generated file (always in the temp dir)
222         string const to_file = doSubstitution(params, buffer,
223                                               outputFormat.updateResult,
224                                               true);
225         string const abs_to_file =
226                 support::MakeAbsPath(to_file, m_buffer->temppath());
227
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,
239                                                        true),
240                                         m_buffer->temppath());
241                         string const file = doSubstitution(params, buffer,
242                                                            *fit,
243                                                            external_in_tmpdir);
244                         // if file is a relative name, it is interpreted
245                         // relative to the master document.
246                         exportdata.addExternalFile(rit->first, source, file);
247                 }
248         }
249
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)
253                 return; // SUCCESS
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);
259         // return success
260 }
261
262
263 string const substituteCommands(InsetExternalParams const & params,
264                                 string const & input, string const & format);
265
266 string const substituteOptions(InsetExternalParams const & params,
267                                string const & input, string const & format);
268
269 } // namespace anon
270
271
272 int writeExternal(InsetExternalParams const & params,
273                   string const & format,
274                   Buffer const & buffer, ostream & os,
275                   ExportData & exportdata,
276                   bool external_in_tmpdir)
277 {
278         Template const * const et_ptr = getTemplatePtr(params);
279         if (!et_ptr)
280                 return 0;
281         Template const & et = *et_ptr;
282
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;
289                 return 0;
290         }
291
292         updateExternal(params, format, buffer, exportdata, external_in_tmpdir);
293
294         string str = doSubstitution(params, buffer, cit->second.product,
295                                     external_in_tmpdir);
296         str = substituteCommands(params, str, format);
297         str = substituteOptions(params, str, format);
298         os << str;
299         return int(lyx::count(str.begin(), str.end(),'\n') + 1);
300 }
301
302 namespace {
303
304 // Empty template, specialised below.
305 template <typename TransformType>
306 string const substituteIt(string const &,
307                           TransformID,
308                           string const &,
309                           Template::Format const &,
310                           InsetExternalParams const &);
311
312
313 template <>
314 string const substituteIt<TransformCommand>(string const & input,
315                                             TransformID id,
316                                             string const & /* formatname */,
317                                             Template::Format const & format,
318                                             InsetExternalParams const & params)
319 {
320         typedef std::map<TransformID, TransformStore> Transformers;
321         Transformers::const_iterator it = format.command_transformers.find(id);
322         if (it == format.command_transformers.end())
323                 return input;
324
325         TransformStore const & store = it->second;
326
327         TransformCommand::ptr_type ptr;
328         if (id == Rotate)
329                 ptr = store.getCommandTransformer(params.rotationdata);
330         else if (id == Resize)
331                 ptr = store.getCommandTransformer(params.resizedata);
332
333         if (!ptr.get())
334                 return input;
335
336         string result =
337                 support::subst(input, ptr->front_placeholder(), ptr->front());
338         return support::subst(result, ptr->back_placeholder(),  ptr->back());
339 }
340
341
342 template <>
343 string const substituteIt<TransformOption>(string const & input,
344                                            TransformID id,
345                                            string const & fname,
346                                            Template::Format const & format,
347                                            InsetExternalParams const & params)
348 {
349         typedef std::map<TransformID, TransformStore> Transformers;
350         Transformers::const_iterator it = format.option_transformers.find(id);
351         if (it == format.option_transformers.end())
352                 return input;
353
354         TransformStore const & store = it->second;
355
356         TransformOption::ptr_type ptr;
357         switch (id) {
358         case Clip:
359                 ptr = store.getOptionTransformer(params.clipdata);
360                 break;
361         case Extra:
362                 ptr = store.getOptionTransformer(params.extradata.get(fname));
363                 break;
364         case Rotate:
365                 ptr = store.getOptionTransformer(params.rotationdata);
366                 break;
367         case Resize:
368                 ptr = store.getOptionTransformer(params.resizedata);
369                 break;
370         }
371
372         if (!ptr.get())
373                 return input;
374
375         return support::subst(input, ptr->placeholder(), ptr->option());
376 }
377
378
379 template <typename TransformerType>
380 string const transformIt(InsetExternalParams const & params,
381                          string const & s, string const & formatname)
382 {
383         Template const * const et = getTemplatePtr(params);
384         if (!et || et->transformIds.empty())
385                 return s;
386
387         Template::Formats::const_iterator fit = et->formats.find(formatname);
388         if (fit == et->formats.end())
389                 return s;
390
391         string result = s;
392         Template::Format const & format =  fit->second;
393
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,
399                                                        format, params);
400         }
401         return result;
402 }
403
404
405 string const substituteCommands(InsetExternalParams const & params,
406                                 string const & input, string const & format)
407 {
408         return transformIt<TransformCommand>(params, input, format);
409 }
410
411
412 string const substituteOption(InsetExternalParams const & params,
413                               string const & input, string const & format)
414 {
415         string opt = transformIt<TransformOption>(params, input, format);
416
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);
423         return opt;
424 }
425
426
427 string const substituteOptions(InsetExternalParams const & params,
428                                string const & input, string const & format)
429 {
430         string output = input;
431
432         Template const * const et = getTemplatePtr(params);
433         if (!et || et->transformIds.empty())
434                 return output;
435
436         Template::Formats::const_iterator fit = et->formats.find(format);
437         if (fit == et->formats.end() || fit->second.options.empty())
438                 return output;
439
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);
448         }
449
450         return output;
451  }
452
453 } // namespace anon
454
455 } // namespace external
456 } // namespace lyx