]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
Fix bugs 3240 and 3241
[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                 // Since use_latex_path may be true we must extract the file
171                 // name from s instead of result and do the substitutions
172                 // again, this time with use_latex_path false.
173                 string::size_type const spos = s.find("$$Contents(\"");
174                 string::size_type const send = s.find("\")", spos);
175                 string const file_template = s.substr(spos + 12, send - (spos + 12));
176                 string const file = doSubstitution(params, buffer,
177                                                    file_template, false,
178                                                    external_in_tmpdir, what);
179                 string contents;
180
181                 FileName const absfile(
182                         support::makeAbsPath(file, m_buffer->temppath()));
183                 if (support::isFileReadable(absfile))
184                         contents = support::getFileContents(absfile);
185
186                 string::size_type const pos = result.find("$$Contents(\"");
187                 string::size_type const end = result.find("\")", pos);
188                 result.replace(pos, end + 2, contents);
189         }
190
191         return result;
192 }
193
194
195 namespace {
196
197 /** update the file represented by the template.
198     If \p external_in_tmpdir == true, then the generated file is
199     placed in the buffer's temporary directory.
200 */
201 void updateExternal(InsetExternalParams const & params,
202                     string const & format,
203                     Buffer const & buffer,
204                     ExportData & exportdata,
205                     bool external_in_tmpdir,
206                     bool dryrun)
207 {
208         Template const * const et_ptr = getTemplatePtr(params);
209         if (!et_ptr)
210                 return; // FAILURE
211         Template const & et = *et_ptr;
212
213         if (!et.automaticProduction)
214                 return; // NOT_NEEDED
215
216         Template::Formats::const_iterator cit = et.formats.find(format);
217         if (cit == et.formats.end())
218                 return; // FAILURE
219
220         Template::Format const & outputFormat = cit->second;
221         if (outputFormat.updateResult.empty())
222                 return; // NOT_NEEDED
223
224         string from_format = et.inputFormat;
225         if (from_format.empty())
226                 return; // NOT_NEEDED
227
228         if (from_format == "*") {
229                 if (params.filename.empty())
230                         return; // NOT_NEEDED
231
232                 // Try and ascertain the file format from its contents.
233                 from_format = formats.getFormatFromFile(params.filename);
234                 if (from_format.empty())
235                         return; // FAILURE
236
237         }
238
239         string const to_format = outputFormat.updateFormat;
240         if (to_format.empty())
241                 return; // NOT_NEEDED
242
243         if (!theConverters().isReachable(from_format, to_format)) {
244                 lyxerr[Debug::EXTERNAL]
245                         << "external::updateExternal. "
246                         << "Unable to convert from "
247                         << from_format << " to " << to_format << endl;
248                 return; // FAILURE
249         }
250
251         // The master buffer. This is useful when there are multiple levels
252         // of include files
253         Buffer const * m_buffer = buffer.getMasterBuffer();
254
255         // We copy the source file to the temp dir and do the conversion
256         // there if necessary
257         FileName const temp_file(
258                 support::makeAbsPath(params.filename.mangledFilename(),
259                                      m_buffer->temppath()));
260         if (!params.filename.empty() && !is_directory(params.filename.toFilesystemEncoding())) {
261                 unsigned long const from_checksum = support::sum(params.filename);
262                 unsigned long const temp_checksum = support::sum(temp_file);
263
264                 if (from_checksum != temp_checksum) {
265                         Mover const & mover = getMover(from_format);
266                         if (!mover.copy(params.filename, temp_file)) {
267                                 lyxerr[Debug::EXTERNAL]
268                                         << "external::updateExternal. "
269                                         << "Unable to copy "
270                                         << params.filename << " to " << temp_file << endl;
271                                 return; // FAILURE
272                         }
273                 }
274         }
275
276         // the generated file (always in the temp dir)
277         string const to_file = doSubstitution(params, buffer,
278                                               outputFormat.updateResult,
279                                               false, true);
280         FileName const abs_to_file(
281                 support::makeAbsPath(to_file, m_buffer->temppath()));
282
283         if (!dryrun) {
284                 // Record the referenced files for the exporter.
285                 // The exporter will copy them to the export dir.
286                 typedef Template::Format::FileMap FileMap;
287                 FileMap::const_iterator rit  = outputFormat.referencedFiles.begin();
288                 FileMap::const_iterator rend = outputFormat.referencedFiles.end();
289                 for (; rit != rend; ++rit) {
290                         vector<string>::const_iterator fit  = rit->second.begin();
291                         vector<string>::const_iterator fend = rit->second.end();
292                         for (; fit != fend; ++fit) {
293                                 FileName const source(support::makeAbsPath(
294                                                 doSubstitution(params, buffer, *fit,
295                                                                false, true),
296                                                 m_buffer->temppath()));
297                                 // The path of the referenced file is never the
298                                 // temp path, but the filename may be the mangled
299                                 // or the real name. Therefore we substitute the
300                                 // paths and names separately.
301                                 string file = support::subst(*fit, "$$FName",
302                                                 "$$FPath$$Basename$$Extension");
303                                 file = doSubstitution(params, buffer, file, false, false,
304                                                       PATHS);
305                                 file = doSubstitution(params, buffer, file,
306                                                       false, external_in_tmpdir,
307                                                       ALL_BUT_PATHS);
308                                 // if file is a relative name, it is interpreted
309                                 // relative to the master document.
310                                 exportdata.addExternalFile(rit->first, source, file);
311                         }
312                 }
313         }
314
315         // Do we need to perform the conversion?
316         // Yes if to_file does not exist or if from_file is newer than to_file
317         if (support::compare_timestamps(temp_file, abs_to_file) < 0)
318                 return; // SUCCESS
319
320         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
321         ErrorList el;
322         /* bool const success = */
323                 theConverters().convert(&buffer, temp_file, abs_to_file,
324                                    params.filename, from_format, to_format, el,
325                                    Converters::try_default | Converters::try_cache);
326         // return success
327 }
328
329
330 string const substituteCommands(InsetExternalParams const & params,
331                                 string const & input, string const & format);
332
333 string const substituteOptions(InsetExternalParams const & params,
334                                string const & input, string const & format);
335
336 } // namespace anon
337
338
339 int writeExternal(InsetExternalParams const & params,
340                   string const & format,
341                   Buffer const & buffer, odocstream & os,
342                   ExportData & exportdata,
343                   bool external_in_tmpdir,
344                   bool dryrun)
345 {
346         Template const * const et_ptr = getTemplatePtr(params);
347         if (!et_ptr)
348                 return 0;
349         Template const & et = *et_ptr;
350
351         Template::Formats::const_iterator cit = et.formats.find(format);
352         if (cit == et.formats.end()) {
353                 lyxerr[Debug::EXTERNAL]
354                         << "External template format '" << format
355                         << "' not specified in template "
356                         << params.templatename() << endl;
357                 return 0;
358         }
359
360         if (!dryrun || support::contains(cit->second.product, "$$Contents"))
361                 updateExternal(params, format, buffer, exportdata,
362                                external_in_tmpdir, dryrun);
363
364         bool const use_latex_path = format == "LaTeX";
365         string str = doSubstitution(params, buffer, cit->second.product,
366                                     use_latex_path, external_in_tmpdir);
367         str = substituteCommands(params, str, format);
368         str = substituteOptions(params, str, format);
369         // FIXME UNICODE
370         os << from_utf8(str);
371         return int(lyx::count(str.begin(), str.end(),'\n'));
372 }
373
374 namespace {
375
376 // Empty template, specialised below.
377 template <typename TransformType>
378 string const substituteIt(string const &,
379                           TransformID,
380                           string const &,
381                           Template::Format const &,
382                           InsetExternalParams const &);
383
384
385 template <>
386 string const substituteIt<TransformCommand>(string const & input,
387                                             TransformID id,
388                                             string const & /* formatname */,
389                                             Template::Format const & format,
390                                             InsetExternalParams const & params)
391 {
392         typedef std::map<TransformID, TransformStore> Transformers;
393         Transformers::const_iterator it = format.command_transformers.find(id);
394         if (it == format.command_transformers.end())
395                 return input;
396
397         TransformStore const & store = it->second;
398
399         TransformCommand::ptr_type ptr;
400         if (id == Rotate)
401                 ptr = store.getCommandTransformer(params.rotationdata);
402         else if (id == Resize)
403                 ptr = store.getCommandTransformer(params.resizedata);
404
405         if (!ptr.get())
406                 return input;
407
408         string result =
409                 support::subst(input, ptr->front_placeholder(), ptr->front());
410         return support::subst(result, ptr->back_placeholder(),  ptr->back());
411 }
412
413
414 template <>
415 string const substituteIt<TransformOption>(string const & input,
416                                            TransformID id,
417                                            string const & fname,
418                                            Template::Format const & format,
419                                            InsetExternalParams const & params)
420 {
421         typedef std::map<TransformID, TransformStore> Transformers;
422         Transformers::const_iterator it = format.option_transformers.find(id);
423         if (it == format.option_transformers.end())
424                 return input;
425
426         TransformStore const & store = it->second;
427
428         TransformOption::ptr_type ptr;
429         switch (id) {
430         case Clip:
431                 ptr = store.getOptionTransformer(params.clipdata);
432                 break;
433         case Extra:
434                 ptr = store.getOptionTransformer(params.extradata.get(fname));
435                 break;
436         case Rotate:
437                 ptr = store.getOptionTransformer(params.rotationdata);
438                 break;
439         case Resize:
440                 ptr = store.getOptionTransformer(params.resizedata);
441                 break;
442         }
443
444         if (!ptr.get())
445                 return input;
446
447         return support::subst(input, ptr->placeholder(), ptr->option());
448 }
449
450
451 template <typename TransformerType>
452 string const transformIt(InsetExternalParams const & params,
453                          string const & s, string const & formatname)
454 {
455         Template const * const et = getTemplatePtr(params);
456         if (!et || et->transformIds.empty())
457                 return s;
458
459         Template::Formats::const_iterator fit = et->formats.find(formatname);
460         if (fit == et->formats.end())
461                 return s;
462
463         string result = s;
464         Template::Format const & format =  fit->second;
465
466         typedef vector<TransformID> TransformsIDs;
467         TransformsIDs::const_iterator it  = et->transformIds.begin();
468         TransformsIDs::const_iterator end = et->transformIds.end();
469         for (; it != end; ++it) {
470                 result = substituteIt<TransformerType>(result, *it, formatname,
471                                                        format, params);
472         }
473         return result;
474 }
475
476
477 string const substituteCommands(InsetExternalParams const & params,
478                                 string const & input, string const & format)
479 {
480         return transformIt<TransformCommand>(params, input, format);
481 }
482
483
484 string const substituteOption(InsetExternalParams const & params,
485                               string const & input, string const & format)
486 {
487         string opt = transformIt<TransformOption>(params, input, format);
488
489         if (format == "LaTeX" || format == "PDFLaTeX")
490                 return sanitizeLatexOption(opt);
491         if (format == "DocBook")
492                 return sanitizeDocBookOption(opt);
493         return opt;
494 }
495
496
497 string const substituteOptions(InsetExternalParams const & params,
498                                string const & input, string const & format)
499 {
500         string output = input;
501
502         Template const * const et = getTemplatePtr(params);
503         if (!et || et->transformIds.empty())
504                 return output;
505
506         Template::Formats::const_iterator fit = et->formats.find(format);
507         if (fit == et->formats.end() || fit->second.options.empty())
508                 return output;
509
510         typedef vector<Template::Option> Options;
511         Options const & options = fit->second.options;
512         Options::const_iterator it  = options.begin();
513         Options::const_iterator end = options.end();
514         for (; it != end; ++it) {
515                 string const opt = substituteOption(params, it->option, format);
516                 string const placeholder = "$$" + it->name;
517                 output = support::subst(output, placeholder, opt);
518         }
519
520         return output;
521 }
522
523 } // namespace anon
524
525 } // namespace external
526
527 } // namespace lyx