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