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/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31 #include "support/lyxlib.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Path.h"
35 #include "support/Systemcall.h"
36 #include "support/FileZipListDir.h"
46 using support::addName;
47 using support::bformat;
48 using support::changeExtension;
49 using support::compare_ascii_no_case;
50 using support::contains;
51 using support::FileName;
52 using support::getExtension;
53 using support::libFileSearch;
54 using support::libScriptSearch;
55 using support::makeAbsPath;
56 using support::makeRelPath;
57 using support::onlyFilename;
58 using support::onlyPath;
59 using support::package;
60 using support::prefixIs;
61 using support::quoteName;
62 using support::removeExtension;
65 using support::Systemcall;
67 namespace Alert = lyx::frontend::Alert;
72 string const token_from("$$i");
73 string const token_base("$$b");
74 string const token_to("$$o");
75 string const token_path("$$p");
79 string const add_options(string const & command, string const & options)
82 string const tail = split(command, head, ' ');
83 return head + ' ' + options + ' ' + tail;
87 string const dvipdfm_options(BufferParams const & bp)
91 if (bp.papersize != PAPER_CUSTOM) {
92 string const paper_size = bp.paperSizeName();
93 if (paper_size != "b5" && paper_size != "foolscap")
94 result = "-p "+ paper_size;
96 if (bp.orientation == ORIENTATION_LANDSCAPE)
104 class ConverterEqual {
106 ConverterEqual(string const & from, string const & to)
107 : from_(from), to_(to) {}
108 bool operator()(Converter const & c) const {
109 return c.from == from_ && c.to == to_;
119 Converter::Converter(string const & f, string const & t,
120 string const & c, string const & l)
121 : from(f), to(t), command(c), flags(l),
122 From(0), To(0), latex(false), xml(false),
127 void Converter::readFlags()
129 string flag_list(flags);
130 while (!flag_list.empty()) {
131 string flag_name, flag_value;
132 flag_list = split(flag_list, flag_value, ',');
133 flag_value = split(flag_value, flag_name, '=');
134 if (flag_name == "latex")
136 else if (flag_name == "xml")
138 else if (flag_name == "needaux")
140 else if (flag_name == "resultdir")
141 result_dir = (flag_value.empty())
142 ? token_base : flag_value;
143 else if (flag_name == "resultfile")
144 result_file = flag_value;
145 else if (flag_name == "parselog")
146 parselog = flag_value;
148 if (!result_dir.empty() && result_file.empty())
149 result_file = "index." + formats.extension(to);
150 //if (!contains(command, token_from))
155 bool operator<(Converter const & a, Converter const & b)
157 // use the compare_ascii_no_case instead of compare_no_case,
158 // because in turkish, 'i' is not the lowercase version of 'I',
159 // and thus turkish locale breaks parsing of tags.
160 int const i = compare_ascii_no_case(a.From->prettyname(),
161 b.From->prettyname());
163 return compare_ascii_no_case(a.To->prettyname(),
164 b.To->prettyname()) < 0;
170 Converter const * Converters::getConverter(string const & from,
171 string const & to) const
173 ConverterList::const_iterator const cit =
174 find_if(converterlist_.begin(), converterlist_.end(),
175 ConverterEqual(from, to));
176 if (cit != converterlist_.end())
183 int Converters::getNumber(string const & from, string const & to) const
185 ConverterList::const_iterator const cit =
186 find_if(converterlist_.begin(), converterlist_.end(),
187 ConverterEqual(from, to));
188 if (cit != converterlist_.end())
189 return distance(converterlist_.begin(), cit);
195 void Converters::add(string const & from, string const & to,
196 string const & command, string const & flags)
200 ConverterList::iterator it = find_if(converterlist_.begin(),
201 converterlist_.end(),
202 ConverterEqual(from , to));
204 Converter converter(from, to, command, flags);
205 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
207 converter.command = command;
208 converter.flags = flags;
210 converter.readFlags();
212 if (converter.latex && (latex_command_.empty() || to == "dvi"))
213 latex_command_ = subst(command, token_from, "");
214 // If we have both latex & pdflatex, we set latex_command to latex.
215 // The latex_command is used to update the .aux file when running
216 // a converter that uses it.
218 if (it == converterlist_.end()) {
219 converterlist_.push_back(converter);
221 converter.From = it->From;
222 converter.To = it->To;
228 void Converters::erase(string const & from, string const & to)
230 ConverterList::iterator const it =
231 find_if(converterlist_.begin(),
232 converterlist_.end(),
233 ConverterEqual(from, to));
234 if (it != converterlist_.end())
235 converterlist_.erase(it);
239 // This method updates the pointers From and To in all the converters.
240 // The code is not very efficient, but it doesn't matter as the number
241 // of formats and converters is small.
242 // Furthermore, this method is called only on startup, or after
243 // adding/deleting a format in FormPreferences (the latter calls can be
244 // eliminated if the formats in the Formats class are stored using a map or
245 // a list (instead of a vector), but this will cause other problems).
246 void Converters::update(Formats const & formats)
248 ConverterList::iterator it = converterlist_.begin();
249 ConverterList::iterator end = converterlist_.end();
250 for (; it != end; ++it) {
251 it->From = formats.getFormat(it->from);
252 it->To = formats.getFormat(it->to);
257 // This method updates the pointers From and To in the last converter.
258 // It is called when adding a new converter in FormPreferences
259 void Converters::updateLast(Formats const & formats)
261 if (converterlist_.begin() != converterlist_.end()) {
262 ConverterList::iterator it = converterlist_.end() - 1;
263 it->From = formats.getFormat(it->from);
264 it->To = formats.getFormat(it->to);
269 void Converters::sort()
271 std::sort(converterlist_.begin(), converterlist_.end());
275 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
277 for (Graph::EdgePath::const_iterator cit = path.begin();
278 cit != path.end(); ++cit) {
279 Converter const & conv = converterlist_[*cit];
281 if (contains(conv.to, "pdf"))
282 return OutputParams::PDFLATEX;
284 return OutputParams::XML;
286 return OutputParams::LATEX;
290 bool Converters::convert(Buffer const * buffer,
291 FileName const & from_file, FileName const & to_file,
292 FileName const & orig_from,
293 string const & from_format, string const & to_format,
294 ErrorList & errorList, int conversionflags)
296 if (from_format == to_format)
297 return move(from_format, from_file, to_file, false);
299 if ((conversionflags & try_cache) &&
300 ConverterCache::get().inCache(orig_from, to_format))
301 return ConverterCache::get().copy(orig_from, to_format, to_file);
303 Graph::EdgePath edgepath = getPath(from_format, to_format);
304 if (edgepath.empty()) {
305 if (conversionflags & try_default) {
306 // if no special converter defined, then we take the
307 // default one from ImageMagic.
308 string const from_ext = from_format.empty() ?
309 getExtension(from_file.absFilename()) :
310 formats.extension(from_format);
311 string const to_ext = formats.extension(to_format);
312 string const command =
313 support::os::python() + ' ' +
314 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
316 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
318 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
319 LYXERR(Debug::FILES, "No converter defined! "
320 "I use convertDefault.py:\n\t" << command);
322 one.startscript(Systemcall::Wait, command);
323 if (to_file.isReadableFile()) {
324 if (conversionflags & try_cache)
325 ConverterCache::get().add(orig_from,
330 Alert::error(_("Cannot convert file"),
331 bformat(_("No information for converting %1$s "
332 "format files to %2$s.\n"
333 "Define a converter in the preferences."),
334 from_ascii(from_format), from_ascii(to_format)));
338 // buffer is only invalid for importing, and then runparams is not
340 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
341 runparams.flavor = getFlavor(edgepath);
343 // Some converters (e.g. lilypond) can only output files to the
344 // current directory, so we need to change the current directory.
345 // This has the added benefit that all other files that may be
346 // generated by the converter are deleted when LyX closes and do not
347 // clutter the real working directory.
348 string const path(onlyPath(from_file.absFilename()));
349 // Prevent the compiler from optimizing away p
351 support::PathChanger p(pp);
353 // empty the error list before any new conversion takes place.
356 bool run_latex = false;
357 string from_base = changeExtension(from_file.absFilename(), "");
358 string to_base = changeExtension(to_file.absFilename(), "");
360 FileName outfile = from_file;
361 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
362 cit != edgepath.end(); ++cit) {
363 Converter const & conv = converterlist_[*cit];
364 bool dummy = conv.To->dummy() && conv.to != "program";
366 LYXERR(Debug::FILES, "Converting from "
367 << conv.from << " to " << conv.to);
370 outfile = FileName(conv.result_dir.empty()
371 ? changeExtension(from_file.absFilename(), conv.To->extension())
372 : addName(subst(conv.result_dir,
373 token_base, from_base),
374 subst(conv.result_file,
375 token_base, onlyFilename(from_base))));
377 // if input and output files are equal, we use a
378 // temporary file as intermediary (JMarc)
379 FileName real_outfile;
380 if (outfile == infile) {
381 real_outfile = infile;
382 // when importing, a buffer does not necessarily exist
384 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
386 outfile = FileName(addName(package().temp_dir().absFilename(),
392 string const command = subst(conv.command, token_from, "");
393 LYXERR(Debug::FILES, "Running " << command);
394 if (!runLaTeX(*buffer, command, runparams, errorList))
397 if (conv.need_aux && !run_latex
398 && !latex_command_.empty()) {
399 LYXERR(Debug::FILES, "Running " << latex_command_
400 << " to update aux file");
401 runLaTeX(*buffer, latex_command_, runparams, errorList);
405 string const infile2 =
406 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
407 string const outfile2 =
408 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
410 string command = conv.command;
411 command = subst(command, token_from, quoteName(infile2));
412 command = subst(command, token_base, quoteName(from_base));
413 command = subst(command, token_to, quoteName(outfile2));
414 command = libScriptSearch(command);
416 if (!conv.parselog.empty())
417 command += " 2> " + quoteName(infile2 + ".out");
419 if (conv.from == "dvi" && conv.to == "ps")
420 command = add_options(command,
421 buffer->params().dvips_options());
422 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
423 command = add_options(command,
424 dvipdfm_options(buffer->params()));
426 LYXERR(Debug::FILES, "Calling " << command);
428 buffer->message(_("Executing command: ")
429 + from_utf8(command));
434 res = one.startscript(Systemcall::DontWait,
435 to_filesystem8bit(from_utf8(command)));
436 // We're not waiting for the result, so we can't do anything
439 res = one.startscript(Systemcall::Wait,
440 to_filesystem8bit(from_utf8(command)));
441 if (!real_outfile.empty()) {
442 Mover const & mover = getMover(conv.to);
443 if (!mover.rename(outfile, real_outfile))
446 LYXERR(Debug::FILES, "renaming file " << outfile
447 << " to " << real_outfile);
448 // Finally, don't forget to tell any future
449 // converters to use the renamed file...
450 outfile = real_outfile;
453 if (!conv.parselog.empty()) {
454 string const logfile = infile2 + ".log";
455 string const script = libScriptSearch(conv.parselog);
456 string const command2 = script +
457 " < " + quoteName(infile2 + ".out") +
458 " > " + quoteName(logfile);
459 one.startscript(Systemcall::Wait,
460 to_filesystem8bit(from_utf8(command2)));
461 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
467 if (conv.to == "program") {
468 Alert::error(_("Build errors"),
469 _("There were errors during the build process."));
471 // FIXME: this should go out of here. For example, here we cannot say if
472 // it is a document (.lyx) or something else. Same goes for elsewhere.
473 Alert::error(_("Cannot convert file"),
474 bformat(_("An error occurred whilst running %1$s"),
475 from_utf8(command.substr(0, 50))));
482 Converter const & conv = converterlist_[edgepath.back()];
483 if (conv.To->dummy())
486 if (!conv.result_dir.empty()) {
487 // The converter has put the file(s) in a directory.
488 // In this case we ignore the given to_file.
489 if (from_base != to_base) {
490 string const from = subst(conv.result_dir,
491 token_base, from_base);
492 string const to = subst(conv.result_dir,
493 token_base, to_base);
494 Mover const & mover = getMover(conv.from);
495 if (!mover.rename(FileName(from), FileName(to))) {
496 Alert::error(_("Cannot convert file"),
497 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
498 from_utf8(from), from_utf8(to)));
504 if (conversionflags & try_cache)
505 ConverterCache::get().add(orig_from, to_format, outfile);
506 return move(conv.to, outfile, to_file, conv.latex);
511 bool Converters::move(string const & fmt,
512 FileName const & from, FileName const & to, bool copy)
517 bool no_errors = true;
518 string const path = onlyPath(from.absFilename());
519 string const base = onlyFilename(removeExtension(from.absFilename()));
520 string const to_base = removeExtension(to.absFilename());
521 string const to_extension = getExtension(to.absFilename());
523 vector<FileName> const files =
524 support::dirList(FileName(path), getExtension(from.absFilename()));
525 for (vector<FileName>::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)) {
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) {
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 G_.init(formats.size());
643 ConverterList::iterator beg = converterlist_.begin();
644 ConverterList::iterator const end = converterlist_.end();
645 for (ConverterList::iterator it = beg; it != end ; ++it) {
646 int const s = formats.getNumber(it->from);
647 int const t = formats.getNumber(it->to);
653 std::vector<Format const *> const
654 Converters::intToFormat(std::vector<int> const & input)
656 vector<Format const *> result(input.size());
658 vector<int>::const_iterator it = input.begin();
659 vector<int>::const_iterator const end = input.end();
660 vector<Format const *>::iterator rit = result.begin();
661 for ( ; it != end; ++it, ++rit) {
662 *rit = &formats.get(*it);
668 vector<Format const *> const
669 Converters::getReachableTo(string const & target, bool const clear_visited)
671 vector<int> const & reachablesto =
672 G_.getReachableTo(formats.getNumber(target), clear_visited);
674 return intToFormat(reachablesto);
678 vector<Format const *> const
679 Converters::getReachable(string const & from, bool const only_viewable,
680 bool const clear_visited)
682 vector<int> const & reachables =
683 G_.getReachable(formats.getNumber(from),
687 return intToFormat(reachables);
691 bool Converters::isReachable(string const & from, string const & to)
693 return G_.isReachable(formats.getNumber(from),
694 formats.getNumber(to));
698 Graph::EdgePath Converters::getPath(string const & from, string const & to)
700 return G_.getPath(formats.getNumber(from),
701 formats.getNumber(to));
705 vector<Format const *> Converters::importableFormats()
707 vector<string> l = loaders();
708 vector<Format const *> result = getReachableTo(l[0], true);
709 for (vector<string>::const_iterator it = l.begin() + 1;
710 it != l.end(); ++it) {
711 vector<Format const *> r = getReachableTo(*it, false);
712 result.insert(result.end(), r.begin(), r.end());
718 vector<string> Converters::loaders() const
723 v.push_back("textparagraph");