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 =
343 buffer->params().bufferFormat() == "latex"
344 && buffer->params().encoding().package() == Encoding::japanese;
345 runparams.use_indices = buffer->params().use_indices;
346 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
347 string() : buffer->params().bibtex_command;
348 runparams.index_command = (buffer->params().index_command == "default") ?
349 string() : buffer->params().index_command;
350 runparams.document_language = buffer->params().language->babel();
353 // Some converters (e.g. lilypond) can only output files to the
354 // current directory, so we need to change the current directory.
355 // This has the added benefit that all other files that may be
356 // generated by the converter are deleted when LyX closes and do not
357 // clutter the real working directory.
358 // FIXME: This does not work if path is an UNC path on windows
360 string const path(onlyPath(from_file.absFileName()));
361 // Prevent the compiler from optimizing away p
365 // empty the error list before any new conversion takes place.
368 bool run_latex = false;
369 string from_base = changeExtension(from_file.absFileName(), "");
370 string to_base = changeExtension(to_file.absFileName(), "");
372 FileName outfile = from_file;
373 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
374 cit != edgepath.end(); ++cit) {
375 Converter const & conv = converterlist_[*cit];
376 bool dummy = conv.To()->dummy() && conv.to() != "program";
378 LYXERR(Debug::FILES, "Converting from "
379 << conv.from() << " to " << conv.to());
382 outfile = FileName(conv.result_file().empty()
383 ? changeExtension(from_file.absFileName(), conv.To()->extension())
384 : addName(subst(conv.result_dir(),
385 token_base, from_base),
386 subst(conv.result_file(),
387 token_base, onlyFileName(from_base))));
389 // if input and output files are equal, we use a
390 // temporary file as intermediary (JMarc)
391 FileName real_outfile;
392 if (!conv.result_file().empty())
393 real_outfile = FileName(changeExtension(from_file.absFileName(),
394 conv.To()->extension()));
395 if (outfile == infile) {
396 real_outfile = infile;
397 // when importing, a buffer does not necessarily exist
399 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
401 outfile = FileName(addName(package().temp_dir().absFileName(),
407 string command = conv.command();
408 command = subst(command, token_from, "");
409 command = subst(command, token_latex_encoding, buffer ?
410 buffer->params().encoding().latexName() : string());
411 LYXERR(Debug::FILES, "Running " << command);
412 if (!runLaTeX(*buffer, command, runparams, errorList))
415 if (conv.need_aux() && !run_latex) {
417 switch (runparams.flavor) {
418 case OutputParams::DVILUATEX:
419 command = dvilualatex_command_;
421 case OutputParams::LUATEX:
422 command = lualatex_command_;
424 case OutputParams::PDFLATEX:
425 command = pdflatex_command_;
427 case OutputParams::XETEX:
428 command = xelatex_command_;
431 command = latex_command_;
434 if (!command.empty()) {
435 LYXERR(Debug::FILES, "Running "
437 << " to update aux file");
438 if (!runLaTeX(*buffer, command,
439 runparams, errorList))
445 string const infile2 =
446 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
447 string const outfile2 =
448 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
450 string command = conv.command();
451 command = subst(command, token_from, quoteName(infile2));
452 command = subst(command, token_base, quoteName(from_base));
453 command = subst(command, token_to, quoteName(outfile2));
454 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
455 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
456 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
457 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
459 if (!conv.parselog().empty())
460 command += " 2> " + quoteName(infile2 + ".out");
462 // it is not actually not necessary to test for buffer here,
463 // but it pleases coverity.
464 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
465 command = add_options(command,
466 buffer->params().dvips_options());
467 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
468 command = add_options(command,
469 dvipdfm_options(buffer->params()));
471 LYXERR(Debug::FILES, "Calling " << command);
473 buffer->message(_("Executing command: ")
474 + from_utf8(command));
479 res = one.startscript(Systemcall::DontWait,
480 to_filesystem8bit(from_utf8(command)),
481 buffer ? buffer->filePath() : string(),
482 buffer ? buffer->layoutPos() : string());
483 // We're not waiting for the result, so we can't do anything
486 res = one.startscript(Systemcall::Wait,
487 to_filesystem8bit(from_utf8(command)),
488 buffer ? buffer->filePath()
490 buffer ? buffer->layoutPos()
492 if (!real_outfile.empty()) {
493 Mover const & mover = getMover(conv.to());
494 if (!mover.rename(outfile, real_outfile))
497 LYXERR(Debug::FILES, "renaming file " << outfile
498 << " to " << real_outfile);
499 // Finally, don't forget to tell any future
500 // converters to use the renamed file...
501 outfile = real_outfile;
504 if (!conv.parselog().empty()) {
505 string const logfile = infile2 + ".log";
506 string const command2 = conv.parselog() +
507 " < " + quoteName(infile2 + ".out") +
508 " > " + quoteName(logfile);
509 one.startscript(Systemcall::Wait,
510 to_filesystem8bit(from_utf8(command2)),
512 buffer->layoutPos());
513 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
519 if (conv.to() == "program") {
520 Alert::error(_("Build errors"),
521 _("There were errors during the build process."));
523 // FIXME: this should go out of here. For example, here we cannot say if
524 // it is a document (.lyx) or something else. Same goes for elsewhere.
525 Alert::error(_("Cannot convert file"),
526 bformat(_("An error occurred while running:\n%1$s"),
527 wrapParas(from_utf8(command))));
534 Converter const & conv = converterlist_[edgepath.back()];
535 if (conv.To()->dummy())
538 if (!conv.result_dir().empty()) {
539 // The converter has put the file(s) in a directory.
540 // In this case we ignore the given to_file.
541 if (from_base != to_base) {
542 string const from = subst(conv.result_dir(),
543 token_base, from_base);
544 string const to = subst(conv.result_dir(),
545 token_base, to_base);
546 Mover const & mover = getMover(conv.from());
547 if (!mover.rename(FileName(from), FileName(to))) {
548 Alert::error(_("Cannot convert file"),
549 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
550 from_utf8(from), from_utf8(to)));
556 if (conversionflags & try_cache)
557 ConverterCache::get().add(orig_from, to_format, outfile);
558 return move(conv.to(), outfile, to_file, conv.latex());
563 bool Converters::move(string const & fmt,
564 FileName const & from, FileName const & to, bool copy)
569 bool no_errors = true;
570 string const path = onlyPath(from.absFileName());
571 string const base = onlyFileName(removeExtension(from.absFileName()));
572 string const to_base = removeExtension(to.absFileName());
573 string const to_extension = getExtension(to.absFileName());
575 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
576 for (support::FileNameList::const_iterator it = files.begin();
577 it != files.end(); ++it) {
578 string const from2 = it->absFileName();
579 string const file2 = onlyFileName(from2);
580 if (prefixIs(file2, base)) {
581 string const to2 = changeExtension(
582 to_base + file2.substr(base.length()),
584 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
586 Mover const & mover = getMover(fmt);
587 bool const moved = copy
588 ? mover.copy(*it, FileName(to2))
589 : mover.rename(*it, FileName(to2));
590 if (!moved && no_errors) {
591 Alert::error(_("Cannot convert file"),
593 _("Could not copy a temporary file from %1$s to %2$s.") :
594 _("Could not move a temporary file from %1$s to %2$s."),
595 from_utf8(from2), from_utf8(to2)));
604 bool Converters::formatIsUsed(string const & format)
606 ConverterList::const_iterator cit = converterlist_.begin();
607 ConverterList::const_iterator end = converterlist_.end();
608 for (; cit != end; ++cit) {
609 if (cit->from() == format || cit->to() == format)
616 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
617 FileName const & filename, ErrorList & errorList)
619 OutputParams runparams(0);
620 runparams.flavor = OutputParams::LATEX;
621 LaTeX latex("", runparams, filename);
623 int const result = latex.scanLogFile(terr);
625 if (result & LaTeX::ERRORS)
626 buffer.bufferErrors(terr, errorList);
635 : public boost::signals2::trackable {
637 ShowMessage(Buffer const & b) : buffer_(b) {}
638 void operator()(docstring const & msg) const { buffer_.message(msg); }
640 Buffer const & buffer_;
646 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
647 OutputParams const & runparams, ErrorList & errorList)
649 buffer.setBusy(true);
650 buffer.message(_("Running LaTeX..."));
652 // do the LaTeX run(s)
653 string const name = buffer.latexName();
654 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
655 buffer.filePath(), buffer.layoutPos(),
656 buffer.lastPreviewError());
658 ShowMessage show(buffer);
659 latex.message.connect(show);
660 int const result = latex.run(terr);
662 if (result & LaTeX::ERRORS)
663 buffer.bufferErrors(terr, errorList);
665 if (!errorList.empty()) {
666 // We will show the LaTeX Errors GUI later which contains
667 // specific error messages so it would be repetitive to give
668 // e.g. the "finished with an error" dialog in addition.
670 else if (result & LaTeX::NO_LOGFILE) {
671 docstring const str =
672 bformat(_("LaTeX did not run successfully. "
673 "Additionally, LyX could not locate "
674 "the LaTeX log %1$s."), from_utf8(name));
675 Alert::error(_("LaTeX failed"), str);
676 } else if (result & LaTeX::NONZERO_ERROR) {
677 docstring const str =
678 bformat(_( "The external program\n%1$s\n"
679 "finished with an error. "
680 "It is recommended you fix the cause of the external "
681 "program's error (check the logs). "), from_utf8(command));
682 Alert::error(_("LaTeX failed"), str);
683 } else if (result & LaTeX::NO_OUTPUT) {
684 Alert::warning(_("Output is empty"),
685 _("No output file was generated."));
689 buffer.setBusy(false);
691 int const ERROR_MASK =
696 return (result & ERROR_MASK) == 0;
701 void Converters::buildGraph()
703 // clear graph's data structures
704 G_.init(formats.size());
705 // each of the converters knows how to convert one format to another
706 // so, for each of them, we create an arrow on the graph, going from
707 // the one to the other
708 ConverterList::iterator it = converterlist_.begin();
709 ConverterList::iterator const end = converterlist_.end();
710 for (; it != end ; ++it) {
711 int const from = formats.getNumber(it->from());
712 int const to = formats.getNumber(it->to());
713 LASSERT(from >= 0, continue);
714 LASSERT(to >= 0, continue);
715 G_.addEdge(from, to);
720 vector<Format const *> const
721 Converters::intToFormat(vector<int> const & input)
723 vector<Format const *> result(input.size());
725 vector<int>::const_iterator it = input.begin();
726 vector<int>::const_iterator const end = input.end();
727 vector<Format const *>::iterator rit = result.begin();
728 for ( ; it != end; ++it, ++rit) {
729 *rit = &formats.get(*it);
735 vector<Format const *> const
736 Converters::getReachableTo(string const & target, bool const clear_visited)
738 vector<int> const & reachablesto =
739 G_.getReachableTo(formats.getNumber(target), clear_visited);
741 return intToFormat(reachablesto);
745 vector<Format const *> const
746 Converters::getReachable(string const & from, bool const only_viewable,
747 bool const clear_visited, set<string> const & excludes)
749 set<int> excluded_numbers;
751 set<string>::const_iterator sit = excludes.begin();
752 set<string>::const_iterator const end = excludes.end();
753 for (; sit != end; ++sit)
754 excluded_numbers.insert(formats.getNumber(*sit));
756 vector<int> const & reachables =
757 G_.getReachable(formats.getNumber(from),
762 return intToFormat(reachables);
766 bool Converters::isReachable(string const & from, string const & to)
768 return G_.isReachable(formats.getNumber(from),
769 formats.getNumber(to));
773 Graph::EdgePath Converters::getPath(string const & from, string const & to)
775 return G_.getPath(formats.getNumber(from),
776 formats.getNumber(to));
780 vector<Format const *> Converters::importableFormats()
782 vector<string> l = loaders();
783 vector<Format const *> result = getReachableTo(l[0], true);
784 vector<string>::const_iterator it = l.begin() + 1;
785 vector<string>::const_iterator en = l.end();
786 for (; it != en; ++it) {
787 vector<Format const *> r = getReachableTo(*it, false);
788 result.insert(result.end(), r.begin(), r.end());
794 vector<Format const *> Converters::exportableFormats(bool only_viewable)
796 vector<string> s = savers();
797 vector<Format const *> result = getReachable(s[0], only_viewable, true);
798 vector<string>::const_iterator it = s.begin() + 1;
799 vector<string>::const_iterator en = s.end();
800 for (; it != en; ++it) {
801 vector<Format const *> r =
802 getReachable(*it, only_viewable, false);
803 result.insert(result.end(), r.begin(), r.end());
809 vector<string> Converters::loaders() const
814 v.push_back("textparagraph");
819 vector<string> Converters::savers() const
822 v.push_back("docbook");
823 v.push_back("latex");
824 v.push_back("literate");
825 v.push_back("luatex");
826 v.push_back("dviluatex");
828 v.push_back("xhtml");
829 v.push_back("pdflatex");
830 v.push_back("platex");
832 v.push_back("xetex");