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 Converter const * Converters::getConverter(string const & from,
135 string const & to) const
137 ConverterList::const_iterator const cit =
138 find_if(converterlist_.begin(), converterlist_.end(),
139 ConverterEqual(from, to));
140 if (cit != converterlist_.end())
147 int Converters::getNumber(string const & from, string const & to) const
149 ConverterList::const_iterator const cit =
150 find_if(converterlist_.begin(), converterlist_.end(),
151 ConverterEqual(from, to));
152 if (cit != converterlist_.end())
153 return distance(converterlist_.begin(), cit);
159 void Converters::add(string const & from, string const & to,
160 string const & command, string const & flags)
164 ConverterList::iterator it = find_if(converterlist_.begin(),
165 converterlist_.end(),
166 ConverterEqual(from , to));
168 Converter converter(from, to, command, flags);
169 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
171 converter.command = command;
172 converter.flags = flags;
174 converter.readFlags();
176 // If we have both latex & pdflatex, we set latex_command to latex.
177 // The latex_command is used to update the .aux file when running
178 // a converter that uses it.
180 && (latex_command_.empty() || converter.latex_flavor == "latex"))
181 latex_command_ = subst(command, token_from, "");
182 // Similarly, set xelatex_command to xelatex.
184 && (xelatex_command_.empty() || converter.latex_flavor == "xelatex"))
185 xelatex_command_ = subst(command, token_from, "");
187 if (it == converterlist_.end()) {
188 converterlist_.push_back(converter);
190 converter.From = it->From;
191 converter.To = it->To;
197 void Converters::erase(string const & from, string const & to)
199 ConverterList::iterator const it =
200 find_if(converterlist_.begin(),
201 converterlist_.end(),
202 ConverterEqual(from, to));
203 if (it != converterlist_.end())
204 converterlist_.erase(it);
208 // This method updates the pointers From and To in all the converters.
209 // The code is not very efficient, but it doesn't matter as the number
210 // of formats and converters is small.
211 // Furthermore, this method is called only on startup, or after
212 // adding/deleting a format in FormPreferences (the latter calls can be
213 // eliminated if the formats in the Formats class are stored using a map or
214 // a list (instead of a vector), but this will cause other problems).
215 void Converters::update(Formats const & formats)
217 ConverterList::iterator it = converterlist_.begin();
218 ConverterList::iterator end = converterlist_.end();
219 for (; it != end; ++it) {
220 it->From = formats.getFormat(it->from);
221 it->To = formats.getFormat(it->to);
226 // This method updates the pointers From and To in the last converter.
227 // It is called when adding a new converter in FormPreferences
228 void Converters::updateLast(Formats const & formats)
230 if (converterlist_.begin() != converterlist_.end()) {
231 ConverterList::iterator it = converterlist_.end() - 1;
232 it->From = formats.getFormat(it->from);
233 it->To = formats.getFormat(it->to);
238 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
240 for (Graph::EdgePath::const_iterator cit = path.begin();
241 cit != path.end(); ++cit) {
242 Converter const & conv = converterlist_[*cit];
244 if (conv.latex_flavor == "xelatex")
245 return OutputParams::XETEX;
246 if (conv.latex_flavor == "lualatex")
247 return OutputParams::LUATEX;
248 if (conv.latex_flavor == "dvilualatex")
249 return OutputParams::DVILUATEX;
250 if (conv.latex_flavor == "pdflatex")
251 return OutputParams::PDFLATEX;
253 return OutputParams::XML;
255 return OutputParams::LATEX;
259 bool Converters::convert(Buffer const * buffer,
260 FileName const & from_file, FileName const & to_file,
261 FileName const & orig_from,
262 string const & from_format, string const & to_format,
263 ErrorList & errorList, int conversionflags)
265 if (from_format == to_format)
266 return move(from_format, from_file, to_file, false);
268 if ((conversionflags & try_cache) &&
269 ConverterCache::get().inCache(orig_from, to_format))
270 return ConverterCache::get().copy(orig_from, to_format, to_file);
272 Graph::EdgePath edgepath = getPath(from_format, to_format);
273 if (edgepath.empty()) {
274 if (conversionflags & try_default) {
275 // if no special converter defined, then we take the
276 // default one from ImageMagic.
277 string const from_ext = from_format.empty() ?
278 getExtension(from_file.absFileName()) :
279 formats.extension(from_format);
280 string const to_ext = formats.extension(to_format);
281 string const command =
283 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
285 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
287 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
288 LYXERR(Debug::FILES, "No converter defined! "
289 "I use convertDefault.py:\n\t" << command);
291 one.startscript(Systemcall::Wait, command, buffer ?
292 buffer->filePath() : string());
293 if (to_file.isReadableFile()) {
294 if (conversionflags & try_cache)
295 ConverterCache::get().add(orig_from,
301 // only warn once per session and per file type
302 static std::map<string, string> warned;
303 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
306 warned.insert(make_pair(from_format, to_format));
308 Alert::error(_("Cannot convert file"),
309 bformat(_("No information for converting %1$s "
310 "format files to %2$s.\n"
311 "Define a converter in the preferences."),
312 from_ascii(from_format), from_ascii(to_format)));
316 // buffer is only invalid for importing, and then runparams is not
318 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
319 runparams.flavor = getFlavor(edgepath);
322 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
323 runparams.use_indices = buffer->params().use_indices;
324 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
325 string() : buffer->params().bibtex_command;
326 runparams.index_command = (buffer->params().index_command == "default") ?
327 string() : buffer->params().index_command;
330 // Some converters (e.g. lilypond) can only output files to the
331 // current directory, so we need to change the current directory.
332 // This has the added benefit that all other files that may be
333 // generated by the converter are deleted when LyX closes and do not
334 // clutter the real working directory.
335 string const path(onlyPath(from_file.absFileName()));
336 // Prevent the compiler from optimizing away p
340 // empty the error list before any new conversion takes place.
343 bool run_latex = false;
344 string from_base = changeExtension(from_file.absFileName(), "");
345 string to_base = changeExtension(to_file.absFileName(), "");
347 FileName outfile = from_file;
348 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
349 cit != edgepath.end(); ++cit) {
350 Converter const & conv = converterlist_[*cit];
351 bool dummy = conv.To->dummy() && conv.to != "program";
353 LYXERR(Debug::FILES, "Converting from "
354 << conv.from << " to " << conv.to);
357 outfile = FileName(conv.result_dir.empty()
358 ? changeExtension(from_file.absFileName(), conv.To->extension())
359 : addName(subst(conv.result_dir,
360 token_base, from_base),
361 subst(conv.result_file,
362 token_base, onlyFileName(from_base))));
364 // if input and output files are equal, we use a
365 // temporary file as intermediary (JMarc)
366 FileName real_outfile;
367 if (outfile == infile) {
368 real_outfile = infile;
369 // when importing, a buffer does not necessarily exist
371 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
373 outfile = FileName(addName(package().temp_dir().absFileName(),
379 string const command = subst(conv.command, token_from, "");
380 LYXERR(Debug::FILES, "Running " << command);
381 if (!runLaTeX(*buffer, command, runparams, errorList))
384 if (conv.need_aux && !run_latex
385 && !latex_command_.empty()) {
386 string const command = (buffer && buffer->params().useNonTeXFonts) ?
387 xelatex_command_ : latex_command_;
388 LYXERR(Debug::FILES, "Running " << command
389 << " to update aux file");
390 if (!runLaTeX(*buffer, command, runparams, errorList))
395 string const infile2 =
396 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
397 string const outfile2 =
398 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
400 string command = conv.command;
401 command = subst(command, token_from, quoteName(infile2));
402 command = subst(command, token_base, quoteName(from_base));
403 command = subst(command, token_to, quoteName(outfile2));
404 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
405 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
406 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
407 command = libScriptSearch(command);
409 if (!conv.parselog.empty())
410 command += " 2> " + quoteName(infile2 + ".out");
412 if (conv.from == "dvi" && conv.to == "ps")
413 command = add_options(command,
414 buffer->params().dvips_options());
415 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
416 command = add_options(command,
417 dvipdfm_options(buffer->params()));
419 LYXERR(Debug::FILES, "Calling " << command);
421 buffer->message(_("Executing command: ")
422 + from_utf8(command));
427 res = one.startscript(Systemcall::DontWait,
428 to_filesystem8bit(from_utf8(command)),
429 buffer ? buffer->filePath() : string());
430 // We're not waiting for the result, so we can't do anything
433 res = one.startscript(Systemcall::Wait,
434 to_filesystem8bit(from_utf8(command)),
435 buffer ? buffer->filePath()
437 if (!real_outfile.empty()) {
438 Mover const & mover = getMover(conv.to);
439 if (!mover.rename(outfile, real_outfile))
442 LYXERR(Debug::FILES, "renaming file " << outfile
443 << " to " << real_outfile);
444 // Finally, don't forget to tell any future
445 // converters to use the renamed file...
446 outfile = real_outfile;
449 if (!conv.parselog.empty()) {
450 string const logfile = infile2 + ".log";
451 string const script = libScriptSearch(conv.parselog);
452 string const command2 = script +
453 " < " + quoteName(infile2 + ".out") +
454 " > " + quoteName(logfile);
455 one.startscript(Systemcall::Wait,
456 to_filesystem8bit(from_utf8(command2)),
458 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
464 if (conv.to == "program") {
465 Alert::error(_("Build errors"),
466 _("There were errors during the build process."));
468 // FIXME: this should go out of here. For example, here we cannot say if
469 // it is a document (.lyx) or something else. Same goes for elsewhere.
470 Alert::error(_("Cannot convert file"),
471 bformat(_("An error occurred while running:\n%1$s"),
472 wrapParas(from_utf8(command))));
479 Converter const & conv = converterlist_[edgepath.back()];
480 if (conv.To->dummy())
483 if (!conv.result_dir.empty()) {
484 // The converter has put the file(s) in a directory.
485 // In this case we ignore the given to_file.
486 if (from_base != to_base) {
487 string const from = subst(conv.result_dir,
488 token_base, from_base);
489 string const to = subst(conv.result_dir,
490 token_base, to_base);
491 Mover const & mover = getMover(conv.from);
492 if (!mover.rename(FileName(from), FileName(to))) {
493 Alert::error(_("Cannot convert file"),
494 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
495 from_utf8(from), from_utf8(to)));
501 if (conversionflags & try_cache)
502 ConverterCache::get().add(orig_from, to_format, outfile);
503 return move(conv.to, outfile, to_file, conv.latex);
508 bool Converters::move(string const & fmt,
509 FileName const & from, FileName const & to, bool copy)
514 bool no_errors = true;
515 string const path = onlyPath(from.absFileName());
516 string const base = onlyFileName(removeExtension(from.absFileName()));
517 string const to_base = removeExtension(to.absFileName());
518 string const to_extension = getExtension(to.absFileName());
520 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
521 for (support::FileNameList::const_iterator it = files.begin();
522 it != files.end(); ++it) {
523 string const from2 = it->absFileName();
524 string const file2 = onlyFileName(from2);
525 if (prefixIs(file2, base)) {
526 string const to2 = changeExtension(
527 to_base + file2.substr(base.length()),
529 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
531 Mover const & mover = getMover(fmt);
532 bool const moved = copy
533 ? mover.copy(*it, FileName(to2))
534 : mover.rename(*it, FileName(to2));
535 if (!moved && no_errors) {
536 Alert::error(_("Cannot convert file"),
538 _("Could not copy a temporary file from %1$s to %2$s.") :
539 _("Could not move a temporary file from %1$s to %2$s."),
540 from_utf8(from2), from_utf8(to2)));
549 bool Converters::formatIsUsed(string const & format)
551 ConverterList::const_iterator cit = converterlist_.begin();
552 ConverterList::const_iterator end = converterlist_.end();
553 for (; cit != end; ++cit) {
554 if (cit->from == format || cit->to == format)
561 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
562 FileName const & filename, ErrorList & errorList)
564 OutputParams runparams(0);
565 runparams.flavor = OutputParams::LATEX;
566 LaTeX latex("", runparams, filename);
568 int const result = latex.scanLogFile(terr);
570 if (result & LaTeX::ERRORS)
571 buffer.bufferErrors(terr, errorList);
580 : public boost::signals::trackable {
582 ShowMessage(Buffer const & b) : buffer_(b) {}
583 void operator()(docstring const & msg) const { buffer_.message(msg); }
585 Buffer const & buffer_;
591 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
592 OutputParams const & runparams, ErrorList & errorList)
594 buffer.setBusy(true);
595 buffer.message(_("Running LaTeX..."));
597 runparams.document_language = buffer.params().language->babel();
599 // do the LaTeX run(s)
600 string const name = buffer.latexName();
601 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
604 ShowMessage show(buffer);
605 latex.message.connect(show);
606 int const result = latex.run(terr);
608 if (result & LaTeX::ERRORS)
609 buffer.bufferErrors(terr, errorList);
611 // check return value from latex.run().
612 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
613 docstring const str =
614 bformat(_("LaTeX did not run successfully. "
615 "Additionally, LyX could not locate "
616 "the LaTeX log %1$s."), from_utf8(name));
617 Alert::error(_("LaTeX failed"), str);
618 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
619 Alert::warning(_("Output is empty"),
620 _("An empty output file was generated."));
624 buffer.setBusy(false);
626 int const ERROR_MASK =
631 return (result & ERROR_MASK) == 0;
637 void Converters::buildGraph()
639 // clear graph's data structures
640 G_.init(formats.size());
641 // each of the converters knows how to convert one format to another
642 // so, for each of them, we create an arrow on the graph, going from
643 // the one to the other
644 ConverterList::iterator it = converterlist_.begin();
645 ConverterList::iterator const end = converterlist_.end();
646 for (; it != end ; ++it) {
647 int const from = formats.getNumber(it->from);
648 int const to = formats.getNumber(it->to);
649 G_.addEdge(from, to);
654 vector<Format const *> const
655 Converters::intToFormat(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, set<string> const & excludes)
683 set<int> excluded_numbers;;
685 set<string>::const_iterator sit = excludes.begin();
686 set<string>::const_iterator const end = excludes.end();
687 for (; sit != end; ++sit)
688 excluded_numbers.insert(formats.getNumber(*sit));
690 vector<int> const & reachables =
691 G_.getReachable(formats.getNumber(from),
696 return intToFormat(reachables);
700 bool Converters::isReachable(string const & from, string const & to)
702 return G_.isReachable(formats.getNumber(from),
703 formats.getNumber(to));
707 Graph::EdgePath Converters::getPath(string const & from, string const & to)
709 return G_.getPath(formats.getNumber(from),
710 formats.getNumber(to));
714 vector<Format const *> Converters::importableFormats()
716 vector<string> l = loaders();
717 vector<Format const *> result = getReachableTo(l[0], true);
718 vector<string>::const_iterator it = l.begin() + 1;
719 vector<string>::const_iterator en = l.end();
720 for (; it != en; ++it) {
721 vector<Format const *> r = getReachableTo(*it, false);
722 result.insert(result.end(), r.begin(), r.end());
728 vector<Format const *> Converters::exportableFormats(bool only_viewable)
730 vector<string> s = savers();
731 vector<Format const *> result = getReachable(s[0], only_viewable, true);
732 vector<string>::const_iterator it = s.begin() + 1;
733 vector<string>::const_iterator en = s.end();
734 for (; it != en; ++it) {
735 vector<Format const *> r =
736 getReachable(*it, only_viewable, false);
737 result.insert(result.end(), r.begin(), r.end());
743 vector<string> Converters::loaders() const
748 v.push_back("textparagraph");
753 vector<string> Converters::savers() const
756 v.push_back("docbook");
757 v.push_back("latex");
758 v.push_back("literate");
759 v.push_back("luatex");
760 v.push_back("dviluatex");
762 v.push_back("xhtml");
763 v.push_back("pdflatex");
764 v.push_back("platex");
766 v.push_back("xetex");