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