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,
306 // only warn once per session and per file type
307 static std::map<string, string> warned;
308 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
311 warned.insert(make_pair(from_format, to_format));
313 Alert::error(_("Cannot convert file"),
314 bformat(_("No information for converting %1$s "
315 "format files to %2$s.\n"
316 "Define a converter in the preferences."),
317 from_ascii(from_format), from_ascii(to_format)));
321 // buffer is only invalid for importing, and then runparams is not
323 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
324 runparams.flavor = getFlavor(edgepath);
326 // Some converters (e.g. lilypond) can only output files to the
327 // current directory, so we need to change the current directory.
328 // This has the added benefit that all other files that may be
329 // generated by the converter are deleted when LyX closes and do not
330 // clutter the real working directory.
331 string const path(onlyPath(from_file.absFilename()));
332 // Prevent the compiler from optimizing away p
336 // empty the error list before any new conversion takes place.
339 bool run_latex = false;
340 string from_base = changeExtension(from_file.absFilename(), "");
341 string to_base = changeExtension(to_file.absFilename(), "");
343 FileName outfile = from_file;
344 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
345 cit != edgepath.end(); ++cit) {
346 Converter const & conv = converterlist_[*cit];
347 bool dummy = conv.To->dummy() && conv.to != "program";
349 LYXERR(Debug::FILES, "Converting from "
350 << conv.from << " to " << conv.to);
353 outfile = FileName(conv.result_dir.empty()
354 ? changeExtension(from_file.absFilename(), conv.To->extension())
355 : addName(subst(conv.result_dir,
356 token_base, from_base),
357 subst(conv.result_file,
358 token_base, onlyFilename(from_base))));
360 // if input and output files are equal, we use a
361 // temporary file as intermediary (JMarc)
362 FileName real_outfile;
363 if (outfile == infile) {
364 real_outfile = infile;
365 // when importing, a buffer does not necessarily exist
367 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
369 outfile = FileName(addName(package().temp_dir().absFilename(),
375 string const command = subst(conv.command, token_from, "");
376 LYXERR(Debug::FILES, "Running " << command);
377 if (!runLaTeX(*buffer, command, runparams, errorList))
380 if (conv.need_aux && !run_latex
381 && !latex_command_.empty()) {
382 LYXERR(Debug::FILES, "Running " << latex_command_
383 << " to update aux file");
384 runLaTeX(*buffer, latex_command_, runparams, errorList);
388 string const infile2 =
389 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
390 string const outfile2 =
391 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
393 string command = conv.command;
394 command = subst(command, token_from, quoteName(infile2));
395 command = subst(command, token_base, quoteName(from_base));
396 command = subst(command, token_to, quoteName(outfile2));
397 command = libScriptSearch(command);
399 if (!conv.parselog.empty())
400 command += " 2> " + quoteName(infile2 + ".out");
402 if (conv.from == "dvi" && conv.to == "ps")
403 command = add_options(command,
404 buffer->params().dvips_options());
405 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
406 command = add_options(command,
407 dvipdfm_options(buffer->params()));
409 LYXERR(Debug::FILES, "Calling " << command);
411 buffer->message(_("Executing command: ")
412 + from_utf8(command));
417 res = one.startscript(Systemcall::DontWait,
418 to_filesystem8bit(from_utf8(command)));
419 // We're not waiting for the result, so we can't do anything
422 res = one.startscript(Systemcall::Wait,
423 to_filesystem8bit(from_utf8(command)));
424 if (!real_outfile.empty()) {
425 Mover const & mover = getMover(conv.to);
426 if (!mover.rename(outfile, real_outfile))
429 LYXERR(Debug::FILES, "renaming file " << outfile
430 << " to " << real_outfile);
431 // Finally, don't forget to tell any future
432 // converters to use the renamed file...
433 outfile = real_outfile;
436 if (!conv.parselog.empty()) {
437 string const logfile = infile2 + ".log";
438 string const script = libScriptSearch(conv.parselog);
439 string const command2 = script +
440 " < " + quoteName(infile2 + ".out") +
441 " > " + quoteName(logfile);
442 one.startscript(Systemcall::Wait,
443 to_filesystem8bit(from_utf8(command2)));
444 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
450 if (conv.to == "program") {
451 Alert::error(_("Build errors"),
452 _("There were errors during the build process."));
454 // FIXME: this should go out of here. For example, here we cannot say if
455 // it is a document (.lyx) or something else. Same goes for elsewhere.
456 Alert::error(_("Cannot convert file"),
457 bformat(_("An error occurred whilst running %1$s"),
458 from_utf8(command.substr(0, 50))));
465 Converter const & conv = converterlist_[edgepath.back()];
466 if (conv.To->dummy())
469 if (!conv.result_dir.empty()) {
470 // The converter has put the file(s) in a directory.
471 // In this case we ignore the given to_file.
472 if (from_base != to_base) {
473 string const from = subst(conv.result_dir,
474 token_base, from_base);
475 string const to = subst(conv.result_dir,
476 token_base, to_base);
477 Mover const & mover = getMover(conv.from);
478 if (!mover.rename(FileName(from), FileName(to))) {
479 Alert::error(_("Cannot convert file"),
480 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
481 from_utf8(from), from_utf8(to)));
487 if (conversionflags & try_cache)
488 ConverterCache::get().add(orig_from, to_format, outfile);
489 return move(conv.to, outfile, to_file, conv.latex);
494 bool Converters::move(string const & fmt,
495 FileName const & from, FileName const & to, bool copy)
500 bool no_errors = true;
501 string const path = onlyPath(from.absFilename());
502 string const base = onlyFilename(removeExtension(from.absFilename()));
503 string const to_base = removeExtension(to.absFilename());
504 string const to_extension = getExtension(to.absFilename());
506 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
507 for (support::FileNameList::const_iterator it = files.begin();
508 it != files.end(); ++it) {
509 string const from2 = it->absFilename();
510 string const file2 = onlyFilename(from2);
511 if (prefixIs(file2, base)) {
512 string const to2 = changeExtension(
513 to_base + file2.substr(base.length()),
515 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
517 Mover const & mover = getMover(fmt);
518 bool const moved = copy
519 ? mover.copy(*it, FileName(to2))
520 : mover.rename(*it, FileName(to2));
521 if (!moved && no_errors) {
522 Alert::error(_("Cannot convert file"),
524 _("Could not copy a temporary file from %1$s to %2$s.") :
525 _("Could not move a temporary file from %1$s to %2$s."),
526 from_utf8(from2), from_utf8(to2)));
535 bool Converters::formatIsUsed(string const & format)
537 ConverterList::const_iterator cit = converterlist_.begin();
538 ConverterList::const_iterator end = converterlist_.end();
539 for (; cit != end; ++cit) {
540 if (cit->from == format || cit->to == format)
547 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
548 FileName const & filename, ErrorList & errorList)
550 OutputParams runparams(0);
551 runparams.flavor = OutputParams::LATEX;
552 LaTeX latex("", runparams, filename);
554 int const result = latex.scanLogFile(terr);
556 if (result & LaTeX::ERRORS)
557 buffer.bufferErrors(terr, errorList);
566 : public boost::signals::trackable {
568 ShowMessage(Buffer const & b) : buffer_(b) {}
569 void operator()(docstring const & msg) const { buffer_.message(msg); }
571 Buffer const & buffer_;
577 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
578 OutputParams const & runparams, ErrorList & errorList)
580 buffer.setBusy(true);
581 buffer.message(_("Running LaTeX..."));
583 runparams.document_language = buffer.params().language->babel();
585 // do the LaTeX run(s)
586 string const name = buffer.latexName();
587 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
589 ShowMessage show(buffer);
590 latex.message.connect(show);
591 int const result = latex.run(terr);
593 if (result & LaTeX::ERRORS)
594 buffer.bufferErrors(terr, errorList);
596 // check return value from latex.run().
597 if ((result & LaTeX::NO_LOGFILE)) {
598 docstring const str =
599 bformat(_("LaTeX did not run successfully. "
600 "Additionally, LyX could not locate "
601 "the LaTeX log %1$s."), from_utf8(name));
602 Alert::error(_("LaTeX failed"), str);
603 } else if (result & LaTeX::NO_OUTPUT) {
604 Alert::warning(_("Output is empty"),
605 _("An empty output file was generated."));
609 buffer.setBusy(false);
611 int const ERROR_MASK =
616 return (result & ERROR_MASK) == 0;
622 void Converters::buildGraph()
624 G_.init(formats.size());
625 ConverterList::iterator beg = converterlist_.begin();
626 ConverterList::iterator const end = converterlist_.end();
627 for (ConverterList::iterator it = beg; it != end ; ++it) {
628 int const s = formats.getNumber(it->from);
629 int const t = formats.getNumber(it->to);
635 vector<Format const *> const
636 Converters::intToFormat(vector<int> const & input)
638 vector<Format const *> result(input.size());
640 vector<int>::const_iterator it = input.begin();
641 vector<int>::const_iterator const end = input.end();
642 vector<Format const *>::iterator rit = result.begin();
643 for ( ; it != end; ++it, ++rit) {
644 *rit = &formats.get(*it);
650 vector<Format const *> const
651 Converters::getReachableTo(string const & target, bool const clear_visited)
653 vector<int> const & reachablesto =
654 G_.getReachableTo(formats.getNumber(target), clear_visited);
656 return intToFormat(reachablesto);
660 vector<Format const *> const
661 Converters::getReachable(string const & from, bool const only_viewable,
662 bool const clear_visited)
664 vector<int> const & reachables =
665 G_.getReachable(formats.getNumber(from),
669 return intToFormat(reachables);
673 bool Converters::isReachable(string const & from, string const & to)
675 return G_.isReachable(formats.getNumber(from),
676 formats.getNumber(to));
680 Graph::EdgePath Converters::getPath(string const & from, string const & to)
682 return G_.getPath(formats.getNumber(from),
683 formats.getNumber(to));
687 vector<Format const *> Converters::importableFormats()
689 vector<string> l = loaders();
690 vector<Format const *> result = getReachableTo(l[0], true);
691 for (vector<string>::const_iterator it = l.begin() + 1;
692 it != l.end(); ++it) {
693 vector<Format const *> r = getReachableTo(*it, false);
694 result.insert(result.end(), r.begin(), r.end());
700 vector<string> Converters::loaders() const
705 v.push_back("textparagraph");