]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
ws changes only
[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
23 #include "support/filetools.h"
24 #include "support/forkedcall.h"
25 #include "support/lstrings.h"
26 #include "support/lyxalgo.h"
27 #include "support/lyxlib.h"
28 #include "support/path.h"
29 #include "support/path_defines.h"
30
31 #include "support/std_ostream.h"
32
33 namespace support = lyx::support;
34
35 using std::endl;
36
37 using std::ostream;
38 using std::string;
39 using std::vector;
40
41
42 namespace lyx {
43 namespace external {
44
45 Template const * getTemplatePtr(InsetExternalParams const & params)
46 {
47         TemplateManager const & etm = TemplateManager::get();
48         return etm.getTemplateByName(params.templatename());
49 }
50
51
52 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
53 {
54         Template const * const et_ptr = getTemplatePtr(params);
55         if (!et_ptr)
56                 return;
57         Template const & et = *et_ptr;
58
59         if (et.editCommand.empty())
60                 return;
61
62         string const command = doSubstitution(params, buffer, et.editCommand);
63
64         support::Path p(buffer.filePath());
65         support::Forkedcall call;
66         if (lyxerr.debugging(Debug::EXTERNAL)) {
67                 lyxerr << "Executing '" << command << "' in '"
68                        << buffer.filePath() << '\'' << endl;
69         }
70         call.startscript(support::Forkedcall::DontWait, command);
71 }
72
73
74 namespace {
75
76 string const doSubstitution(InsetExternalParams const & params,
77                             Buffer const & buffer, string const & s,
78                             string const & filename)
79 {
80         string result;
81         string const basename = support::ChangeExtension(filename, string());
82         string const filepath = support::OnlyPath(filename);
83
84         result = support::subst(s, "$$FName", filename);
85         result = support::subst(result, "$$Basename", basename);
86         result = support::subst(result, "$$FPath", filepath);
87         result = support::subst(result, "$$Tempname", params.tempname());
88         result = support::subst(result, "$$Sysdir", support::system_lyxdir());
89
90         // Handle the $$Contents(filename) syntax
91         if (support::contains(result, "$$Contents(\"")) {
92
93                 string::size_type const pos = result.find("$$Contents(\"");
94                 string::size_type const end = result.find("\")", pos);
95                 string const file = result.substr(pos + 12, end - (pos + 12));
96                 string contents;
97
98                 string const filepath = support::IsFileReadable(file) ?
99                         buffer.filePath() : buffer.temppath();
100                 support::Path p(filepath);
101
102                 if (support::IsFileReadable(file))
103                         contents = support::GetFileContents(file);
104
105                 result = support::subst(result,
106                                         ("$$Contents(\"" + file + "\")").c_str(),
107                                         contents);
108         }
109
110         return result;
111 }
112
113 /** update the file represented by the template.
114     If \param external_in_tmpdir == true, then the generated file is
115     place in the buffer's temporary directory.
116 */
117 void updateExternal(InsetExternalParams const & params,
118                     string const & format,
119                     Buffer const & buffer,
120                     bool external_in_tmpdir)
121 {
122         Template const * const et_ptr = getTemplatePtr(params);
123         if (!et_ptr)
124                 return; // FAILURE
125         Template const & et = *et_ptr;
126
127         if (!et.automaticProduction)
128                 return; // NOT_NEEDED
129
130         Template::Formats::const_iterator cit = et.formats.find(format);
131         if (cit == et.formats.end())
132                 return; // FAILURE
133
134         Template::Format const & outputFormat = cit->second;
135         if (outputFormat.updateResult.empty())
136                 return; // NOT_NEEDED
137
138         string from_format = et.inputFormat;
139         if (from_format.empty())
140                 return; // NOT_NEEDED
141
142         string from_file = params.filename.absFilename();
143
144         if (from_format == "*") {
145                 if (from_file.empty())
146                         return; // NOT_NEEDED
147
148                 // Try and ascertain the file format from its contents.
149                 from_format = support::getExtFromContents(from_file);
150                 if (from_format.empty())
151                         return; // FAILURE
152         }
153
154         string const to_format = outputFormat.updateFormat;
155         if (to_format.empty())
156                 return; // NOT_NEEDED
157
158         if (!converters.isReachable(from_format, to_format)) {
159                 lyxerr[Debug::EXTERNAL]
160                         << "external::updateExternal. "
161                         << "Unable to convert from "
162                         << from_format << " to " << to_format << endl;
163                 return; // FAILURE
164         }
165
166         if (external_in_tmpdir && !from_file.empty()) {
167                 // We are running stuff through LaTeX
168                 string const temp_file =
169                         support::MakeAbsPath(params.filename.mangledFilename(),
170                                              buffer.temppath());
171                 unsigned long const from_checksum = support::sum(from_file);
172                 unsigned long const temp_checksum = support::sum(temp_file);
173
174                 if (from_checksum != temp_checksum) {
175                         if (!support::copy(from_file, temp_file))
176                                 return; // FAILURE
177                 }
178
179                 from_file = temp_file;
180         }
181
182         string const to_file = doSubstitution(params, buffer,
183                                               outputFormat.updateResult,
184                                               from_file);
185
186         string const abs_to_file =
187                 support::MakeAbsPath(to_file, buffer.filePath());
188
189         // Do we need to perform the conversion?
190         // Yes if to_file does not exist or if from_file is newer than to_file
191         if (support::compare_timestamps(from_file, abs_to_file) < 0)
192                 return; // SUCCESS
193
194         string const to_file_base =
195                 support::ChangeExtension(to_file, string());
196         /* bool const success = */
197                 converters.convert(&buffer, from_file, to_file_base,
198                                    from_format, to_format);
199         // return success
200 }
201
202
203 string const substituteCommands(InsetExternalParams const & params,
204                                 string const & input, string const & format);
205
206 string const substituteOptions(InsetExternalParams const & params,
207                                string const & input, string const & format);
208
209 } // namespace anon
210
211
212 int writeExternal(InsetExternalParams const & params,
213                   string const & format,
214                   Buffer const & buffer, ostream & os,
215                   bool external_in_tmpdir)
216 {
217         Template const * const et_ptr = getTemplatePtr(params);
218         if (!et_ptr)
219                 return 0;
220         Template const & et = *et_ptr;
221
222         Template::Formats::const_iterator cit = et.formats.find(format);
223         if (cit == et.formats.end()) {
224                 lyxerr[Debug::EXTERNAL]
225                         << "External template format '" << format
226                         << "' not specified in template "
227                         << params.templatename() << endl;
228                 return 0;
229         }
230
231         updateExternal(params, format, buffer, external_in_tmpdir);
232
233         string from_file = params.filename.outputFilename(buffer.filePath());
234         if (external_in_tmpdir && !from_file.empty()) {
235                 // We are running stuff through LaTeX
236                 from_file =
237                         support::MakeAbsPath(params.filename.mangledFilename(),
238                                              buffer.temppath());
239         }
240
241         string str = doSubstitution(params, buffer, cit->second.product,
242                                     from_file);
243         str = substituteCommands(params, str, format);
244         str = substituteOptions(params, str, format);
245         os << str;
246         return int(lyx::count(str.begin(), str.end(),'\n') + 1);
247 }
248
249
250 /// Substitute meta-variables in this string
251 string const doSubstitution(InsetExternalParams const & params,
252                             Buffer const & buffer, string const & s)
253 {
254         string const buffer_path = buffer.filePath();
255         string const filename = params.filename.outputFilename(buffer_path);
256         return doSubstitution(params, buffer, s, filename);
257 }
258
259 namespace {
260
261 // Empty template, specialised below.
262 template <typename TransformType>
263 string const substituteIt(string const &,
264                           TransformID,
265                           string const &,
266                           Template::Format const &,
267                           InsetExternalParams const &);
268
269
270 template <>
271 string const substituteIt<TransformCommand>(string const & input,
272                                             TransformID id,
273                                             string const & /* formatname */,
274                                             Template::Format const & format,
275                                             InsetExternalParams const & params)
276 {
277         typedef std::map<TransformID, TransformStore> Transformers;
278         Transformers::const_iterator it = format.command_transformers.find(id);
279         if (it == format.command_transformers.end())
280                 return input;
281
282         TransformStore const & store = it->second;
283
284         TransformCommand::ptr_type ptr;
285         if (id == Rotate)
286                 ptr = store.getCommandTransformer(params.rotationdata);
287         else if (id == Resize)
288                 ptr = store.getCommandTransformer(params.resizedata);
289
290         if (!ptr.get())
291                 return input;
292
293         string result =
294                 support::subst(input, ptr->front_placeholder(), ptr->front());
295         return support::subst(result, ptr->back_placeholder(),  ptr->back());
296 }
297
298
299 template <>
300 string const substituteIt<TransformOption>(string const & input,
301                                            TransformID id,
302                                            string const & fname,
303                                            Template::Format const & format,
304                                            InsetExternalParams const & params)
305 {
306         typedef std::map<TransformID, TransformStore> Transformers;
307         Transformers::const_iterator it = format.option_transformers.find(id);
308         if (it == format.option_transformers.end())
309                 return input;
310
311         TransformStore const & store = it->second;
312
313         TransformOption::ptr_type ptr;
314         switch (id) {
315         case Clip:
316                 ptr = store.getOptionTransformer(params.clipdata);
317                 break;
318         case Extra:
319                 ptr = store.getOptionTransformer(params.extradata.get(fname));
320                 break;
321         case Rotate:
322                 ptr = store.getOptionTransformer(params.rotationdata);
323                 break;
324         case Resize:
325                 ptr = store.getOptionTransformer(params.resizedata);
326                 break;
327         }
328
329         if (!ptr.get())
330                 return input;
331
332         return support::subst(input, ptr->placeholder(), ptr->option());
333 }
334
335
336 template <typename TransformerType>
337 string const transformIt(InsetExternalParams const & params,
338                          string const & s, string const & formatname)
339 {
340         Template const * const et = getTemplatePtr(params);
341         if (!et || et->transformIds.empty())
342                 return s;
343
344         Template::Formats::const_iterator fit = et->formats.find(formatname);
345         if (fit == et->formats.end())
346                 return s;
347
348         string result = s;
349         Template::Format const & format =  fit->second;
350
351         typedef vector<TransformID> TransformsIDs;
352         TransformsIDs::const_iterator it  = et->transformIds.begin();
353         TransformsIDs::const_iterator end = et->transformIds.end();
354         for (; it != end; ++it) {
355                 result = substituteIt<TransformerType>(result, *it, formatname,
356                                                        format, params);
357         }
358         return result;
359 }
360
361
362 string const substituteCommands(InsetExternalParams const & params,
363                                 string const & input, string const & format)
364 {
365         return transformIt<TransformCommand>(params, input, format);
366 }
367
368
369 string const substituteOption(InsetExternalParams const & params,
370                               string const & input, string const & format)
371 {
372         string opt = transformIt<TransformOption>(params, input, format);
373
374         if (format == "LaTeX" || format == "PDFLaTeX")
375                 return sanitizeLatexOption(opt);
376         if (format == "DocBook")
377                 return sanitizeDocBookOption(opt);
378         if (format == "LinuxDoc")
379                 return sanitizeLinuxDocOption(opt);
380         return opt;
381 }
382
383
384 string const substituteOptions(InsetExternalParams const & params,
385                                string const & input, string const & format)
386 {
387         string output = input;
388
389         Template const * const et = getTemplatePtr(params);
390         if (!et || et->transformIds.empty())
391                 return output;
392
393         Template::Formats::const_iterator fit = et->formats.find(format);
394         if (fit == et->formats.end() || fit->second.options.empty())
395                 return output;
396
397         typedef vector<Template::Option> Options;
398         Options const & options = fit->second.options;
399         Options::const_iterator it  = options.begin();
400         Options::const_iterator end = options.end();
401         for (; it != end; ++it) {
402                 string const opt = substituteOption(params, it->option, format);
403                 string const placeholder = "$$" + it->name;
404                 output = support::subst(output, placeholder, opt);
405         }
406
407         return output;
408  }
409
410 } // namespace anon
411
412 } // namespace external
413 } // namespace lyx