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