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"
15 #include "ConverterCache.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "ErrorList.h"
25 #include "frontends/alert.h"
27 #include "support/debug.h"
28 #include "support/FileNameList.h"
29 #include "support/filetools.h"
30 #include "support/FileZipListDir.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/Path.h"
37 #include "support/Systemcall.h"
43 using support::addName;
44 using support::bformat;
45 using support::changeExtension;
46 using support::compare_ascii_no_case;
47 using support::contains;
48 using support::FileName;
49 using support::FileNameList;
50 using support::getExtension;
51 using support::libFileSearch;
52 using support::libScriptSearch;
53 using support::makeAbsPath;
54 using support::makeRelPath;
55 using support::onlyFilename;
56 using support::onlyPath;
57 using support::package;
58 using support::prefixIs;
59 using support::quoteName;
60 using support::removeExtension;
63 using support::Systemcall;
65 namespace Alert = lyx::frontend::Alert;
70 string const token_from("$$i");
71 string const token_base("$$b");
72 string const token_to("$$o");
73 string const token_path("$$p");
77 string const add_options(string const & command, string const & options)
80 string const tail = split(command, head, ' ');
81 return head + ' ' + options + ' ' + tail;
85 string const dvipdfm_options(BufferParams const & bp)
89 if (bp.papersize != PAPER_CUSTOM) {
90 string const paper_size = bp.paperSizeName();
91 if (paper_size != "b5" && paper_size != "foolscap")
92 result = "-p "+ paper_size;
94 if (bp.orientation == ORIENTATION_LANDSCAPE)
102 class ConverterEqual {
104 ConverterEqual(string const & from, string const & to)
105 : from_(from), to_(to) {}
106 bool operator()(Converter const & c) const {
107 return c.from == from_ && c.to == to_;
117 Converter::Converter(string const & f, string const & t,
118 string const & c, string const & l)
119 : from(f), to(t), command(c), flags(l),
120 From(0), To(0), latex(false), xml(false),
125 void Converter::readFlags()
127 string flag_list(flags);
128 while (!flag_list.empty()) {
129 string flag_name, flag_value;
130 flag_list = split(flag_list, flag_value, ',');
131 flag_value = split(flag_value, flag_name, '=');
132 if (flag_name == "latex")
134 else if (flag_name == "xml")
136 else if (flag_name == "needaux")
138 else if (flag_name == "resultdir")
139 result_dir = (flag_value.empty())
140 ? token_base : flag_value;
141 else if (flag_name == "resultfile")
142 result_file = flag_value;
143 else if (flag_name == "parselog")
144 parselog = flag_value;
146 if (!result_dir.empty() && result_file.empty())
147 result_file = "index." + formats.extension(to);
148 //if (!contains(command, token_from))
153 bool operator<(Converter const & a, Converter const & b)
155 // use the compare_ascii_no_case instead of compare_no_case,
156 // because in turkish, 'i' is not the lowercase version of 'I',
157 // and thus turkish locale breaks parsing of tags.
158 int const i = compare_ascii_no_case(a.From->prettyname(),
159 b.From->prettyname());
161 return compare_ascii_no_case(a.To->prettyname(),
162 b.To->prettyname()) < 0;
168 Converter const * Converters::getConverter(string const & from,
169 string const & to) const
171 ConverterList::const_iterator const cit =
172 find_if(converterlist_.begin(), converterlist_.end(),
173 ConverterEqual(from, to));
174 if (cit != converterlist_.end())
181 int Converters::getNumber(string const & from, string const & to) const
183 ConverterList::const_iterator const cit =
184 find_if(converterlist_.begin(), converterlist_.end(),
185 ConverterEqual(from, to));
186 if (cit != converterlist_.end())
187 return distance(converterlist_.begin(), cit);
193 void Converters::add(string const & from, string const & to,
194 string const & command, string const & flags)
198 ConverterList::iterator it = find_if(converterlist_.begin(),
199 converterlist_.end(),
200 ConverterEqual(from , to));
202 Converter converter(from, to, command, flags);
203 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
205 converter.command = command;
206 converter.flags = flags;
208 converter.readFlags();
210 if (converter.latex && (latex_command_.empty() || to == "dvi"))
211 latex_command_ = subst(command, token_from, "");
212 // If we have both latex & pdflatex, we set latex_command to latex.
213 // The latex_command is used to update the .aux file when running
214 // a converter that uses it.
216 if (it == converterlist_.end()) {
217 converterlist_.push_back(converter);
219 converter.From = it->From;
220 converter.To = it->To;
226 void Converters::erase(string const & from, string const & to)
228 ConverterList::iterator const it =
229 find_if(converterlist_.begin(),
230 converterlist_.end(),
231 ConverterEqual(from, to));
232 if (it != converterlist_.end())
233 converterlist_.erase(it);
237 // This method updates the pointers From and To in all the converters.
238 // The code is not very efficient, but it doesn't matter as the number
239 // of formats and converters is small.
240 // Furthermore, this method is called only on startup, or after
241 // adding/deleting a format in FormPreferences (the latter calls can be
242 // eliminated if the formats in the Formats class are stored using a map or
243 // a list (instead of a vector), but this will cause other problems).
244 void Converters::update(Formats const & formats)
246 ConverterList::iterator it = converterlist_.begin();
247 ConverterList::iterator end = converterlist_.end();
248 for (; it != end; ++it) {
249 it->From = formats.getFormat(it->from);
250 it->To = formats.getFormat(it->to);
255 // This method updates the pointers From and To in the last converter.
256 // It is called when adding a new converter in FormPreferences
257 void Converters::updateLast(Formats const & formats)
259 if (converterlist_.begin() != converterlist_.end()) {
260 ConverterList::iterator it = converterlist_.end() - 1;
261 it->From = formats.getFormat(it->from);
262 it->To = formats.getFormat(it->to);
267 void Converters::sort()
269 std::sort(converterlist_.begin(), converterlist_.end());
273 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
275 for (Graph::EdgePath::const_iterator cit = path.begin();
276 cit != path.end(); ++cit) {
277 Converter const & conv = converterlist_[*cit];
279 if (contains(conv.to, "pdf"))
280 return OutputParams::PDFLATEX;
282 return OutputParams::XML;
284 return OutputParams::LATEX;
288 bool Converters::convert(Buffer const * buffer,
289 FileName const & from_file, FileName const & to_file,
290 FileName const & orig_from,
291 string const & from_format, string const & to_format,
292 ErrorList & errorList, int conversionflags)
294 if (from_format == to_format)
295 return move(from_format, from_file, to_file, false);
297 if ((conversionflags & try_cache) &&
298 ConverterCache::get().inCache(orig_from, to_format))
299 return ConverterCache::get().copy(orig_from, to_format, to_file);
301 Graph::EdgePath edgepath = getPath(from_format, to_format);
302 if (edgepath.empty()) {
303 if (conversionflags & try_default) {
304 // if no special converter defined, then we take the
305 // default one from ImageMagic.
306 string const from_ext = from_format.empty() ?
307 getExtension(from_file.absFilename()) :
308 formats.extension(from_format);
309 string const to_ext = formats.extension(to_format);
310 string const command =
311 support::os::python() + ' ' +
312 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
314 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
316 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
317 LYXERR(Debug::FILES, "No converter defined! "
318 "I use convertDefault.py:\n\t" << command);
320 one.startscript(Systemcall::Wait, command);
321 if (to_file.isReadableFile()) {
322 if (conversionflags & try_cache)
323 ConverterCache::get().add(orig_from,
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);
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
349 support::PathChanger p(pp);
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 = libScriptSearch(command);
414 if (!conv.parselog.empty())
415 command += " 2> " + quoteName(infile2 + ".out");
417 if (conv.from == "dvi" && conv.to == "ps")
418 command = add_options(command,
419 buffer->params().dvips_options());
420 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
421 command = add_options(command,
422 dvipdfm_options(buffer->params()));
424 LYXERR(Debug::FILES, "Calling " << command);
426 buffer->message(_("Executing command: ")
427 + from_utf8(command));
432 res = one.startscript(Systemcall::DontWait,
433 to_filesystem8bit(from_utf8(command)));
434 // We're not waiting for the result, so we can't do anything
437 res = one.startscript(Systemcall::Wait,
438 to_filesystem8bit(from_utf8(command)));
439 if (!real_outfile.empty()) {
440 Mover const & mover = getMover(conv.to);
441 if (!mover.rename(outfile, real_outfile))
444 LYXERR(Debug::FILES, "renaming file " << outfile
445 << " to " << real_outfile);
446 // Finally, don't forget to tell any future
447 // converters to use the renamed file...
448 outfile = real_outfile;
451 if (!conv.parselog.empty()) {
452 string const logfile = infile2 + ".log";
453 string const script = libScriptSearch(conv.parselog);
454 string const command2 = script +
455 " < " + quoteName(infile2 + ".out") +
456 " > " + quoteName(logfile);
457 one.startscript(Systemcall::Wait,
458 to_filesystem8bit(from_utf8(command2)));
459 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
465 if (conv.to == "program") {
466 Alert::error(_("Build errors"),
467 _("There were errors during the build process."));
469 // FIXME: this should go out of here. For example, here we cannot say if
470 // it is a document (.lyx) or something else. Same goes for elsewhere.
471 Alert::error(_("Cannot convert file"),
472 bformat(_("An error occurred whilst running %1$s"),
473 from_utf8(command.substr(0, 50))));
480 Converter const & conv = converterlist_[edgepath.back()];
481 if (conv.To->dummy())
484 if (!conv.result_dir.empty()) {
485 // The converter has put the file(s) in a directory.
486 // In this case we ignore the given to_file.
487 if (from_base != to_base) {
488 string const from = subst(conv.result_dir,
489 token_base, from_base);
490 string const to = subst(conv.result_dir,
491 token_base, to_base);
492 Mover const & mover = getMover(conv.from);
493 if (!mover.rename(FileName(from), FileName(to))) {
494 Alert::error(_("Cannot convert file"),
495 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
496 from_utf8(from), from_utf8(to)));
502 if (conversionflags & try_cache)
503 ConverterCache::get().add(orig_from, to_format, outfile);
504 return move(conv.to, outfile, to_file, conv.latex);
509 bool Converters::move(string const & fmt,
510 FileName const & from, FileName const & to, bool copy)
515 bool no_errors = true;
516 string const path = onlyPath(from.absFilename());
517 string const base = onlyFilename(removeExtension(from.absFilename()));
518 string const to_base = removeExtension(to.absFilename());
519 string const to_extension = getExtension(to.absFilename());
521 FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
522 for (FileNameList::const_iterator it = files.begin();
523 it != files.end(); ++it) {
524 string const from2 = it->absFilename();
525 string const file2 = onlyFilename(from2);
526 if (prefixIs(file2, base)) {
527 string const to2 = changeExtension(
528 to_base + file2.substr(base.length()),
530 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
532 Mover const & mover = getMover(fmt);
533 bool const moved = copy
534 ? mover.copy(*it, FileName(to2))
535 : mover.rename(*it, FileName(to2));
536 if (!moved && no_errors) {
537 Alert::error(_("Cannot convert file"),
539 _("Could not copy a temporary file from %1$s to %2$s.") :
540 _("Could not move a temporary file from %1$s to %2$s."),
541 from_utf8(from2), from_utf8(to2)));
550 bool Converters::formatIsUsed(string const & format)
552 ConverterList::const_iterator cit = converterlist_.begin();
553 ConverterList::const_iterator end = converterlist_.end();
554 for (; cit != end; ++cit) {
555 if (cit->from == format || cit->to == format)
562 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
563 FileName const & filename, ErrorList & errorList)
565 OutputParams runparams(0);
566 runparams.flavor = OutputParams::LATEX;
567 LaTeX latex("", runparams, filename);
569 int const result = latex.scanLogFile(terr);
571 if (result & LaTeX::ERRORS)
572 buffer.bufferErrors(terr, errorList);
581 : public boost::signals::trackable {
583 ShowMessage(Buffer const & b) : buffer_(b) {}
584 void operator()(docstring const & msg) const { buffer_.message(msg); }
586 Buffer const & buffer_;
592 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
593 OutputParams const & runparams, ErrorList & errorList)
595 buffer.setBusy(true);
596 buffer.message(_("Running LaTeX..."));
598 runparams.document_language = buffer.params().language->babel();
600 // do the LaTeX run(s)
601 string const name = buffer.latexName();
602 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
604 ShowMessage show(buffer);
605 latex.message.connect(show);
606 int const result = latex.run(terr);
608 if (result & LaTeX::ERRORS)
609 buffer.bufferErrors(terr, errorList);
611 // check return value from latex.run().
612 if ((result & LaTeX::NO_LOGFILE)) {
613 docstring const str =
614 bformat(_("LaTeX did not run successfully. "
615 "Additionally, LyX could not locate "
616 "the LaTeX log %1$s."), from_utf8(name));
617 Alert::error(_("LaTeX failed"), str);
618 } else if (result & LaTeX::NO_OUTPUT) {
619 Alert::warning(_("Output is empty"),
620 _("An empty output file was generated."));
624 buffer.setBusy(false);
626 int const ERROR_MASK =
631 return (result & ERROR_MASK) == 0;
637 void Converters::buildGraph()
639 G_.init(formats.size());
640 ConverterList::iterator beg = converterlist_.begin();
641 ConverterList::iterator const end = converterlist_.end();
642 for (ConverterList::iterator it = beg; it != end ; ++it) {
643 int const s = formats.getNumber(it->from);
644 int const t = formats.getNumber(it->to);
650 std::vector<Format const *> const
651 Converters::intToFormat(std::vector<int> const & input)
653 vector<Format const *> result(input.size());
655 vector<int>::const_iterator it = input.begin();
656 vector<int>::const_iterator const end = input.end();
657 vector<Format const *>::iterator rit = result.begin();
658 for ( ; it != end; ++it, ++rit) {
659 *rit = &formats.get(*it);
665 vector<Format const *> const
666 Converters::getReachableTo(string const & target, bool const clear_visited)
668 vector<int> const & reachablesto =
669 G_.getReachableTo(formats.getNumber(target), clear_visited);
671 return intToFormat(reachablesto);
675 vector<Format const *> const
676 Converters::getReachable(string const & from, bool const only_viewable,
677 bool const clear_visited)
679 vector<int> const & reachables =
680 G_.getReachable(formats.getNumber(from),
684 return intToFormat(reachables);
688 bool Converters::isReachable(string const & from, string const & to)
690 return G_.isReachable(formats.getNumber(from),
691 formats.getNumber(to));
695 Graph::EdgePath Converters::getPath(string const & from, string const & to)
697 return G_.getPath(formats.getNumber(from),
698 formats.getNumber(to));
702 vector<Format const *> Converters::importableFormats()
704 vector<string> l = loaders();
705 vector<Format const *> result = getReachableTo(l[0], true);
706 for (vector<string>::const_iterator it = l.begin() + 1;
707 it != l.end(); ++it) {
708 vector<Format const *> r = getReachableTo(*it, false);
709 result.insert(result.end(), r.begin(), r.end());
715 vector<string> Converters::loaders() const
720 v.push_back("textparagraph");