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