]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.cpp
This should be the last of the commits refactoring the InsetLayout code.
[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.availableFile(),
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(filename).isAbsolute()) {
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.availableFile(), 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                                 exportdata.addExternalFile(rit->first, source, file);
300                         }
301                 }
302         }
303
304         // Do we need to perform the conversion?
305         // Yes if to_file does not exist or if from_file is newer than to_file
306         if (compare_timestamps(temp_file, abs_to_file) < 0)
307                 return; // SUCCESS
308
309         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
310         ErrorList el;
311         bool const success =
312                 theConverters().convert(&buffer, temp_file, abs_to_file,
313                                    params.filename.availableFile(), from_format, to_format, el,
314                                    Converters::try_default | Converters::try_cache);
315
316         if (!success) {
317                 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
318                         << "Unable to convert from " << from_format << " to " << to_format);
319         }
320
321         // return success
322 }
323
324
325 string const substituteCommands(InsetExternalParams const & params,
326                                 string const & input, string const & format);
327
328 string const substituteOptions(InsetExternalParams const & params,
329                                string const & input, string const & format);
330
331 } // namespace anon
332
333
334 int writeExternal(InsetExternalParams const & params,
335                   string const & format,
336                   Buffer const & buffer, odocstream & os,
337                   ExportData & exportdata,
338                   bool external_in_tmpdir,
339                   bool dryrun)
340 {
341         Template const * const et_ptr = getTemplatePtr(params);
342         if (!et_ptr)
343                 return 0;
344         Template const & et = *et_ptr;
345
346         Template::Formats::const_iterator cit = et.formats.find(format);
347         if (cit == et.formats.end()) {
348                 LYXERR(Debug::EXTERNAL, "External template format '" << format
349                         << "' not specified in template " << params.templatename());
350                 return 0;
351         }
352
353         if (!dryrun || contains(cit->second.product, "$$Contents"))
354                 updateExternal(params, format, buffer, exportdata,
355                                external_in_tmpdir, dryrun);
356
357         bool const use_latex_path = format == "LaTeX";
358         string str = doSubstitution(params, buffer, cit->second.product,
359                                     use_latex_path, external_in_tmpdir);
360
361         string const absname = makeAbsPath(
362                 params.filename.outputFilename(buffer.filePath()), buffer.filePath()).absFilename();
363
364         if (!external_in_tmpdir && !isValidLaTeXFilename(absname)) {
365                 lyx::frontend::Alert::warning(_("Invalid filename"),
366                                               _("The following filename is likely to cause trouble "
367                                                 "when running the exported file through LaTeX: ") +
368                                               from_utf8(absname));
369         }
370
371         str = substituteCommands(params, str, format);
372         str = substituteOptions(params, str, format);
373         // FIXME UNICODE
374         os << from_utf8(str);
375         return int(count(str.begin(), str.end(),'\n'));
376 }
377
378 namespace {
379
380 // Empty template, specialised below.
381 template <typename TransformType>
382 string const substituteIt(string const &,
383                           TransformID,
384                           string const &,
385                           Template::Format const &,
386                           InsetExternalParams const &);
387
388
389 template <>
390 string const substituteIt<TransformCommand>(string const & input,
391                                             TransformID id,
392                                             string const & /* formatname */,
393                                             Template::Format const & format,
394                                             InsetExternalParams const & params)
395 {
396         typedef map<TransformID, TransformStore> Transformers;
397         Transformers::const_iterator it = format.command_transformers.find(id);
398         if (it == format.command_transformers.end())
399                 return input;
400
401         TransformStore const & store = it->second;
402
403         TransformCommand::ptr_type ptr;
404         if (id == Rotate)
405                 ptr = store.getCommandTransformer(params.rotationdata);
406         else if (id == Resize)
407                 ptr = store.getCommandTransformer(params.resizedata);
408
409         if (!ptr.get())
410                 return input;
411
412         string result =
413                 subst(input, ptr->front_placeholder(), ptr->front());
414         return subst(result, ptr->back_placeholder(),  ptr->back());
415 }
416
417
418 template <>
419 string const substituteIt<TransformOption>(string const & input,
420                                            TransformID id,
421                                            string const & fname,
422                                            Template::Format const & format,
423                                            InsetExternalParams const & params)
424 {
425         typedef map<TransformID, TransformStore> Transformers;
426         Transformers::const_iterator it = format.option_transformers.find(id);
427         if (it == format.option_transformers.end())
428                 return input;
429
430         TransformStore const & store = it->second;
431
432         TransformOption::ptr_type ptr;
433         switch (id) {
434         case Clip:
435                 ptr = store.getOptionTransformer(params.clipdata);
436                 break;
437         case Extra:
438                 ptr = store.getOptionTransformer(params.extradata.get(fname));
439                 break;
440         case Rotate:
441                 ptr = store.getOptionTransformer(params.rotationdata);
442                 break;
443         case Resize:
444                 ptr = store.getOptionTransformer(params.resizedata);
445                 break;
446         }
447
448         if (!ptr.get())
449                 return input;
450
451         return subst(input, ptr->placeholder(), ptr->option());
452 }
453
454
455 template <typename TransformerType>
456 string const transformIt(InsetExternalParams const & params,
457                          string const & s, string const & formatname)
458 {
459         Template const * const et = getTemplatePtr(params);
460         if (!et || et->transformIds.empty())
461                 return s;
462
463         Template::Formats::const_iterator fit = et->formats.find(formatname);
464         if (fit == et->formats.end())
465                 return s;
466
467         string result = s;
468         Template::Format const & format =  fit->second;
469
470         typedef vector<TransformID> TransformsIDs;
471         TransformsIDs::const_iterator it  = et->transformIds.begin();
472         TransformsIDs::const_iterator end = et->transformIds.end();
473         for (; it != end; ++it) {
474                 result = substituteIt<TransformerType>(result, *it, formatname,
475                                                        format, params);
476         }
477         return result;
478 }
479
480
481 string const substituteCommands(InsetExternalParams const & params,
482                                 string const & input, string const & format)
483 {
484         return transformIt<TransformCommand>(params, input, format);
485 }
486
487
488 string const substituteOption(InsetExternalParams const & params,
489                               string const & input, string const & format)
490 {
491         string opt = transformIt<TransformOption>(params, input, format);
492
493         if (format == "LaTeX" || format == "PDFLaTeX")
494                 return sanitizeLatexOption(opt);
495         if (format == "DocBook")
496                 return sanitizeDocBookOption(opt);
497         return opt;
498 }
499
500
501 string const substituteOptions(InsetExternalParams const & params,
502                                string const & input, string const & format)
503 {
504         string output = input;
505
506         Template const * const et = getTemplatePtr(params);
507         if (!et || et->transformIds.empty())
508                 return output;
509
510         Template::Formats::const_iterator fit = et->formats.find(format);
511         if (fit == et->formats.end() || fit->second.options.empty())
512                 return output;
513
514         typedef vector<Template::Option> Options;
515         Options const & options = fit->second.options;
516         Options::const_iterator it  = options.begin();
517         Options::const_iterator end = options.end();
518         for (; it != end; ++it) {
519                 string const opt = substituteOption(params, it->option, format);
520                 string const placeholder = "$$" + it->name;
521                 output = subst(output, placeholder, opt);
522         }
523
524         return output;
525 }
526
527 } // namespace anon
528
529 } // namespace external
530
531 } // namespace lyx