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