]> git.lyx.org Git - lyx.git/blob - src/insets/ExternalSupport.cpp
Change cursor shape for clickable math insets
[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
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- pos, 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 RetVal 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 = theFormats().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         Converters::RetVal 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         switch (success) {
335         case Converters::SUCCESS:
336                 return SUCCESS;
337         case Converters::FAILURE:
338                 LYXERR(Debug::EXTERNAL, "external::updateExternal. "
339                         << "Unable to convert from " << from_format << " to " << to_format);
340                         return FAILURE;
341         case Converters::KILLED:
342                 return KILLED;
343         }
344         // squash warning
345         return SUCCESS;
346 }
347
348
349 string const substituteCommands(InsetExternalParams const & params,
350                                 string const & input, string const & format);
351
352 string const substituteOptions(InsetExternalParams const & params,
353                                string const & input, string const & format);
354
355 } // namespace
356
357
358 RetVal writeExternal(InsetExternalParams const & params,
359                    string const & format,
360                    Buffer const & buffer, otexstream & os,
361                    ExportData & exportdata,
362                    bool external_in_tmpdir,
363                    bool dryrun)
364 {
365         Template const * const et_ptr = getTemplatePtr(params);
366         if (!et_ptr)
367                 return FAILURE;
368         Template const & et = *et_ptr;
369
370         Template::Formats::const_iterator cit = et.formats.find(format);
371         if (cit == et.formats.end()) {
372                 LYXERR(Debug::EXTERNAL, "External template format '" << format
373                         << "' not specified in template " << params.templatename());
374                 return FAILURE;
375         }
376
377         if (!dryrun || contains(cit->second.product, "$$Contents")) {
378                 RetVal const success = 
379                         updateExternal(params, format, buffer, exportdata, 
380                                 external_in_tmpdir, dryrun);
381                 if (success == FAILURE || success == KILLED)
382                         return success;
383         }
384
385         bool const use_latex_path = format == "LaTeX";
386         string str = doSubstitution(params, buffer, cit->second.product,
387                                     use_latex_path, external_in_tmpdir);
388
389         string const absname = makeAbsPath(
390                 params.filename.outputFileName(buffer.filePath()), buffer.filePath()).absFileName();
391
392         if (!dryrun && !external_in_tmpdir) {
393                 if (!isValidLaTeXFileName(absname)) {
394                         lyx::frontend::Alert::warning(_("Invalid filename"),
395                                  _("The following filename will cause troubles "
396                                  "when running the exported file through LaTeX: ") +
397                               from_utf8(absname));
398                 }
399                 if (!isValidDVIFileName(absname)) {
400                         lyx::frontend::Alert::warning(_("Problematic filename for DVI"),
401                                  _("The following filename can cause troubles "
402                                  "when running the exported file through LaTeX "
403                                  "and opening the resulting DVI: ") +
404                                from_utf8(absname), true);
405                 }
406         }
407
408         str = substituteCommands(params, str, format);
409         str = substituteOptions(params, str, format);
410         // FIXME UNICODE
411         os << from_utf8(str);
412         return SUCCESS;
413 }
414
415 namespace {
416
417 // Empty template, specialised below.
418 template <typename TransformType>
419 string const substituteIt(string const &,
420                           TransformID,
421                           string const &,
422                           Template::Format const &,
423                           InsetExternalParams const &);
424
425
426 template <>
427 string const substituteIt<TransformCommand>(string const & input,
428                                             TransformID id,
429                                             string const & /* formatname */,
430                                             Template::Format const & format,
431                                             InsetExternalParams const & params)
432 {
433         typedef map<TransformID, TransformStore> Transformers;
434         Transformers::const_iterator it = format.command_transformers.find(id);
435         if (it == format.command_transformers.end())
436                 return input;
437
438         TransformStore const & store = it->second;
439
440         TransformCommand::ptr_type ptr;
441         if (id == Rotate)
442                 ptr = store.getCommandTransformer(params.rotationdata);
443         else if (id == Resize)
444                 ptr = store.getCommandTransformer(params.resizedata);
445
446         if (!ptr)
447                 return input;
448
449         string result =
450                 subst(input, ptr->front_placeholder(), ptr->front());
451         return subst(result, ptr->back_placeholder(),  ptr->back());
452 }
453
454
455 template <>
456 string const substituteIt<TransformOption>(string const & input,
457                                            TransformID id,
458                                            string const & fname,
459                                            Template::Format const & format,
460                                            InsetExternalParams const & params)
461 {
462         typedef map<TransformID, TransformStore> Transformers;
463         Transformers::const_iterator it = format.option_transformers.find(id);
464         if (it == format.option_transformers.end())
465                 return input;
466
467         TransformStore const & store = it->second;
468
469         TransformOption::ptr_type ptr;
470         switch (id) {
471         case Clip:
472                 ptr = store.getOptionTransformer(params.clipdata);
473                 break;
474         case Extra:
475                 ptr = store.getOptionTransformer(params.extradata.get(fname));
476                 break;
477         case Rotate:
478                 ptr = store.getOptionTransformer(params.rotationdata);
479                 break;
480         case Resize:
481                 ptr = store.getOptionTransformer(params.resizedata);
482                 break;
483         case None:
484                 break;
485         }
486
487         if (!ptr)
488                 return input;
489
490         return subst(input, ptr->placeholder(), ptr->option());
491 }
492
493
494 template <typename TransformerType>
495 string const transformIt(InsetExternalParams const & params,
496                          string const & s, string const & formatname)
497 {
498         Template const * const et = getTemplatePtr(params);
499         if (!et || et->transformIds.empty())
500                 return s;
501
502         Template::Formats::const_iterator fit = et->formats.find(formatname);
503         if (fit == et->formats.end())
504                 return s;
505
506         string result = s;
507         Template::Format const & format =  fit->second;
508
509         typedef vector<TransformID> TransformsIDs;
510         TransformsIDs::const_iterator it  = et->transformIds.begin();
511         TransformsIDs::const_iterator end = et->transformIds.end();
512         for (; it != end; ++it) {
513                 result = substituteIt<TransformerType>(result, *it, formatname,
514                                                        format, params);
515         }
516         return result;
517 }
518
519
520 string const substituteCommands(InsetExternalParams const & params,
521                                 string const & input, string const & format)
522 {
523         return transformIt<TransformCommand>(params, input, format);
524 }
525
526
527 string const substituteOption(InsetExternalParams const & params,
528                               string const & input, string const & format)
529 {
530         string opt = transformIt<TransformOption>(params, input, format);
531
532         if (format == "LaTeX" || format == "PDFLaTeX")
533                 return sanitizeLatexOption(opt);
534         if (format == "DocBook")
535                 return sanitizeDocBookOption(opt);
536         return opt;
537 }
538
539
540 string const substituteOptions(InsetExternalParams const & params,
541                                string const & input, string const & format)
542 {
543         string output = input;
544
545         Template const * const et = getTemplatePtr(params);
546         if (!et || et->transformIds.empty())
547                 return output;
548
549         Template::Formats::const_iterator fit = et->formats.find(format);
550         if (fit == et->formats.end() || fit->second.options.empty())
551                 return output;
552
553         typedef vector<Template::Option> Options;
554         Options const & options = fit->second.options;
555         Options::const_iterator it  = options.begin();
556         Options::const_iterator end = options.end();
557         for (; it != end; ++it) {
558                 string const opt = substituteOption(params, it->option, format);
559                 string const placeholder = "$$" + it->name;
560                 output = subst(output, placeholder, opt);
561         }
562
563         return output;
564 }
565
566 } // namespace
567
568 } // namespace external
569
570 } // namespace lyx