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"
19 #include "ErrorList.h"
25 #include "frontends/alert.h"
27 #include "support/debug.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Path.h"
35 #include "support/Systemcall.h"
45 using support::addName;
46 using support::bformat;
47 using support::changeExtension;
48 using support::compare_ascii_no_case;
49 using support::contains;
50 using support::FileName;
51 using support::getExtension;
52 using support::libFileSearch;
53 using support::libScriptSearch;
54 using support::makeAbsPath;
55 using support::makeRelPath;
56 using support::onlyFilename;
57 using support::onlyPath;
58 using support::package;
59 using support::prefixIs;
60 using support::quoteName;
61 using support::removeExtension;
64 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 {
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());
318 LYXERR(Debug::FILES, "No converter defined! "
319 "I use convertDefault.py:\n\t" << command);
321 one.startscript(Systemcall::Wait, command);
322 if (to_file.isReadableFile()) {
323 if (conversionflags & try_cache)
324 ConverterCache::get().add(orig_from,
329 Alert::error(_("Cannot convert file"),
330 bformat(_("No information for converting %1$s "
331 "format files to %2$s.\n"
332 "Define a converter in the preferences."),
333 from_ascii(from_format), from_ascii(to_format)));
337 // buffer is only invalid for importing, and then runparams is not
339 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
340 runparams.flavor = getFlavor(edgepath);
342 // Some converters (e.g. lilypond) can only output files to the
343 // current directory, so we need to change the current directory.
344 // This has the added benefit that all other files that may be
345 // generated by the converter are deleted when LyX closes and do not
346 // clutter the real working directory.
347 string const path(onlyPath(from_file.absFilename()));
348 // Prevent the compiler from optimizing away p
350 support::PathChanger p(pp);
352 // empty the error list before any new conversion takes place.
355 bool run_latex = false;
356 string from_base = changeExtension(from_file.absFilename(), "");
357 string to_base = changeExtension(to_file.absFilename(), "");
359 FileName outfile = from_file;
360 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
361 cit != edgepath.end(); ++cit) {
362 Converter const & conv = converterlist_[*cit];
363 bool dummy = conv.To->dummy() && conv.to != "program";
365 LYXERR(Debug::FILES, "Converting from "
366 << conv.from << " to " << conv.to);
369 outfile = FileName(conv.result_dir.empty()
370 ? changeExtension(from_file.absFilename(), conv.To->extension())
371 : addName(subst(conv.result_dir,
372 token_base, from_base),
373 subst(conv.result_file,
374 token_base, onlyFilename(from_base))));
376 // if input and output files are equal, we use a
377 // temporary file as intermediary (JMarc)
378 FileName real_outfile;
379 if (outfile == infile) {
380 real_outfile = infile;
381 // when importing, a buffer does not necessarily exist
383 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
385 outfile = FileName(addName(package().temp_dir().absFilename(),
391 string const command = subst(conv.command, token_from, "");
392 LYXERR(Debug::FILES, "Running " << command);
393 if (!runLaTeX(*buffer, command, runparams, errorList))
396 if (conv.need_aux && !run_latex
397 && !latex_command_.empty()) {
398 LYXERR(Debug::FILES, "Running " << latex_command_
399 << " to update aux file");
400 runLaTeX(*buffer, latex_command_, runparams, errorList);
404 string const infile2 =
405 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
406 string const outfile2 =
407 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
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);
415 if (!conv.parselog.empty())
416 command += " 2> " + quoteName(infile2 + ".out");
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()));
425 LYXERR(Debug::FILES, "Calling " << command);
427 buffer->message(_("Executing command: ")
428 + from_utf8(command));
433 res = one.startscript(Systemcall::DontWait,
434 to_filesystem8bit(from_utf8(command)));
435 // We're not waiting for the result, so we can't do anything
438 res = one.startscript(Systemcall::Wait,
439 to_filesystem8bit(from_utf8(command)));
440 if (!real_outfile.empty()) {
441 Mover const & mover = getMover(conv.to);
442 if (!mover.rename(outfile, real_outfile))
445 LYXERR(Debug::FILES, "renaming file " << outfile
446 << " to " << real_outfile);
447 // Finally, don't forget to tell any future
448 // converters to use the renamed file...
449 outfile = real_outfile;
452 if (!conv.parselog.empty()) {
453 string const logfile = infile2 + ".log";
454 string const script = libScriptSearch(conv.parselog);
455 string const command2 = script +
456 " < " + quoteName(infile2 + ".out") +
457 " > " + quoteName(logfile);
458 one.startscript(Systemcall::Wait,
459 to_filesystem8bit(from_utf8(command2)));
460 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
466 if (conv.to == "program") {
467 Alert::error(_("Build errors"),
468 _("There were errors during the build process."));
470 // FIXME: this should go out of here. For example, here we cannot say if
471 // it is a document (.lyx) or something else. Same goes for elsewhere.
472 Alert::error(_("Cannot convert file"),
473 bformat(_("An error occurred whilst running %1$s"),
474 from_utf8(command.substr(0, 50))));
481 Converter const & conv = converterlist_[edgepath.back()];
482 if (conv.To->dummy())
485 if (!conv.result_dir.empty()) {
486 // The converter has put the file(s) in a directory.
487 // In this case we ignore the given to_file.
488 if (from_base != to_base) {
489 string const from = subst(conv.result_dir,
490 token_base, from_base);
491 string const to = subst(conv.result_dir,
492 token_base, to_base);
493 Mover const & mover = getMover(conv.from);
494 if (!mover.rename(FileName(from), FileName(to))) {
495 Alert::error(_("Cannot convert file"),
496 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
497 from_utf8(from), from_utf8(to)));
503 if (conversionflags & try_cache)
504 ConverterCache::get().add(orig_from, to_format, outfile);
505 return move(conv.to, outfile, to_file, conv.latex);
510 bool Converters::move(string const & fmt,
511 FileName const & from, FileName const & to, bool copy)
516 bool no_errors = true;
517 string const path = onlyPath(from.absFilename());
518 string const base = onlyFilename(removeExtension(from.absFilename()));
519 string const to_base = removeExtension(to.absFilename());
520 string const to_extension = getExtension(to.absFilename());
522 vector<FileName> const files =
523 support::dirList(FileName(path), getExtension(from.absFilename()));
524 for (vector<FileName>::const_iterator it = files.begin();
525 it != files.end(); ++it) {
526 string const from2 = it->absFilename();
527 string const file2 = onlyFilename(from2);
528 if (prefixIs(file2, base)) {
529 string const to2 = changeExtension(
530 to_base + file2.substr(base.length()),
532 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
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 buffer.bufferErrors(terr, errorList);
583 : public boost::signals::trackable {
585 ShowMessage(Buffer const & b) : buffer_(b) {}
586 void operator()(docstring const & msg) const { buffer_.message(msg); }
588 Buffer const & buffer_;
594 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
595 OutputParams const & runparams, ErrorList & errorList)
597 buffer.setBusy(true);
598 buffer.message(_("Running LaTeX..."));
600 runparams.document_language = buffer.params().language->babel();
602 // do the LaTeX run(s)
603 string const name = buffer.latexName();
604 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
606 ShowMessage show(buffer);
607 latex.message.connect(show);
608 int const result = latex.run(terr);
610 if (result & LaTeX::ERRORS)
611 buffer.bufferErrors(terr, errorList);
613 // check return value from latex.run().
614 if ((result & LaTeX::NO_LOGFILE)) {
615 docstring const str =
616 bformat(_("LaTeX did not run successfully. "
617 "Additionally, LyX could not locate "
618 "the LaTeX log %1$s."), from_utf8(name));
619 Alert::error(_("LaTeX failed"), str);
620 } else if (result & LaTeX::NO_OUTPUT) {
621 Alert::warning(_("Output is empty"),
622 _("An empty output file was generated."));
626 buffer.setBusy(false);
628 int const ERROR_MASK =
633 return (result & ERROR_MASK) == 0;
639 void Converters::buildGraph()
641 G_.init(formats.size());
642 ConverterList::iterator beg = converterlist_.begin();
643 ConverterList::iterator const end = converterlist_.end();
644 for (ConverterList::iterator it = beg; it != end ; ++it) {
645 int const s = formats.getNumber(it->from);
646 int const t = formats.getNumber(it->to);
652 std::vector<Format const *> const
653 Converters::intToFormat(std::vector<int> const & input)
655 vector<Format const *> result(input.size());
657 vector<int>::const_iterator it = input.begin();
658 vector<int>::const_iterator const end = input.end();
659 vector<Format const *>::iterator rit = result.begin();
660 for ( ; it != end; ++it, ++rit) {
661 *rit = &formats.get(*it);
667 vector<Format const *> const
668 Converters::getReachableTo(string const & target, bool const clear_visited)
670 vector<int> const & reachablesto =
671 G_.getReachableTo(formats.getNumber(target), clear_visited);
673 return intToFormat(reachablesto);
677 vector<Format const *> const
678 Converters::getReachable(string const & from, bool const only_viewable,
679 bool const clear_visited)
681 vector<int> const & reachables =
682 G_.getReachable(formats.getNumber(from),
686 return intToFormat(reachables);
690 bool Converters::isReachable(string const & from, string const & to)
692 return G_.isReachable(formats.getNumber(from),
693 formats.getNumber(to));
697 Graph::EdgePath Converters::getPath(string const & from, string const & to)
699 return G_.getPath(formats.getNumber(from),
700 formats.getNumber(to));
704 vector<Format const *> Converters::importableFormats()
706 vector<string> l = loaders();
707 vector<Format const *> result = getReachableTo(l[0], true);
708 for (vector<string>::const_iterator it = l.begin() + 1;
709 it != l.end(); ++it) {
710 vector<Format const *> r = getReachableTo(*it, false);
711 result.insert(result.end(), r.begin(), r.end());
717 vector<string> Converters::loaders() const
722 v.push_back("textparagraph");