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