3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "Converter.h"
15 #include "ConverterCache.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
20 #include "ErrorList.h"
27 #include "frontends/alert.h"
29 #include "support/filetools.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/Path.h"
33 #include "support/Systemcall.h"
38 using support::addName;
39 using support::bformat;
40 using support::changeExtension;
41 using support::compare_ascii_no_case;
42 using support::contains;
43 using support::dirList;
44 using support::FileName;
45 using support::getExtension;
46 using support::isFileReadable;
47 using support::libFileSearch;
48 using support::libScriptSearch;
49 using support::makeAbsPath;
50 using support::makeRelPath;
51 using support::onlyFilename;
52 using support::onlyPath;
53 using support::prefixIs;
54 using support::quoteName;
55 using support::removeExtension;
58 using support::Systemcall;
66 namespace Alert = lyx::frontend::Alert;
71 string const token_from("$$i");
72 string const token_base("$$b");
73 string const token_to("$$o");
74 string const token_path("$$p");
78 string const add_options(string const & command, string const & options)
81 string const tail = split(command, head, ' ');
82 return head + ' ' + options + ' ' + tail;
86 string const dvipdfm_options(BufferParams const & bp)
90 if (bp.papersize != PAPER_CUSTOM) {
91 string const paper_size = bp.paperSizeName();
92 if (paper_size != "b5" && paper_size != "foolscap")
93 result = "-p "+ paper_size;
95 if (bp.orientation == ORIENTATION_LANDSCAPE)
103 class ConverterEqual : public std::binary_function<string, string, bool> {
105 ConverterEqual(string const & from, string const & to)
106 : from_(from), to_(to) {}
107 bool operator()(Converter const & c) const {
108 return c.from == from_ && c.to == to_;
118 Converter::Converter(string const & f, string const & t,
119 string const & c, string const & l)
120 : from(f), to(t), command(c), flags(l),
121 From(0), To(0), latex(false), xml(false),
126 void Converter::readFlags()
128 string flag_list(flags);
129 while (!flag_list.empty()) {
130 string flag_name, flag_value;
131 flag_list = split(flag_list, flag_value, ',');
132 flag_value = split(flag_value, flag_name, '=');
133 if (flag_name == "latex")
135 else if (flag_name == "xml")
137 else if (flag_name == "needaux")
139 else if (flag_name == "resultdir")
140 result_dir = (flag_value.empty())
141 ? token_base : flag_value;
142 else if (flag_name == "resultfile")
143 result_file = flag_value;
144 else if (flag_name == "parselog")
145 parselog = flag_value;
147 if (!result_dir.empty() && result_file.empty())
148 result_file = "index." + formats.extension(to);
149 //if (!contains(command, token_from))
154 bool operator<(Converter const & a, Converter const & b)
156 // use the compare_ascii_no_case instead of compare_no_case,
157 // because in turkish, 'i' is not the lowercase version of 'I',
158 // and thus turkish locale breaks parsing of tags.
159 int const i = compare_ascii_no_case(a.From->prettyname(),
160 b.From->prettyname());
162 return compare_ascii_no_case(a.To->prettyname(),
163 b.To->prettyname()) < 0;
169 Converter const * Converters::getConverter(string const & from,
170 string const & to) const
172 ConverterList::const_iterator const cit =
173 find_if(converterlist_.begin(), converterlist_.end(),
174 ConverterEqual(from, to));
175 if (cit != converterlist_.end())
182 int Converters::getNumber(string const & from, string const & to) const
184 ConverterList::const_iterator const cit =
185 find_if(converterlist_.begin(), converterlist_.end(),
186 ConverterEqual(from, to));
187 if (cit != converterlist_.end())
188 return distance(converterlist_.begin(), cit);
194 void Converters::add(string const & from, string const & to,
195 string const & command, string const & flags)
199 ConverterList::iterator it = find_if(converterlist_.begin(),
200 converterlist_.end(),
201 ConverterEqual(from , to));
203 Converter converter(from, to, command, flags);
204 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
206 converter.command = command;
207 converter.flags = flags;
209 converter.readFlags();
211 if (converter.latex && (latex_command_.empty() || to == "dvi"))
212 latex_command_ = subst(command, token_from, "");
213 // If we have both latex & pdflatex, we set latex_command to latex.
214 // The latex_command is used to update the .aux file when running
215 // a converter that uses it.
217 if (it == converterlist_.end()) {
218 converterlist_.push_back(converter);
220 converter.From = it->From;
221 converter.To = it->To;
227 void Converters::erase(string const & from, string const & to)
229 ConverterList::iterator const it =
230 find_if(converterlist_.begin(),
231 converterlist_.end(),
232 ConverterEqual(from, to));
233 if (it != converterlist_.end())
234 converterlist_.erase(it);
238 // This method updates the pointers From and To in all the converters.
239 // The code is not very efficient, but it doesn't matter as the number
240 // of formats and converters is small.
241 // Furthermore, this method is called only on startup, or after
242 // adding/deleting a format in FormPreferences (the latter calls can be
243 // eliminated if the formats in the Formats class are stored using a map or
244 // a list (instead of a vector), but this will cause other problems).
245 void Converters::update(Formats const & formats)
247 ConverterList::iterator it = converterlist_.begin();
248 ConverterList::iterator end = converterlist_.end();
249 for (; it != end; ++it) {
250 it->From = formats.getFormat(it->from);
251 it->To = formats.getFormat(it->to);
256 // This method updates the pointers From and To in the last converter.
257 // It is called when adding a new converter in FormPreferences
258 void Converters::updateLast(Formats const & formats)
260 if (converterlist_.begin() != converterlist_.end()) {
261 ConverterList::iterator it = converterlist_.end() - 1;
262 it->From = formats.getFormat(it->from);
263 it->To = formats.getFormat(it->to);
268 void Converters::sort()
270 std::sort(converterlist_.begin(), converterlist_.end());
274 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
276 for (Graph::EdgePath::const_iterator cit = path.begin();
277 cit != path.end(); ++cit) {
278 Converter const & conv = converterlist_[*cit];
280 if (contains(conv.to, "pdf"))
281 return OutputParams::PDFLATEX;
283 return OutputParams::XML;
285 return OutputParams::LATEX;
289 bool Converters::convert(Buffer const * buffer,
290 FileName const & from_file, FileName const & to_file,
291 FileName const & orig_from,
292 string const & from_format, string const & to_format,
293 ErrorList & errorList, int conversionflags)
295 if (from_format == to_format)
296 return move(from_format, from_file, to_file, false);
298 if ((conversionflags & try_cache) &&
299 ConverterCache::get().inCache(orig_from, to_format))
300 return ConverterCache::get().copy(orig_from, to_format, to_file);
302 Graph::EdgePath edgepath = getPath(from_format, to_format);
303 if (edgepath.empty()) {
304 if (conversionflags & try_default) {
305 // if no special converter defined, then we take the
306 // default one from ImageMagic.
307 string const from_ext = from_format.empty() ?
308 getExtension(from_file.absFilename()) :
309 formats.extension(from_format);
310 string const to_ext = formats.extension(to_format);
311 string const command =
312 support::os::python() + ' ' +
313 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
315 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
317 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
319 << "No converter defined! "
320 "I use convertDefault.py:\n\t"
323 one.startscript(Systemcall::Wait, command);
324 if (isFileReadable(to_file)) {
325 if (conversionflags & try_cache)
326 ConverterCache::get().add(orig_from,
331 Alert::error(_("Cannot convert file"),
332 bformat(_("No information for converting %1$s "
333 "format files to %2$s.\n"
334 "Define a converter in the preferences."),
335 from_ascii(from_format), from_ascii(to_format)));
339 // buffer is only invalid for importing, and then runparams is not
341 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
342 runparams.flavor = getFlavor(edgepath);
344 // Some converters (e.g. lilypond) can only output files to the
345 // current directory, so we need to change the current directory.
346 // This has the added benefit that all other files that may be
347 // generated by the converter are deleted when LyX closes and do not
348 // clutter the real working directory.
349 string const path(onlyPath(from_file.absFilename()));
350 // Prevent the compiler from optimizing away p
354 // empty the error list before any new conversion takes place.
357 bool run_latex = false;
358 string from_base = changeExtension(from_file.absFilename(), "");
359 string to_base = changeExtension(to_file.absFilename(), "");
361 FileName outfile = from_file;
362 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
363 cit != edgepath.end(); ++cit) {
364 Converter const & conv = converterlist_[*cit];
365 bool dummy = conv.To->dummy() && conv.to != "program";
367 LYXERR(Debug::FILES) << "Converting from "
368 << conv.from << " to " << conv.to << endl;
370 outfile = FileName(conv.result_dir.empty()
371 ? changeExtension(from_file.absFilename(), conv.To->extension())
372 : addName(subst(conv.result_dir,
373 token_base, from_base),
374 subst(conv.result_file,
375 token_base, onlyFilename(from_base))));
377 // if input and output files are equal, we use a
378 // temporary file as intermediary (JMarc)
379 FileName real_outfile;
380 if (outfile == infile) {
381 real_outfile = infile;
382 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
387 string const command = subst(conv.command, token_from, "");
388 LYXERR(Debug::FILES) << "Running " << command << endl;
389 if (!runLaTeX(*buffer, command, runparams, errorList))
392 if (conv.need_aux && !run_latex
393 && !latex_command_.empty()) {
395 << "Running " << latex_command_
396 << " to update aux file"<< endl;
397 runLaTeX(*buffer, latex_command_, runparams, errorList);
401 string const infile2 =
402 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
403 string const outfile2 =
404 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
406 string command = conv.command;
407 command = subst(command, token_from, quoteName(infile2));
408 command = subst(command, token_base, quoteName(from_base));
409 command = subst(command, token_to, quoteName(outfile2));
410 command = libScriptSearch(command);
412 if (!conv.parselog.empty())
413 command += " 2> " + quoteName(infile2 + ".out");
415 if (conv.from == "dvi" && conv.to == "ps")
416 command = add_options(command,
417 buffer->params().dvips_options());
418 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
419 command = add_options(command,
420 dvipdfm_options(buffer->params()));
422 LYXERR(Debug::FILES) << "Calling " << command << endl;
424 buffer->message(_("Executing command: ")
425 + from_utf8(command));
430 res = one.startscript(Systemcall::DontWait,
431 to_filesystem8bit(from_utf8(command)));
432 // We're not waiting for the result, so we can't do anything
435 res = one.startscript(Systemcall::Wait,
436 to_filesystem8bit(from_utf8(command)));
437 if (!real_outfile.empty()) {
438 Mover const & mover = getMover(conv.to);
439 if (!mover.rename(outfile, real_outfile))
443 << "renaming file " << outfile
444 << " to " << real_outfile
446 // Finally, don't forget to tell any future
447 // converters to use the renamed file...
448 outfile = real_outfile;
451 if (!conv.parselog.empty()) {
452 string const logfile = infile2 + ".log";
453 string const script = libScriptSearch(conv.parselog);
454 string const command2 = script +
455 " < " + quoteName(infile2 + ".out") +
456 " > " + quoteName(logfile);
457 one.startscript(Systemcall::Wait,
458 to_filesystem8bit(from_utf8(command2)));
459 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
465 if (conv.to == "program") {
466 Alert::error(_("Build errors"),
467 _("There were errors during the build process."));
469 // FIXME: this should go out of here. For example, here we cannot say if
470 // it is a document (.lyx) or something else. Same goes for elsewhere.
471 Alert::error(_("Cannot convert file"),
472 bformat(_("An error occurred whilst running %1$s"),
473 from_utf8(command.substr(0, 50))));
480 Converter const & conv = converterlist_[edgepath.back()];
481 if (conv.To->dummy())
484 if (!conv.result_dir.empty()) {
485 // The converter has put the file(s) in a directory.
486 // In this case we ignore the given to_file.
487 if (from_base != to_base) {
488 string const from = subst(conv.result_dir,
489 token_base, from_base);
490 string const to = subst(conv.result_dir,
491 token_base, to_base);
492 Mover const & mover = getMover(conv.from);
493 if (!mover.rename(FileName(from), FileName(to))) {
494 Alert::error(_("Cannot convert file"),
495 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
496 from_utf8(from), from_utf8(to)));
502 if (conversionflags & try_cache)
503 ConverterCache::get().add(orig_from, to_format, outfile);
504 return move(conv.to, outfile, to_file, conv.latex);
509 bool Converters::move(string const & fmt,
510 FileName const & from, FileName const & to, bool copy)
515 bool no_errors = true;
516 string const path = onlyPath(from.absFilename());
517 string const base = onlyFilename(removeExtension(from.absFilename()));
518 string const to_base = removeExtension(to.absFilename());
519 string const to_extension = getExtension(to.absFilename());
521 vector<FileName> const files = dirList(FileName(path),
522 getExtension(from.absFilename()));
523 for (vector<FileName>::const_iterator it = files.begin();
524 it != files.end(); ++it) {
525 string const from2 = it->absFilename();
526 string const file2 = onlyFilename(from2);
527 if (prefixIs(file2, base)) {
528 string const to2 = changeExtension(
529 to_base + file2.substr(base.length()),
531 LYXERR(Debug::FILES) << "moving " << from2
532 << " to " << to2 << endl;
534 Mover const & mover = getMover(fmt);
535 bool const moved = copy
536 ? mover.copy(*it, FileName(to2))
537 : mover.rename(*it, FileName(to2));
538 if (!moved && no_errors) {
539 Alert::error(_("Cannot convert file"),
541 _("Could not copy a temporary file from %1$s to %2$s.") :
542 _("Could not move a temporary file from %1$s to %2$s."),
543 from_utf8(from2), from_utf8(to2)));
552 bool Converters::formatIsUsed(string const & format)
554 ConverterList::const_iterator cit = converterlist_.begin();
555 ConverterList::const_iterator end = converterlist_.end();
556 for (; cit != end; ++cit) {
557 if (cit->from == format || cit->to == format)
564 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
565 FileName const & filename, ErrorList & errorList)
567 OutputParams runparams(0);
568 runparams.flavor = OutputParams::LATEX;
569 LaTeX latex("", runparams, filename);
571 int const result = latex.scanLogFile(terr);
573 if (result & LaTeX::ERRORS)
574 bufferErrors(buffer, terr, errorList);
582 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
584 showMessage(Buffer const & b) : buffer_(b) {};
585 void operator()(docstring const & m) const
590 Buffer const & buffer_;
596 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
597 OutputParams const & runparams, ErrorList & errorList)
600 buffer.message(_("Running LaTeX..."));
602 runparams.document_language = buffer.params().language->babel();
604 // do the LaTeX run(s)
605 string const name = buffer.getLatexName();
606 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
608 showMessage show(buffer);
609 latex.message.connect(show);
610 int const result = latex.run(terr);
612 if (result & LaTeX::ERRORS)
613 bufferErrors(buffer, terr, errorList);
615 // check return value from latex.run().
616 if ((result & LaTeX::NO_LOGFILE)) {
617 docstring const str =
618 bformat(_("LaTeX did not run successfully. "
619 "Additionally, LyX could not locate "
620 "the LaTeX log %1$s."), from_utf8(name));
621 Alert::error(_("LaTeX failed"), str);
622 } else if (result & LaTeX::NO_OUTPUT) {
623 Alert::warning(_("Output is empty"),
624 _("An empty output file was generated."));
630 int const ERROR_MASK =
635 return (result & ERROR_MASK) == 0;
641 void Converters::buildGraph()
643 G_.init(formats.size());
644 ConverterList::iterator beg = converterlist_.begin();
645 ConverterList::iterator const end = converterlist_.end();
646 for (ConverterList::iterator it = beg; it != end ; ++it) {
647 int const s = formats.getNumber(it->from);
648 int const t = formats.getNumber(it->to);
654 std::vector<Format const *> const
655 Converters::intToFormat(std::vector<int> const & input)
657 vector<Format const *> result(input.size());
659 vector<int>::const_iterator it = input.begin();
660 vector<int>::const_iterator const end = input.end();
661 vector<Format const *>::iterator rit = result.begin();
662 for ( ; it != end; ++it, ++rit) {
663 *rit = &formats.get(*it);
669 vector<Format const *> const
670 Converters::getReachableTo(string const & target, bool const clear_visited)
672 vector<int> const & reachablesto =
673 G_.getReachableTo(formats.getNumber(target), clear_visited);
675 return intToFormat(reachablesto);
679 vector<Format const *> const
680 Converters::getReachable(string const & from, bool const only_viewable,
681 bool const clear_visited)
683 vector<int> const & reachables =
684 G_.getReachable(formats.getNumber(from),
688 return intToFormat(reachables);
692 bool Converters::isReachable(string const & from, string const & to)
694 return G_.isReachable(formats.getNumber(from),
695 formats.getNumber(to));
699 Graph::EdgePath const
700 Converters::getPath(string const & from, string const & to)
702 return G_.getPath(formats.getNumber(from),
703 formats.getNumber(to));