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