]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
Fix bug 3240
[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/os.h"
32 #include "support/package.h"
33
34 #include <boost/filesystem/operations.hpp>
35
36 using std::endl;
37 using std::string;
38 using std::vector;
39
40 using boost::filesystem::is_directory;
41
42
43 namespace lyx {
44
45 using support::FileName;
46
47 namespace external {
48
49 Template const * getTemplatePtr(InsetExternalParams const & params)
50 {
51         TemplateManager const & etm = TemplateManager::get();
52         return etm.getTemplateByName(params.templatename());
53 }
54
55
56 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
57 {
58         formats.edit(buffer, params.filename,
59                      formats.getFormatFromFile(params.filename));
60 }
61
62
63 namespace {
64
65 string const subst_path(string const & input,
66                         string const & placeholder,
67                         string const & path,
68                         bool use_latex_path,
69                         support::latex_path_extension ext = support::PROTECT_EXTENSION,
70                         support::latex_path_dots dots = support::LEAVE_DOTS)
71 {
72         if (input.find(placeholder) == string::npos)
73                 return input;
74         // Don't use external_path here when use_latex_path is false, as the
75         // path will be compared with another one in internal style later
76         // in Converters::move.
77         string const path2 = use_latex_path ?
78                 support::latex_path(path, ext, dots) : path;
79         return support::subst(input, placeholder, path2);
80 }
81
82 } // namespace anon
83
84
85 string const doSubstitution(InsetExternalParams const & params,
86                             Buffer const & buffer, string const & s,
87                             bool use_latex_path,
88                             bool external_in_tmpdir,
89                             Substitute what)
90 {
91         Buffer const * m_buffer = buffer.getMasterBuffer();
92         string const parentpath = external_in_tmpdir ?
93                 m_buffer->temppath() :
94                 buffer.filePath();
95         string const filename = external_in_tmpdir ?
96                 params.filename.mangledFilename() :
97                 params.filename.outputFilename(parentpath);
98         string const basename = support::changeExtension(
99                         support::onlyFilename(filename), string());
100         string const absname = support::makeAbsPath(filename, parentpath).absFilename();
101
102         string result = s;
103         if (what != ALL_BUT_PATHS) {
104                 string const filepath = support::onlyPath(filename);
105                 string const abspath = support::onlyPath(absname);
106                 string const masterpath = external_in_tmpdir ?
107                         m_buffer->temppath() :
108                         m_buffer->filePath();
109                 string relToMasterPath = support::onlyPath(
110                                 support::makeRelPath(absname, masterpath));
111                 if (relToMasterPath == "./")
112                         relToMasterPath.clear();
113                 string relToParentPath = support::onlyPath(
114                                 support::makeRelPath(absname, parentpath));
115                 if (relToParentPath == "./")
116                         relToParentPath.clear();
117
118                 result = subst_path(result, "$$FPath", filepath,
119                                     use_latex_path,
120                                     support::PROTECT_EXTENSION,
121                                     support::ESCAPE_DOTS);
122                 result = subst_path(result, "$$AbsPath", abspath,
123                                     use_latex_path,
124                                     support::PROTECT_EXTENSION,
125                                     support::ESCAPE_DOTS);
126                 result = subst_path(result, "$$RelPathMaster",
127                                     relToMasterPath, use_latex_path,
128                                     support::PROTECT_EXTENSION,
129                                     support::ESCAPE_DOTS);
130                 result = subst_path(result, "$$RelPathParent",
131                                     relToParentPath, use_latex_path,
132                                     support::PROTECT_EXTENSION,
133                                     support::ESCAPE_DOTS);
134                 if (support::absolutePath(filename)) {
135                         result = subst_path(result, "$$AbsOrRelPathMaster",
136                                             abspath, use_latex_path,
137                                             support::PROTECT_EXTENSION,
138                                             support::ESCAPE_DOTS);
139                         result = subst_path(result, "$$AbsOrRelPathParent",
140                                             abspath, use_latex_path,
141                                             support::PROTECT_EXTENSION,
142                                             support::ESCAPE_DOTS);
143                 } else {
144                         result = subst_path(result, "$$AbsOrRelPathMaster",
145                                             relToMasterPath, use_latex_path,
146                                             support::PROTECT_EXTENSION,
147                                             support::ESCAPE_DOTS);
148                         result = subst_path(result, "$$AbsOrRelPathParent",
149                                             relToParentPath, use_latex_path,
150                                             support::PROTECT_EXTENSION,
151                                             support::ESCAPE_DOTS);
152                 }
153         }
154
155         if (what == PATHS)
156                 return result;
157
158         result = subst_path(result, "$$FName", filename, use_latex_path,
159                             support::EXCLUDE_EXTENSION);
160         result = subst_path(result, "$$Basename", basename, use_latex_path,
161                             support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
162         result = subst_path(result, "$$Extension",
163                         '.' + support::getExtension(filename), use_latex_path);
164         result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
165         result = subst_path(result, "$$Sysdir",
166                                 support::package().system_support(), use_latex_path);
167
168         // Handle the $$Contents(filename) syntax
169         if (support::contains(result, "$$Contents(\"")) {
170
171                 string::size_type const pos = result.find("$$Contents(\"");
172                 string::size_type const end = result.find("\")", pos);
173                 string const file = result.substr(pos + 12, end - (pos + 12));
174                 string contents;
175
176                 FileName const absfile(
177                         support::makeAbsPath(file, m_buffer->temppath()));
178                 if (support::isFileReadable(absfile))
179                         contents = support::getFileContents(absfile);
180
181                 result = support::subst(result,
182                                         ("$$Contents(\"" + file + "\")").c_str(),
183                                         contents);
184         }
185
186         return result;
187 }
188
189
190 namespace {
191
192 /** update the file represented by the template.
193     If \p external_in_tmpdir == true, then the generated file is
194     placed in the buffer's temporary directory.
195 */
196 void updateExternal(InsetExternalParams const & params,
197                     string const & format,
198                     Buffer const & buffer,
199                     ExportData & exportdata,
200                     bool external_in_tmpdir,
201                     bool dryrun)
202 {
203         Template const * const et_ptr = getTemplatePtr(params);
204         if (!et_ptr)
205                 return; // FAILURE
206         Template const & et = *et_ptr;
207
208         if (!et.automaticProduction)
209                 return; // NOT_NEEDED
210
211         Template::Formats::const_iterator cit = et.formats.find(format);
212         if (cit == et.formats.end())
213                 return; // FAILURE
214
215         Template::Format const & outputFormat = cit->second;
216         if (outputFormat.updateResult.empty())
217                 return; // NOT_NEEDED
218
219         string from_format = et.inputFormat;
220         if (from_format.empty())
221                 return; // NOT_NEEDED
222
223         if (from_format == "*") {
224                 if (params.filename.empty())
225                         return; // NOT_NEEDED
226
227                 // Try and ascertain the file format from its contents.
228                 from_format = formats.getFormatFromFile(params.filename);
229                 if (from_format.empty())
230                         return; // FAILURE
231
232         }
233
234         string const to_format = outputFormat.updateFormat;
235         if (to_format.empty())
236                 return; // NOT_NEEDED
237
238         if (!theConverters().isReachable(from_format, to_format)) {
239                 lyxerr[Debug::EXTERNAL]
240                         << "external::updateExternal. "
241                         << "Unable to convert from "
242                         << from_format << " to " << to_format << endl;
243                 return; // FAILURE
244         }
245
246         // The master buffer. This is useful when there are multiple levels
247         // of include files
248         Buffer const * m_buffer = buffer.getMasterBuffer();
249
250         // We copy the source file to the temp dir and do the conversion
251         // there if necessary
252         FileName const temp_file(
253                 support::makeAbsPath(params.filename.mangledFilename(),
254                                      m_buffer->temppath()));
255         if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
256                 unsigned long const from_checksum = support::sum(params.filename);
257                 unsigned long const temp_checksum = support::sum(temp_file);
258
259                 if (from_checksum != temp_checksum) {
260                         Mover const & mover = getMover(from_format);
261                         if (!mover.copy(params.filename, temp_file)) {
262                                 lyxerr[Debug::EXTERNAL]
263                                         << "external::updateExternal. "
264                                         << "Unable to copy "
265                                         << params.filename << " to " << temp_file << endl;
266                                 return; // FAILURE
267                         }
268                 }
269         }
270
271         // the generated file (always in the temp dir)
272         string const to_file = doSubstitution(params, buffer,
273                                               outputFormat.updateResult,
274                                               false, true);
275         FileName const abs_to_file(
276                 support::makeAbsPath(to_file, m_buffer->temppath()));
277
278         if (!dryrun) {
279                 // Record the referenced files for the exporter.
280                 // The exporter will copy them to the export dir.
281                 typedef Template::Format::FileMap FileMap;
282                 FileMap::const_iterator rit  = outputFormat.referencedFiles.begin();
283                 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
284                 for (; rit != rend; ++rit) {
285                         vector<string>::const_iterator fit  = rit->second.begin();
286                         vector<string>::const_iterator fend = rit->second.end();
287                         for (; fit != fend; ++fit) {
288                                 FileName const source(support::makeAbsPath(
289                                                 doSubstitution(params, buffer, *fit,
290                                                                false, true),
291                                                 m_buffer->temppath()));
292                                 // The path of the referenced file is never the
293                                 // temp path, but the filename may be the mangled
294                                 // or the real name. Therefore we substitute the
295                                 // paths and names separately.
296                                 string file = support::subst(*fit, "$$FName",
297                                                 "$$FPath$$Basename$$Extension");
298                                 file = doSubstitution(params, buffer, file, false, false,
299                                                       PATHS);
300                                 file = doSubstitution(params, buffer, file,
301                                                       false, external_in_tmpdir,
302                                                       ALL_BUT_PATHS);
303                                 // if file is a relative name, it is interpreted
304                                 // relative to the master document.
305                                 exportdata.addExternalFile(rit->first, source, file);
306                         }
307                 }
308         }
309
310         // Do we need to perform the conversion?
311         // Yes if to_file does not exist or if from_file is newer than to_file
312         if (support::compare_timestamps(temp_file, abs_to_file) < 0)
313                 return; // SUCCESS
314
315         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
316         ErrorList el;
317         /* bool const success = */
318                 theConverters().convert(&buffer, temp_file, abs_to_file,
319                                    params.filename, from_format, to_format, el,
320                                    Converters::try_default | Converters::try_cache);
321         // return success
322 }
323
324
325 string const substituteCommands(InsetExternalParams const & params,
326                                 string const & input, string const & format);
327
328 string const substituteOptions(InsetExternalParams const & params,
329                                string const & input, string const & format);
330
331 } // namespace anon
332
333
334 int writeExternal(InsetExternalParams const & params,
335                   string const & format,
336                   Buffer const & buffer, odocstream & os,
337                   ExportData & exportdata,
338                   bool external_in_tmpdir,
339                   bool dryrun)
340 {
341         Template const * const et_ptr = getTemplatePtr(params);
342         if (!et_ptr)
343                 return 0;
344         Template const & et = *et_ptr;
345
346         Template::Formats::const_iterator cit = et.formats.find(format);
347         if (cit == et.formats.end()) {
348                 lyxerr[Debug::EXTERNAL]
349                         << "External template format '" << format
350                         << "' not specified in template "
351                         << params.templatename() << endl;
352                 return 0;
353         }
354
355         if (!dryrun || support::contains(cit->second.product, "$$Contents"))
356                 updateExternal(params, format, buffer, exportdata,
357                                external_in_tmpdir, dryrun);
358
359         bool const use_latex_path = format == "LaTeX";
360         string str = doSubstitution(params, buffer, cit->second.product,
361                                     use_latex_path, external_in_tmpdir);
362         str = substituteCommands(params, str, format);
363         str = substituteOptions(params, str, format);
364         // FIXME UNICODE
365         os << from_utf8(str);
366         return int(lyx::count(str.begin(), str.end(),'\n'));
367 }
368
369 namespace {
370
371 // Empty template, specialised below.
372 template <typename TransformType>
373 string const substituteIt(string const &,
374                           TransformID,
375                           string const &,
376                           Template::Format const &,
377                           InsetExternalParams const &);
378
379
380 template <>
381 string const substituteIt<TransformCommand>(string const & input,
382                                             TransformID id,
383                                             string const & /* formatname */,
384                                             Template::Format const & format,
385                                             InsetExternalParams const & params)
386 {
387         typedef std::map<TransformID, TransformStore> Transformers;
388         Transformers::const_iterator it = format.command_transformers.find(id);
389         if (it == format.command_transformers.end())
390                 return input;
391
392         TransformStore const & store = it->second;
393
394         TransformCommand::ptr_type ptr;
395         if (id == Rotate)
396                 ptr = store.getCommandTransformer(params.rotationdata);
397         else if (id == Resize)
398                 ptr = store.getCommandTransformer(params.resizedata);
399
400         if (!ptr.get())
401                 return input;
402
403         string result =
404                 support::subst(input, ptr->front_placeholder(), ptr->front());
405         return support::subst(result, ptr->back_placeholder(),  ptr->back());
406 }
407
408
409 template <>
410 string const substituteIt<TransformOption>(string const & input,
411                                            TransformID id,
412                                            string const & fname,
413                                            Template::Format const & format,
414                                            InsetExternalParams const & params)
415 {
416         typedef std::map<TransformID, TransformStore> Transformers;
417         Transformers::const_iterator it = format.option_transformers.find(id);
418         if (it == format.option_transformers.end())
419                 return input;
420
421         TransformStore const & store = it->second;
422
423         TransformOption::ptr_type ptr;
424         switch (id) {
425         case Clip:
426                 ptr = store.getOptionTransformer(params.clipdata);
427                 break;
428         case Extra:
429                 ptr = store.getOptionTransformer(params.extradata.get(fname));
430                 break;
431         case Rotate:
432                 ptr = store.getOptionTransformer(params.rotationdata);
433                 break;
434         case Resize:
435                 ptr = store.getOptionTransformer(params.resizedata);
436                 break;
437         }
438
439         if (!ptr.get())
440                 return input;
441
442         return support::subst(input, ptr->placeholder(), ptr->option());
443 }
444
445
446 template <typename TransformerType>
447 string const transformIt(InsetExternalParams const & params,
448                          string const & s, string const & formatname)
449 {
450         Template const * const et = getTemplatePtr(params);
451         if (!et || et->transformIds.empty())
452                 return s;
453
454         Template::Formats::const_iterator fit = et->formats.find(formatname);
455         if (fit == et->formats.end())
456                 return s;
457
458         string result = s;
459         Template::Format const & format =  fit->second;
460
461         typedef vector<TransformID> TransformsIDs;
462         TransformsIDs::const_iterator it  = et->transformIds.begin();
463         TransformsIDs::const_iterator end = et->transformIds.end();
464         for (; it != end; ++it) {
465                 result = substituteIt<TransformerType>(result, *it, formatname,
466                                                        format, params);
467         }
468         return result;
469 }
470
471
472 string const substituteCommands(InsetExternalParams const & params,
473                                 string const & input, string const & format)
474 {
475         return transformIt<TransformCommand>(params, input, format);
476 }
477
478
479 string const substituteOption(InsetExternalParams const & params,
480                               string const & input, string const & format)
481 {
482         string opt = transformIt<TransformOption>(params, input, format);
483
484         if (format == "LaTeX" || format == "PDFLaTeX")
485                 return sanitizeLatexOption(opt);
486         if (format == "DocBook")
487                 return sanitizeDocBookOption(opt);
488         return opt;
489 }
490
491
492 string const substituteOptions(InsetExternalParams const & params,
493                                string const & input, string const & format)
494 {
495         string output = input;
496
497         Template const * const et = getTemplatePtr(params);
498         if (!et || et->transformIds.empty())
499                 return output;
500
501         Template::Formats::const_iterator fit = et->formats.find(format);
502         if (fit == et->formats.end() || fit->second.options.empty())
503                 return output;
504
505         typedef vector<Template::Option> Options;
506         Options const & options = fit->second.options;
507         Options::const_iterator it  = options.begin();
508         Options::const_iterator end = options.end();
509         for (; it != end; ++it) {
510                 string const opt = substituteOption(params, it->option, format);
511                 string const placeholder = "$$" + it->name;
512                 output = support::subst(output, placeholder, opt);
513         }
514
515         return output;
516 }
517
518 } // namespace anon
519
520 } // namespace external
521
522 } // namespace lyx