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