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 latex_flavor = flag_value.empty() ?
114 "latex" : flag_value;
115 } else if (flag_name == "xml")
117 else if (flag_name == "needaux")
119 else if (flag_name == "resultdir")
120 result_dir = (flag_value.empty())
121 ? token_base : flag_value;
122 else if (flag_name == "resultfile")
123 result_file = flag_value;
124 else if (flag_name == "parselog")
125 parselog = flag_value;
127 if (!result_dir.empty() && result_file.empty())
128 result_file = "index." + formats.extension(to);
129 //if (!contains(command, token_from))
134 bool operator<(Converter const & a, Converter const & b)
136 // use the compare_ascii_no_case instead of compare_no_case,
137 // because in turkish, 'i' is not the lowercase version of 'I',
138 // and thus turkish locale breaks parsing of tags.
139 int const i = compare_ascii_no_case(a.From->prettyname(),
140 b.From->prettyname());
142 return compare_ascii_no_case(a.To->prettyname(),
143 b.To->prettyname()) < 0;
149 Converter const * Converters::getConverter(string const & from,
150 string const & to) const
152 ConverterList::const_iterator const cit =
153 find_if(converterlist_.begin(), converterlist_.end(),
154 ConverterEqual(from, to));
155 if (cit != converterlist_.end())
162 int Converters::getNumber(string const & from, string const & to) const
164 ConverterList::const_iterator const cit =
165 find_if(converterlist_.begin(), converterlist_.end(),
166 ConverterEqual(from, to));
167 if (cit != converterlist_.end())
168 return distance(converterlist_.begin(), cit);
174 void Converters::add(string const & from, string const & to,
175 string const & command, string const & flags)
179 ConverterList::iterator it = find_if(converterlist_.begin(),
180 converterlist_.end(),
181 ConverterEqual(from , to));
183 Converter converter(from, to, command, flags);
184 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
186 converter.command = command;
187 converter.flags = flags;
189 converter.readFlags();
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 && (latex_command_.empty() || converter.latex_flavor == "latex"))
196 latex_command_ = subst(command, token_from, "");
198 if (it == converterlist_.end()) {
199 converterlist_.push_back(converter);
201 converter.From = it->From;
202 converter.To = it->To;
208 void Converters::erase(string const & from, string const & to)
210 ConverterList::iterator const it =
211 find_if(converterlist_.begin(),
212 converterlist_.end(),
213 ConverterEqual(from, to));
214 if (it != converterlist_.end())
215 converterlist_.erase(it);
219 // This method updates the pointers From and To in all the converters.
220 // The code is not very efficient, but it doesn't matter as the number
221 // of formats and converters is small.
222 // Furthermore, this method is called only on startup, or after
223 // adding/deleting a format in FormPreferences (the latter calls can be
224 // eliminated if the formats in the Formats class are stored using a map or
225 // a list (instead of a vector), but this will cause other problems).
226 void Converters::update(Formats const & formats)
228 ConverterList::iterator it = converterlist_.begin();
229 ConverterList::iterator end = converterlist_.end();
230 for (; it != end; ++it) {
231 it->From = formats.getFormat(it->from);
232 it->To = formats.getFormat(it->to);
237 // This method updates the pointers From and To in the last converter.
238 // It is called when adding a new converter in FormPreferences
239 void Converters::updateLast(Formats const & formats)
241 if (converterlist_.begin() != converterlist_.end()) {
242 ConverterList::iterator it = converterlist_.end() - 1;
243 it->From = formats.getFormat(it->from);
244 it->To = formats.getFormat(it->to);
249 void Converters::sort()
251 std::sort(converterlist_.begin(), converterlist_.end());
255 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
257 for (Graph::EdgePath::const_iterator cit = path.begin();
258 cit != path.end(); ++cit) {
259 Converter const & conv = converterlist_[*cit];
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 == "pdflatex")
266 return OutputParams::PDFLATEX;
268 return OutputParams::XML;
270 return OutputParams::LATEX;
274 bool Converters::convert(Buffer const * buffer,
275 FileName const & from_file, FileName const & to_file,
276 FileName const & orig_from,
277 string const & from_format, string const & to_format,
278 ErrorList & errorList, int conversionflags)
280 if (from_format == to_format)
281 return move(from_format, from_file, to_file, false);
283 if ((conversionflags & try_cache) &&
284 ConverterCache::get().inCache(orig_from, to_format))
285 return ConverterCache::get().copy(orig_from, to_format, to_file);
287 Graph::EdgePath edgepath = getPath(from_format, to_format);
288 if (edgepath.empty()) {
289 if (conversionflags & try_default) {
290 // if no special converter defined, then we take the
291 // default one from ImageMagic.
292 string const from_ext = from_format.empty() ?
293 getExtension(from_file.absFileName()) :
294 formats.extension(from_format);
295 string const to_ext = formats.extension(to_format);
296 string const command =
298 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
300 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
302 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
303 LYXERR(Debug::FILES, "No converter defined! "
304 "I use convertDefault.py:\n\t" << command);
306 one.startscript(Systemcall::Wait, command);
307 if (to_file.isReadableFile()) {
308 if (conversionflags & try_cache)
309 ConverterCache::get().add(orig_from,
315 // only warn once per session and per file type
316 static std::map<string, string> warned;
317 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
320 warned.insert(make_pair(from_format, to_format));
322 Alert::error(_("Cannot convert file"),
323 bformat(_("No information for converting %1$s "
324 "format files to %2$s.\n"
325 "Define a converter in the preferences."),
326 from_ascii(from_format), from_ascii(to_format)));
330 // buffer is only invalid for importing, and then runparams is not
332 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
333 runparams.flavor = getFlavor(edgepath);
336 runparams.use_japanese = buffer->bufferFormat() == "platex";
337 runparams.use_indices = buffer->params().use_indices;
338 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
339 string() : buffer->params().bibtex_command;
340 runparams.index_command = (buffer->params().index_command == "default") ?
341 string() : buffer->params().index_command;
344 // Some converters (e.g. lilypond) can only output files to the
345 // current directory, so we need to change the current directory.
346 // This has the added benefit that all other files that may be
347 // generated by the converter are deleted when LyX closes and do not
348 // clutter the real working directory.
349 string const path(onlyPath(from_file.absFileName()));
350 // Prevent the compiler from optimizing away p
354 // empty the error list before any new conversion takes place.
357 bool run_latex = false;
358 string from_base = changeExtension(from_file.absFileName(), "");
359 string to_base = changeExtension(to_file.absFileName(), "");
361 FileName outfile = from_file;
362 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
363 cit != edgepath.end(); ++cit) {
364 Converter const & conv = converterlist_[*cit];
365 bool dummy = conv.To->dummy() && conv.to != "program";
367 LYXERR(Debug::FILES, "Converting from "
368 << conv.from << " to " << conv.to);
371 outfile = FileName(conv.result_dir.empty()
372 ? changeExtension(from_file.absFileName(), conv.To->extension())
373 : addName(subst(conv.result_dir,
374 token_base, from_base),
375 subst(conv.result_file,
376 token_base, onlyFileName(from_base))));
378 // if input and output files are equal, we use a
379 // temporary file as intermediary (JMarc)
380 FileName real_outfile;
381 if (outfile == infile) {
382 real_outfile = infile;
383 // when importing, a buffer does not necessarily exist
385 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
387 outfile = FileName(addName(package().temp_dir().absFileName(),
393 string const command = subst(conv.command, token_from, "");
394 LYXERR(Debug::FILES, "Running " << command);
395 if (!runLaTeX(*buffer, command, runparams, errorList))
398 if (conv.need_aux && !run_latex
399 && !latex_command_.empty()) {
400 LYXERR(Debug::FILES, "Running " << latex_command_
401 << " to update aux file");
402 runLaTeX(*buffer, latex_command_, runparams, errorList);
406 string const infile2 =
407 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
408 string const outfile2 =
409 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
411 string command = conv.command;
412 command = subst(command, token_from, quoteName(infile2));
413 command = subst(command, token_base, quoteName(from_base));
414 command = subst(command, token_to, quoteName(outfile2));
415 command = subst(command, token_path, quoteName(infile.onlyPath().absFileName()));
416 command = subst(command, token_orig_path, quoteName(orig_from.onlyPath().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 // We're not waiting for the result, so we can't do anything
443 res = one.startscript(Systemcall::Wait,
444 to_filesystem8bit(from_utf8(command)));
445 if (!real_outfile.empty()) {
446 Mover const & mover = getMover(conv.to);
447 if (!mover.rename(outfile, real_outfile))
450 LYXERR(Debug::FILES, "renaming file " << outfile
451 << " to " << real_outfile);
452 // Finally, don't forget to tell any future
453 // converters to use the renamed file...
454 outfile = real_outfile;
457 if (!conv.parselog.empty()) {
458 string const logfile = infile2 + ".log";
459 string const script = libScriptSearch(conv.parselog);
460 string const command2 = script +
461 " < " + quoteName(infile2 + ".out") +
462 " > " + quoteName(logfile);
463 one.startscript(Systemcall::Wait,
464 to_filesystem8bit(from_utf8(command2)));
465 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
471 if (conv.to == "program") {
472 Alert::error(_("Build errors"),
473 _("There were errors during the build process."));
475 // FIXME: this should go out of here. For example, here we cannot say if
476 // it is a document (.lyx) or something else. Same goes for elsewhere.
477 Alert::error(_("Cannot convert file"),
478 bformat(_("An error occurred while running:\n%1$s"),
479 wrapParas(from_utf8(command))));
486 Converter const & conv = converterlist_[edgepath.back()];
487 if (conv.To->dummy())
490 if (!conv.result_dir.empty()) {
491 // The converter has put the file(s) in a directory.
492 // In this case we ignore the given to_file.
493 if (from_base != to_base) {
494 string const from = subst(conv.result_dir,
495 token_base, from_base);
496 string const to = subst(conv.result_dir,
497 token_base, to_base);
498 Mover const & mover = getMover(conv.from);
499 if (!mover.rename(FileName(from), FileName(to))) {
500 Alert::error(_("Cannot convert file"),
501 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
502 from_utf8(from), from_utf8(to)));
508 if (conversionflags & try_cache)
509 ConverterCache::get().add(orig_from, to_format, outfile);
510 return move(conv.to, outfile, to_file, conv.latex);
515 bool Converters::move(string const & fmt,
516 FileName const & from, FileName const & to, bool copy)
521 bool no_errors = true;
522 string const path = onlyPath(from.absFileName());
523 string const base = onlyFileName(removeExtension(from.absFileName()));
524 string const to_base = removeExtension(to.absFileName());
525 string const to_extension = getExtension(to.absFileName());
527 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
528 for (support::FileNameList::const_iterator it = files.begin();
529 it != files.end(); ++it) {
530 string const from2 = it->absFileName();
531 string const file2 = onlyFileName(from2);
532 if (prefixIs(file2, base)) {
533 string const to2 = changeExtension(
534 to_base + file2.substr(base.length()),
536 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
538 Mover const & mover = getMover(fmt);
539 bool const moved = copy
540 ? mover.copy(*it, FileName(to2))
541 : mover.rename(*it, FileName(to2));
542 if (!moved && no_errors) {
543 Alert::error(_("Cannot convert file"),
545 _("Could not copy a temporary file from %1$s to %2$s.") :
546 _("Could not move a temporary file from %1$s to %2$s."),
547 from_utf8(from2), from_utf8(to2)));
556 bool Converters::formatIsUsed(string const & format)
558 ConverterList::const_iterator cit = converterlist_.begin();
559 ConverterList::const_iterator end = converterlist_.end();
560 for (; cit != end; ++cit) {
561 if (cit->from == format || cit->to == format)
568 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
569 FileName const & filename, ErrorList & errorList)
571 OutputParams runparams(0);
572 runparams.flavor = OutputParams::LATEX;
573 LaTeX latex("", runparams, filename);
575 int const result = latex.scanLogFile(terr);
577 if (result & LaTeX::ERRORS)
578 buffer.bufferErrors(terr, errorList);
587 : public boost::signals::trackable {
589 ShowMessage(Buffer const & b) : buffer_(b) {}
590 void operator()(docstring const & msg) const { buffer_.message(msg); }
592 Buffer const & buffer_;
598 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
599 OutputParams const & runparams, ErrorList & errorList)
601 buffer.setBusy(true);
602 buffer.message(_("Running LaTeX..."));
604 runparams.document_language = buffer.params().language->babel();
606 // do the LaTeX run(s)
607 string const name = buffer.latexName();
608 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
610 ShowMessage show(buffer);
611 latex.message.connect(show);
612 int const result = latex.run(terr);
614 if (result & LaTeX::ERRORS)
615 buffer.bufferErrors(terr, errorList);
617 // check return value from latex.run().
618 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
619 docstring const str =
620 bformat(_("LaTeX did not run successfully. "
621 "Additionally, LyX could not locate "
622 "the LaTeX log %1$s."), from_utf8(name));
623 Alert::error(_("LaTeX failed"), str);
624 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
625 Alert::warning(_("Output is empty"),
626 _("An empty output file was generated."));
630 buffer.setBusy(false);
632 int const ERROR_MASK =
637 return (result & ERROR_MASK) == 0;
643 void Converters::buildGraph()
645 // clear graph's data structures
646 G_.init(formats.size());
647 // each of the converters knows how to convert one format to another
648 // so, for each of them, we create an arrow on the graph, going from
649 // the one to the other
650 ConverterList::iterator it = converterlist_.begin();
651 ConverterList::iterator const end = converterlist_.end();
652 for (; it != end ; ++it) {
653 int const from = formats.getNumber(it->from);
654 int const to = formats.getNumber(it->to);
655 G_.addEdge(from, to);
660 vector<Format const *> const
661 Converters::intToFormat(vector<int> const & input)
663 vector<Format const *> result(input.size());
665 vector<int>::const_iterator it = input.begin();
666 vector<int>::const_iterator const end = input.end();
667 vector<Format const *>::iterator rit = result.begin();
668 for ( ; it != end; ++it, ++rit) {
669 *rit = &formats.get(*it);
675 vector<Format const *> const
676 Converters::getReachableTo(string const & target, bool const clear_visited)
678 vector<int> const & reachablesto =
679 G_.getReachableTo(formats.getNumber(target), clear_visited);
681 return intToFormat(reachablesto);
685 vector<Format const *> const
686 Converters::getReachable(string const & from, bool const only_viewable,
687 bool const clear_visited)
689 vector<int> const & reachables =
690 G_.getReachable(formats.getNumber(from),
694 return intToFormat(reachables);
698 bool Converters::isReachable(string const & from, string const & to)
700 return G_.isReachable(formats.getNumber(from),
701 formats.getNumber(to));
705 Graph::EdgePath Converters::getPath(string const & from, string const & to)
707 return G_.getPath(formats.getNumber(from),
708 formats.getNumber(to));
712 vector<Format const *> Converters::importableFormats()
714 vector<string> l = loaders();
715 vector<Format const *> result = getReachableTo(l[0], true);
716 vector<string>::const_iterator it = l.begin() + 1;
717 vector<string>::const_iterator en = l.end();
718 for (; it != en; ++it) {
719 vector<Format const *> r = getReachableTo(*it, false);
720 result.insert(result.end(), r.begin(), r.end());
726 vector<Format const *> Converters::exportableFormats(bool only_viewable)
728 vector<string> s = savers();
729 vector<Format const *> result = getReachable(s[0], only_viewable, true);
730 vector<string>::const_iterator it = s.begin() + 1;
731 vector<string>::const_iterator en = s.end();
732 for (; it != en; ++it) {
733 vector<Format const *> r =
734 getReachable(*it, only_viewable, false);
735 result.insert(result.end(), r.begin(), r.end());
741 vector<string> Converters::loaders() const
746 v.push_back("textparagraph");
751 vector<string> Converters::savers() const
754 v.push_back("docbook");
755 v.push_back("latex");
756 v.push_back("literate");
757 v.push_back("luatex");
759 v.push_back("xhtml");
760 v.push_back("pdflatex");
761 v.push_back("platex");
763 v.push_back("xetex");