]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.cpp
Make use of otexstream also in external::writeExternal
[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 void writeExternal(InsetExternalParams const & params,
337                    string const & format,
338                    Buffer const & buffer, otexstream & 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;
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;
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         // FIXME UNICODE
385         os << from_utf8(str);
386         return;
387 }
388
389 namespace {
390
391 // Empty template, specialised below.
392 template <typename TransformType>
393 string const substituteIt(string const &,
394                           TransformID,
395                           string const &,
396                           Template::Format const &,
397                           InsetExternalParams const &);
398
399
400 template <>
401 string const substituteIt<TransformCommand>(string const & input,
402                                             TransformID id,
403                                             string const & /* formatname */,
404                                             Template::Format const & format,
405                                             InsetExternalParams const & params)
406 {
407         typedef map<TransformID, TransformStore> Transformers;
408         Transformers::const_iterator it = format.command_transformers.find(id);
409         if (it == format.command_transformers.end())
410                 return input;
411
412         TransformStore const & store = it->second;
413
414         TransformCommand::ptr_type ptr;
415         if (id == Rotate)
416                 ptr = store.getCommandTransformer(params.rotationdata);
417         else if (id == Resize)
418                 ptr = store.getCommandTransformer(params.resizedata);
419
420         if (!ptr.get())
421                 return input;
422
423         string result =
424                 subst(input, ptr->front_placeholder(), ptr->front());
425         return subst(result, ptr->back_placeholder(),  ptr->back());
426 }
427
428
429 template <>
430 string const substituteIt<TransformOption>(string const & input,
431                                            TransformID id,
432                                            string const & fname,
433                                            Template::Format const & format,
434                                            InsetExternalParams const & params)
435 {
436         typedef map<TransformID, TransformStore> Transformers;
437         Transformers::const_iterator it = format.option_transformers.find(id);
438         if (it == format.option_transformers.end())
439                 return input;
440
441         TransformStore const & store = it->second;
442
443         TransformOption::ptr_type ptr;
444         switch (id) {
445         case Clip:
446                 ptr = store.getOptionTransformer(params.clipdata);
447                 break;
448         case Extra:
449                 ptr = store.getOptionTransformer(params.extradata.get(fname));
450                 break;
451         case Rotate:
452                 ptr = store.getOptionTransformer(params.rotationdata);
453                 break;
454         case Resize:
455                 ptr = store.getOptionTransformer(params.resizedata);
456                 break;
457         }
458
459         if (!ptr.get())
460                 return input;
461
462         return subst(input, ptr->placeholder(), ptr->option());
463 }
464
465
466 template <typename TransformerType>
467 string const transformIt(InsetExternalParams const & params,
468                          string const & s, string const & formatname)
469 {
470         Template const * const et = getTemplatePtr(params);
471         if (!et || et->transformIds.empty())
472                 return s;
473
474         Template::Formats::const_iterator fit = et->formats.find(formatname);
475         if (fit == et->formats.end())
476                 return s;
477
478         string result = s;
479         Template::Format const & format =  fit->second;
480
481         typedef vector<TransformID> TransformsIDs;
482         TransformsIDs::const_iterator it  = et->transformIds.begin();
483         TransformsIDs::const_iterator end = et->transformIds.end();
484         for (; it != end; ++it) {
485                 result = substituteIt<TransformerType>(result, *it, formatname,
486                                                        format, params);
487         }
488         return result;
489 }
490
491
492 string const substituteCommands(InsetExternalParams const & params,
493                                 string const & input, string const & format)
494 {
495         return transformIt<TransformCommand>(params, input, format);
496 }
497
498
499 string const substituteOption(InsetExternalParams const & params,
500                               string const & input, string const & format)
501 {
502         string opt = transformIt<TransformOption>(params, input, format);
503
504         if (format == "LaTeX" || format == "PDFLaTeX")
505                 return sanitizeLatexOption(opt);
506         if (format == "DocBook")
507                 return sanitizeDocBookOption(opt);
508         return opt;
509 }
510
511
512 string const substituteOptions(InsetExternalParams const & params,
513                                string const & input, string const & format)
514 {
515         string output = input;
516
517         Template const * const et = getTemplatePtr(params);
518         if (!et || et->transformIds.empty())
519                 return output;
520
521         Template::Formats::const_iterator fit = et->formats.find(format);
522         if (fit == et->formats.end() || fit->second.options.empty())
523                 return output;
524
525         typedef vector<Template::Option> Options;
526         Options const & options = fit->second.options;
527         Options::const_iterator it  = options.begin();
528         Options::const_iterator end = options.end();
529         for (; it != end; ++it) {
530                 string const opt = substituteOption(params, it->option, format);
531                 string const placeholder = "$$" + it->name;
532                 output = subst(output, placeholder, opt);
533         }
534
535         return output;
536 }
537
538 } // namespace anon
539
540 } // namespace external
541
542 } // namespace lyx