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");
56 string const add_options(string const & command, string const & options)
59 string const tail = split(command, head, ' ');
60 return head + ' ' + options + ' ' + tail;
64 string const dvipdfm_options(BufferParams const & bp)
68 if (bp.papersize != PAPER_CUSTOM) {
69 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
70 if (!paper_size.empty())
71 result = "-p "+ paper_size;
73 if (bp.orientation == ORIENTATION_LANDSCAPE)
81 class ConverterEqual {
83 ConverterEqual(string const & from, string const & to)
84 : from_(from), to_(to) {}
85 bool operator()(Converter const & c) const {
86 return c.from == from_ && c.to == to_;
96 Converter::Converter(string const & f, string const & t,
97 string const & c, string const & l)
98 : from(f), to(t), command(c), flags(l),
99 From(0), To(0), latex(false), xml(false),
104 void Converter::readFlags()
106 string flag_list(flags);
107 while (!flag_list.empty()) {
108 string flag_name, flag_value;
109 flag_list = split(flag_list, flag_value, ',');
110 flag_value = split(flag_value, flag_name, '=');
111 if (flag_name == "latex") {
113 latex_flavor = flag_value.empty() ?
114 "latex" : flag_value;
115 } else if (flag_name == "xml")
117 else if (flag_name == "needaux")
119 else if (flag_name == "resultdir")
120 result_dir = (flag_value.empty())
121 ? token_base : flag_value;
122 else if (flag_name == "resultfile")
123 result_file = flag_value;
124 else if (flag_name == "parselog")
125 parselog = flag_value;
127 if (!result_dir.empty() && result_file.empty())
128 result_file = "index." + formats.extension(to);
129 //if (!contains(command, token_from))
134 bool operator<(Converter const & a, Converter const & b)
136 // use the compare_ascii_no_case instead of compare_no_case,
137 // because in turkish, 'i' is not the lowercase version of 'I',
138 // and thus turkish locale breaks parsing of tags.
139 int const i = compare_ascii_no_case(a.From->prettyname(),
140 b.From->prettyname());
142 return compare_ascii_no_case(a.To->prettyname(),
143 b.To->prettyname()) < 0;
149 Converter const * Converters::getConverter(string const & from,
150 string const & to) const
152 ConverterList::const_iterator const cit =
153 find_if(converterlist_.begin(), converterlist_.end(),
154 ConverterEqual(from, to));
155 if (cit != converterlist_.end())
162 int Converters::getNumber(string const & from, string const & to) const
164 ConverterList::const_iterator const cit =
165 find_if(converterlist_.begin(), converterlist_.end(),
166 ConverterEqual(from, to));
167 if (cit != converterlist_.end())
168 return distance(converterlist_.begin(), cit);
174 void Converters::add(string const & from, string const & to,
175 string const & command, string const & flags)
179 ConverterList::iterator it = find_if(converterlist_.begin(),
180 converterlist_.end(),
181 ConverterEqual(from , to));
183 Converter converter(from, to, command, flags);
184 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
186 converter.command = command;
187 converter.flags = flags;
189 converter.readFlags();
191 // If we have both latex & pdflatex, we set latex_command to latex.
192 // The latex_command is used to update the .aux file when running
193 // a converter that uses it.
195 && (latex_command_.empty() || converter.latex_flavor == "latex"))
196 latex_command_ = subst(command, token_from, "");
197 // Similarly, set xelatex_command to xelatex.
199 && (xelatex_command_.empty() || converter.latex_flavor == "xelatex"))
200 xelatex_command_ = subst(command, token_from, "");
202 if (it == converterlist_.end()) {
203 converterlist_.push_back(converter);
205 converter.From = it->From;
206 converter.To = it->To;
212 void Converters::erase(string const & from, string const & to)
214 ConverterList::iterator const it =
215 find_if(converterlist_.begin(),
216 converterlist_.end(),
217 ConverterEqual(from, to));
218 if (it != converterlist_.end())
219 converterlist_.erase(it);
223 // This method updates the pointers From and To in all the converters.
224 // The code is not very efficient, but it doesn't matter as the number
225 // of formats and converters is small.
226 // Furthermore, this method is called only on startup, or after
227 // adding/deleting a format in FormPreferences (the latter calls can be
228 // eliminated if the formats in the Formats class are stored using a map or
229 // a list (instead of a vector), but this will cause other problems).
230 void Converters::update(Formats const & formats)
232 ConverterList::iterator it = converterlist_.begin();
233 ConverterList::iterator end = converterlist_.end();
234 for (; it != end; ++it) {
235 it->From = formats.getFormat(it->from);
236 it->To = formats.getFormat(it->to);
241 // This method updates the pointers From and To in the last converter.
242 // It is called when adding a new converter in FormPreferences
243 void Converters::updateLast(Formats const & formats)
245 if (converterlist_.begin() != converterlist_.end()) {
246 ConverterList::iterator it = converterlist_.end() - 1;
247 it->From = formats.getFormat(it->from);
248 it->To = formats.getFormat(it->to);
253 void Converters::sort()
255 std::sort(converterlist_.begin(), converterlist_.end());
259 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
261 for (Graph::EdgePath::const_iterator cit = path.begin();
262 cit != path.end(); ++cit) {
263 Converter const & conv = converterlist_[*cit];
265 if (conv.latex_flavor == "xelatex")
266 return OutputParams::XETEX;
267 if (conv.latex_flavor == "lualatex")
268 return OutputParams::LUATEX;
269 if (conv.latex_flavor == "pdflatex")
270 return OutputParams::PDFLATEX;
272 return OutputParams::XML;
274 return OutputParams::LATEX;
278 bool Converters::convert(Buffer const * buffer,
279 FileName const & from_file, FileName const & to_file,
280 FileName const & orig_from,
281 string const & from_format, string const & to_format,
282 ErrorList & errorList, int conversionflags)
284 if (from_format == to_format)
285 return move(from_format, from_file, to_file, false);
287 if ((conversionflags & try_cache) &&
288 ConverterCache::get().inCache(orig_from, to_format))
289 return ConverterCache::get().copy(orig_from, to_format, to_file);
291 Graph::EdgePath edgepath = getPath(from_format, to_format);
292 if (edgepath.empty()) {
293 if (conversionflags & try_default) {
294 // if no special converter defined, then we take the
295 // default one from ImageMagic.
296 string const from_ext = from_format.empty() ?
297 getExtension(from_file.absFileName()) :
298 formats.extension(from_format);
299 string const to_ext = formats.extension(to_format);
300 string const command =
302 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
304 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
306 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
307 LYXERR(Debug::FILES, "No converter defined! "
308 "I use convertDefault.py:\n\t" << command);
310 one.startscript(Systemcall::Wait, command, buffer ?
311 buffer->filePath() : string());
312 if (to_file.isReadableFile()) {
313 if (conversionflags & try_cache)
314 ConverterCache::get().add(orig_from,
320 // only warn once per session and per file type
321 static std::map<string, string> warned;
322 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
325 warned.insert(make_pair(from_format, to_format));
327 Alert::error(_("Cannot convert file"),
328 bformat(_("No information for converting %1$s "
329 "format files to %2$s.\n"
330 "Define a converter in the preferences."),
331 from_ascii(from_format), from_ascii(to_format)));
335 // buffer is only invalid for importing, and then runparams is not
337 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
338 runparams.flavor = getFlavor(edgepath);
341 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
342 runparams.use_indices = buffer->params().use_indices;
343 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
344 string() : buffer->params().bibtex_command;
345 runparams.index_command = (buffer->params().index_command == "default") ?
346 string() : buffer->params().index_command;
349 // Some converters (e.g. lilypond) can only output files to the
350 // current directory, so we need to change the current directory.
351 // This has the added benefit that all other files that may be
352 // generated by the converter are deleted when LyX closes and do not
353 // clutter the real working directory.
354 string const path(onlyPath(from_file.absFileName()));
355 // Prevent the compiler from optimizing away p
359 // empty the error list before any new conversion takes place.
362 bool run_latex = false;
363 string from_base = changeExtension(from_file.absFileName(), "");
364 string to_base = changeExtension(to_file.absFileName(), "");
366 FileName outfile = from_file;
367 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
368 cit != edgepath.end(); ++cit) {
369 Converter const & conv = converterlist_[*cit];
370 bool dummy = conv.To->dummy() && conv.to != "program";
372 LYXERR(Debug::FILES, "Converting from "
373 << conv.from << " to " << conv.to);
376 outfile = FileName(conv.result_dir.empty()
377 ? changeExtension(from_file.absFileName(), conv.To->extension())
378 : addName(subst(conv.result_dir,
379 token_base, from_base),
380 subst(conv.result_file,
381 token_base, onlyFileName(from_base))));
383 // if input and output files are equal, we use a
384 // temporary file as intermediary (JMarc)
385 FileName real_outfile;
386 if (outfile == infile) {
387 real_outfile = infile;
388 // when importing, a buffer does not necessarily exist
390 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
392 outfile = FileName(addName(package().temp_dir().absFileName(),
398 string const command = subst(conv.command, token_from, "");
399 LYXERR(Debug::FILES, "Running " << command);
400 if (!runLaTeX(*buffer, command, runparams, errorList))
403 if (conv.need_aux && !run_latex
404 && !latex_command_.empty()) {
405 string const command = (buffer && buffer->params().useNonTeXFonts) ?
406 xelatex_command_ : latex_command_;
407 LYXERR(Debug::FILES, "Running " << command
408 << " to update aux file");
409 if (!runLaTeX(*buffer, command, runparams, errorList))
414 string const infile2 =
415 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
416 string const outfile2 =
417 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
419 string command = conv.command;
420 command = subst(command, token_from, quoteName(infile2));
421 command = subst(command, token_base, quoteName(from_base));
422 command = subst(command, token_to, quoteName(outfile2));
423 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
424 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
425 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
426 command = libScriptSearch(command);
428 if (!conv.parselog.empty())
429 command += " 2> " + quoteName(infile2 + ".out");
431 if (conv.from == "dvi" && conv.to == "ps")
432 command = add_options(command,
433 buffer->params().dvips_options());
434 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
435 command = add_options(command,
436 dvipdfm_options(buffer->params()));
438 LYXERR(Debug::FILES, "Calling " << command);
440 buffer->message(_("Executing command: ")
441 + from_utf8(command));
446 res = one.startscript(Systemcall::DontWait,
447 to_filesystem8bit(from_utf8(command)),
448 buffer ? buffer->filePath() : string());
449 // We're not waiting for the result, so we can't do anything
452 res = one.startscript(Systemcall::Wait,
453 to_filesystem8bit(from_utf8(command)),
454 buffer ? buffer->filePath()
456 if (!real_outfile.empty()) {
457 Mover const & mover = getMover(conv.to);
458 if (!mover.rename(outfile, real_outfile))
461 LYXERR(Debug::FILES, "renaming file " << outfile
462 << " to " << real_outfile);
463 // Finally, don't forget to tell any future
464 // converters to use the renamed file...
465 outfile = real_outfile;
468 if (!conv.parselog.empty()) {
469 string const logfile = infile2 + ".log";
470 string const script = libScriptSearch(conv.parselog);
471 string const command2 = script +
472 " < " + quoteName(infile2 + ".out") +
473 " > " + quoteName(logfile);
474 one.startscript(Systemcall::Wait,
475 to_filesystem8bit(from_utf8(command2)),
477 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
483 if (conv.to == "program") {
484 Alert::error(_("Build errors"),
485 _("There were errors during the build process."));
487 // FIXME: this should go out of here. For example, here we cannot say if
488 // it is a document (.lyx) or something else. Same goes for elsewhere.
489 Alert::error(_("Cannot convert file"),
490 bformat(_("An error occurred while running:\n%1$s"),
491 wrapParas(from_utf8(command))));
498 Converter const & conv = converterlist_[edgepath.back()];
499 if (conv.To->dummy())
502 if (!conv.result_dir.empty()) {
503 // The converter has put the file(s) in a directory.
504 // In this case we ignore the given to_file.
505 if (from_base != to_base) {
506 string const from = subst(conv.result_dir,
507 token_base, from_base);
508 string const to = subst(conv.result_dir,
509 token_base, to_base);
510 Mover const & mover = getMover(conv.from);
511 if (!mover.rename(FileName(from), FileName(to))) {
512 Alert::error(_("Cannot convert file"),
513 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
514 from_utf8(from), from_utf8(to)));
520 if (conversionflags & try_cache)
521 ConverterCache::get().add(orig_from, to_format, outfile);
522 return move(conv.to, outfile, to_file, conv.latex);
527 bool Converters::move(string const & fmt,
528 FileName const & from, FileName const & to, bool copy)
533 bool no_errors = true;
534 string const path = onlyPath(from.absFileName());
535 string const base = onlyFileName(removeExtension(from.absFileName()));
536 string const to_base = removeExtension(to.absFileName());
537 string const to_extension = getExtension(to.absFileName());
539 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
540 for (support::FileNameList::const_iterator it = files.begin();
541 it != files.end(); ++it) {
542 string const from2 = it->absFileName();
543 string const file2 = onlyFileName(from2);
544 if (prefixIs(file2, base)) {
545 string const to2 = changeExtension(
546 to_base + file2.substr(base.length()),
548 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
550 Mover const & mover = getMover(fmt);
551 bool const moved = copy
552 ? mover.copy(*it, FileName(to2))
553 : mover.rename(*it, FileName(to2));
554 if (!moved && no_errors) {
555 Alert::error(_("Cannot convert file"),
557 _("Could not copy a temporary file from %1$s to %2$s.") :
558 _("Could not move a temporary file from %1$s to %2$s."),
559 from_utf8(from2), from_utf8(to2)));
568 bool Converters::formatIsUsed(string const & format)
570 ConverterList::const_iterator cit = converterlist_.begin();
571 ConverterList::const_iterator end = converterlist_.end();
572 for (; cit != end; ++cit) {
573 if (cit->from == format || cit->to == format)
580 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
581 FileName const & filename, ErrorList & errorList)
583 OutputParams runparams(0);
584 runparams.flavor = OutputParams::LATEX;
585 LaTeX latex("", runparams, filename);
587 int const result = latex.scanLogFile(terr);
589 if (result & LaTeX::ERRORS)
590 buffer.bufferErrors(terr, errorList);
599 : public boost::signals::trackable {
601 ShowMessage(Buffer const & b) : buffer_(b) {}
602 void operator()(docstring const & msg) const { buffer_.message(msg); }
604 Buffer const & buffer_;
610 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
611 OutputParams const & runparams, ErrorList & errorList)
613 buffer.setBusy(true);
614 buffer.message(_("Running LaTeX..."));
616 runparams.document_language = buffer.params().language->babel();
618 // do the LaTeX run(s)
619 string const name = buffer.latexName();
620 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
623 ShowMessage show(buffer);
624 latex.message.connect(show);
625 int const result = latex.run(terr);
627 if (result & LaTeX::ERRORS)
628 buffer.bufferErrors(terr, errorList);
630 // check return value from latex.run().
631 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
632 docstring const str =
633 bformat(_("LaTeX did not run successfully. "
634 "Additionally, LyX could not locate "
635 "the LaTeX log %1$s."), from_utf8(name));
636 Alert::error(_("LaTeX failed"), str);
637 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
638 Alert::warning(_("Output is empty"),
639 _("An empty output file was generated."));
643 buffer.setBusy(false);
645 int const ERROR_MASK =
650 return (result & ERROR_MASK) == 0;
656 void Converters::buildGraph()
658 // clear graph's data structures
659 G_.init(formats.size());
660 // each of the converters knows how to convert one format to another
661 // so, for each of them, we create an arrow on the graph, going from
662 // the one to the other
663 ConverterList::iterator it = converterlist_.begin();
664 ConverterList::iterator const end = converterlist_.end();
665 for (; it != end ; ++it) {
666 int const from = formats.getNumber(it->from);
667 int const to = formats.getNumber(it->to);
668 G_.addEdge(from, to);
673 vector<Format const *> const
674 Converters::intToFormat(vector<int> const & input)
676 vector<Format const *> result(input.size());
678 vector<int>::const_iterator it = input.begin();
679 vector<int>::const_iterator const end = input.end();
680 vector<Format const *>::iterator rit = result.begin();
681 for ( ; it != end; ++it, ++rit) {
682 *rit = &formats.get(*it);
688 vector<Format const *> const
689 Converters::getReachableTo(string const & target, bool const clear_visited)
691 vector<int> const & reachablesto =
692 G_.getReachableTo(formats.getNumber(target), clear_visited);
694 return intToFormat(reachablesto);
698 vector<Format const *> const
699 Converters::getReachable(string const & from, bool const only_viewable,
700 bool const clear_visited, set<string> const & excludes)
702 set<int> excluded_numbers;;
704 set<string>::const_iterator sit = excludes.begin();
705 set<string>::const_iterator const end = excludes.end();
706 for (; sit != end; ++sit)
707 excluded_numbers.insert(formats.getNumber(*sit));
709 vector<int> const & reachables =
710 G_.getReachable(formats.getNumber(from),
715 return intToFormat(reachables);
719 bool Converters::isReachable(string const & from, string const & to)
721 return G_.isReachable(formats.getNumber(from),
722 formats.getNumber(to));
726 Graph::EdgePath Converters::getPath(string const & from, string const & to)
728 return G_.getPath(formats.getNumber(from),
729 formats.getNumber(to));
733 vector<Format const *> Converters::importableFormats()
735 vector<string> l = loaders();
736 vector<Format const *> result = getReachableTo(l[0], true);
737 vector<string>::const_iterator it = l.begin() + 1;
738 vector<string>::const_iterator en = l.end();
739 for (; it != en; ++it) {
740 vector<Format const *> r = getReachableTo(*it, false);
741 result.insert(result.end(), r.begin(), r.end());
747 vector<Format const *> Converters::exportableFormats(bool only_viewable)
749 vector<string> s = savers();
750 vector<Format const *> result = getReachable(s[0], only_viewable, true);
751 vector<string>::const_iterator it = s.begin() + 1;
752 vector<string>::const_iterator en = s.end();
753 for (; it != en; ++it) {
754 vector<Format const *> r =
755 getReachable(*it, only_viewable, false);
756 result.insert(result.end(), r.begin(), r.end());
762 vector<string> Converters::loaders() const
767 v.push_back("textparagraph");
772 vector<string> Converters::savers() const
775 v.push_back("docbook");
776 v.push_back("latex");
777 v.push_back("literate");
778 v.push_back("luatex");
780 v.push_back("xhtml");
781 v.push_back("pdflatex");
782 v.push_back("platex");
784 v.push_back("xetex");