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/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Path.h"
35 #include "support/Systemcall.h"
38 using namespace lyx::support;
42 namespace Alert = lyx::frontend::Alert;
47 string const token_from("$$i");
48 string const token_base("$$b");
49 string const token_to("$$o");
50 string const token_path("$$p");
54 string const add_options(string const & command, string const & options)
57 string const tail = split(command, head, ' ');
58 return head + ' ' + options + ' ' + tail;
62 string const dvipdfm_options(BufferParams const & bp)
66 if (bp.papersize != PAPER_CUSTOM) {
67 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
68 if (!paper_size.empty())
69 result = "-p "+ paper_size;
71 if (bp.orientation == ORIENTATION_LANDSCAPE)
79 class ConverterEqual {
81 ConverterEqual(string const & from, string const & to)
82 : from_(from), to_(to) {}
83 bool operator()(Converter const & c) const {
84 return c.from == from_ && c.to == to_;
94 Converter::Converter(string const & f, string const & t,
95 string const & c, string const & l)
96 : from(f), to(t), command(c), flags(l),
97 From(0), To(0), latex(false), xml(false),
102 void Converter::readFlags()
104 string flag_list(flags);
105 while (!flag_list.empty()) {
106 string flag_name, flag_value;
107 flag_list = split(flag_list, flag_value, ',');
108 flag_value = split(flag_value, flag_name, '=');
109 if (flag_name == "latex")
111 else if (flag_name == "xml")
113 else if (flag_name == "needaux")
115 else if (flag_name == "resultdir")
116 result_dir = (flag_value.empty())
117 ? token_base : flag_value;
118 else if (flag_name == "resultfile")
119 result_file = flag_value;
120 else if (flag_name == "parselog")
121 parselog = flag_value;
123 if (!result_dir.empty() && result_file.empty())
124 result_file = "index." + formats.extension(to);
125 //if (!contains(command, token_from))
130 bool operator<(Converter const & a, Converter const & b)
132 // use the compare_ascii_no_case instead of compare_no_case,
133 // because in turkish, 'i' is not the lowercase version of 'I',
134 // and thus turkish locale breaks parsing of tags.
135 int const i = compare_ascii_no_case(a.From->prettyname(),
136 b.From->prettyname());
138 return compare_ascii_no_case(a.To->prettyname(),
139 b.To->prettyname()) < 0;
145 Converter const * Converters::getConverter(string const & from,
146 string const & to) const
148 ConverterList::const_iterator const cit =
149 find_if(converterlist_.begin(), converterlist_.end(),
150 ConverterEqual(from, to));
151 if (cit != converterlist_.end())
158 int Converters::getNumber(string const & from, string const & to) const
160 ConverterList::const_iterator const cit =
161 find_if(converterlist_.begin(), converterlist_.end(),
162 ConverterEqual(from, to));
163 if (cit != converterlist_.end())
164 return distance(converterlist_.begin(), cit);
170 void Converters::add(string const & from, string const & to,
171 string const & command, string const & flags)
175 ConverterList::iterator it = find_if(converterlist_.begin(),
176 converterlist_.end(),
177 ConverterEqual(from , to));
179 Converter converter(from, to, command, flags);
180 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
182 converter.command = command;
183 converter.flags = flags;
185 converter.readFlags();
187 if (converter.latex && (latex_command_.empty() || to == "dvi"))
188 latex_command_ = subst(command, token_from, "");
189 // If we have both latex & pdflatex, we set latex_command to latex.
190 // The latex_command is used to update the .aux file when running
191 // a converter that uses it.
193 if (it == converterlist_.end()) {
194 converterlist_.push_back(converter);
196 converter.From = it->From;
197 converter.To = it->To;
203 void Converters::erase(string const & from, string const & to)
205 ConverterList::iterator const it =
206 find_if(converterlist_.begin(),
207 converterlist_.end(),
208 ConverterEqual(from, to));
209 if (it != converterlist_.end())
210 converterlist_.erase(it);
214 // This method updates the pointers From and To in all the converters.
215 // The code is not very efficient, but it doesn't matter as the number
216 // of formats and converters is small.
217 // Furthermore, this method is called only on startup, or after
218 // adding/deleting a format in FormPreferences (the latter calls can be
219 // eliminated if the formats in the Formats class are stored using a map or
220 // a list (instead of a vector), but this will cause other problems).
221 void Converters::update(Formats const & formats)
223 ConverterList::iterator it = converterlist_.begin();
224 ConverterList::iterator end = converterlist_.end();
225 for (; it != end; ++it) {
226 it->From = formats.getFormat(it->from);
227 it->To = formats.getFormat(it->to);
232 // This method updates the pointers From and To in the last converter.
233 // It is called when adding a new converter in FormPreferences
234 void Converters::updateLast(Formats const & formats)
236 if (converterlist_.begin() != converterlist_.end()) {
237 ConverterList::iterator it = converterlist_.end() - 1;
238 it->From = formats.getFormat(it->from);
239 it->To = formats.getFormat(it->to);
244 void Converters::sort()
246 std::sort(converterlist_.begin(), converterlist_.end());
250 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
252 for (Graph::EdgePath::const_iterator cit = path.begin();
253 cit != path.end(); ++cit) {
254 Converter const & conv = converterlist_[*cit];
256 if (contains(conv.to, "pdf"))
257 return OutputParams::PDFLATEX;
259 return OutputParams::XML;
261 return OutputParams::LATEX;
265 bool Converters::convert(Buffer const * buffer,
266 FileName const & from_file, FileName const & to_file,
267 FileName const & orig_from,
268 string const & from_format, string const & to_format,
269 ErrorList & errorList, int conversionflags)
271 if (from_format == to_format)
272 return move(from_format, from_file, to_file, false);
274 if ((conversionflags & try_cache) &&
275 ConverterCache::get().inCache(orig_from, to_format))
276 return ConverterCache::get().copy(orig_from, to_format, to_file);
278 Graph::EdgePath edgepath = getPath(from_format, to_format);
279 if (edgepath.empty()) {
280 if (conversionflags & try_default) {
281 // if no special converter defined, then we take the
282 // default one from ImageMagic.
283 string const from_ext = from_format.empty() ?
284 getExtension(from_file.absFilename()) :
285 formats.extension(from_format);
286 string const to_ext = formats.extension(to_format);
287 string const command =
289 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
291 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
293 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
294 LYXERR(Debug::FILES, "No converter defined! "
295 "I use convertDefault.py:\n\t" << command);
297 one.startscript(Systemcall::Wait, command);
298 if (to_file.isReadableFile()) {
299 if (conversionflags & try_cache)
300 ConverterCache::get().add(orig_from,
305 Alert::error(_("Cannot convert file"),
306 bformat(_("No information for converting %1$s "
307 "format files to %2$s.\n"
308 "Define a converter in the preferences."),
309 from_ascii(from_format), from_ascii(to_format)));
313 // buffer is only invalid for importing, and then runparams is not
315 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
316 runparams.flavor = getFlavor(edgepath);
318 // Some converters (e.g. lilypond) can only output files to the
319 // current directory, so we need to change the current directory.
320 // This has the added benefit that all other files that may be
321 // generated by the converter are deleted when LyX closes and do not
322 // clutter the real working directory.
323 string const path(onlyPath(from_file.absFilename()));
324 // Prevent the compiler from optimizing away p
328 // empty the error list before any new conversion takes place.
331 bool run_latex = false;
332 string from_base = changeExtension(from_file.absFilename(), "");
333 string to_base = changeExtension(to_file.absFilename(), "");
335 FileName outfile = from_file;
336 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
337 cit != edgepath.end(); ++cit) {
338 Converter const & conv = converterlist_[*cit];
339 bool dummy = conv.To->dummy() && conv.to != "program";
341 LYXERR(Debug::FILES, "Converting from "
342 << conv.from << " to " << conv.to);
345 outfile = FileName(conv.result_dir.empty()
346 ? changeExtension(from_file.absFilename(), conv.To->extension())
347 : addName(subst(conv.result_dir,
348 token_base, from_base),
349 subst(conv.result_file,
350 token_base, onlyFilename(from_base))));
352 // if input and output files are equal, we use a
353 // temporary file as intermediary (JMarc)
354 FileName real_outfile;
355 if (outfile == infile) {
356 real_outfile = infile;
357 // when importing, a buffer does not necessarily exist
359 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
361 outfile = FileName(addName(package().temp_dir().absFilename(),
367 string const command = subst(conv.command, token_from, "");
368 LYXERR(Debug::FILES, "Running " << command);
369 if (!runLaTeX(*buffer, command, runparams, errorList))
372 if (conv.need_aux && !run_latex
373 && !latex_command_.empty()) {
374 LYXERR(Debug::FILES, "Running " << latex_command_
375 << " to update aux file");
376 runLaTeX(*buffer, latex_command_, runparams, errorList);
380 string const infile2 =
381 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
382 string const outfile2 =
383 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
385 string command = conv.command;
386 command = subst(command, token_from, quoteName(infile2));
387 command = subst(command, token_base, quoteName(from_base));
388 command = subst(command, token_to, quoteName(outfile2));
389 command = libScriptSearch(command);
391 if (!conv.parselog.empty())
392 command += " 2> " + quoteName(infile2 + ".out");
394 if (conv.from == "dvi" && conv.to == "ps")
395 command = add_options(command,
396 buffer->params().dvips_options());
397 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
398 command = add_options(command,
399 dvipdfm_options(buffer->params()));
401 LYXERR(Debug::FILES, "Calling " << command);
403 buffer->message(_("Executing command: ")
404 + from_utf8(command));
409 res = one.startscript(Systemcall::DontWait,
410 to_filesystem8bit(from_utf8(command)));
411 // We're not waiting for the result, so we can't do anything
414 res = one.startscript(Systemcall::Wait,
415 to_filesystem8bit(from_utf8(command)));
416 if (!real_outfile.empty()) {
417 Mover const & mover = getMover(conv.to);
418 if (!mover.rename(outfile, real_outfile))
421 LYXERR(Debug::FILES, "renaming file " << outfile
422 << " to " << real_outfile);
423 // Finally, don't forget to tell any future
424 // converters to use the renamed file...
425 outfile = real_outfile;
428 if (!conv.parselog.empty()) {
429 string const logfile = infile2 + ".log";
430 string const script = libScriptSearch(conv.parselog);
431 string const command2 = script +
432 " < " + quoteName(infile2 + ".out") +
433 " > " + quoteName(logfile);
434 one.startscript(Systemcall::Wait,
435 to_filesystem8bit(from_utf8(command2)));
436 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
442 if (conv.to == "program") {
443 Alert::error(_("Build errors"),
444 _("There were errors during the build process."));
446 // FIXME: this should go out of here. For example, here we cannot say if
447 // it is a document (.lyx) or something else. Same goes for elsewhere.
448 Alert::error(_("Cannot convert file"),
449 bformat(_("An error occurred whilst running %1$s"),
450 from_utf8(command.substr(0, 50))));
457 Converter const & conv = converterlist_[edgepath.back()];
458 if (conv.To->dummy())
461 if (!conv.result_dir.empty()) {
462 // The converter has put the file(s) in a directory.
463 // In this case we ignore the given to_file.
464 if (from_base != to_base) {
465 string const from = subst(conv.result_dir,
466 token_base, from_base);
467 string const to = subst(conv.result_dir,
468 token_base, to_base);
469 Mover const & mover = getMover(conv.from);
470 if (!mover.rename(FileName(from), FileName(to))) {
471 Alert::error(_("Cannot convert file"),
472 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
473 from_utf8(from), from_utf8(to)));
479 if (conversionflags & try_cache)
480 ConverterCache::get().add(orig_from, to_format, outfile);
481 return move(conv.to, outfile, to_file, conv.latex);
486 bool Converters::move(string const & fmt,
487 FileName const & from, FileName const & to, bool copy)
492 bool no_errors = true;
493 string const path = onlyPath(from.absFilename());
494 string const base = onlyFilename(removeExtension(from.absFilename()));
495 string const to_base = removeExtension(to.absFilename());
496 string const to_extension = getExtension(to.absFilename());
498 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
499 for (support::FileNameList::const_iterator it = files.begin();
500 it != files.end(); ++it) {
501 string const from2 = it->absFilename();
502 string const file2 = onlyFilename(from2);
503 if (prefixIs(file2, base)) {
504 string const to2 = changeExtension(
505 to_base + file2.substr(base.length()),
507 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
509 Mover const & mover = getMover(fmt);
510 bool const moved = copy
511 ? mover.copy(*it, FileName(to2))
512 : mover.rename(*it, FileName(to2));
513 if (!moved && no_errors) {
514 Alert::error(_("Cannot convert file"),
516 _("Could not copy a temporary file from %1$s to %2$s.") :
517 _("Could not move a temporary file from %1$s to %2$s."),
518 from_utf8(from2), from_utf8(to2)));
527 bool Converters::formatIsUsed(string const & format)
529 ConverterList::const_iterator cit = converterlist_.begin();
530 ConverterList::const_iterator end = converterlist_.end();
531 for (; cit != end; ++cit) {
532 if (cit->from == format || cit->to == format)
539 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
540 FileName const & filename, ErrorList & errorList)
542 OutputParams runparams(0);
543 runparams.flavor = OutputParams::LATEX;
544 LaTeX latex("", runparams, filename);
546 int const result = latex.scanLogFile(terr);
548 if (result & LaTeX::ERRORS)
549 buffer.bufferErrors(terr, errorList);
558 : public boost::signals::trackable {
560 ShowMessage(Buffer const & b) : buffer_(b) {}
561 void operator()(docstring const & msg) const { buffer_.message(msg); }
563 Buffer const & buffer_;
569 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
570 OutputParams const & runparams, ErrorList & errorList)
572 buffer.setBusy(true);
573 buffer.message(_("Running LaTeX..."));
575 runparams.document_language = buffer.params().language->babel();
577 // do the LaTeX run(s)
578 string const name = buffer.latexName();
579 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
581 ShowMessage show(buffer);
582 latex.message.connect(show);
583 int const result = latex.run(terr);
585 if (result & LaTeX::ERRORS)
586 buffer.bufferErrors(terr, errorList);
588 // check return value from latex.run().
589 if ((result & LaTeX::NO_LOGFILE)) {
590 docstring const str =
591 bformat(_("LaTeX did not run successfully. "
592 "Additionally, LyX could not locate "
593 "the LaTeX log %1$s."), from_utf8(name));
594 Alert::error(_("LaTeX failed"), str);
595 } else if (result & LaTeX::NO_OUTPUT) {
596 Alert::warning(_("Output is empty"),
597 _("An empty output file was generated."));
601 buffer.setBusy(false);
603 int const ERROR_MASK =
608 return (result & ERROR_MASK) == 0;
614 void Converters::buildGraph()
616 G_.init(formats.size());
617 ConverterList::iterator beg = converterlist_.begin();
618 ConverterList::iterator const end = converterlist_.end();
619 for (ConverterList::iterator it = beg; it != end ; ++it) {
620 int const s = formats.getNumber(it->from);
621 int const t = formats.getNumber(it->to);
627 vector<Format const *> const
628 Converters::intToFormat(vector<int> const & input)
630 vector<Format const *> result(input.size());
632 vector<int>::const_iterator it = input.begin();
633 vector<int>::const_iterator const end = input.end();
634 vector<Format const *>::iterator rit = result.begin();
635 for ( ; it != end; ++it, ++rit) {
636 *rit = &formats.get(*it);
642 vector<Format const *> const
643 Converters::getReachableTo(string const & target, bool const clear_visited)
645 vector<int> const & reachablesto =
646 G_.getReachableTo(formats.getNumber(target), clear_visited);
648 return intToFormat(reachablesto);
652 vector<Format const *> const
653 Converters::getReachable(string const & from, bool const only_viewable,
654 bool const clear_visited)
656 vector<int> const & reachables =
657 G_.getReachable(formats.getNumber(from),
661 return intToFormat(reachables);
665 bool Converters::isReachable(string const & from, string const & to)
667 return G_.isReachable(formats.getNumber(from),
668 formats.getNumber(to));
672 Graph::EdgePath Converters::getPath(string const & from, string const & to)
674 return G_.getPath(formats.getNumber(from),
675 formats.getNumber(to));
679 vector<Format const *> Converters::importableFormats()
681 vector<string> l = loaders();
682 vector<Format const *> result = getReachableTo(l[0], true);
683 for (vector<string>::const_iterator it = l.begin() + 1;
684 it != l.end(); ++it) {
685 vector<Format const *> r = getReachableTo(*it, false);
686 result.insert(result.end(), r.begin(), r.end());
692 vector<string> Converters::loaders() const
697 v.push_back("textparagraph");