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