]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
rename MathArray into MathData
[lyx.git] / src / Converter.cpp
1 /**
2  * \file Converter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Converter.h"
14
15 #include "ConverterCache.h"
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "Format.h"
21 #include "gettext.h"
22 #include "Language.h"
23 #include "LaTeX.h"
24 #include "Mover.h"
25
26 #include "frontends/Alert.h"
27
28 #include "support/filetools.h"
29 #include "support/lyxlib.h"
30 #include "support/os.h"
31 #include "support/Path.h"
32 #include "support/Systemcall.h"
33
34
35 namespace lyx {
36
37 using support::addName;
38 using support::bformat;
39 using support::changeExtension;
40 using support::compare_ascii_no_case;
41 using support::contains;
42 using support::dirList;
43 using support::FileName;
44 using support::getExtension;
45 using support::isFileReadable;
46 using support::libFileSearch;
47 using support::libScriptSearch;
48 using support::makeAbsPath;
49 using support::makeRelPath;
50 using support::onlyFilename;
51 using support::onlyPath;
52 using support::prefixIs;
53 using support::quoteName;
54 using support::removeExtension;
55 using support::split;
56 using support::subst;
57 using support::Systemcall;
58
59 using std::endl;
60 using std::find_if;
61 using std::string;
62 using std::vector;
63 using std::distance;
64
65 namespace Alert = lyx::frontend::Alert;
66
67
68 namespace {
69
70 string const token_from("$$i");
71 string const token_base("$$b");
72 string const token_to("$$o");
73 string const token_path("$$p");
74
75
76
77 string const add_options(string const & command, string const & options)
78 {
79         string head;
80         string const tail = split(command, head, ' ');
81         return head + ' ' + options + ' ' + tail;
82 }
83
84
85 string const dvipdfm_options(BufferParams const & bp)
86 {
87         string result;
88
89         if (bp.papersize != PAPER_CUSTOM) {
90                 string const paper_size = bp.paperSizeName();
91                 if (paper_size != "b5" && paper_size != "foolscap")
92                         result = "-p "+ paper_size;
93
94                 if (bp.orientation == ORIENTATION_LANDSCAPE)
95                         result += " -l";
96         }
97
98         return result;
99 }
100
101
102 class ConverterEqual : public std::binary_function<string, string, bool> {
103 public:
104         ConverterEqual(string const & from, string const & to)
105                 : from_(from), to_(to) {}
106         bool operator()(Converter const & c) const {
107                 return c.from == from_ && c.to == to_;
108         }
109 private:
110         string const from_;
111         string const to_;
112 };
113
114 } // namespace anon
115
116
117 Converter::Converter(string const & f, string const & t,
118                      string const & c, string const & l)
119         : from(f), to(t), command(c), flags(l),
120           From(0), To(0), latex(false), xml(false),
121           original_dir(false), need_aux(false)
122 {}
123
124
125 void Converter::readFlags()
126 {
127         string flag_list(flags);
128         while (!flag_list.empty()) {
129                 string flag_name, flag_value;
130                 flag_list = split(flag_list, flag_value, ',');
131                 flag_value = split(flag_value, flag_name, '=');
132                 if (flag_name == "latex")
133                         latex = true;
134                 else if (flag_name == "xml")
135                         xml = true;
136                 else if (flag_name == "originaldir")
137                         original_dir = true;
138                 else if (flag_name == "needaux")
139                         need_aux = true;
140                 else if (flag_name == "resultdir")
141                         result_dir = (flag_value.empty())
142                                 ? token_base : flag_value;
143                 else if (flag_name == "resultfile")
144                         result_file = flag_value;
145                 else if (flag_name == "parselog")
146                         parselog = flag_value;
147         }
148         if (!result_dir.empty() && result_file.empty())
149                 result_file = "index." + formats.extension(to);
150         //if (!contains(command, token_from))
151         //      latex = true;
152 }
153
154
155 bool operator<(Converter const & a, Converter const & b)
156 {
157         // use the compare_ascii_no_case instead of compare_no_case,
158         // because in turkish, 'i' is not the lowercase version of 'I',
159         // and thus turkish locale breaks parsing of tags.
160         int const i = compare_ascii_no_case(a.From->prettyname(),
161                                             b.From->prettyname());
162         if (i == 0)
163                 return compare_ascii_no_case(a.To->prettyname(),
164                                              b.To->prettyname()) < 0;
165         else
166                 return i < 0;
167 }
168
169
170 Converter const * Converters::getConverter(string const & from,
171                                             string const & to) const
172 {
173         ConverterList::const_iterator const cit =
174                 find_if(converterlist_.begin(), converterlist_.end(),
175                         ConverterEqual(from, to));
176         if (cit != converterlist_.end())
177                 return &(*cit);
178         else
179                 return 0;
180 }
181
182
183 int Converters::getNumber(string const & from, string const & to) const
184 {
185         ConverterList::const_iterator const cit =
186                 find_if(converterlist_.begin(), converterlist_.end(),
187                         ConverterEqual(from, to));
188         if (cit != converterlist_.end())
189                 return distance(converterlist_.begin(), cit);
190         else
191                 return -1;
192 }
193
194
195 void Converters::add(string const & from, string const & to,
196                      string const & command, string const & flags)
197 {
198         formats.add(from);
199         formats.add(to);
200         ConverterList::iterator it = find_if(converterlist_.begin(),
201                                              converterlist_.end(),
202                                              ConverterEqual(from , to));
203
204         Converter converter(from, to, command, flags);
205         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
206                 converter = *it;
207                 converter.command = command;
208                 converter.flags = flags;
209         }
210         converter.readFlags();
211
212         if (converter.latex && (latex_command_.empty() || to == "dvi"))
213                 latex_command_ = subst(command, token_from, "");
214         // If we have both latex & pdflatex, we set latex_command to latex.
215         // The latex_command is used to update the .aux file when running
216         // a converter that uses it.
217
218         if (it == converterlist_.end()) {
219                 converterlist_.push_back(converter);
220         } else {
221                 converter.From = it->From;
222                 converter.To = it->To;
223                 *it = converter;
224         }
225 }
226
227
228 void Converters::erase(string const & from, string const & to)
229 {
230         ConverterList::iterator const it =
231                 find_if(converterlist_.begin(),
232                         converterlist_.end(),
233                         ConverterEqual(from, to));
234         if (it != converterlist_.end())
235                 converterlist_.erase(it);
236 }
237
238
239 // This method updates the pointers From and To in all the converters.
240 // The code is not very efficient, but it doesn't matter as the number
241 // of formats and converters is small.
242 // Furthermore, this method is called only on startup, or after
243 // adding/deleting a format in FormPreferences (the latter calls can be
244 // eliminated if the formats in the Formats class are stored using a map or
245 // a list (instead of a vector), but this will cause other problems).
246 void Converters::update(Formats const & formats)
247 {
248         ConverterList::iterator it = converterlist_.begin();
249         ConverterList::iterator end = converterlist_.end();
250         for (; it != end; ++it) {
251                 it->From = formats.getFormat(it->from);
252                 it->To = formats.getFormat(it->to);
253         }
254 }
255
256
257 // This method updates the pointers From and To in the last converter.
258 // It is called when adding a new converter in FormPreferences
259 void Converters::updateLast(Formats const & formats)
260 {
261         if (converterlist_.begin() != converterlist_.end()) {
262                 ConverterList::iterator it = converterlist_.end() - 1;
263                 it->From = formats.getFormat(it->from);
264                 it->To = formats.getFormat(it->to);
265         }
266 }
267
268
269 void Converters::sort()
270 {
271         std::sort(converterlist_.begin(), converterlist_.end());
272 }
273
274
275 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
276 {
277         for (Graph::EdgePath::const_iterator cit = path.begin();
278              cit != path.end(); ++cit) {
279                 Converter const & conv = converterlist_[*cit];
280                 if (conv.latex)
281                         if (contains(conv.to, "pdf"))
282                                 return OutputParams::PDFLATEX;
283                 if (conv.xml)
284                         return OutputParams::XML;
285         }
286         return OutputParams::LATEX;
287 }
288
289
290 bool Converters::convert(Buffer const * buffer,
291                          FileName const & from_file, FileName const & to_file,
292                          FileName const & orig_from,
293                          string const & from_format, string const & to_format,
294                          ErrorList & errorList, int conversionflags)
295 {
296         if (from_format == to_format)
297                 return move(from_format, from_file, to_file, false);
298
299         if ((conversionflags & try_cache) &&
300             ConverterCache::get().inCache(orig_from, to_format))
301                 return ConverterCache::get().copy(orig_from, to_format, to_file);
302
303         Graph::EdgePath edgepath = getPath(from_format, to_format);
304         if (edgepath.empty()) {
305                 if (conversionflags & try_default) {
306                         // if no special converter defined, then we take the
307                         // default one from ImageMagic.
308                         string const from_ext = from_format.empty() ?
309                                 getExtension(from_file.absFilename()) :
310                                 formats.extension(from_format);
311                         string const to_ext = formats.extension(to_format);
312                         string const command =
313                                 support::os::python() + ' ' +
314                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
315                                 ' ' +
316                                 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
317                                 ' ' +
318                                 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
319                         LYXERR(Debug::FILES)
320                                 << "No converter defined! "
321                                    "I use convertDefault.py:\n\t"
322                                 << command << endl;
323                         Systemcall one;
324                         one.startscript(Systemcall::Wait, command);
325                         if (isFileReadable(to_file)) {
326                                 if (conversionflags & try_cache)
327                                         ConverterCache::get().add(orig_from,
328                                                         to_format, to_file);
329                                 return true;
330                         }
331                 }
332                 Alert::error(_("Cannot convert file"),
333                              bformat(_("No information for converting %1$s "
334                                                     "format files to %2$s.\n"
335                                                     "Define a converter in the preferences."),
336                                                         from_ascii(from_format), from_ascii(to_format)));
337                 return false;
338         }
339
340         // buffer is only invalid for importing, and then runparams is not
341         // used anyway.
342         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
343         runparams.flavor = getFlavor(edgepath);
344
345         // Some converters (e.g. lilypond) can only output files to the
346         // current directory, so we need to change the current directory.
347         // This has the added benefit that all other files that may be
348         // generated by the converter are deleted when LyX closes and do not
349         // clutter the real working directory.
350         string const path(onlyPath(from_file.absFilename()));
351         // Prevent the compiler from optimizing away p
352         FileName pp(path);
353         support::Path p(pp);
354
355         // empty the error list before any new conversion takes place.
356         errorList.clear();
357
358         bool run_latex = false;
359         string from_base = changeExtension(from_file.absFilename(), "");
360         string to_base = changeExtension(to_file.absFilename(), "");
361         FileName infile;
362         FileName outfile = from_file;
363         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
364              cit != edgepath.end(); ++cit) {
365                 Converter const & conv = converterlist_[*cit];
366                 bool dummy = conv.To->dummy() && conv.to != "program";
367                 if (!dummy)
368                         LYXERR(Debug::FILES) << "Converting from  "
369                                << conv.from << " to " << conv.to << endl;
370                 infile = outfile;
371                 outfile = FileName(conv.result_dir.empty()
372                         ? changeExtension(from_file.absFilename(), conv.To->extension())
373                         : addName(subst(conv.result_dir,
374                                         token_base, from_base),
375                                   subst(conv.result_file,
376                                         token_base, onlyFilename(from_base))));
377
378                 // if input and output files are equal, we use a
379                 // temporary file as intermediary (JMarc)
380                 FileName real_outfile;
381                 if (outfile == infile) {
382                         real_outfile = infile;
383                         outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
384                 }
385
386                 if (conv.latex) {
387                         run_latex = true;
388                         string const command = subst(conv.command, token_from, "");
389                         LYXERR(Debug::FILES) << "Running " << command << endl;
390                         if (!runLaTeX(*buffer, command, runparams, errorList))
391                                 return false;
392                 } else {
393                         if (conv.need_aux && !run_latex
394                             && !latex_command_.empty()) {
395                                 LYXERR(Debug::FILES)
396                                         << "Running " << latex_command_
397                                         << " to update aux file"<<  endl;
398                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
399                         }
400
401                         // FIXME UNICODE
402                         string const infile2 = (conv.original_dir)
403                                 ? infile.absFilename() : to_utf8(makeRelPath(from_utf8(infile.absFilename()),
404                                                                              from_utf8(path)));
405                         string const outfile2 = (conv.original_dir)
406                                 ? outfile.absFilename() : to_utf8(makeRelPath(from_utf8(outfile.absFilename()),
407                                                                               from_utf8(path)));
408
409                         string command = conv.command;
410                         command = subst(command, token_from, quoteName(infile2));
411                         command = subst(command, token_base, quoteName(from_base));
412                         command = subst(command, token_to, quoteName(outfile2));
413                         command = libScriptSearch(command);
414
415                         if (!conv.parselog.empty())
416                                 command += " 2> " + quoteName(infile2 + ".out");
417
418                         if (conv.from == "dvi" && conv.to == "ps")
419                                 command = add_options(command,
420                                                       buffer->params().dvips_options());
421                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
422                                 command = add_options(command,
423                                                       dvipdfm_options(buffer->params()));
424
425                         LYXERR(Debug::FILES) << "Calling " << command << endl;
426                         if (buffer)
427                                 buffer->message(_("Executing command: ")
428                                 + from_utf8(command));
429
430                         Systemcall::Starttype const type = (dummy)
431                                 ? Systemcall::DontWait : Systemcall::Wait;
432                         Systemcall one;
433                         int res;
434                         if (conv.original_dir) {
435                                 FileName path(buffer->filePath());
436                                 support::Path p(path);
437                                 res = one.startscript(type,
438                                         to_filesystem8bit(from_utf8(command)));
439                         } else
440                                 res = one.startscript(type,
441                                         to_filesystem8bit(from_utf8(command)));
442
443                         if (!real_outfile.empty()) {
444                                 Mover const & mover = getMover(conv.to);
445                                 if (!mover.rename(outfile, real_outfile))
446                                         res = -1;
447                                 else
448                                         LYXERR(Debug::FILES)
449                                                 << "renaming file " << outfile
450                                                 << " to " << real_outfile
451                                                 << endl;
452                                 // Finally, don't forget to tell any future
453                                 // converters to use the renamed file...
454                                 outfile = real_outfile;
455                         }
456
457                         if (!conv.parselog.empty()) {
458                                 string const logfile =  infile2 + ".log";
459                                 string const script = libScriptSearch(conv.parselog);
460                                 string const command2 = script +
461                                         " < " + quoteName(infile2 + ".out") +
462                                         " > " + quoteName(logfile);
463                                 one.startscript(Systemcall::Wait,
464                                         to_filesystem8bit(from_utf8(command2)));
465                                 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
466                                         return false;
467                         }
468
469                         if (res) {
470                                 if (conv.to == "program") {
471                                         Alert::error(_("Build errors"),
472                                                 _("There were errors during the build process."));
473                                 } else {
474 // FIXME: this should go out of here. For example, here we cannot say if
475 // it is a document (.lyx) or something else. Same goes for elsewhere.
476                                         Alert::error(_("Cannot convert file"),
477                                                 bformat(_("An error occurred whilst running %1$s"),
478                                                 from_utf8(command.substr(0, 50))));
479                                 }
480                                 return false;
481                         }
482                 }
483         }
484
485         Converter const & conv = converterlist_[edgepath.back()];
486         if (conv.To->dummy())
487                 return true;
488
489         if (!conv.result_dir.empty()) {
490                 // The converter has put the file(s) in a directory.
491                 // In this case we ignore the given to_file.
492                 if (from_base != to_base) {
493                         string const from = subst(conv.result_dir,
494                                             token_base, from_base);
495                         string const to = subst(conv.result_dir,
496                                           token_base, to_base);
497                         Mover const & mover = getMover(conv.from);
498                         if (!mover.rename(FileName(from), FileName(to))) {
499                                 Alert::error(_("Cannot convert file"),
500                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
501                                                 from_utf8(from), from_utf8(to)));
502                                 return false;
503                         }
504                 }
505                 return true;
506         } else {
507                 if (conversionflags & try_cache)
508                         ConverterCache::get().add(orig_from, to_format, outfile);
509                 return move(conv.to, outfile, to_file, conv.latex);
510         }
511 }
512
513
514 bool Converters::move(string const & fmt,
515                       FileName const & from, FileName const & to, bool copy)
516 {
517         if (from == to)
518                 return true;
519
520         bool no_errors = true;
521         string const path = onlyPath(from.absFilename());
522         string const base = onlyFilename(removeExtension(from.absFilename()));
523         string const to_base = removeExtension(to.absFilename());
524         string const to_extension = getExtension(to.absFilename());
525
526         vector<FileName> const files = dirList(FileName(path),
527                         getExtension(from.absFilename()));
528         for (vector<FileName>::const_iterator it = files.begin();
529              it != files.end(); ++it) {
530                 string const from2 = it->absFilename();
531                 string const file2 = onlyFilename(from2);
532                 if (prefixIs(file2, base)) {
533                         string const to2 = changeExtension(
534                                 to_base + file2.substr(base.length()),
535                                 to_extension);
536                         LYXERR(Debug::FILES) << "moving " << from2
537                                              << " to " << to2 << endl;
538
539                         Mover const & mover = getMover(fmt);
540                         bool const moved = copy
541                                 ? mover.copy(*it, FileName(to2))
542                                 : mover.rename(*it, FileName(to2));
543                         if (!moved && no_errors) {
544                                 Alert::error(_("Cannot convert file"),
545                                         bformat(copy ?
546                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
547                                                 _("Could not move a temporary file from %1$s to %2$s."),
548                                                 from_utf8(from2), from_utf8(to2)));
549                                 no_errors = false;
550                         }
551                 }
552         }
553         return no_errors;
554 }
555
556
557 bool Converters::formatIsUsed(string const & format)
558 {
559         ConverterList::const_iterator cit = converterlist_.begin();
560         ConverterList::const_iterator end = converterlist_.end();
561         for (; cit != end; ++cit) {
562                 if (cit->from == format || cit->to == format)
563                         return true;
564         }
565         return false;
566 }
567
568
569 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
570                          FileName const & filename, ErrorList & errorList)
571 {
572         OutputParams runparams(0);
573         runparams.flavor = OutputParams::LATEX;
574         LaTeX latex("", runparams, filename);
575         TeXErrors terr;
576         int const result = latex.scanLogFile(terr);
577
578         if (result & LaTeX::ERRORS)
579                 bufferErrors(buffer, terr, errorList);
580
581         return true;
582 }
583
584
585 namespace {
586
587 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
588 public:
589         showMessage(Buffer const & b) : buffer_(b) {};
590         void operator()(docstring const & m) const
591         {
592                 buffer_.message(m);
593         }
594 private:
595         Buffer const & buffer_;
596 };
597
598 }
599
600
601 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
602                           OutputParams const & runparams, ErrorList & errorList)
603 {
604         buffer.busy(true);
605         buffer.message(_("Running LaTeX..."));
606
607         runparams.document_language = buffer.params().language->babel();
608
609         // do the LaTeX run(s)
610         string const name = buffer.getLatexName();
611         LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
612         TeXErrors terr;
613         showMessage show(buffer);
614         latex.message.connect(show);
615         int const result = latex.run(terr);
616
617         if (result & LaTeX::ERRORS)
618                 bufferErrors(buffer, terr, errorList);
619
620         // check return value from latex.run().
621         if ((result & LaTeX::NO_LOGFILE)) {
622                 docstring const str =
623                         bformat(_("LaTeX did not run successfully. "
624                                                "Additionally, LyX could not locate "
625                                                "the LaTeX log %1$s."), from_utf8(name));
626                 Alert::error(_("LaTeX failed"), str);
627         } else if (result & LaTeX::NO_OUTPUT) {
628                 Alert::warning(_("Output is empty"),
629                                _("An empty output file was generated."));
630         }
631
632
633         buffer.busy(false);
634
635         int const ERROR_MASK =
636                         LaTeX::NO_LOGFILE |
637                         LaTeX::ERRORS |
638                         LaTeX::NO_OUTPUT;
639
640         return (result & ERROR_MASK) == 0;
641
642 }
643
644
645
646 void Converters::buildGraph()
647 {
648         G_.init(formats.size());
649         ConverterList::iterator beg = converterlist_.begin();
650         ConverterList::iterator const end = converterlist_.end();
651         for (ConverterList::iterator it = beg; it != end ; ++it) {
652                 int const s = formats.getNumber(it->from);
653                 int const t = formats.getNumber(it->to);
654                 G_.addEdge(s,t);
655         }
656 }
657
658
659 std::vector<Format const *> const
660 Converters::intToFormat(std::vector<int> const & input)
661 {
662         vector<Format const *> result(input.size());
663
664         vector<int>::const_iterator it = input.begin();
665         vector<int>::const_iterator const end = input.end();
666         vector<Format const *>::iterator rit = result.begin();
667         for ( ; it != end; ++it, ++rit) {
668                 *rit = &formats.get(*it);
669         }
670         return result;
671 }
672
673
674 vector<Format const *> const
675 Converters::getReachableTo(string const & target, bool const clear_visited)
676 {
677         vector<int> const & reachablesto =
678                 G_.getReachableTo(formats.getNumber(target), clear_visited);
679
680         return intToFormat(reachablesto);
681 }
682
683
684 vector<Format const *> const
685 Converters::getReachable(string const & from, bool const only_viewable,
686                          bool const clear_visited)
687 {
688         vector<int> const & reachables =
689                 G_.getReachable(formats.getNumber(from),
690                                 only_viewable,
691                                 clear_visited);
692
693         return intToFormat(reachables);
694 }
695
696
697 bool Converters::isReachable(string const & from, string const & to)
698 {
699         return G_.isReachable(formats.getNumber(from),
700                               formats.getNumber(to));
701 }
702
703
704 Graph::EdgePath const
705 Converters::getPath(string const & from, string const & to)
706 {
707         return G_.getPath(formats.getNumber(from),
708                           formats.getNumber(to));
709 }
710
711 } // namespace lyx