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),
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;
129 if (!result_dir.empty() && result_file.empty())
130 result_file = "index." + formats.extension(to);
131 //if (!contains(command, token_from))
136 Converter const * Converters::getConverter(string const & from,
137 string const & to) const
139 ConverterList::const_iterator const cit =
140 find_if(converterlist_.begin(), converterlist_.end(),
141 ConverterEqual(from, to));
142 if (cit != converterlist_.end())
149 int Converters::getNumber(string const & from, string const & to) const
151 ConverterList::const_iterator const cit =
152 find_if(converterlist_.begin(), converterlist_.end(),
153 ConverterEqual(from, to));
154 if (cit != converterlist_.end())
155 return distance(converterlist_.begin(), cit);
161 void Converters::add(string const & from, string const & to,
162 string const & command, string const & flags)
166 ConverterList::iterator it = find_if(converterlist_.begin(),
167 converterlist_.end(),
168 ConverterEqual(from , to));
170 Converter converter(from, to, command, flags);
171 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
173 converter.command = command;
174 converter.flags = flags;
176 converter.readFlags();
178 // If we have both latex & pdflatex, we set latex_command to latex.
179 // The latex_command is used to update the .aux file when running
180 // a converter that uses it.
182 && (latex_command_.empty() || converter.latex_flavor == "latex"))
183 latex_command_ = subst(command, token_from, "");
184 // Similarly, set xelatex_command to xelatex.
186 && (xelatex_command_.empty() || converter.latex_flavor == "xelatex"))
187 xelatex_command_ = subst(command, token_from, "");
189 if (it == converterlist_.end()) {
190 converterlist_.push_back(converter);
192 converter.From = it->From;
193 converter.To = it->To;
199 void Converters::erase(string const & from, string const & to)
201 ConverterList::iterator const it =
202 find_if(converterlist_.begin(),
203 converterlist_.end(),
204 ConverterEqual(from, to));
205 if (it != converterlist_.end())
206 converterlist_.erase(it);
210 // This method updates the pointers From and To in all the converters.
211 // The code is not very efficient, but it doesn't matter as the number
212 // of formats and converters is small.
213 // Furthermore, this method is called only on startup, or after
214 // adding/deleting a format in FormPreferences (the latter calls can be
215 // eliminated if the formats in the Formats class are stored using a map or
216 // a list (instead of a vector), but this will cause other problems).
217 void Converters::update(Formats const & formats)
219 ConverterList::iterator it = converterlist_.begin();
220 ConverterList::iterator end = converterlist_.end();
221 for (; it != end; ++it) {
222 it->From = formats.getFormat(it->from);
223 it->To = formats.getFormat(it->to);
228 // This method updates the pointers From and To in the last converter.
229 // It is called when adding a new converter in FormPreferences
230 void Converters::updateLast(Formats const & formats)
232 if (converterlist_.begin() != converterlist_.end()) {
233 ConverterList::iterator it = converterlist_.end() - 1;
234 it->From = formats.getFormat(it->from);
235 it->To = formats.getFormat(it->to);
240 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
242 for (Graph::EdgePath::const_iterator cit = path.begin();
243 cit != path.end(); ++cit) {
244 Converter const & conv = converterlist_[*cit];
246 if (conv.latex_flavor == "xelatex")
247 return OutputParams::XETEX;
248 if (conv.latex_flavor == "lualatex")
249 return OutputParams::LUATEX;
250 if (conv.latex_flavor == "dvilualatex")
251 return OutputParams::DVILUATEX;
252 if (conv.latex_flavor == "pdflatex")
253 return OutputParams::PDFLATEX;
255 return OutputParams::XML;
257 return OutputParams::LATEX;
261 bool Converters::convert(Buffer const * buffer,
262 FileName const & from_file, FileName const & to_file,
263 FileName const & orig_from,
264 string const & from_format, string const & to_format,
265 ErrorList & errorList, int conversionflags)
267 if (from_format == to_format)
268 return move(from_format, from_file, to_file, false);
270 if ((conversionflags & try_cache) &&
271 ConverterCache::get().inCache(orig_from, to_format))
272 return ConverterCache::get().copy(orig_from, to_format, to_file);
274 Graph::EdgePath edgepath = getPath(from_format, to_format);
275 if (edgepath.empty()) {
276 if (conversionflags & try_default) {
277 // if no special converter defined, then we take the
278 // default one from ImageMagic.
279 string const from_ext = from_format.empty() ?
280 getExtension(from_file.absFileName()) :
281 formats.extension(from_format);
282 string const to_ext = formats.extension(to_format);
283 string const command =
285 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
287 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
289 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
290 LYXERR(Debug::FILES, "No converter defined! "
291 "I use convertDefault.py:\n\t" << command);
293 one.startscript(Systemcall::Wait, command, buffer ?
294 buffer->filePath() : string());
295 if (to_file.isReadableFile()) {
296 if (conversionflags & try_cache)
297 ConverterCache::get().add(orig_from,
303 // only warn once per session and per file type
304 static std::map<string, string> warned;
305 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
308 warned.insert(make_pair(from_format, to_format));
310 Alert::error(_("Cannot convert file"),
311 bformat(_("No information for converting %1$s "
312 "format files to %2$s.\n"
313 "Define a converter in the preferences."),
314 from_ascii(from_format), from_ascii(to_format)));
318 // buffer is only invalid for importing, and then runparams is not
320 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
321 runparams.flavor = getFlavor(edgepath);
324 runparams.use_japanese = buffer->params().bufferFormat() == "platex";
325 runparams.use_indices = buffer->params().use_indices;
326 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
327 string() : buffer->params().bibtex_command;
328 runparams.index_command = (buffer->params().index_command == "default") ?
329 string() : buffer->params().index_command;
332 // Some converters (e.g. lilypond) can only output files to the
333 // current directory, so we need to change the current directory.
334 // This has the added benefit that all other files that may be
335 // generated by the converter are deleted when LyX closes and do not
336 // clutter the real working directory.
337 // FIXME: This does not work if path is an UNC path on windows
339 string const path(onlyPath(from_file.absFileName()));
340 // Prevent the compiler from optimizing away p
344 // empty the error list before any new conversion takes place.
347 bool run_latex = false;
348 string from_base = changeExtension(from_file.absFileName(), "");
349 string to_base = changeExtension(to_file.absFileName(), "");
351 FileName outfile = from_file;
352 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
353 cit != edgepath.end(); ++cit) {
354 Converter const & conv = converterlist_[*cit];
355 bool dummy = conv.To->dummy() && conv.to != "program";
357 LYXERR(Debug::FILES, "Converting from "
358 << conv.from << " to " << conv.to);
361 outfile = FileName(conv.result_file.empty()
362 ? changeExtension(from_file.absFileName(), conv.To->extension())
363 : addName(subst(conv.result_dir,
364 token_base, from_base),
365 subst(conv.result_file,
366 token_base, onlyFileName(from_base))));
368 // if input and output files are equal, we use a
369 // temporary file as intermediary (JMarc)
370 FileName real_outfile;
371 if (!conv.result_file.empty())
372 real_outfile = FileName(changeExtension(from_file.absFileName(),
373 conv.To->extension()));
374 if (outfile == infile) {
375 real_outfile = infile;
376 // when importing, a buffer does not necessarily exist
378 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
380 outfile = FileName(addName(package().temp_dir().absFileName(),
386 string command = conv.command;
387 command = subst(command, token_from, "");
388 command = subst(command, token_latex_encoding, buffer ?
389 buffer->params().encoding().latexName() : string());
390 LYXERR(Debug::FILES, "Running " << command);
391 if (!runLaTeX(*buffer, command, runparams, errorList))
394 if (conv.need_aux && !run_latex
395 && !latex_command_.empty()) {
396 string const command = (buffer && buffer->params().useNonTeXFonts) ?
397 xelatex_command_ : latex_command_;
398 LYXERR(Debug::FILES, "Running " << command
399 << " to update aux file");
400 if (!runLaTeX(*buffer, command, runparams, errorList))
405 string const infile2 =
406 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
407 string const outfile2 =
408 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
410 string command = conv.command;
411 command = subst(command, token_from, quoteName(infile2));
412 command = subst(command, token_base, quoteName(from_base));
413 command = subst(command, token_to, quoteName(outfile2));
414 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
415 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
416 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
417 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
418 command = libScriptSearch(command);
420 if (!conv.parselog.empty())
421 command += " 2> " + quoteName(infile2 + ".out");
423 if (conv.from == "dvi" && conv.to == "ps")
424 command = add_options(command,
425 buffer->params().dvips_options());
426 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
427 command = add_options(command,
428 dvipdfm_options(buffer->params()));
430 LYXERR(Debug::FILES, "Calling " << command);
432 buffer->message(_("Executing command: ")
433 + from_utf8(command));
438 res = one.startscript(Systemcall::DontWait,
439 to_filesystem8bit(from_utf8(command)),
440 buffer ? buffer->filePath() : string());
441 // We're not waiting for the result, so we can't do anything
444 res = one.startscript(Systemcall::Wait,
445 to_filesystem8bit(from_utf8(command)),
446 buffer ? buffer->filePath()
448 if (!real_outfile.empty()) {
449 Mover const & mover = getMover(conv.to);
450 if (!mover.rename(outfile, real_outfile))
453 LYXERR(Debug::FILES, "renaming file " << outfile
454 << " to " << real_outfile);
455 // Finally, don't forget to tell any future
456 // converters to use the renamed file...
457 outfile = real_outfile;
460 if (!conv.parselog.empty()) {
461 string const logfile = infile2 + ".log";
462 string const script = libScriptSearch(conv.parselog);
463 string const command2 = script +
464 " < " + quoteName(infile2 + ".out") +
465 " > " + quoteName(logfile);
466 one.startscript(Systemcall::Wait,
467 to_filesystem8bit(from_utf8(command2)),
469 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
475 if (conv.to == "program") {
476 Alert::error(_("Build errors"),
477 _("There were errors during the build process."));
479 // FIXME: this should go out of here. For example, here we cannot say if
480 // it is a document (.lyx) or something else. Same goes for elsewhere.
481 Alert::error(_("Cannot convert file"),
482 bformat(_("An error occurred while running:\n%1$s"),
483 wrapParas(from_utf8(command))));
490 Converter const & conv = converterlist_[edgepath.back()];
491 if (conv.To->dummy())
494 if (!conv.result_dir.empty()) {
495 // The converter has put the file(s) in a directory.
496 // In this case we ignore the given to_file.
497 if (from_base != to_base) {
498 string const from = subst(conv.result_dir,
499 token_base, from_base);
500 string const to = subst(conv.result_dir,
501 token_base, to_base);
502 Mover const & mover = getMover(conv.from);
503 if (!mover.rename(FileName(from), FileName(to))) {
504 Alert::error(_("Cannot convert file"),
505 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
506 from_utf8(from), from_utf8(to)));
512 if (conversionflags & try_cache)
513 ConverterCache::get().add(orig_from, to_format, outfile);
514 return move(conv.to, outfile, to_file, conv.latex);
519 bool Converters::move(string const & fmt,
520 FileName const & from, FileName const & to, bool copy)
525 bool no_errors = true;
526 string const path = onlyPath(from.absFileName());
527 string const base = onlyFileName(removeExtension(from.absFileName()));
528 string const to_base = removeExtension(to.absFileName());
529 string const to_extension = getExtension(to.absFileName());
531 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
532 for (support::FileNameList::const_iterator it = files.begin();
533 it != files.end(); ++it) {
534 string const from2 = it->absFileName();
535 string const file2 = onlyFileName(from2);
536 if (prefixIs(file2, base)) {
537 string const to2 = changeExtension(
538 to_base + file2.substr(base.length()),
540 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
542 Mover const & mover = getMover(fmt);
543 bool const moved = copy
544 ? mover.copy(*it, FileName(to2))
545 : mover.rename(*it, FileName(to2));
546 if (!moved && no_errors) {
547 Alert::error(_("Cannot convert file"),
549 _("Could not copy a temporary file from %1$s to %2$s.") :
550 _("Could not move a temporary file from %1$s to %2$s."),
551 from_utf8(from2), from_utf8(to2)));
560 bool Converters::formatIsUsed(string const & format)
562 ConverterList::const_iterator cit = converterlist_.begin();
563 ConverterList::const_iterator end = converterlist_.end();
564 for (; cit != end; ++cit) {
565 if (cit->from == format || cit->to == format)
572 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
573 FileName const & filename, ErrorList & errorList)
575 OutputParams runparams(0);
576 runparams.flavor = OutputParams::LATEX;
577 LaTeX latex("", runparams, filename);
579 int const result = latex.scanLogFile(terr);
581 if (result & LaTeX::ERRORS)
582 buffer.bufferErrors(terr, errorList);
591 : public boost::signals::trackable {
593 ShowMessage(Buffer const & b) : buffer_(b) {}
594 void operator()(docstring const & msg) const { buffer_.message(msg); }
596 Buffer const & buffer_;
602 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
603 OutputParams const & runparams, ErrorList & errorList)
605 buffer.setBusy(true);
606 buffer.message(_("Running LaTeX..."));
608 runparams.document_language = buffer.params().language->babel();
610 // do the LaTeX run(s)
611 string const name = buffer.latexName();
612 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
615 ShowMessage show(buffer);
616 latex.message.connect(show);
617 int const result = latex.run(terr);
619 if (result & LaTeX::ERRORS)
620 buffer.bufferErrors(terr, errorList);
622 // check return value from latex.run().
623 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
624 docstring const str =
625 bformat(_("LaTeX did not run successfully. "
626 "Additionally, LyX could not locate "
627 "the LaTeX log %1$s."), from_utf8(name));
628 Alert::error(_("LaTeX failed"), str);
629 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
630 Alert::warning(_("Output is empty"),
631 _("An empty output file was generated."));
635 buffer.setBusy(false);
637 int const ERROR_MASK =
642 return (result & ERROR_MASK) == 0;
648 void Converters::buildGraph()
650 // clear graph's data structures
651 G_.init(formats.size());
652 // each of the converters knows how to convert one format to another
653 // so, for each of them, we create an arrow on the graph, going from
654 // the one to the other
655 ConverterList::iterator it = converterlist_.begin();
656 ConverterList::iterator const end = converterlist_.end();
657 for (; it != end ; ++it) {
658 int const from = formats.getNumber(it->from);
659 int const to = formats.getNumber(it->to);
660 G_.addEdge(from, to);
665 vector<Format const *> const
666 Converters::intToFormat(vector<int> const & input)
668 vector<Format const *> result(input.size());
670 vector<int>::const_iterator it = input.begin();
671 vector<int>::const_iterator const end = input.end();
672 vector<Format const *>::iterator rit = result.begin();
673 for ( ; it != end; ++it, ++rit) {
674 *rit = &formats.get(*it);
680 vector<Format const *> const
681 Converters::getReachableTo(string const & target, bool const clear_visited)
683 vector<int> const & reachablesto =
684 G_.getReachableTo(formats.getNumber(target), clear_visited);
686 return intToFormat(reachablesto);
690 vector<Format const *> const
691 Converters::getReachable(string const & from, bool const only_viewable,
692 bool const clear_visited, set<string> const & excludes)
694 set<int> excluded_numbers;;
696 set<string>::const_iterator sit = excludes.begin();
697 set<string>::const_iterator const end = excludes.end();
698 for (; sit != end; ++sit)
699 excluded_numbers.insert(formats.getNumber(*sit));
701 vector<int> const & reachables =
702 G_.getReachable(formats.getNumber(from),
707 return intToFormat(reachables);
711 bool Converters::isReachable(string const & from, string const & to)
713 return G_.isReachable(formats.getNumber(from),
714 formats.getNumber(to));
718 Graph::EdgePath Converters::getPath(string const & from, string const & to)
720 return G_.getPath(formats.getNumber(from),
721 formats.getNumber(to));
725 vector<Format const *> Converters::importableFormats()
727 vector<string> l = loaders();
728 vector<Format const *> result = getReachableTo(l[0], true);
729 vector<string>::const_iterator it = l.begin() + 1;
730 vector<string>::const_iterator en = l.end();
731 for (; it != en; ++it) {
732 vector<Format const *> r = getReachableTo(*it, false);
733 result.insert(result.end(), r.begin(), r.end());
739 vector<Format const *> Converters::exportableFormats(bool only_viewable)
741 vector<string> s = savers();
742 vector<Format const *> result = getReachable(s[0], only_viewable, true);
743 vector<string>::const_iterator it = s.begin() + 1;
744 vector<string>::const_iterator en = s.end();
745 for (; it != en; ++it) {
746 vector<Format const *> r =
747 getReachable(*it, only_viewable, false);
748 result.insert(result.end(), r.begin(), r.end());
754 vector<string> Converters::loaders() const
759 v.push_back("textparagraph");
764 vector<string> Converters::savers() const
767 v.push_back("docbook");
768 v.push_back("latex");
769 v.push_back("literate");
770 v.push_back("luatex");
771 v.push_back("dviluatex");
773 v.push_back("xhtml");
774 v.push_back("pdflatex");
775 v.push_back("platex");
777 v.push_back("xetex");