]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
don't pass temporary string objects as parameters
[lyx.git] / src / insets / ExternalSupport.C
1 /**
2  * \file ExternalSupport.C
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 "exporter.h"
23 #include "format.h"
24 #include "mover.h"
25
26 #include "support/filetools.h"
27 #include "support/forkedcall.h"
28 #include "support/lstrings.h"
29 #include "support/lyxalgo.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/package.h"
33 #include "support/path.h"
34
35 using std::endl;
36 using std::string;
37 using std::vector;
38
39
40 namespace lyx {
41 namespace external {
42
43 Template const * getTemplatePtr(InsetExternalParams const & params)
44 {
45         TemplateManager const & etm = TemplateManager::get();
46         return etm.getTemplateByName(params.templatename());
47 }
48
49
50 void editExternal(InsetExternalParams const & params, Buffer const & buffer)
51 {
52         string const file_with_path = params.filename.absFilename();
53         formats.edit(buffer, file_with_path,
54                      formats.getFormatFromFile(file_with_path));
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                         support::latex_path_extension ext = support::PROTECT_EXTENSION,
65                         support::latex_path_dots dots = support::LEAVE_DOTS)
66 {
67         if (input.find(placeholder) == string::npos)
68                 return input;
69         string const path2 = use_latex_path ?
70                 support::latex_path(path, ext, dots) :
71                 support::os::external_path(path);
72         return support::subst(input, placeholder, path2);
73 }
74
75 } // namespace anon
76
77
78 string const doSubstitution(InsetExternalParams const & params,
79                             Buffer const & buffer, string const & s,
80                             bool use_latex_path,
81                             bool external_in_tmpdir,
82                             Substitute what)
83 {
84         Buffer const * m_buffer = buffer.getMasterBuffer();
85         string const parentpath = external_in_tmpdir ?
86                 m_buffer->temppath() :
87                 buffer.filePath();
88         string const filename = external_in_tmpdir ?
89                 params.filename.mangledFilename() :
90                 params.filename.outputFilename(parentpath);
91         string const basename = support::changeExtension(
92                         support::onlyFilename(filename), string());
93         string const absname = support::makeAbsPath(filename, parentpath);
94
95         string result = s;
96         if (what != ALL_BUT_PATHS) {
97                 string const filepath = support::onlyPath(filename);
98                 string const abspath = support::onlyPath(absname);
99                 string const masterpath = external_in_tmpdir ?
100                         m_buffer->temppath() :
101                         m_buffer->filePath();
102                 string relToMasterPath = support::onlyPath(
103                                 support::makeRelPath(absname, masterpath));
104                 if (relToMasterPath == "./")
105                         relToMasterPath.clear();
106                 string relToParentPath = support::onlyPath(
107                                 support::makeRelPath(absname, parentpath));
108                 if (relToParentPath == "./")
109                         relToParentPath.clear();
110
111                 result = subst_path(result, "$$FPath", filepath,
112                                     use_latex_path,
113                                     support::PROTECT_EXTENSION,
114                                     support::ESCAPE_DOTS);
115                 result = subst_path(result, "$$AbsPath", abspath,
116                                     use_latex_path,
117                                     support::PROTECT_EXTENSION,
118                                     support::ESCAPE_DOTS);
119                 result = subst_path(result, "$$RelPathMaster",
120                                     relToMasterPath, use_latex_path,
121                                     support::PROTECT_EXTENSION,
122                                     support::ESCAPE_DOTS);
123                 result = subst_path(result, "$$RelPathParent",
124                                     relToParentPath, use_latex_path,
125                                     support::PROTECT_EXTENSION,
126                                     support::ESCAPE_DOTS);
127                 if (support::absolutePath(filename)) {
128                         result = subst_path(result, "$$AbsOrRelPathMaster",
129                                             abspath, use_latex_path,
130                                             support::PROTECT_EXTENSION,
131                                             support::ESCAPE_DOTS);
132                         result = subst_path(result, "$$AbsOrRelPathParent",
133                                             abspath, use_latex_path,
134                                             support::PROTECT_EXTENSION,
135                                             support::ESCAPE_DOTS);
136                 } else {
137                         result = subst_path(result, "$$AbsOrRelPathMaster",
138                                             relToMasterPath, use_latex_path,
139                                             support::PROTECT_EXTENSION,
140                                             support::ESCAPE_DOTS);
141                         result = subst_path(result, "$$AbsOrRelPathParent",
142                                             relToParentPath, use_latex_path,
143                                             support::PROTECT_EXTENSION,
144                                             support::ESCAPE_DOTS);
145                 }
146         }
147
148         if (what == PATHS)
149                 return result;
150
151         result = subst_path(result, "$$FName", filename, use_latex_path,
152                             support::EXCLUDE_EXTENSION);
153         result = subst_path(result, "$$Basename", basename, use_latex_path,
154                             support::PROTECT_EXTENSION, support::ESCAPE_DOTS);
155         result = subst_path(result, "$$Extension",
156                         '.' + support::getExtension(filename), use_latex_path);
157         result = subst_path(result, "$$Tempname", params.tempname(), use_latex_path);
158         result = subst_path(result, "$$Sysdir",
159                                 support::package().system_support(), use_latex_path);
160
161         // Handle the $$Contents(filename) syntax
162         if (support::contains(result, "$$Contents(\"")) {
163
164                 string::size_type const pos = result.find("$$Contents(\"");
165                 string::size_type const end = result.find("\")", pos);
166                 string const file = result.substr(pos + 12, end - (pos + 12));
167                 string contents;
168
169                 string const filepath = support::isFileReadable(file) ?
170                         buffer.filePath() : m_buffer->temppath();
171                 support::Path p(filepath);
172
173                 if (support::isFileReadable(file))
174                         contents = support::getFileContents(file);
175
176                 result = support::subst(result,
177                                         ("$$Contents(\"" + file + "\")").c_str(),
178                                         contents);
179         }
180
181         return result;
182 }
183
184
185 namespace {
186
187 /** update the file represented by the template.
188     If \p external_in_tmpdir == true, then the generated file is
189     placed in the buffer's temporary directory.
190 */
191 void updateExternal(InsetExternalParams const & params,
192                     string const & format,
193                     Buffer const & buffer,
194                     ExportData & exportdata,
195                     bool external_in_tmpdir)
196 {
197         Template const * const et_ptr = getTemplatePtr(params);
198         if (!et_ptr)
199                 return; // FAILURE
200         Template const & et = *et_ptr;
201
202         if (!et.automaticProduction)
203                 return; // NOT_NEEDED
204
205         Template::Formats::const_iterator cit = et.formats.find(format);
206         if (cit == et.formats.end())
207                 return; // FAILURE
208
209         Template::Format const & outputFormat = cit->second;
210         if (outputFormat.updateResult.empty())
211                 return; // NOT_NEEDED
212
213         string from_format = et.inputFormat;
214         if (from_format.empty())
215                 return; // NOT_NEEDED
216
217         string abs_from_file = params.filename.absFilename();
218
219         if (from_format == "*") {
220                 if (abs_from_file.empty())
221                         return; // NOT_NEEDED
222
223                 // Try and ascertain the file format from its contents.
224                 from_format = formats.getFormatFromFile(abs_from_file);
225                 if (from_format.empty())
226                         return; // FAILURE
227
228         }
229
230         string const to_format = outputFormat.updateFormat;
231         if (to_format.empty())
232                 return; // NOT_NEEDED
233
234         if (!converters.isReachable(from_format, to_format)) {
235                 lyxerr[Debug::EXTERNAL]
236                         << "external::updateExternal. "
237                         << "Unable to convert from "
238                         << from_format << " to " << to_format << endl;
239                 return; // FAILURE
240         }
241
242         // The master buffer. This is useful when there are multiple levels
243         // of include files
244         Buffer const * m_buffer = buffer.getMasterBuffer();
245
246         // We copy the source file to the temp dir and do the conversion
247         // there if necessary
248         string const temp_file =
249                 support::makeAbsPath(params.filename.mangledFilename(),
250                                      m_buffer->temppath());
251         if (!abs_from_file.empty()) {
252                 unsigned long const from_checksum = support::sum(abs_from_file);
253                 unsigned long const temp_checksum = support::sum(temp_file);
254
255                 if (from_checksum != temp_checksum) {
256                         Mover const & mover = movers(from_format);
257                         if (!mover.copy(abs_from_file, temp_file)) {
258                                 lyxerr[Debug::EXTERNAL]
259                                         << "external::updateExternal. "
260                                         << "Unable to copy "
261                                         << abs_from_file << " to " << temp_file << endl;
262                                 return; // FAILURE
263                         }
264                 }
265         }
266
267         // the generated file (always in the temp dir)
268         string const to_file = doSubstitution(params, buffer,
269                                               outputFormat.updateResult,
270                                               false, true);
271         string const abs_to_file =
272                 support::makeAbsPath(to_file, m_buffer->temppath());
273
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                         string const source = support::makeAbsPath(
284                                         doSubstitution(params, buffer, *fit,
285                                                        false, true),
286                                         m_buffer->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 = support::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         // 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 (support::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                 converters.convert(&buffer, temp_file, abs_to_file,
313                                    abs_from_file, from_format, to_format, el,
314                                    Converters::try_default | Converters::try_cache);
315         // return success
316 }
317
318
319 string const substituteCommands(InsetExternalParams const & params,
320                                 string const & input, string const & format);
321
322 string const substituteOptions(InsetExternalParams const & params,
323                                string const & input, string const & format);
324
325 } // namespace anon
326
327
328 int writeExternal(InsetExternalParams const & params,
329                   string const & format,
330                   Buffer const & buffer, odocstream & os,
331                   ExportData & exportdata,
332                   bool external_in_tmpdir,
333                   bool external_in_comment)
334 {
335         Template const * const et_ptr = getTemplatePtr(params);
336         if (!et_ptr)
337                 return 0;
338         Template const & et = *et_ptr;
339
340         Template::Formats::const_iterator cit = et.formats.find(format);
341         if (cit == et.formats.end()) {
342                 lyxerr[Debug::EXTERNAL]
343                         << "External template format '" << format
344                         << "' not specified in template "
345                         << params.templatename() << endl;
346                 return 0;
347         }
348
349         if (!external_in_comment)
350                 updateExternal(params, format, buffer, exportdata,
351                                external_in_tmpdir);
352
353         bool const use_latex_path = format == "LaTeX";
354         string str = doSubstitution(params, buffer, cit->second.product,
355                                     use_latex_path, external_in_tmpdir);
356         str = substituteCommands(params, str, format);
357         str = substituteOptions(params, str, format);
358         // FIXME UNICODE
359         os << from_utf8(str);
360         return int(lyx::count(str.begin(), str.end(),'\n'));
361 }
362
363 namespace {
364
365 // Empty template, specialised below.
366 template <typename TransformType>
367 string const substituteIt(string const &,
368                           TransformID,
369                           string const &,
370                           Template::Format const &,
371                           InsetExternalParams const &);
372
373
374 template <>
375 string const substituteIt<TransformCommand>(string const & input,
376                                             TransformID id,
377                                             string const & /* formatname */,
378                                             Template::Format const & format,
379                                             InsetExternalParams const & params)
380 {
381         typedef std::map<TransformID, TransformStore> Transformers;
382         Transformers::const_iterator it = format.command_transformers.find(id);
383         if (it == format.command_transformers.end())
384                 return input;
385
386         TransformStore const & store = it->second;
387
388         TransformCommand::ptr_type ptr;
389         if (id == Rotate)
390                 ptr = store.getCommandTransformer(params.rotationdata);
391         else if (id == Resize)
392                 ptr = store.getCommandTransformer(params.resizedata);
393
394         if (!ptr.get())
395                 return input;
396
397         string result =
398                 support::subst(input, ptr->front_placeholder(), ptr->front());
399         return support::subst(result, ptr->back_placeholder(),  ptr->back());
400 }
401
402
403 template <>
404 string const substituteIt<TransformOption>(string const & input,
405                                            TransformID id,
406                                            string const & fname,
407                                            Template::Format const & format,
408                                            InsetExternalParams const & params)
409 {
410         typedef std::map<TransformID, TransformStore> Transformers;
411         Transformers::const_iterator it = format.option_transformers.find(id);
412         if (it == format.option_transformers.end())
413                 return input;
414
415         TransformStore const & store = it->second;
416
417         TransformOption::ptr_type ptr;
418         switch (id) {
419         case Clip:
420                 ptr = store.getOptionTransformer(params.clipdata);
421                 break;
422         case Extra:
423                 ptr = store.getOptionTransformer(params.extradata.get(fname));
424                 break;
425         case Rotate:
426                 ptr = store.getOptionTransformer(params.rotationdata);
427                 break;
428         case Resize:
429                 ptr = store.getOptionTransformer(params.resizedata);
430                 break;
431         }
432
433         if (!ptr.get())
434                 return input;
435
436         return support::subst(input, ptr->placeholder(), ptr->option());
437 }
438
439
440 template <typename TransformerType>
441 string const transformIt(InsetExternalParams const & params,
442                          string const & s, string const & formatname)
443 {
444         Template const * const et = getTemplatePtr(params);
445         if (!et || et->transformIds.empty())
446                 return s;
447
448         Template::Formats::const_iterator fit = et->formats.find(formatname);
449         if (fit == et->formats.end())
450                 return s;
451
452         string result = s;
453         Template::Format const & format =  fit->second;
454
455         typedef vector<TransformID> TransformsIDs;
456         TransformsIDs::const_iterator it  = et->transformIds.begin();
457         TransformsIDs::const_iterator end = et->transformIds.end();
458         for (; it != end; ++it) {
459                 result = substituteIt<TransformerType>(result, *it, formatname,
460                                                        format, params);
461         }
462         return result;
463 }
464
465
466 string const substituteCommands(InsetExternalParams const & params,
467                                 string const & input, string const & format)
468 {
469         return transformIt<TransformCommand>(params, input, format);
470 }
471
472
473 string const substituteOption(InsetExternalParams const & params,
474                               string const & input, string const & format)
475 {
476         string opt = transformIt<TransformOption>(params, input, format);
477
478         if (format == "LaTeX" || format == "PDFLaTeX")
479                 return sanitizeLatexOption(opt);
480         if (format == "DocBook")
481                 return sanitizeDocBookOption(opt);
482         return opt;
483 }
484
485
486 string const substituteOptions(InsetExternalParams const & params,
487                                string const & input, string const & format)
488 {
489         string output = input;
490
491         Template const * const et = getTemplatePtr(params);
492         if (!et || et->transformIds.empty())
493                 return output;
494
495         Template::Formats::const_iterator fit = et->formats.find(format);
496         if (fit == et->formats.end() || fit->second.options.empty())
497                 return output;
498
499         typedef vector<Template::Option> Options;
500         Options const & options = fit->second.options;
501         Options::const_iterator it  = options.begin();
502         Options::const_iterator end = options.end();
503         for (; it != end; ++it) {
504                 string const opt = substituteOption(params, it->option, format);
505                 string const placeholder = "$$" + it->name;
506                 output = support::subst(output, placeholder, opt);
507         }
508
509         return output;
510 }
511
512 } // namespace anon
513
514 } // namespace external
515
516 } // namespace lyx