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/lassert.h"
33 #include "support/lstrings.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/PathChanger.h"
37 #include "support/Systemcall.h"
40 using namespace lyx::support;
44 namespace Alert = lyx::frontend::Alert;
49 string const token_from("$$i");
50 string const token_base("$$b");
51 string const token_to("$$o");
52 string const token_path("$$p");
53 string const token_orig_path("$$r");
54 string const token_orig_from("$$f");
55 string const token_encoding("$$e");
56 string const token_latex_encoding("$$E");
59 string const add_options(string const & command, string const & options)
62 string const tail = split(command, head, ' ');
63 return head + ' ' + options + ' ' + tail;
67 string const dvipdfm_options(BufferParams const & bp)
71 if (bp.papersize != PAPER_CUSTOM) {
72 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
73 if (!paper_size.empty())
74 result = "-p "+ paper_size;
76 if (bp.orientation == ORIENTATION_LANDSCAPE)
84 class ConverterEqual {
86 ConverterEqual(string const & from, string const & to)
87 : from_(from), to_(to) {}
88 bool operator()(Converter const & c) const {
89 return c.from() == from_ && c.to() == to_;
99 Converter::Converter(string const & f, string const & t,
100 string const & c, string const & l)
101 : from_(f), to_(t), command_(c), flags_(l),
102 From_(0), To_(0), latex_(false), xml_(false),
103 need_aux_(false), nice_(false)
107 void Converter::readFlags()
109 string flag_list(flags_);
110 while (!flag_list.empty()) {
111 string flag_name, flag_value;
112 flag_list = split(flag_list, flag_value, ',');
113 flag_value = split(flag_value, flag_name, '=');
114 if (flag_name == "latex") {
116 latex_flavor_ = flag_value.empty() ?
117 "latex" : flag_value;
118 } else if (flag_name == "xml")
120 else if (flag_name == "needaux")
122 else if (flag_name == "resultdir")
123 result_dir_ = (flag_value.empty())
124 ? token_base : flag_value;
125 else if (flag_name == "resultfile")
126 result_file_ = flag_value;
127 else if (flag_name == "parselog")
128 parselog_ = flag_value;
129 else if (flag_name == "nice")
132 if (!result_dir_.empty() && result_file_.empty())
133 result_file_ = "index." + formats.extension(to_);
134 //if (!contains(command, token_from))
139 Converter const * Converters::getConverter(string const & from,
140 string const & to) const
142 ConverterList::const_iterator const cit =
143 find_if(converterlist_.begin(), converterlist_.end(),
144 ConverterEqual(from, to));
145 if (cit != converterlist_.end())
152 int Converters::getNumber(string const & from, string const & to) const
154 ConverterList::const_iterator const cit =
155 find_if(converterlist_.begin(), converterlist_.end(),
156 ConverterEqual(from, to));
157 if (cit != converterlist_.end())
158 return distance(converterlist_.begin(), cit);
164 void Converters::add(string const & from, string const & to,
165 string const & command, string const & flags)
169 ConverterList::iterator it = find_if(converterlist_.begin(),
170 converterlist_.end(),
171 ConverterEqual(from , to));
173 Converter converter(from, to, command, flags);
174 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
176 converter.setCommand(command);
177 converter.setFlags(flags);
179 converter.readFlags();
181 // The latex_command is used to update the .aux file when running
182 // a converter that uses it.
183 if (converter.latex()) {
184 if (latex_command_.empty() ||
185 converter.latex_flavor() == "latex")
186 latex_command_ = subst(command, token_from, "");
187 if (dvilualatex_command_.empty() ||
188 converter.latex_flavor() == "dvilualatex")
189 dvilualatex_command_ = subst(command, token_from, "");
190 if (lualatex_command_.empty() ||
191 converter.latex_flavor() == "lualatex")
192 lualatex_command_ = subst(command, token_from, "");
193 if (pdflatex_command_.empty() ||
194 converter.latex_flavor() == "pdflatex")
195 pdflatex_command_ = subst(command, token_from, "");
196 if (xelatex_command_.empty() ||
197 converter.latex_flavor() == "xelatex")
198 xelatex_command_ = subst(command, token_from, "");
201 if (it == converterlist_.end()) {
202 converterlist_.push_back(converter);
204 converter.setFrom(it->From());
205 converter.setTo(it->To());
211 void Converters::erase(string const & from, string const & to)
213 ConverterList::iterator const it =
214 find_if(converterlist_.begin(),
215 converterlist_.end(),
216 ConverterEqual(from, to));
217 if (it != converterlist_.end())
218 converterlist_.erase(it);
222 // This method updates the pointers From and To in all the converters.
223 // The code is not very efficient, but it doesn't matter as the number
224 // of formats and converters is small.
225 // Furthermore, this method is called only on startup, or after
226 // adding/deleting a format in FormPreferences (the latter calls can be
227 // eliminated if the formats in the Formats class are stored using a map or
228 // a list (instead of a vector), but this will cause other problems).
229 void Converters::update(Formats const & formats)
231 ConverterList::iterator it = converterlist_.begin();
232 ConverterList::iterator end = converterlist_.end();
233 for (; it != end; ++it) {
234 it->setFrom(formats.getFormat(it->from()));
235 it->setTo(formats.getFormat(it->to()));
240 // This method updates the pointers From and To in the last converter.
241 // It is called when adding a new converter in FormPreferences
242 void Converters::updateLast(Formats const & formats)
244 if (converterlist_.begin() != converterlist_.end()) {
245 ConverterList::iterator it = converterlist_.end() - 1;
246 it->setFrom(formats.getFormat(it->from()));
247 it->setTo(formats.getFormat(it->to()));
252 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
253 Buffer const * buffer)
255 for (Graph::EdgePath::const_iterator cit = path.begin();
256 cit != path.end(); ++cit) {
257 Converter const & conv = converterlist_[*cit];
259 if (conv.latex_flavor() == "latex")
260 return OutputParams::LATEX;
261 if (conv.latex_flavor() == "xelatex")
262 return OutputParams::XETEX;
263 if (conv.latex_flavor() == "lualatex")
264 return OutputParams::LUATEX;
265 if (conv.latex_flavor() == "dvilualatex")
266 return OutputParams::DVILUATEX;
267 if (conv.latex_flavor() == "pdflatex")
268 return OutputParams::PDFLATEX;
271 return OutputParams::XML;
273 return buffer ? buffer->params().getOutputFlavor()
274 : 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()) +
303 ' ' + from_ext + ' ' +
304 quoteName(from_file.toFilesystemEncoding()) +
306 quoteName(to_file.toFilesystemEncoding());
307 LYXERR(Debug::FILES, "No converter defined! "
308 "I use convertDefault.py:\n\t" << command);
310 one.startscript(Systemcall::Wait, command,
311 buffer ? buffer->filePath() : string(),
312 buffer ? buffer->layoutPos() : string());
313 if (to_file.isReadableFile()) {
314 if (conversionflags & try_cache)
315 ConverterCache::get().add(orig_from,
321 // only warn once per session and per file type
322 static std::map<string, string> warned;
323 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
326 warned.insert(make_pair(from_format, to_format));
328 Alert::error(_("Cannot convert file"),
329 bformat(_("No information for converting %1$s "
330 "format files to %2$s.\n"
331 "Define a converter in the preferences."),
332 from_ascii(from_format), from_ascii(to_format)));
336 // buffer is only invalid for importing, and then runparams is not
338 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
339 runparams.flavor = getFlavor(edgepath, buffer);
342 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
343 runparams.use_indices = buffer->params().use_indices;
344 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
345 string() : buffer->params().bibtex_command;
346 runparams.index_command = (buffer->params().index_command == "default") ?
347 string() : buffer->params().index_command;
348 runparams.document_language = buffer->params().language->babel();
351 // Some converters (e.g. lilypond) can only output files to the
352 // current directory, so we need to change the current directory.
353 // This has the added benefit that all other files that may be
354 // generated by the converter are deleted when LyX closes and do not
355 // clutter the real working directory.
356 // FIXME: This does not work if path is an UNC path on windows
358 string const path(onlyPath(from_file.absFileName()));
359 // Prevent the compiler from optimizing away p
363 // empty the error list before any new conversion takes place.
366 bool run_latex = false;
367 string from_base = changeExtension(from_file.absFileName(), "");
368 string to_base = changeExtension(to_file.absFileName(), "");
370 FileName outfile = from_file;
371 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
372 cit != edgepath.end(); ++cit) {
373 Converter const & conv = converterlist_[*cit];
374 bool dummy = conv.To()->dummy() && conv.to() != "program";
376 LYXERR(Debug::FILES, "Converting from "
377 << conv.from() << " to " << conv.to());
380 outfile = FileName(conv.result_file().empty()
381 ? changeExtension(from_file.absFileName(), conv.To()->extension())
382 : addName(subst(conv.result_dir(),
383 token_base, from_base),
384 subst(conv.result_file(),
385 token_base, onlyFileName(from_base))));
387 // if input and output files are equal, we use a
388 // temporary file as intermediary (JMarc)
389 FileName real_outfile;
390 if (!conv.result_file().empty())
391 real_outfile = FileName(changeExtension(from_file.absFileName(),
392 conv.To()->extension()));
393 if (outfile == infile) {
394 real_outfile = infile;
395 // when importing, a buffer does not necessarily exist
397 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
399 outfile = FileName(addName(package().temp_dir().absFileName(),
405 string command = conv.command();
406 command = subst(command, token_from, "");
407 command = subst(command, token_latex_encoding, buffer ?
408 buffer->params().encoding().latexName() : string());
409 LYXERR(Debug::FILES, "Running " << command);
410 if (!runLaTeX(*buffer, command, runparams, errorList))
413 if (conv.need_aux() && !run_latex) {
415 switch (runparams.flavor) {
416 case OutputParams::DVILUATEX:
417 command = dvilualatex_command_;
419 case OutputParams::LUATEX:
420 command = lualatex_command_;
422 case OutputParams::PDFLATEX:
423 command = pdflatex_command_;
425 case OutputParams::XETEX:
426 command = xelatex_command_;
429 command = latex_command_;
432 if (!command.empty()) {
433 LYXERR(Debug::FILES, "Running "
435 << " to update aux file");
436 if (!runLaTeX(*buffer, command,
437 runparams, errorList))
443 string const infile2 =
444 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
445 string const outfile2 =
446 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
448 string command = conv.command();
449 command = subst(command, token_from, quoteName(infile2));
450 command = subst(command, token_base, quoteName(from_base));
451 command = subst(command, token_to, quoteName(outfile2));
452 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
453 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
454 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
455 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
457 if (!conv.parselog().empty())
458 command += " 2> " + quoteName(infile2 + ".out");
460 // it is not actually not necessary to test for buffer here,
461 // but it pleases coverity.
462 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
463 command = add_options(command,
464 buffer->params().dvips_options());
465 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
466 command = add_options(command,
467 dvipdfm_options(buffer->params()));
469 LYXERR(Debug::FILES, "Calling " << command);
471 buffer->message(_("Executing command: ")
472 + from_utf8(command));
477 res = one.startscript(Systemcall::DontWait,
478 to_filesystem8bit(from_utf8(command)),
479 buffer ? buffer->filePath() : string(),
480 buffer ? buffer->layoutPos() : string());
481 // We're not waiting for the result, so we can't do anything
484 res = one.startscript(Systemcall::Wait,
485 to_filesystem8bit(from_utf8(command)),
486 buffer ? buffer->filePath()
488 buffer ? buffer->layoutPos()
490 if (!real_outfile.empty()) {
491 Mover const & mover = getMover(conv.to());
492 if (!mover.rename(outfile, real_outfile))
495 LYXERR(Debug::FILES, "renaming file " << outfile
496 << " to " << real_outfile);
497 // Finally, don't forget to tell any future
498 // converters to use the renamed file...
499 outfile = real_outfile;
502 if (!conv.parselog().empty()) {
503 string const logfile = infile2 + ".log";
504 string const command2 = conv.parselog() +
505 " < " + quoteName(infile2 + ".out") +
506 " > " + quoteName(logfile);
507 one.startscript(Systemcall::Wait,
508 to_filesystem8bit(from_utf8(command2)),
510 buffer->layoutPos());
511 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
517 if (conv.to() == "program") {
518 Alert::error(_("Build errors"),
519 _("There were errors during the build process."));
521 // FIXME: this should go out of here. For example, here we cannot say if
522 // it is a document (.lyx) or something else. Same goes for elsewhere.
523 Alert::error(_("Cannot convert file"),
524 bformat(_("An error occurred while running:\n%1$s"),
525 wrapParas(from_utf8(command))));
532 Converter const & conv = converterlist_[edgepath.back()];
533 if (conv.To()->dummy())
536 if (!conv.result_dir().empty()) {
537 // The converter has put the file(s) in a directory.
538 // In this case we ignore the given to_file.
539 if (from_base != to_base) {
540 string const from = subst(conv.result_dir(),
541 token_base, from_base);
542 string const to = subst(conv.result_dir(),
543 token_base, to_base);
544 Mover const & mover = getMover(conv.from());
545 if (!mover.rename(FileName(from), FileName(to))) {
546 Alert::error(_("Cannot convert file"),
547 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
548 from_utf8(from), from_utf8(to)));
554 if (conversionflags & try_cache)
555 ConverterCache::get().add(orig_from, to_format, outfile);
556 return move(conv.to(), outfile, to_file, conv.latex());
561 bool Converters::move(string const & fmt,
562 FileName const & from, FileName const & to, bool copy)
567 bool no_errors = true;
568 string const path = onlyPath(from.absFileName());
569 string const base = onlyFileName(removeExtension(from.absFileName()));
570 string const to_base = removeExtension(to.absFileName());
571 string const to_extension = getExtension(to.absFileName());
573 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
574 for (support::FileNameList::const_iterator it = files.begin();
575 it != files.end(); ++it) {
576 string const from2 = it->absFileName();
577 string const file2 = onlyFileName(from2);
578 if (prefixIs(file2, base)) {
579 string const to2 = changeExtension(
580 to_base + file2.substr(base.length()),
582 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
584 Mover const & mover = getMover(fmt);
585 bool const moved = copy
586 ? mover.copy(*it, FileName(to2))
587 : mover.rename(*it, FileName(to2));
588 if (!moved && no_errors) {
589 Alert::error(_("Cannot convert file"),
591 _("Could not copy a temporary file from %1$s to %2$s.") :
592 _("Could not move a temporary file from %1$s to %2$s."),
593 from_utf8(from2), from_utf8(to2)));
602 bool Converters::formatIsUsed(string const & format)
604 ConverterList::const_iterator cit = converterlist_.begin();
605 ConverterList::const_iterator end = converterlist_.end();
606 for (; cit != end; ++cit) {
607 if (cit->from() == format || cit->to() == format)
614 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
615 FileName const & filename, ErrorList & errorList)
617 OutputParams runparams(0);
618 runparams.flavor = OutputParams::LATEX;
619 LaTeX latex("", runparams, filename);
621 int const result = latex.scanLogFile(terr);
623 if (result & LaTeX::ERRORS)
624 buffer.bufferErrors(terr, errorList);
633 : public boost::signals2::trackable {
635 ShowMessage(Buffer const & b) : buffer_(b) {}
636 void operator()(docstring const & msg) const { buffer_.message(msg); }
638 Buffer const & buffer_;
644 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
645 OutputParams const & runparams, ErrorList & errorList)
647 buffer.setBusy(true);
648 buffer.message(_("Running LaTeX..."));
650 // do the LaTeX run(s)
651 string const name = buffer.latexName();
652 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
653 buffer.filePath(), buffer.layoutPos(),
654 buffer.lastPreviewError());
656 ShowMessage show(buffer);
657 latex.message.connect(show);
658 int const result = latex.run(terr);
660 if (result & LaTeX::ERRORS)
661 buffer.bufferErrors(terr, errorList);
663 if (!errorList.empty()) {
664 // We will show the LaTeX Errors GUI later which contains
665 // specific error messages so it would be repetitive to give
666 // e.g. the "finished with an error" dialog in addition.
668 else if (result & LaTeX::NO_LOGFILE) {
669 docstring const str =
670 bformat(_("LaTeX did not run successfully. "
671 "Additionally, LyX could not locate "
672 "the LaTeX log %1$s."), from_utf8(name));
673 Alert::error(_("LaTeX failed"), str);
674 } else if (result & LaTeX::NONZERO_ERROR) {
675 docstring const str =
676 bformat(_( "The external program\n%1$s\n"
677 "finished with an error. "
678 "It is recommended you fix the cause of the external "
679 "program's error (check the logs). "), from_utf8(command));
680 Alert::error(_("LaTeX failed"), str);
681 } else if (result & LaTeX::NO_OUTPUT) {
682 Alert::warning(_("Output is empty"),
683 _("No output file was generated."));
687 buffer.setBusy(false);
689 int const ERROR_MASK =
694 return (result & ERROR_MASK) == 0;
699 void Converters::buildGraph()
701 // clear graph's data structures
702 G_.init(formats.size());
703 // each of the converters knows how to convert one format to another
704 // so, for each of them, we create an arrow on the graph, going from
705 // the one to the other
706 ConverterList::iterator it = converterlist_.begin();
707 ConverterList::iterator const end = converterlist_.end();
708 for (; it != end ; ++it) {
709 int const from = formats.getNumber(it->from());
710 int const to = formats.getNumber(it->to());
711 LASSERT(from >= 0, continue);
712 LASSERT(to >= 0, continue);
713 G_.addEdge(from, to);
718 vector<Format const *> const
719 Converters::intToFormat(vector<int> const & input)
721 vector<Format const *> result(input.size());
723 vector<int>::const_iterator it = input.begin();
724 vector<int>::const_iterator const end = input.end();
725 vector<Format const *>::iterator rit = result.begin();
726 for ( ; it != end; ++it, ++rit) {
727 *rit = &formats.get(*it);
733 vector<Format const *> const
734 Converters::getReachableTo(string const & target, bool const clear_visited)
736 vector<int> const & reachablesto =
737 G_.getReachableTo(formats.getNumber(target), clear_visited);
739 return intToFormat(reachablesto);
743 vector<Format const *> const
744 Converters::getReachable(string const & from, bool const only_viewable,
745 bool const clear_visited, set<string> const & excludes)
747 set<int> excluded_numbers;
749 set<string>::const_iterator sit = excludes.begin();
750 set<string>::const_iterator const end = excludes.end();
751 for (; sit != end; ++sit)
752 excluded_numbers.insert(formats.getNumber(*sit));
754 vector<int> const & reachables =
755 G_.getReachable(formats.getNumber(from),
760 return intToFormat(reachables);
764 bool Converters::isReachable(string const & from, string const & to)
766 return G_.isReachable(formats.getNumber(from),
767 formats.getNumber(to));
771 Graph::EdgePath Converters::getPath(string const & from, string const & to)
773 return G_.getPath(formats.getNumber(from),
774 formats.getNumber(to));
778 vector<Format const *> Converters::importableFormats()
780 vector<string> l = loaders();
781 vector<Format const *> result = getReachableTo(l[0], true);
782 vector<string>::const_iterator it = l.begin() + 1;
783 vector<string>::const_iterator en = l.end();
784 for (; it != en; ++it) {
785 vector<Format const *> r = getReachableTo(*it, false);
786 result.insert(result.end(), r.begin(), r.end());
792 vector<Format const *> Converters::exportableFormats(bool only_viewable)
794 vector<string> s = savers();
795 vector<Format const *> result = getReachable(s[0], only_viewable, true);
796 vector<string>::const_iterator it = s.begin() + 1;
797 vector<string>::const_iterator en = s.end();
798 for (; it != en; ++it) {
799 vector<Format const *> r =
800 getReachable(*it, only_viewable, false);
801 result.insert(result.end(), r.begin(), r.end());
807 vector<string> Converters::loaders() const
812 v.push_back("textparagraph");
817 vector<string> Converters::savers() const
820 v.push_back("docbook");
821 v.push_back("latex");
822 v.push_back("literate");
823 v.push_back("luatex");
824 v.push_back("dviluatex");
826 v.push_back("xhtml");
827 v.push_back("pdflatex");
828 v.push_back("platex");
830 v.push_back("xetex");