]> git.lyx.org Git - features.git/blob - src/insets/ExternalSupport.cpp
lyxlib.h:sum -> FileName::checksum()
[features.git] / src / insets / ExternalSupport.cpp
1 /**
2  * \file ExternalSupport.cpp
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 "ErrorList.h"
22 #include "Exporter.h"
23 #include "Format.h"
24 #include "Mover.h"
25
26 #include "frontends/alert.h"
27
28 #include "support/debug.h"
29 #include "support/filetools.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/lyxalgo.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36
37 #include <algorithm>
38
39 using std::endl;
40 using std::string;
41 using std::vector;
42
43
44 namespace lyx {
45
46 using support::FileName;
47 using support::isValidLaTeXFilename;
48
49 namespace external {
50
51 Template const * getTemplatePtr(InsetExternalParams const & params)
52 {
53         TemplateManager const & etm = TemplateManager::get();
54         return etm.getTemplateByName(params.templatename());
55 }
56
57
58 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
59 {
60         formats.edit(buffer, params.filename,
61                      formats.getFormatFromFile(params.filename));
62 }
63
64
65 namespace {
66
67 string const subst_path(string const & input,
68                         string const & placeholder,
69                         string const & path,
70                         bool use_latex_path,
71                         support::latex_path_extension ext = support::PROTECT_EXTENSION,
72                         support::latex_path_dots dots = support::LEAVE_DOTS)
73 {
74         if (input.find(placeholder) == string::npos)
75                 return input;
76         // Don't use external_path here when use_latex_path is false, as the
77         // path will be compared with another one in internal style later
78         // in Converters::move.
79         string const path2 = use_latex_path ?
80                 support::latex_path(path, ext, dots) : path;
81         return support::subst(input, placeholder, path2);
82 }
83
84 } // namespace anon
85
86
87 string const doSubstitution(InsetExternalParams const & params,
88                             Buffer const & buffer, string const & s,
89                             bool use_latex_path,
90                             bool external_in_tmpdir,
91                             Substitute what)
92 {
93         Buffer const * masterBuffer = buffer.masterBuffer();
94         string const parentpath = external_in_tmpdir ?
95                 masterBuffer->temppath() :
96                 buffer.filePath();
97         string const filename = external_in_tmpdir ?
98                 params.filename.mangledFilename() :
99                 params.filename.outputFilename(parentpath);
100         string const basename = support::changeExtension(
101                         support::onlyFilename(filename), string());
102         string const absname = support::makeAbsPath(filename, parentpath).absFilename();
103
104         string result = s;
105         if (what != ALL_BUT_PATHS) {
106                 string const filepath = support::onlyPath(filename);
107                 string const abspath = support::onlyPath(absname);
108                 string const masterpath = external_in_tmpdir ?
109                         masterBuffer->temppath() :
110                         masterBuffer->filePath();
111                 // FIXME UNICODE
112                 string relToMasterPath = support::onlyPath(
113                                 to_utf8(support::makeRelPath(from_utf8(absname),
114                                                              from_utf8(masterpath))));
115                 if (relToMasterPath == "./")
116                         relToMasterPath.clear();
117                 // FIXME UNICODE
118                 string relToParentPath = support::onlyPath(
119                                 to_utf8(support::makeRelPath(from_utf8(absname),
120                                                              from_utf8(parentpath))));
121                 if (relToParentPath == "./")
122                         relToParentPath.clear();
123
124                 result = subst_path(result, "$$FPath", filepath,
125                                     use_latex_path,
126                                     support::PROTECT_EXTENSION,
127                                     support::ESCAPE_DOTS);
128                 result = subst_path(result, "$$AbsPath", abspath,
129                                     use_latex_path,
130                                     support::PROTECT_EXTENSION,
131                                     support::ESCAPE_DOTS);
132                 result = subst_path(result, "$$RelPathMaster",
133                                     relToMasterPath, use_latex_path,
134                                     support::PROTECT_EXTENSION,
135                                     support::ESCAPE_DOTS);
136                 result = subst_path(result, "$$RelPathParent",
137                                     relToParentPath, use_latex_path,
138                                     support::PROTECT_EXTENSION,
139                                     support::ESCAPE_DOTS);
140                 if (support::absolutePath(filename)) {
141                         result = subst_path(result, "$$AbsOrRelPathMaster",
142                                             abspath, use_latex_path,
143                                             support::PROTECT_EXTENSION,
144                                             support::ESCAPE_DOTS);
145                         result = subst_path(result, "$$AbsOrRelPathParent",
146                                             abspath, use_latex_path,
147                                             support::PROTECT_EXTENSION,
148                                             support::ESCAPE_DOTS);
149                 } else {
150                         result = subst_path(result, "$$AbsOrRelPathMaster",
151                                             relToMasterPath, use_latex_path,
152                                             support::PROTECT_EXTENSION,
153                                             support::ESCAPE_DOTS);
154                         result = subst_path(result, "$$AbsOrRelPathParent",
155                                             relToParentPath, use_latex_path,
156                                             support::PROTECT_EXTENSION,
157                                             support::ESCAPE_DOTS);
158                 }
159         }
160
161         if (what == PATHS)
162                 return result;
163
164         result = subst_path(result, "$$FName", filename, use_latex_path,
165                             support::EXCLUDE_EXTENSION);
166         result = subst_path(result, "$$Basename", basename, use_latex_path,
167                             support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
168         result = subst_path(result, "$$Extension",
169                         '.' + support::getExtension(filename), use_latex_path);
170         result = subst_path(result, "$$Tempname", params.tempname().absFilename(), use_latex_path);
171         result = subst_path(result, "$$Sysdir",
172                                 support::package().system_support().absFilename(), use_latex_path);
173
174         // Handle the $$Contents(filename) syntax
175         if (support::contains(result, "$$Contents(\"")) {
176                 // Since use_latex_path may be true we must extract the file
177                 // name from s instead of result and do the substitutions
178                 // again, this time with use_latex_path false.
179                 size_t const spos = s.find("$$Contents(\"");
180                 size_t const send = s.find("\")", spos);
181                 string const file_template = s.substr(spos + 12, send - (spos + 12));
182                 string const file = doSubstitution(params, buffer,
183                                                    file_template, false,
184                                                    external_in_tmpdir, what);
185                 string contents;
186
187                 FileName const absfile(
188                         support::makeAbsPath(file, masterBuffer->temppath()));
189                 if (absfile.isReadableFile())
190                         contents = absfile.fileContents();
191
192                 size_t const pos = result.find("$$Contents(\"");
193                 size_t const end = result.find("\")", pos);
194                 result.replace(pos, end + 2, contents);
195         }
196
197         return result;
198 }
199
200
201 namespace {
202
203 /** update the file represented by the template.
204     If \p external_in_tmpdir == true, then the generated file is
205     placed in the buffer's temporary directory.
206 */
207 void updateExternal(InsetExternalParams const & params,
208                     string const & format,
209                     Buffer const & buffer,
210                     ExportData & exportdata,
211                     bool external_in_tmpdir,
212                     bool dryrun)
213 {
214         Template const * const et_ptr = getTemplatePtr(params);
215         if (!et_ptr)
216                 return; // FAILURE
217         Template const & et = *et_ptr;
218
219         if (!et.automaticProduction)
220                 return; // NOT_NEEDED
221
222         Template::Formats::const_iterator cit = et.formats.find(format);
223         if (cit == et.formats.end())
224                 return; // FAILURE
225
226         Template::Format const & outputFormat = cit->second;
227         if (outputFormat.updateResult.empty())
228                 return; // NOT_NEEDED
229
230         string from_format = et.inputFormat;
231         if (from_format.empty())
232                 return; // NOT_NEEDED
233
234         if (from_format == "*") {
235                 if (params.filename.empty())
236                         return; // NOT_NEEDED
237
238                 // Try and ascertain the file format from its contents.
239                 from_format = formats.getFormatFromFile(params.filename);
240                 if (from_format.empty())
241                         return; // FAILURE
242         }
243
244         string const to_format = outputFormat.updateFormat;
245         if (to_format.empty())
246                 return; // NOT_NEEDED
247
248         // The master buffer. This is useful when there are multiple levels
249         // of include files
250         Buffer const * masterBuffer = buffer.masterBuffer();
251
252         // We copy the source file to the temp dir and do the conversion
253         // there if necessary
254         FileName const temp_file(
255                 support::makeAbsPath(params.filename.mangledFilename(),
256                                      masterBuffer->temppath()));
257         if (!params.filename.empty() && !params.filename.isDirectory()) {
258                 unsigned long const from_checksum = params.filename.checksum();
259                 unsigned long const temp_checksum = temp_file.checksum();
260
261                 if (from_checksum != temp_checksum) {
262                         Mover const & mover = getMover(from_format);
263                         if (!mover.copy(params.filename, temp_file)) {
264                                 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
265                                         << "Unable to copy " << params.filename << " to " << temp_file);
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, masterBuffer->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                                                 masterBuffer->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
322         if (!success) {
323                 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
324                         << "Unable to convert from " << from_format << " to " << to_format);
325         }
326
327         // return success
328 }
329
330
331 string const substituteCommands(InsetExternalParams const & params,
332                                 string const & input, string const & format);
333
334 string const substituteOptions(InsetExternalParams const & params,
335                                string const & input, string const & format);
336
337 } // namespace anon
338
339
340 int writeExternal(InsetExternalParams const & params,
341                   string const & format,
342                   Buffer const & buffer, odocstream & os,
343                   ExportData & exportdata,
344                   bool external_in_tmpdir,
345                   bool dryrun)
346 {
347         Template const * const et_ptr = getTemplatePtr(params);
348         if (!et_ptr)
349                 return 0;
350         Template const & et = *et_ptr;
351
352         Template::Formats::const_iterator cit = et.formats.find(format);
353         if (cit == et.formats.end()) {
354                 LYXERR(Debug::EXTERNAL, "External template format '" << format
355                         << "' not specified in template " << params.templatename());
356                 return 0;
357         }
358
359         if (!dryrun || support::contains(cit->second.product, "$$Contents"))
360                 updateExternal(params, format, buffer, exportdata,
361                                external_in_tmpdir, dryrun);
362
363         bool const use_latex_path = format == "LaTeX";
364         string str = doSubstitution(params, buffer, cit->second.product,
365                                     use_latex_path, external_in_tmpdir);
366
367         string const absname = support::makeAbsPath(
368                 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
369
370         if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
371                 lyx::frontend::Alert::warning(_("Invalid filename"),
372                                               _("The following filename is likely to cause trouble "
373                                                 "when running the exported file through LaTeX: ") +
374                                               from_utf8(absname));
375         }
376
377         str = substituteCommands(params, str, format);
378         str = substituteOptions(params, str, format);
379         // FIXME UNICODE
380         os << from_utf8(str);
381         return int(std::count(str.begin(), str.end(),'\n'));
382 }
383
384 namespace {
385
386 // Empty template, specialised below.
387 template <typename TransformType>
388 string const substituteIt(string const &,
389                           TransformID,
390                           string const &,
391                           Template::Format const &,
392                           InsetExternalParams const &);
393
394
395 template <>
396 string const substituteIt<TransformCommand>(string const & input,
397                                             TransformID id,
398                                             string const & /* formatname */,
399                                             Template::Format const & format,
400                                             InsetExternalParams const & params)
401 {
402         typedef std::map<TransformID, TransformStore> Transformers;
403         Transformers::const_iterator it = format.command_transformers.find(id);
404         if (it == format.command_transformers.end())
405                 return input;
406
407         TransformStore const & store = it->second;
408
409         TransformCommand::ptr_type ptr;
410         if (id == Rotate)
411                 ptr = store.getCommandTransformer(params.rotationdata);
412         else if (id == Resize)
413                 ptr = store.getCommandTransformer(params.resizedata);
414
415         if (!ptr.get())
416                 return input;
417
418         string result =
419                 support::subst(input, ptr->front_placeholder(), ptr->front());
420         return support::subst(result, ptr->back_placeholder(),  ptr->back());
421 }
422
423
424 template <>
425 string const substituteIt<TransformOption>(string const & input,
426                                            TransformID id,
427                                            string const & fname,
428                                            Template::Format const & format,
429                                            InsetExternalParams const & params)
430 {
431         typedef std::map<TransformID, TransformStore> Transformers;
432         Transformers::const_iterator it = format.option_transformers.find(id);
433         if (it == format.option_transformers.end())
434                 return input;
435
436         TransformStore const & store = it->second;
437
438         TransformOption::ptr_type ptr;
439         switch (id) {
440         case Clip:
441                 ptr = store.getOptionTransformer(params.clipdata);
442                 break;
443         case Extra:
444                 ptr = store.getOptionTransformer(params.extradata.get(fname));
445                 break;
446         case Rotate:
447                 ptr = store.getOptionTransformer(params.rotationdata);
448                 break;
449         case Resize:
450                 ptr = store.getOptionTransformer(params.resizedata);
451                 break;
452         }
453
454         if (!ptr.get())
455                 return input;
456
457         return support::subst(input, ptr->placeholder(), ptr->option());
458 }
459
460
461 template <typename TransformerType>
462 string const transformIt(InsetExternalParams const & params,
463                          string const & s, string const & formatname)
464 {
465         Template const * const et = getTemplatePtr(params);
466         if (!et || et->transformIds.empty())
467                 return s;
468
469         Template::Formats::const_iterator fit = et->formats.find(formatname);
470         if (fit == et->formats.end())
471                 return s;
472
473         string result = s;
474         Template::Format const & format =  fit->second;
475
476         typedef vector<TransformID> TransformsIDs;
477         TransformsIDs::const_iterator it  = et->transformIds.begin();
478         TransformsIDs::const_iterator end = et->transformIds.end();
479         for (; it != end; ++it) {
480                 result = substituteIt<TransformerType>(result, *it, formatname,
481                                                        format, params);
482         }
483         return result;
484 }
485
486
487 string const substituteCommands(InsetExternalParams const & params,
488                                 string const & input, string const & format)
489 {
490         return transformIt<TransformCommand>(params, input, format);
491 }
492
493
494 string const substituteOption(InsetExternalParams const & params,
495                               string const & input, string const & format)
496 {
497         string opt = transformIt<TransformOption>(params, input, format);
498
499         if (format == "LaTeX" || format == "PDFLaTeX")
500                 return sanitizeLatexOption(opt);
501         if (format == "DocBook")
502                 return sanitizeDocBookOption(opt);
503         return opt;
504 }
505
506
507 string const substituteOptions(InsetExternalParams const & params,
508                                string const & input, string const & format)
509 {
510         string output = input;
511
512         Template const * const et = getTemplatePtr(params);
513         if (!et || et->transformIds.empty())
514                 return output;
515
516         Template::Formats::const_iterator fit = et->formats.find(format);
517         if (fit == et->formats.end() || fit->second.options.empty())
518                 return output;
519
520         typedef vector<Template::Option> Options;
521         Options const & options = fit->second.options;
522         Options::const_iterator it  = options.begin();
523         Options::const_iterator end = options.end();
524         for (; it != end; ++it) {
525                 string const opt = substituteOption(params, it->option, format);
526                 string const placeholder = "$$" + it->name;
527                 output = support::subst(output, placeholder, opt);
528         }
529
530         return output;
531 }
532
533 } // namespace anon
534
535 } // namespace external
536
537 } // namespace lyx