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_orig_from("$$f");
54 string const token_encoding("$$e");
55 string const token_latex_encoding("$$E");
58 string const add_options(string const & command, string const & options)
61 string const tail = split(command, head, ' ');
62 return head + ' ' + options + ' ' + tail;
66 string const dvipdfm_options(BufferParams const & bp)
70 if (bp.papersize != PAPER_CUSTOM) {
71 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
72 if (!paper_size.empty())
73 result = "-p "+ paper_size;
75 if (bp.orientation == ORIENTATION_LANDSCAPE)
83 class ConverterEqual {
85 ConverterEqual(string const & from, string const & to)
86 : from_(from), to_(to) {}
87 bool operator()(Converter const & c) const {
88 return c.from == from_ && c.to == to_;
98 Converter::Converter(string const & f, string const & t,
99 string const & c, string const & l)
100 : from(f), to(t), command(c), flags(l),
101 From(0), To(0), latex(false), xml(false),
102 need_aux(false), nice(false)
106 void Converter::readFlags()
108 string flag_list(flags);
109 while (!flag_list.empty()) {
110 string flag_name, flag_value;
111 flag_list = split(flag_list, flag_value, ',');
112 flag_value = split(flag_value, flag_name, '=');
113 if (flag_name == "latex") {
115 latex_flavor = flag_value.empty() ?
116 "latex" : flag_value;
117 } else if (flag_name == "xml")
119 else if (flag_name == "needaux")
121 else if (flag_name == "resultdir")
122 result_dir = (flag_value.empty())
123 ? token_base : flag_value;
124 else if (flag_name == "resultfile")
125 result_file = flag_value;
126 else if (flag_name == "parselog")
127 parselog = flag_value;
128 else if (flag_name == "nice")
131 if (!result_dir.empty() && result_file.empty())
132 result_file = "index." + formats.extension(to);
133 //if (!contains(command, token_from))
138 Converter const * Converters::getConverter(string const & from,
139 string const & to) const
141 ConverterList::const_iterator const cit =
142 find_if(converterlist_.begin(), converterlist_.end(),
143 ConverterEqual(from, to));
144 if (cit != converterlist_.end())
151 int Converters::getNumber(string const & from, string const & to) const
153 ConverterList::const_iterator const cit =
154 find_if(converterlist_.begin(), converterlist_.end(),
155 ConverterEqual(from, to));
156 if (cit != converterlist_.end())
157 return distance(converterlist_.begin(), cit);
163 void Converters::add(string const & from, string const & to,
164 string const & command, string const & flags)
168 ConverterList::iterator it = find_if(converterlist_.begin(),
169 converterlist_.end(),
170 ConverterEqual(from , to));
172 Converter converter(from, to, command, flags);
173 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
175 converter.command = command;
176 converter.flags = flags;
178 converter.readFlags();
180 // The latex_command is used to update the .aux file when running
181 // a converter that uses it.
182 if (converter.latex) {
183 if (latex_command_.empty() ||
184 converter.latex_flavor == "latex")
185 latex_command_ = subst(command, token_from, "");
186 if (dvilualatex_command_.empty() ||
187 converter.latex_flavor == "dvilualatex")
188 dvilualatex_command_ = subst(command, token_from, "");
189 if (lualatex_command_.empty() ||
190 converter.latex_flavor == "lualatex")
191 lualatex_command_ = subst(command, token_from, "");
192 if (pdflatex_command_.empty() ||
193 converter.latex_flavor == "pdflatex")
194 pdflatex_command_ = subst(command, token_from, "");
195 if (xelatex_command_.empty() ||
196 converter.latex_flavor == "xelatex")
197 xelatex_command_ = subst(command, token_from, "");
200 if (it == converterlist_.end()) {
201 converterlist_.push_back(converter);
203 converter.From = it->From;
204 converter.To = it->To;
210 void Converters::erase(string const & from, string const & to)
212 ConverterList::iterator const it =
213 find_if(converterlist_.begin(),
214 converterlist_.end(),
215 ConverterEqual(from, to));
216 if (it != converterlist_.end())
217 converterlist_.erase(it);
221 // This method updates the pointers From and To in all the converters.
222 // The code is not very efficient, but it doesn't matter as the number
223 // of formats and converters is small.
224 // Furthermore, this method is called only on startup, or after
225 // adding/deleting a format in FormPreferences (the latter calls can be
226 // eliminated if the formats in the Formats class are stored using a map or
227 // a list (instead of a vector), but this will cause other problems).
228 void Converters::update(Formats const & formats)
230 ConverterList::iterator it = converterlist_.begin();
231 ConverterList::iterator end = converterlist_.end();
232 for (; it != end; ++it) {
233 it->From = formats.getFormat(it->from);
234 it->To = formats.getFormat(it->to);
239 // This method updates the pointers From and To in the last converter.
240 // It is called when adding a new converter in FormPreferences
241 void Converters::updateLast(Formats const & formats)
243 if (converterlist_.begin() != converterlist_.end()) {
244 ConverterList::iterator it = converterlist_.end() - 1;
245 it->From = formats.getFormat(it->from);
246 it->To = formats.getFormat(it->to);
251 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
252 Buffer const * buffer)
254 for (Graph::EdgePath::const_iterator cit = path.begin();
255 cit != path.end(); ++cit) {
256 Converter const & conv = converterlist_[*cit];
258 if (conv.latex_flavor == "latex")
259 return OutputParams::LATEX;
260 if (conv.latex_flavor == "xelatex")
261 return OutputParams::XETEX;
262 if (conv.latex_flavor == "lualatex")
263 return OutputParams::LUATEX;
264 if (conv.latex_flavor == "dvilualatex")
265 return OutputParams::DVILUATEX;
266 if (conv.latex_flavor == "pdflatex")
267 return OutputParams::PDFLATEX;
270 return OutputParams::XML;
272 return buffer ? buffer->params().getOutputFlavor()
273 : OutputParams::LATEX;
277 bool Converters::convert(Buffer const * buffer,
278 FileName const & from_file, FileName const & to_file,
279 FileName const & orig_from,
280 string const & from_format, string const & to_format,
281 ErrorList & errorList, int conversionflags)
283 if (from_format == to_format)
284 return move(from_format, from_file, to_file, false);
286 if ((conversionflags & try_cache) &&
287 ConverterCache::get().inCache(orig_from, to_format))
288 return ConverterCache::get().copy(orig_from, to_format, to_file);
290 Graph::EdgePath edgepath = getPath(from_format, to_format);
291 if (edgepath.empty()) {
292 if (conversionflags & try_default) {
293 // if no special converter defined, then we take the
294 // default one from ImageMagic.
295 string const from_ext = from_format.empty() ?
296 getExtension(from_file.absFileName()) :
297 formats.extension(from_format);
298 string const to_ext = formats.extension(to_format);
299 string const command =
301 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
303 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
305 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
306 LYXERR(Debug::FILES, "No converter defined! "
307 "I use convertDefault.py:\n\t" << command);
309 one.startscript(Systemcall::Wait, command, buffer ?
310 buffer->filePath() : string());
311 if (to_file.isReadableFile()) {
312 if (conversionflags & try_cache)
313 ConverterCache::get().add(orig_from,
319 // only warn once per session and per file type
320 static std::map<string, string> warned;
321 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
324 warned.insert(make_pair(from_format, to_format));
326 Alert::error(_("Cannot convert file"),
327 bformat(_("No information for converting %1$s "
328 "format files to %2$s.\n"
329 "Define a converter in the preferences."),
330 from_ascii(from_format), from_ascii(to_format)));
334 // buffer is only invalid for importing, and then runparams is not
336 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
337 runparams.flavor = getFlavor(edgepath, buffer);
340 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
341 runparams.use_indices = buffer->params().use_indices;
342 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
343 string() : buffer->params().bibtex_command;
344 runparams.index_command = (buffer->params().index_command == "default") ?
345 string() : buffer->params().index_command;
348 // Some converters (e.g. lilypond) can only output files to the
349 // current directory, so we need to change the current directory.
350 // This has the added benefit that all other files that may be
351 // generated by the converter are deleted when LyX closes and do not
352 // clutter the real working directory.
353 // FIXME: This does not work if path is an UNC path on windows
355 string const path(onlyPath(from_file.absFileName()));
356 // Prevent the compiler from optimizing away p
360 // empty the error list before any new conversion takes place.
363 bool run_latex = false;
364 string from_base = changeExtension(from_file.absFileName(), "");
365 string to_base = changeExtension(to_file.absFileName(), "");
367 FileName outfile = from_file;
368 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
369 cit != edgepath.end(); ++cit) {
370 Converter const & conv = converterlist_[*cit];
371 bool dummy = conv.To->dummy() && conv.to != "program";
373 LYXERR(Debug::FILES, "Converting from "
374 << conv.from << " to " << conv.to);
377 outfile = FileName(conv.result_file.empty()
378 ? changeExtension(from_file.absFileName(), conv.To->extension())
379 : addName(subst(conv.result_dir,
380 token_base, from_base),
381 subst(conv.result_file,
382 token_base, onlyFileName(from_base))));
384 // if input and output files are equal, we use a
385 // temporary file as intermediary (JMarc)
386 FileName real_outfile;
387 if (!conv.result_file.empty())
388 real_outfile = FileName(changeExtension(from_file.absFileName(),
389 conv.To->extension()));
390 if (outfile == infile) {
391 real_outfile = infile;
392 // when importing, a buffer does not necessarily exist
394 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
396 outfile = FileName(addName(package().temp_dir().absFileName(),
402 string command = conv.command;
403 command = subst(command, token_from, "");
404 command = subst(command, token_latex_encoding, buffer ?
405 buffer->params().encoding().latexName() : string());
406 LYXERR(Debug::FILES, "Running " << command);
407 if (!runLaTeX(*buffer, command, runparams, errorList))
410 if (conv.need_aux && !run_latex) {
412 switch (runparams.flavor) {
413 case OutputParams::DVILUATEX:
414 command = dvilualatex_command_;
416 case OutputParams::LUATEX:
417 command = lualatex_command_;
419 case OutputParams::PDFLATEX:
420 command = pdflatex_command_;
422 case OutputParams::XETEX:
423 command = xelatex_command_;
426 command = latex_command_;
429 if (!command.empty()) {
430 LYXERR(Debug::FILES, "Running "
432 << " to update aux file");
433 if (!runLaTeX(*buffer, command,
434 runparams, errorList))
440 string const infile2 =
441 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
442 string const outfile2 =
443 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
445 string command = conv.command;
446 command = subst(command, token_from, quoteName(infile2));
447 command = subst(command, token_base, quoteName(from_base));
448 command = subst(command, token_to, quoteName(outfile2));
449 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
450 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
451 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
452 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
453 command = libScriptSearch(command);
455 if (!conv.parselog.empty())
456 command += " 2> " + quoteName(infile2 + ".out");
458 if (conv.from == "dvi" && conv.to == "ps")
459 command = add_options(command,
460 buffer->params().dvips_options());
461 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
462 command = add_options(command,
463 dvipdfm_options(buffer->params()));
465 LYXERR(Debug::FILES, "Calling " << command);
467 buffer->message(_("Executing command: ")
468 + from_utf8(command));
473 res = one.startscript(Systemcall::DontWait,
474 to_filesystem8bit(from_utf8(command)),
475 buffer ? buffer->filePath() : string());
476 // We're not waiting for the result, so we can't do anything
479 res = one.startscript(Systemcall::Wait,
480 to_filesystem8bit(from_utf8(command)),
481 buffer ? buffer->filePath()
483 if (!real_outfile.empty()) {
484 Mover const & mover = getMover(conv.to);
485 if (!mover.rename(outfile, real_outfile))
488 LYXERR(Debug::FILES, "renaming file " << outfile
489 << " to " << real_outfile);
490 // Finally, don't forget to tell any future
491 // converters to use the renamed file...
492 outfile = real_outfile;
495 if (!conv.parselog.empty()) {
496 string const logfile = infile2 + ".log";
497 string const script = libScriptSearch(conv.parselog);
498 string const command2 = script +
499 " < " + quoteName(infile2 + ".out") +
500 " > " + quoteName(logfile);
501 one.startscript(Systemcall::Wait,
502 to_filesystem8bit(from_utf8(command2)),
504 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
510 if (conv.to == "program") {
511 Alert::error(_("Build errors"),
512 _("There were errors during the build process."));
514 // FIXME: this should go out of here. For example, here we cannot say if
515 // it is a document (.lyx) or something else. Same goes for elsewhere.
516 Alert::error(_("Cannot convert file"),
517 bformat(_("An error occurred while running:\n%1$s"),
518 wrapParas(from_utf8(command))));
525 Converter const & conv = converterlist_[edgepath.back()];
526 if (conv.To->dummy())
529 if (!conv.result_dir.empty()) {
530 // The converter has put the file(s) in a directory.
531 // In this case we ignore the given to_file.
532 if (from_base != to_base) {
533 string const from = subst(conv.result_dir,
534 token_base, from_base);
535 string const to = subst(conv.result_dir,
536 token_base, to_base);
537 Mover const & mover = getMover(conv.from);
538 if (!mover.rename(FileName(from), FileName(to))) {
539 Alert::error(_("Cannot convert file"),
540 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
541 from_utf8(from), from_utf8(to)));
547 if (conversionflags & try_cache)
548 ConverterCache::get().add(orig_from, to_format, outfile);
549 return move(conv.to, outfile, to_file, conv.latex);
554 bool Converters::move(string const & fmt,
555 FileName const & from, FileName const & to, bool copy)
560 bool no_errors = true;
561 string const path = onlyPath(from.absFileName());
562 string const base = onlyFileName(removeExtension(from.absFileName()));
563 string const to_base = removeExtension(to.absFileName());
564 string const to_extension = getExtension(to.absFileName());
566 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
567 for (support::FileNameList::const_iterator it = files.begin();
568 it != files.end(); ++it) {
569 string const from2 = it->absFileName();
570 string const file2 = onlyFileName(from2);
571 if (prefixIs(file2, base)) {
572 string const to2 = changeExtension(
573 to_base + file2.substr(base.length()),
575 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
577 Mover const & mover = getMover(fmt);
578 bool const moved = copy
579 ? mover.copy(*it, FileName(to2))
580 : mover.rename(*it, FileName(to2));
581 if (!moved && no_errors) {
582 Alert::error(_("Cannot convert file"),
584 _("Could not copy a temporary file from %1$s to %2$s.") :
585 _("Could not move a temporary file from %1$s to %2$s."),
586 from_utf8(from2), from_utf8(to2)));
595 bool Converters::formatIsUsed(string const & format)
597 ConverterList::const_iterator cit = converterlist_.begin();
598 ConverterList::const_iterator end = converterlist_.end();
599 for (; cit != end; ++cit) {
600 if (cit->from == format || cit->to == format)
607 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
608 FileName const & filename, ErrorList & errorList)
610 OutputParams runparams(0);
611 runparams.flavor = OutputParams::LATEX;
612 LaTeX latex("", runparams, filename);
614 int const result = latex.scanLogFile(terr);
616 if (result & LaTeX::ERRORS)
617 buffer.bufferErrors(terr, errorList);
626 : public boost::signals::trackable {
628 ShowMessage(Buffer const & b) : buffer_(b) {}
629 void operator()(docstring const & msg) const { buffer_.message(msg); }
631 Buffer const & buffer_;
637 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
638 OutputParams const & runparams, ErrorList & errorList)
640 buffer.setBusy(true);
641 buffer.message(_("Running LaTeX..."));
643 runparams.document_language = buffer.params().language->babel();
645 // do the LaTeX run(s)
646 string const name = buffer.latexName();
647 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
650 ShowMessage show(buffer);
651 latex.message.connect(show);
652 int const result = latex.run(terr);
654 if (result & LaTeX::ERRORS)
655 buffer.bufferErrors(terr, errorList);
657 // check return value from latex.run().
658 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
659 docstring const str =
660 bformat(_("LaTeX did not run successfully. "
661 "Additionally, LyX could not locate "
662 "the LaTeX log %1$s."), from_utf8(name));
663 Alert::error(_("LaTeX failed"), str);
664 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
665 Alert::warning(_("Output is empty"),
666 _("An empty output file was generated."));
670 buffer.setBusy(false);
672 int const ERROR_MASK =
677 return (result & ERROR_MASK) == 0;
683 void Converters::buildGraph()
685 // clear graph's data structures
686 G_.init(formats.size());
687 // each of the converters knows how to convert one format to another
688 // so, for each of them, we create an arrow on the graph, going from
689 // the one to the other
690 ConverterList::iterator it = converterlist_.begin();
691 ConverterList::iterator const end = converterlist_.end();
692 for (; it != end ; ++it) {
693 int const from = formats.getNumber(it->from);
694 int const to = formats.getNumber(it->to);
695 G_.addEdge(from, to);
700 vector<Format const *> const
701 Converters::intToFormat(vector<int> const & input)
703 vector<Format const *> result(input.size());
705 vector<int>::const_iterator it = input.begin();
706 vector<int>::const_iterator const end = input.end();
707 vector<Format const *>::iterator rit = result.begin();
708 for ( ; it != end; ++it, ++rit) {
709 *rit = &formats.get(*it);
715 vector<Format const *> const
716 Converters::getReachableTo(string const & target, bool const clear_visited)
718 vector<int> const & reachablesto =
719 G_.getReachableTo(formats.getNumber(target), clear_visited);
721 return intToFormat(reachablesto);
725 vector<Format const *> const
726 Converters::getReachable(string const & from, bool const only_viewable,
727 bool const clear_visited, set<string> const & excludes)
729 set<int> excluded_numbers;;
731 set<string>::const_iterator sit = excludes.begin();
732 set<string>::const_iterator const end = excludes.end();
733 for (; sit != end; ++sit)
734 excluded_numbers.insert(formats.getNumber(*sit));
736 vector<int> const & reachables =
737 G_.getReachable(formats.getNumber(from),
742 return intToFormat(reachables);
746 bool Converters::isReachable(string const & from, string const & to)
748 return G_.isReachable(formats.getNumber(from),
749 formats.getNumber(to));
753 Graph::EdgePath Converters::getPath(string const & from, string const & to)
755 return G_.getPath(formats.getNumber(from),
756 formats.getNumber(to));
760 vector<Format const *> Converters::importableFormats()
762 vector<string> l = loaders();
763 vector<Format const *> result = getReachableTo(l[0], true);
764 vector<string>::const_iterator it = l.begin() + 1;
765 vector<string>::const_iterator en = l.end();
766 for (; it != en; ++it) {
767 vector<Format const *> r = getReachableTo(*it, false);
768 result.insert(result.end(), r.begin(), r.end());
774 vector<Format const *> Converters::exportableFormats(bool only_viewable)
776 vector<string> s = savers();
777 vector<Format const *> result = getReachable(s[0], only_viewable, true);
778 vector<string>::const_iterator it = s.begin() + 1;
779 vector<string>::const_iterator en = s.end();
780 for (; it != en; ++it) {
781 vector<Format const *> r =
782 getReachable(*it, only_viewable, false);
783 result.insert(result.end(), r.begin(), r.end());
789 vector<string> Converters::loaders() const
794 v.push_back("textparagraph");
799 vector<string> Converters::savers() const
802 v.push_back("docbook");
803 v.push_back("latex");
804 v.push_back("literate");
805 v.push_back("luatex");
806 v.push_back("dviluatex");
808 v.push_back("xhtml");
809 v.push_back("pdflatex");
810 v.push_back("platex");
812 v.push_back("xetex");