]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.C
move everything into namespace lyx
[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         string const to_file_base =
309                 support::changeExtension(to_file, string());
310
311         // FIXME (Abdel 12/08/06): Is there a need to show these errors?
312         ErrorList el;
313         /* bool const success = */
314                 converters.convert(&buffer, temp_file, to_file_base,
315                                    from_format, to_format, el, true);
316         // return success
317 }
318
319
320 string const substituteCommands(InsetExternalParams const & params,
321                                 string const & input, string const & format);
322
323 string const substituteOptions(InsetExternalParams const & params,
324                                string const & input, string const & format);
325
326 } // namespace anon
327
328
329 int writeExternal(InsetExternalParams const & params,
330                   string const & format,
331                   Buffer const & buffer, odocstream & os,
332                   ExportData & exportdata,
333                   bool external_in_tmpdir,
334                   bool external_in_comment)
335 {
336         Template const * const et_ptr = getTemplatePtr(params);
337         if (!et_ptr)
338                 return 0;
339         Template const & et = *et_ptr;
340
341         Template::Formats::const_iterator cit = et.formats.find(format);
342         if (cit == et.formats.end()) {
343                 lyxerr[Debug::EXTERNAL]
344                         << "External template format '" << format
345                         << "' not specified in template "
346                         << params.templatename() << endl;
347                 return 0;
348         }
349
350         if (!external_in_comment)
351                 updateExternal(params, format, buffer, exportdata,
352                                external_in_tmpdir);
353
354         bool const use_latex_path = format == "LaTeX";
355         string str = doSubstitution(params, buffer, cit->second.product,
356                                     use_latex_path, external_in_tmpdir);
357         str = substituteCommands(params, str, format);
358         str = substituteOptions(params, str, format);
359         // FIXME UNICODE
360         os << from_utf8(str);
361         return int(lyx::count(str.begin(), str.end(),'\n'));
362 }
363
364 namespace {
365
366 // Empty template, specialised below.
367 template <typename TransformType>
368 string const substituteIt(string const &,
369                           TransformID,
370                           string const &,
371                           Template::Format const &,
372                           InsetExternalParams const &);
373
374
375 template <>
376 string const substituteIt<TransformCommand>(string const & input,
377                                             TransformID id,
378                                             string const & /* formatname */,
379                                             Template::Format const & format,
380                                             InsetExternalParams const & params)
381 {
382         typedef std::map<TransformID, TransformStore> Transformers;
383         Transformers::const_iterator it = format.command_transformers.find(id);
384         if (it == format.command_transformers.end())
385                 return input;
386
387         TransformStore const & store = it->second;
388
389         TransformCommand::ptr_type ptr;
390         if (id == Rotate)
391                 ptr = store.getCommandTransformer(params.rotationdata);
392         else if (id == Resize)
393                 ptr = store.getCommandTransformer(params.resizedata);
394
395         if (!ptr.get())
396                 return input;
397
398         string result =
399                 support::subst(input, ptr->front_placeholder(), ptr->front());
400         return support::subst(result, ptr->back_placeholder(),  ptr->back());
401 }
402
403
404 template <>
405 string const substituteIt<TransformOption>(string const & input,
406                                            TransformID id,
407                                            string const & fname,
408                                            Template::Format const & format,
409                                            InsetExternalParams const & params)
410 {
411         typedef std::map<TransformID, TransformStore> Transformers;
412         Transformers::const_iterator it = format.option_transformers.find(id);
413         if (it == format.option_transformers.end())
414                 return input;
415
416         TransformStore const & store = it->second;
417
418         TransformOption::ptr_type ptr;
419         switch (id) {
420         case Clip:
421                 ptr = store.getOptionTransformer(params.clipdata);
422                 break;
423         case Extra:
424                 ptr = store.getOptionTransformer(params.extradata.get(fname));
425                 break;
426         case Rotate:
427                 ptr = store.getOptionTransformer(params.rotationdata);
428                 break;
429         case Resize:
430                 ptr = store.getOptionTransformer(params.resizedata);
431                 break;
432         }
433
434         if (!ptr.get())
435                 return input;
436
437         return support::subst(input, ptr->placeholder(), ptr->option());
438 }
439
440
441 template <typename TransformerType>
442 string const transformIt(InsetExternalParams const & params,
443                          string const & s, string const & formatname)
444 {
445         Template const * const et = getTemplatePtr(params);
446         if (!et || et->transformIds.empty())
447                 return s;
448
449         Template::Formats::const_iterator fit = et->formats.find(formatname);
450         if (fit == et->formats.end())
451                 return s;
452
453         string result = s;
454         Template::Format const & format =  fit->second;
455
456         typedef vector<TransformID> TransformsIDs;
457         TransformsIDs::const_iterator it  = et->transformIds.begin();
458         TransformsIDs::const_iterator end = et->transformIds.end();
459         for (; it != end; ++it) {
460                 result = substituteIt<TransformerType>(result, *it, formatname,
461                                                        format, params);
462         }
463         return result;
464 }
465
466
467 string const substituteCommands(InsetExternalParams const & params,
468                                 string const & input, string const & format)
469 {
470         return transformIt<TransformCommand>(params, input, format);
471 }
472
473
474 string const substituteOption(InsetExternalParams const & params,
475                               string const & input, string const & format)
476 {
477         string opt = transformIt<TransformOption>(params, input, format);
478
479         if (format == "LaTeX" || format == "PDFLaTeX")
480                 return sanitizeLatexOption(opt);
481         if (format == "DocBook")
482                 return sanitizeDocBookOption(opt);
483         return opt;
484 }
485
486
487 string const substituteOptions(InsetExternalParams const & params,
488                                string const & input, string const & format)
489 {
490         string output = input;
491
492         Template const * const et = getTemplatePtr(params);
493         if (!et || et->transformIds.empty())
494                 return output;
495
496         Template::Formats::const_iterator fit = et->formats.find(format);
497         if (fit == et->formats.end() || fit->second.options.empty())
498                 return output;
499
500         typedef vector<Template::Option> Options;
501         Options const & options = fit->second.options;
502         Options::const_iterator it  = options.begin();
503         Options::const_iterator end = options.end();
504         for (; it != end; ++it) {
505                 string const opt = substituteOption(params, it->option, format);
506                 string const placeholder = "$$" + it->name;
507                 output = support::subst(output, placeholder, opt);
508         }
509
510         return output;
511 }
512
513 } // namespace anon
514
515 } // namespace external
516
517 } // namespace lyx