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"
16 #include "buffer_funcs.h"
17 #include "BufferParams.h"
18 #include "ConverterCache.h"
20 #include "ErrorList.h"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/FileNameList.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 #include "support/Path.h"
36 #include "support/Systemcall.h"
39 using namespace lyx::support;
43 namespace Alert = lyx::frontend::Alert;
48 string const token_from("$$i");
49 string const token_base("$$b");
50 string const token_to("$$o");
51 string const token_path("$$p");
52 string const token_orig_path("$$r");
53 string const token_encoding("$$e");
54 string const token_latex_encoding("$$E");
57 string const add_options(string const & command, string const & options)
60 string const tail = split(command, head, ' ');
61 return head + ' ' + options + ' ' + tail;
65 string const dvipdfm_options(BufferParams const & bp)
69 if (bp.papersize != PAPER_CUSTOM) {
70 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
71 if (!paper_size.empty())
72 result = "-p "+ paper_size;
74 if (bp.orientation == ORIENTATION_LANDSCAPE)
82 class ConverterEqual {
84 ConverterEqual(string const & from, string const & to)
85 : from_(from), to_(to) {}
86 bool operator()(Converter const & c) const {
87 return c.from == from_ && c.to == to_;
97 Converter::Converter(string const & f, string const & t,
98 string const & c, string const & l)
99 : from(f), to(t), command(c), flags(l),
100 From(0), To(0), latex(false), xml(false),
105 void Converter::readFlags()
107 string flag_list(flags);
108 while (!flag_list.empty()) {
109 string flag_name, flag_value;
110 flag_list = split(flag_list, flag_value, ',');
111 flag_value = split(flag_value, flag_name, '=');
112 if (flag_name == "latex") {
114 latex_flavor = flag_value.empty() ?
115 "latex" : flag_value;
116 } else if (flag_name == "xml")
118 else if (flag_name == "needaux")
120 else if (flag_name == "resultdir")
121 result_dir = (flag_value.empty())
122 ? token_base : flag_value;
123 else if (flag_name == "resultfile")
124 result_file = flag_value;
125 else if (flag_name == "parselog")
126 parselog = flag_value;
128 if (!result_dir.empty() && result_file.empty())
129 result_file = "index." + formats.extension(to);
130 //if (!contains(command, token_from))
135 Converter const * Converters::getConverter(string const & from,
136 string const & to) const
138 ConverterList::const_iterator const cit =
139 find_if(converterlist_.begin(), converterlist_.end(),
140 ConverterEqual(from, to));
141 if (cit != converterlist_.end())
148 int Converters::getNumber(string const & from, string const & to) const
150 ConverterList::const_iterator const cit =
151 find_if(converterlist_.begin(), converterlist_.end(),
152 ConverterEqual(from, to));
153 if (cit != converterlist_.end())
154 return distance(converterlist_.begin(), cit);
160 void Converters::add(string const & from, string const & to,
161 string const & command, string const & flags)
165 ConverterList::iterator it = find_if(converterlist_.begin(),
166 converterlist_.end(),
167 ConverterEqual(from , to));
169 Converter converter(from, to, command, flags);
170 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
172 converter.command = command;
173 converter.flags = flags;
175 converter.readFlags();
177 // If we have both latex & pdflatex, we set latex_command to latex.
178 // The latex_command is used to update the .aux file when running
179 // a converter that uses it.
181 && (latex_command_.empty() || converter.latex_flavor == "latex"))
182 latex_command_ = subst(command, token_from, "");
183 // Similarly, set xelatex_command to xelatex.
185 && (xelatex_command_.empty() || converter.latex_flavor == "xelatex"))
186 xelatex_command_ = subst(command, token_from, "");
188 if (it == converterlist_.end()) {
189 converterlist_.push_back(converter);
191 converter.From = it->From;
192 converter.To = it->To;
198 void Converters::erase(string const & from, string const & to)
200 ConverterList::iterator const it =
201 find_if(converterlist_.begin(),
202 converterlist_.end(),
203 ConverterEqual(from, to));
204 if (it != converterlist_.end())
205 converterlist_.erase(it);
209 // This method updates the pointers From and To in all the converters.
210 // The code is not very efficient, but it doesn't matter as the number
211 // of formats and converters is small.
212 // Furthermore, this method is called only on startup, or after
213 // adding/deleting a format in FormPreferences (the latter calls can be
214 // eliminated if the formats in the Formats class are stored using a map or
215 // a list (instead of a vector), but this will cause other problems).
216 void Converters::update(Formats const & formats)
218 ConverterList::iterator it = converterlist_.begin();
219 ConverterList::iterator end = converterlist_.end();
220 for (; it != end; ++it) {
221 it->From = formats.getFormat(it->from);
222 it->To = formats.getFormat(it->to);
227 // This method updates the pointers From and To in the last converter.
228 // It is called when adding a new converter in FormPreferences
229 void Converters::updateLast(Formats const & formats)
231 if (converterlist_.begin() != converterlist_.end()) {
232 ConverterList::iterator it = converterlist_.end() - 1;
233 it->From = formats.getFormat(it->from);
234 it->To = formats.getFormat(it->to);
239 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
241 for (Graph::EdgePath::const_iterator cit = path.begin();
242 cit != path.end(); ++cit) {
243 Converter const & conv = converterlist_[*cit];
245 if (conv.latex_flavor == "xelatex")
246 return OutputParams::XETEX;
247 if (conv.latex_flavor == "lualatex")
248 return OutputParams::LUATEX;
249 if (conv.latex_flavor == "dvilualatex")
250 return OutputParams::DVILUATEX;
251 if (conv.latex_flavor == "pdflatex")
252 return OutputParams::PDFLATEX;
254 return OutputParams::XML;
256 return OutputParams::LATEX;
260 bool Converters::convert(Buffer const * buffer,
261 FileName const & from_file, FileName const & to_file,
262 FileName const & orig_from,
263 string const & from_format, string const & to_format,
264 ErrorList & errorList, int conversionflags)
266 if (from_format == to_format)
267 return move(from_format, from_file, to_file, false);
269 if ((conversionflags & try_cache) &&
270 ConverterCache::get().inCache(orig_from, to_format))
271 return ConverterCache::get().copy(orig_from, to_format, to_file);
273 Graph::EdgePath edgepath = getPath(from_format, to_format);
274 if (edgepath.empty()) {
275 if (conversionflags & try_default) {
276 // if no special converter defined, then we take the
277 // default one from ImageMagic.
278 string const from_ext = from_format.empty() ?
279 getExtension(from_file.absFileName()) :
280 formats.extension(from_format);
281 string const to_ext = formats.extension(to_format);
282 string const command =
284 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
286 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
288 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
289 LYXERR(Debug::FILES, "No converter defined! "
290 "I use convertDefault.py:\n\t" << command);
292 one.startscript(Systemcall::Wait, command, buffer ?
293 buffer->filePath() : string());
294 if (to_file.isReadableFile()) {
295 if (conversionflags & try_cache)
296 ConverterCache::get().add(orig_from,
302 // only warn once per session and per file type
303 static std::map<string, string> warned;
304 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
307 warned.insert(make_pair(from_format, to_format));
309 Alert::error(_("Cannot convert file"),
310 bformat(_("No information for converting %1$s "
311 "format files to %2$s.\n"
312 "Define a converter in the preferences."),
313 from_ascii(from_format), from_ascii(to_format)));
317 // buffer is only invalid for importing, and then runparams is not
319 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
320 runparams.flavor = getFlavor(edgepath);
323 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
324 runparams.use_indices = buffer->params().use_indices;
325 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
326 string() : buffer->params().bibtex_command;
327 runparams.index_command = (buffer->params().index_command == "default") ?
328 string() : buffer->params().index_command;
331 // Some converters (e.g. lilypond) can only output files to the
332 // current directory, so we need to change the current directory.
333 // This has the added benefit that all other files that may be
334 // generated by the converter are deleted when LyX closes and do not
335 // clutter the real working directory.
336 string const path(onlyPath(from_file.absFileName()));
337 // Prevent the compiler from optimizing away p
341 // empty the error list before any new conversion takes place.
344 bool run_latex = false;
345 string from_base = changeExtension(from_file.absFileName(), "");
346 string to_base = changeExtension(to_file.absFileName(), "");
348 FileName outfile = from_file;
349 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
350 cit != edgepath.end(); ++cit) {
351 Converter const & conv = converterlist_[*cit];
352 bool dummy = conv.To->dummy() && conv.to != "program";
354 LYXERR(Debug::FILES, "Converting from "
355 << conv.from << " to " << conv.to);
358 outfile = FileName(conv.result_file.empty()
359 ? changeExtension(from_file.absFileName(), conv.To->extension())
360 : addName(subst(conv.result_dir,
361 token_base, from_base),
362 subst(conv.result_file,
363 token_base, onlyFileName(from_base))));
365 // if input and output files are equal, we use a
366 // temporary file as intermediary (JMarc)
367 FileName real_outfile;
368 if (!conv.result_file.empty())
369 real_outfile = FileName(changeExtension(from_file.absFileName(),
370 conv.To->extension()));
371 if (outfile == infile) {
372 real_outfile = infile;
373 // when importing, a buffer does not necessarily exist
375 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
377 outfile = FileName(addName(package().temp_dir().absFileName(),
383 string command = conv.command;
384 command = subst(command, token_from, "");
385 command = subst(command, token_latex_encoding, buffer ?
386 buffer->params().encoding().latexName() : string());
387 LYXERR(Debug::FILES, "Running " << command);
388 if (!runLaTeX(*buffer, command, runparams, errorList))
391 if (conv.need_aux && !run_latex
392 && !latex_command_.empty()) {
393 string const command = (buffer && buffer->params().useNonTeXFonts) ?
394 xelatex_command_ : latex_command_;
395 LYXERR(Debug::FILES, "Running " << command
396 << " to update aux file");
397 if (!runLaTeX(*buffer, command, runparams, errorList))
402 string const infile2 =
403 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
404 string const outfile2 =
405 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
407 string command = conv.command;
408 command = subst(command, token_from, quoteName(infile2));
409 command = subst(command, token_base, quoteName(from_base));
410 command = subst(command, token_to, quoteName(outfile2));
411 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
412 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
413 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
414 command = libScriptSearch(command);
416 if (!conv.parselog.empty())
417 command += " 2> " + quoteName(infile2 + ".out");
419 if (conv.from == "dvi" && conv.to == "ps")
420 command = add_options(command,
421 buffer->params().dvips_options());
422 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
423 command = add_options(command,
424 dvipdfm_options(buffer->params()));
426 LYXERR(Debug::FILES, "Calling " << command);
428 buffer->message(_("Executing command: ")
429 + from_utf8(command));
434 res = one.startscript(Systemcall::DontWait,
435 to_filesystem8bit(from_utf8(command)),
436 buffer ? buffer->filePath() : string());
437 // We're not waiting for the result, so we can't do anything
440 res = one.startscript(Systemcall::Wait,
441 to_filesystem8bit(from_utf8(command)),
442 buffer ? buffer->filePath()
444 if (!real_outfile.empty()) {
445 Mover const & mover = getMover(conv.to);
446 if (!mover.rename(outfile, real_outfile))
449 LYXERR(Debug::FILES, "renaming file " << outfile
450 << " to " << real_outfile);
451 // Finally, don't forget to tell any future
452 // converters to use the renamed file...
453 outfile = real_outfile;
456 if (!conv.parselog.empty()) {
457 string const logfile = infile2 + ".log";
458 string const script = libScriptSearch(conv.parselog);
459 string const command2 = script +
460 " < " + quoteName(infile2 + ".out") +
461 " > " + quoteName(logfile);
462 one.startscript(Systemcall::Wait,
463 to_filesystem8bit(from_utf8(command2)),
465 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
471 if (conv.to == "program") {
472 Alert::error(_("Build errors"),
473 _("There were errors during the build process."));
475 // FIXME: this should go out of here. For example, here we cannot say if
476 // it is a document (.lyx) or something else. Same goes for elsewhere.
477 Alert::error(_("Cannot convert file"),
478 bformat(_("An error occurred while running:\n%1$s"),
479 wrapParas(from_utf8(command))));
486 Converter const & conv = converterlist_[edgepath.back()];
487 if (conv.To->dummy())
490 if (!conv.result_dir.empty()) {
491 // The converter has put the file(s) in a directory.
492 // In this case we ignore the given to_file.
493 if (from_base != to_base) {
494 string const from = subst(conv.result_dir,
495 token_base, from_base);
496 string const to = subst(conv.result_dir,
497 token_base, to_base);
498 Mover const & mover = getMover(conv.from);
499 if (!mover.rename(FileName(from), FileName(to))) {
500 Alert::error(_("Cannot convert file"),
501 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
502 from_utf8(from), from_utf8(to)));
508 if (conversionflags & try_cache)
509 ConverterCache::get().add(orig_from, to_format, outfile);
510 return move(conv.to, outfile, to_file, conv.latex);
515 bool Converters::move(string const & fmt,
516 FileName const & from, FileName const & to, bool copy)
521 bool no_errors = true;
522 string const path = onlyPath(from.absFileName());
523 string const base = onlyFileName(removeExtension(from.absFileName()));
524 string const to_base = removeExtension(to.absFileName());
525 string const to_extension = getExtension(to.absFileName());
527 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
528 for (support::FileNameList::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()),
536 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
538 Mover const & mover = getMover(fmt);
539 bool const moved = copy
540 ? mover.copy(*it, FileName(to2))
541 : mover.rename(*it, FileName(to2));
542 if (!moved && no_errors) {
543 Alert::error(_("Cannot convert file"),
545 _("Could not copy a temporary file from %1$s to %2$s.") :
546 _("Could not move a temporary file from %1$s to %2$s."),
547 from_utf8(from2), from_utf8(to2)));
556 bool Converters::formatIsUsed(string const & format)
558 ConverterList::const_iterator cit = converterlist_.begin();
559 ConverterList::const_iterator end = converterlist_.end();
560 for (; cit != end; ++cit) {
561 if (cit->from == format || cit->to == format)
568 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
569 FileName const & filename, ErrorList & errorList)
571 OutputParams runparams(0);
572 runparams.flavor = OutputParams::LATEX;
573 LaTeX latex("", runparams, filename);
575 int const result = latex.scanLogFile(terr);
577 if (result & LaTeX::ERRORS)
578 buffer.bufferErrors(terr, errorList);
587 : public boost::signals::trackable {
589 ShowMessage(Buffer const & b) : buffer_(b) {}
590 void operator()(docstring const & msg) const { buffer_.message(msg); }
592 Buffer const & buffer_;
598 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
599 OutputParams const & runparams, ErrorList & errorList)
601 buffer.setBusy(true);
602 buffer.message(_("Running LaTeX..."));
604 runparams.document_language = buffer.params().language->babel();
606 // do the LaTeX run(s)
607 string const name = buffer.latexName();
608 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
611 ShowMessage show(buffer);
612 latex.message.connect(show);
613 int const result = latex.run(terr);
615 if (result & LaTeX::ERRORS)
616 buffer.bufferErrors(terr, errorList);
618 // check return value from latex.run().
619 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
620 docstring const str =
621 bformat(_("LaTeX did not run successfully. "
622 "Additionally, LyX could not locate "
623 "the LaTeX log %1$s."), from_utf8(name));
624 Alert::error(_("LaTeX failed"), str);
625 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
626 Alert::warning(_("Output is empty"),
627 _("An empty output file was generated."));
631 buffer.setBusy(false);
633 int const ERROR_MASK =
638 return (result & ERROR_MASK) == 0;
644 void Converters::buildGraph()
646 // clear graph's data structures
647 G_.init(formats.size());
648 // each of the converters knows how to convert one format to another
649 // so, for each of them, we create an arrow on the graph, going from
650 // the one to the other
651 ConverterList::iterator it = converterlist_.begin();
652 ConverterList::iterator const end = converterlist_.end();
653 for (; it != end ; ++it) {
654 int const from = formats.getNumber(it->from);
655 int const to = formats.getNumber(it->to);
656 G_.addEdge(from, to);
661 vector<Format const *> const
662 Converters::intToFormat(vector<int> const & input)
664 vector<Format const *> result(input.size());
666 vector<int>::const_iterator it = input.begin();
667 vector<int>::const_iterator const end = input.end();
668 vector<Format const *>::iterator rit = result.begin();
669 for ( ; it != end; ++it, ++rit) {
670 *rit = &formats.get(*it);
676 vector<Format const *> const
677 Converters::getReachableTo(string const & target, bool const clear_visited)
679 vector<int> const & reachablesto =
680 G_.getReachableTo(formats.getNumber(target), clear_visited);
682 return intToFormat(reachablesto);
686 vector<Format const *> const
687 Converters::getReachable(string const & from, bool const only_viewable,
688 bool const clear_visited, set<string> const & excludes)
690 set<int> excluded_numbers;;
692 set<string>::const_iterator sit = excludes.begin();
693 set<string>::const_iterator const end = excludes.end();
694 for (; sit != end; ++sit)
695 excluded_numbers.insert(formats.getNumber(*sit));
697 vector<int> const & reachables =
698 G_.getReachable(formats.getNumber(from),
703 return intToFormat(reachables);
707 bool Converters::isReachable(string const & from, string const & to)
709 return G_.isReachable(formats.getNumber(from),
710 formats.getNumber(to));
714 Graph::EdgePath Converters::getPath(string const & from, string const & to)
716 return G_.getPath(formats.getNumber(from),
717 formats.getNumber(to));
721 vector<Format const *> Converters::importableFormats()
723 vector<string> l = loaders();
724 vector<Format const *> result = getReachableTo(l[0], true);
725 vector<string>::const_iterator it = l.begin() + 1;
726 vector<string>::const_iterator en = l.end();
727 for (; it != en; ++it) {
728 vector<Format const *> r = getReachableTo(*it, false);
729 result.insert(result.end(), r.begin(), r.end());
735 vector<Format const *> Converters::exportableFormats(bool only_viewable)
737 vector<string> s = savers();
738 vector<Format const *> result = getReachable(s[0], only_viewable, true);
739 vector<string>::const_iterator it = s.begin() + 1;
740 vector<string>::const_iterator en = s.end();
741 for (; it != en; ++it) {
742 vector<Format const *> r =
743 getReachable(*it, only_viewable, false);
744 result.insert(result.end(), r.begin(), r.end());
750 vector<string> Converters::loaders() const
755 v.push_back("textparagraph");
760 vector<string> Converters::savers() const
763 v.push_back("docbook");
764 v.push_back("latex");
765 v.push_back("literate");
766 v.push_back("luatex");
767 v.push_back("dviluatex");
769 v.push_back("xhtml");
770 v.push_back("pdflatex");
771 v.push_back("platex");
773 v.push_back("xetex");