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