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 else if (flag_name == "xml")
115 else if (flag_name == "needaux")
117 else if (flag_name == "resultdir")
118 result_dir = (flag_value.empty())
119 ? token_base : flag_value;
120 else if (flag_name == "resultfile")
121 result_file = flag_value;
122 else if (flag_name == "parselog")
123 parselog = flag_value;
125 if (!result_dir.empty() && result_file.empty())
126 result_file = "index." + formats.extension(to);
127 //if (!contains(command, token_from))
132 bool operator<(Converter const & a, Converter const & b)
134 // use the compare_ascii_no_case instead of compare_no_case,
135 // because in turkish, 'i' is not the lowercase version of 'I',
136 // and thus turkish locale breaks parsing of tags.
137 int const i = compare_ascii_no_case(a.From->prettyname(),
138 b.From->prettyname());
140 return compare_ascii_no_case(a.To->prettyname(),
141 b.To->prettyname()) < 0;
147 Converter const * Converters::getConverter(string const & from,
148 string const & to) const
150 ConverterList::const_iterator const cit =
151 find_if(converterlist_.begin(), converterlist_.end(),
152 ConverterEqual(from, to));
153 if (cit != converterlist_.end())
160 int Converters::getNumber(string const & from, string const & to) const
162 ConverterList::const_iterator const cit =
163 find_if(converterlist_.begin(), converterlist_.end(),
164 ConverterEqual(from, to));
165 if (cit != converterlist_.end())
166 return distance(converterlist_.begin(), cit);
172 void Converters::add(string const & from, string const & to,
173 string const & command, string const & flags)
177 ConverterList::iterator it = find_if(converterlist_.begin(),
178 converterlist_.end(),
179 ConverterEqual(from , to));
181 Converter converter(from, to, command, flags);
182 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
184 converter.command = command;
185 converter.flags = flags;
187 converter.readFlags();
189 if (converter.latex && (latex_command_.empty() || to == "dvi"))
190 latex_command_ = subst(command, token_from, "");
191 // If we have both latex & pdflatex, we set latex_command to latex.
192 // The latex_command is used to update the .aux file when running
193 // a converter that uses it.
195 if (it == converterlist_.end()) {
196 converterlist_.push_back(converter);
198 converter.From = it->From;
199 converter.To = it->To;
205 void Converters::erase(string const & from, string const & to)
207 ConverterList::iterator const it =
208 find_if(converterlist_.begin(),
209 converterlist_.end(),
210 ConverterEqual(from, to));
211 if (it != converterlist_.end())
212 converterlist_.erase(it);
216 // This method updates the pointers From and To in all the converters.
217 // The code is not very efficient, but it doesn't matter as the number
218 // of formats and converters is small.
219 // Furthermore, this method is called only on startup, or after
220 // adding/deleting a format in FormPreferences (the latter calls can be
221 // eliminated if the formats in the Formats class are stored using a map or
222 // a list (instead of a vector), but this will cause other problems).
223 void Converters::update(Formats const & formats)
225 ConverterList::iterator it = converterlist_.begin();
226 ConverterList::iterator end = converterlist_.end();
227 for (; it != end; ++it) {
228 it->From = formats.getFormat(it->from);
229 it->To = formats.getFormat(it->to);
234 // This method updates the pointers From and To in the last converter.
235 // It is called when adding a new converter in FormPreferences
236 void Converters::updateLast(Formats const & formats)
238 if (converterlist_.begin() != converterlist_.end()) {
239 ConverterList::iterator it = converterlist_.end() - 1;
240 it->From = formats.getFormat(it->from);
241 it->To = formats.getFormat(it->to);
246 void Converters::sort()
248 std::sort(converterlist_.begin(), converterlist_.end());
252 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
254 for (Graph::EdgePath::const_iterator cit = path.begin();
255 cit != path.end(); ++cit) {
256 Converter const & conv = converterlist_[*cit];
258 if (contains(conv.from, "xetex"))
259 return OutputParams::XETEX;
260 if (contains(conv.from, "luatex"))
261 return OutputParams::LUATEX;
262 if (contains(conv.to, "pdf"))
263 return OutputParams::PDFLATEX;
265 return OutputParams::XML;
267 return OutputParams::LATEX;
271 bool Converters::convert(Buffer const * buffer,
272 FileName const & from_file, FileName const & to_file,
273 FileName const & orig_from,
274 string const & from_format, string const & to_format,
275 ErrorList & errorList, int conversionflags)
277 if (from_format == to_format)
278 return move(from_format, from_file, to_file, false);
280 if ((conversionflags & try_cache) &&
281 ConverterCache::get().inCache(orig_from, to_format))
282 return ConverterCache::get().copy(orig_from, to_format, to_file);
284 Graph::EdgePath edgepath = getPath(from_format, to_format);
285 if (edgepath.empty()) {
286 if (conversionflags & try_default) {
287 // if no special converter defined, then we take the
288 // default one from ImageMagic.
289 string const from_ext = from_format.empty() ?
290 getExtension(from_file.absFileName()) :
291 formats.extension(from_format);
292 string const to_ext = formats.extension(to_format);
293 string const command =
295 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
297 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
299 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
300 LYXERR(Debug::FILES, "No converter defined! "
301 "I use convertDefault.py:\n\t" << command);
303 one.startscript(Systemcall::Wait, command);
304 if (to_file.isReadableFile()) {
305 if (conversionflags & try_cache)
306 ConverterCache::get().add(orig_from,
312 // only warn once per session and per file type
313 static std::map<string, string> warned;
314 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
317 warned.insert(make_pair(from_format, to_format));
319 Alert::error(_("Cannot convert file"),
320 bformat(_("No information for converting %1$s "
321 "format files to %2$s.\n"
322 "Define a converter in the preferences."),
323 from_ascii(from_format), from_ascii(to_format)));
327 // buffer is only invalid for importing, and then runparams is not
329 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
330 runparams.flavor = getFlavor(edgepath);
333 runparams.use_japanese = buffer->bufferFormat() == "platex";
334 runparams.use_indices = buffer->params().use_indices;
335 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
336 string() : buffer->params().bibtex_command;
337 runparams.index_command = (buffer->params().index_command == "default") ?
338 string() : buffer->params().index_command;
341 // Some converters (e.g. lilypond) can only output files to the
342 // current directory, so we need to change the current directory.
343 // This has the added benefit that all other files that may be
344 // generated by the converter are deleted when LyX closes and do not
345 // clutter the real working directory.
346 string const path(onlyPath(from_file.absFileName()));
347 // Prevent the compiler from optimizing away p
351 // empty the error list before any new conversion takes place.
354 bool run_latex = false;
355 string from_base = changeExtension(from_file.absFileName(), "");
356 string to_base = changeExtension(to_file.absFileName(), "");
358 FileName outfile = from_file;
359 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
360 cit != edgepath.end(); ++cit) {
361 Converter const & conv = converterlist_[*cit];
362 bool dummy = conv.To->dummy() && conv.to != "program";
364 LYXERR(Debug::FILES, "Converting from "
365 << conv.from << " to " << conv.to);
368 outfile = FileName(conv.result_dir.empty()
369 ? changeExtension(from_file.absFileName(), conv.To->extension())
370 : addName(subst(conv.result_dir,
371 token_base, from_base),
372 subst(conv.result_file,
373 token_base, onlyFileName(from_base))));
375 // if input and output files are equal, we use a
376 // temporary file as intermediary (JMarc)
377 FileName real_outfile;
378 if (outfile == infile) {
379 real_outfile = infile;
380 // when importing, a buffer does not necessarily exist
382 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
384 outfile = FileName(addName(package().temp_dir().absFileName(),
390 string const command = subst(conv.command, token_from, "");
391 LYXERR(Debug::FILES, "Running " << command);
392 if (!runLaTeX(*buffer, command, runparams, errorList))
395 if (conv.need_aux && !run_latex
396 && !latex_command_.empty()) {
397 LYXERR(Debug::FILES, "Running " << latex_command_
398 << " to update aux file");
399 runLaTeX(*buffer, latex_command_, runparams, errorList);
403 string const infile2 =
404 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
405 string const outfile2 =
406 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
408 string command = conv.command;
409 command = subst(command, token_from, quoteName(infile2));
410 command = subst(command, token_base, quoteName(from_base));
411 command = subst(command, token_to, quoteName(outfile2));
412 command = subst(command, token_path, quoteName(infile.onlyPath().absFileName()));
413 command = subst(command, token_orig_path, quoteName(orig_from.onlyPath().absFileName()));
414 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
415 command = libScriptSearch(command);
417 if (!conv.parselog.empty())
418 command += " 2> " + quoteName(infile2 + ".out");
420 if (conv.from == "dvi" && conv.to == "ps")
421 command = add_options(command,
422 buffer->params().dvips_options());
423 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
424 command = add_options(command,
425 dvipdfm_options(buffer->params()));
427 LYXERR(Debug::FILES, "Calling " << command);
429 buffer->message(_("Executing command: ")
430 + from_utf8(command));
435 res = one.startscript(Systemcall::DontWait,
436 to_filesystem8bit(from_utf8(command)));
437 // We're not waiting for the result, so we can't do anything
440 res = one.startscript(Systemcall::Wait,
441 to_filesystem8bit(from_utf8(command)));
442 if (!real_outfile.empty()) {
443 Mover const & mover = getMover(conv.to);
444 if (!mover.rename(outfile, real_outfile))
447 LYXERR(Debug::FILES, "renaming file " << outfile
448 << " to " << real_outfile);
449 // Finally, don't forget to tell any future
450 // converters to use the renamed file...
451 outfile = real_outfile;
454 if (!conv.parselog.empty()) {
455 string const logfile = infile2 + ".log";
456 string const script = libScriptSearch(conv.parselog);
457 string const command2 = script +
458 " < " + quoteName(infile2 + ".out") +
459 " > " + quoteName(logfile);
460 one.startscript(Systemcall::Wait,
461 to_filesystem8bit(from_utf8(command2)));
462 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
468 if (conv.to == "program") {
469 Alert::error(_("Build errors"),
470 _("There were errors during the build process."));
472 // FIXME: this should go out of here. For example, here we cannot say if
473 // it is a document (.lyx) or something else. Same goes for elsewhere.
474 Alert::error(_("Cannot convert file"),
475 bformat(_("An error occurred while running:\n%1$s"),
476 wrapParas(from_utf8(command))));
483 Converter const & conv = converterlist_[edgepath.back()];
484 if (conv.To->dummy())
487 if (!conv.result_dir.empty()) {
488 // The converter has put the file(s) in a directory.
489 // In this case we ignore the given to_file.
490 if (from_base != to_base) {
491 string const from = subst(conv.result_dir,
492 token_base, from_base);
493 string const to = subst(conv.result_dir,
494 token_base, to_base);
495 Mover const & mover = getMover(conv.from);
496 if (!mover.rename(FileName(from), FileName(to))) {
497 Alert::error(_("Cannot convert file"),
498 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
499 from_utf8(from), from_utf8(to)));
505 if (conversionflags & try_cache)
506 ConverterCache::get().add(orig_from, to_format, outfile);
507 return move(conv.to, outfile, to_file, conv.latex);
512 bool Converters::move(string const & fmt,
513 FileName const & from, FileName const & to, bool copy)
518 bool no_errors = true;
519 string const path = onlyPath(from.absFileName());
520 string const base = onlyFileName(removeExtension(from.absFileName()));
521 string const to_base = removeExtension(to.absFileName());
522 string const to_extension = getExtension(to.absFileName());
524 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
525 for (support::FileNameList::const_iterator it = files.begin();
526 it != files.end(); ++it) {
527 string const from2 = it->absFileName();
528 string const file2 = onlyFileName(from2);
529 if (prefixIs(file2, base)) {
530 string const to2 = changeExtension(
531 to_base + file2.substr(base.length()),
533 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
535 Mover const & mover = getMover(fmt);
536 bool const moved = copy
537 ? mover.copy(*it, FileName(to2))
538 : mover.rename(*it, FileName(to2));
539 if (!moved && no_errors) {
540 Alert::error(_("Cannot convert file"),
542 _("Could not copy a temporary file from %1$s to %2$s.") :
543 _("Could not move a temporary file from %1$s to %2$s."),
544 from_utf8(from2), from_utf8(to2)));
553 bool Converters::formatIsUsed(string const & format)
555 ConverterList::const_iterator cit = converterlist_.begin();
556 ConverterList::const_iterator end = converterlist_.end();
557 for (; cit != end; ++cit) {
558 if (cit->from == format || cit->to == format)
565 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
566 FileName const & filename, ErrorList & errorList)
568 OutputParams runparams(0);
569 runparams.flavor = OutputParams::LATEX;
570 LaTeX latex("", runparams, filename);
572 int const result = latex.scanLogFile(terr);
574 if (result & LaTeX::ERRORS)
575 buffer.bufferErrors(terr, errorList);
584 : public boost::signals::trackable {
586 ShowMessage(Buffer const & b) : buffer_(b) {}
587 void operator()(docstring const & msg) const { buffer_.message(msg); }
589 Buffer const & buffer_;
595 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
596 OutputParams const & runparams, ErrorList & errorList)
598 buffer.setBusy(true);
599 buffer.message(_("Running LaTeX..."));
601 runparams.document_language = buffer.params().language->babel();
603 // do the LaTeX run(s)
604 string const name = buffer.latexName();
605 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
607 ShowMessage show(buffer);
608 latex.message.connect(show);
609 int const result = latex.run(terr);
611 if (result & LaTeX::ERRORS)
612 buffer.bufferErrors(terr, errorList);
614 // check return value from latex.run().
615 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
616 docstring const str =
617 bformat(_("LaTeX did not run successfully. "
618 "Additionally, LyX could not locate "
619 "the LaTeX log %1$s."), from_utf8(name));
620 Alert::error(_("LaTeX failed"), str);
621 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
622 Alert::warning(_("Output is empty"),
623 _("An empty output file was generated."));
627 buffer.setBusy(false);
629 int const ERROR_MASK =
634 return (result & ERROR_MASK) == 0;
640 void Converters::buildGraph()
642 // clear graph's data structures
643 G_.init(formats.size());
644 // each of the converters knows how to convert one format to another
645 // so, for each of them, we create an arrow on the graph, going from
646 // the one to the other
647 ConverterList::iterator it = converterlist_.begin();
648 ConverterList::iterator const end = converterlist_.end();
649 for (; it != end ; ++it) {
650 int const from = formats.getNumber(it->from);
651 int const to = formats.getNumber(it->to);
652 G_.addEdge(from, to);
657 vector<Format const *> const
658 Converters::intToFormat(vector<int> const & input)
660 vector<Format const *> result(input.size());
662 vector<int>::const_iterator it = input.begin();
663 vector<int>::const_iterator const end = input.end();
664 vector<Format const *>::iterator rit = result.begin();
665 for ( ; it != end; ++it, ++rit) {
666 *rit = &formats.get(*it);
672 vector<Format const *> const
673 Converters::getReachableTo(string const & target, bool const clear_visited)
675 vector<int> const & reachablesto =
676 G_.getReachableTo(formats.getNumber(target), clear_visited);
678 return intToFormat(reachablesto);
682 vector<Format const *> const
683 Converters::getReachable(string const & from, bool const only_viewable,
684 bool const clear_visited)
686 vector<int> const & reachables =
687 G_.getReachable(formats.getNumber(from),
691 return intToFormat(reachables);
695 bool Converters::isReachable(string const & from, string const & to)
697 return G_.isReachable(formats.getNumber(from),
698 formats.getNumber(to));
702 Graph::EdgePath Converters::getPath(string const & from, string const & to)
704 return G_.getPath(formats.getNumber(from),
705 formats.getNumber(to));
709 vector<Format const *> Converters::importableFormats()
711 vector<string> l = loaders();
712 vector<Format const *> result = getReachableTo(l[0], true);
713 for (vector<string>::const_iterator it = l.begin() + 1;
714 it != l.end(); ++it) {
715 vector<Format const *> r = getReachableTo(*it, false);
716 result.insert(result.end(), r.begin(), r.end());
722 vector<Format const *> Converters::exportableFormats(bool only_viewable)
724 vector<string> s = savers();
725 vector<Format const *> result = getReachable(s[0], only_viewable, true);
726 for (vector<string>::const_iterator it = s.begin() + 1;
727 it != s.end(); ++it) {
728 vector<Format const *> r =
729 getReachable(*it, only_viewable, false);
730 result.insert(result.end(), r.begin(), r.end());
736 vector<string> Converters::loaders() const
741 v.push_back("textparagraph");
746 vector<string> Converters::savers() const
749 v.push_back("docbook");
750 v.push_back("latex");
751 v.push_back("literate");
752 v.push_back("luatex");
754 v.push_back("xhtml");
755 v.push_back("pdflatex");
756 v.push_back("platex");
758 v.push_back("xetex");