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