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