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