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