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"
47 using support::addName;
48 using support::bformat;
49 using support::changeExtension;
50 using support::compare_ascii_no_case;
51 using support::contains;
52 using support::FileName;
53 using support::FileNameList;
54 using support::getExtension;
55 using support::libFileSearch;
56 using support::libScriptSearch;
57 using support::makeAbsPath;
58 using support::makeRelPath;
59 using support::onlyFilename;
60 using support::onlyPath;
61 using support::package;
62 using support::prefixIs;
63 using support::quoteName;
64 using support::removeExtension;
67 using support::Systemcall;
69 namespace Alert = lyx::frontend::Alert;
74 string const token_from("$$i");
75 string const token_base("$$b");
76 string const token_to("$$o");
77 string const token_path("$$p");
81 string const add_options(string const & command, string const & options)
84 string const tail = split(command, head, ' ');
85 return head + ' ' + options + ' ' + tail;
89 string const dvipdfm_options(BufferParams const & bp)
93 if (bp.papersize != PAPER_CUSTOM) {
94 string const paper_size = bp.paperSizeName();
95 if (paper_size != "b5" && paper_size != "foolscap")
96 result = "-p "+ paper_size;
98 if (bp.orientation == ORIENTATION_LANDSCAPE)
106 class ConverterEqual {
108 ConverterEqual(string const & from, string const & to)
109 : from_(from), to_(to) {}
110 bool operator()(Converter const & c) const {
111 return c.from == from_ && c.to == to_;
121 Converter::Converter(string const & f, string const & t,
122 string const & c, string const & l)
123 : from(f), to(t), command(c), flags(l),
124 From(0), To(0), latex(false), xml(false),
129 void Converter::readFlags()
131 string flag_list(flags);
132 while (!flag_list.empty()) {
133 string flag_name, flag_value;
134 flag_list = split(flag_list, flag_value, ',');
135 flag_value = split(flag_value, flag_name, '=');
136 if (flag_name == "latex")
138 else if (flag_name == "xml")
140 else if (flag_name == "needaux")
142 else if (flag_name == "resultdir")
143 result_dir = (flag_value.empty())
144 ? token_base : flag_value;
145 else if (flag_name == "resultfile")
146 result_file = flag_value;
147 else if (flag_name == "parselog")
148 parselog = flag_value;
150 if (!result_dir.empty() && result_file.empty())
151 result_file = "index." + formats.extension(to);
152 //if (!contains(command, token_from))
157 bool operator<(Converter const & a, Converter const & b)
159 // use the compare_ascii_no_case instead of compare_no_case,
160 // because in turkish, 'i' is not the lowercase version of 'I',
161 // and thus turkish locale breaks parsing of tags.
162 int const i = compare_ascii_no_case(a.From->prettyname(),
163 b.From->prettyname());
165 return compare_ascii_no_case(a.To->prettyname(),
166 b.To->prettyname()) < 0;
172 Converter const * Converters::getConverter(string const & from,
173 string const & to) const
175 ConverterList::const_iterator const cit =
176 find_if(converterlist_.begin(), converterlist_.end(),
177 ConverterEqual(from, to));
178 if (cit != converterlist_.end())
185 int Converters::getNumber(string const & from, string const & to) const
187 ConverterList::const_iterator const cit =
188 find_if(converterlist_.begin(), converterlist_.end(),
189 ConverterEqual(from, to));
190 if (cit != converterlist_.end())
191 return distance(converterlist_.begin(), cit);
197 void Converters::add(string const & from, string const & to,
198 string const & command, string const & flags)
202 ConverterList::iterator it = find_if(converterlist_.begin(),
203 converterlist_.end(),
204 ConverterEqual(from , to));
206 Converter converter(from, to, command, flags);
207 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
209 converter.command = command;
210 converter.flags = flags;
212 converter.readFlags();
214 if (converter.latex && (latex_command_.empty() || to == "dvi"))
215 latex_command_ = subst(command, token_from, "");
216 // If we have both latex & pdflatex, we set latex_command to latex.
217 // The latex_command is used to update the .aux file when running
218 // a converter that uses it.
220 if (it == converterlist_.end()) {
221 converterlist_.push_back(converter);
223 converter.From = it->From;
224 converter.To = it->To;
230 void Converters::erase(string const & from, string const & to)
232 ConverterList::iterator const it =
233 find_if(converterlist_.begin(),
234 converterlist_.end(),
235 ConverterEqual(from, to));
236 if (it != converterlist_.end())
237 converterlist_.erase(it);
241 // This method updates the pointers From and To in all the converters.
242 // The code is not very efficient, but it doesn't matter as the number
243 // of formats and converters is small.
244 // Furthermore, this method is called only on startup, or after
245 // adding/deleting a format in FormPreferences (the latter calls can be
246 // eliminated if the formats in the Formats class are stored using a map or
247 // a list (instead of a vector), but this will cause other problems).
248 void Converters::update(Formats const & formats)
250 ConverterList::iterator it = converterlist_.begin();
251 ConverterList::iterator end = converterlist_.end();
252 for (; it != end; ++it) {
253 it->From = formats.getFormat(it->from);
254 it->To = formats.getFormat(it->to);
259 // This method updates the pointers From and To in the last converter.
260 // It is called when adding a new converter in FormPreferences
261 void Converters::updateLast(Formats const & formats)
263 if (converterlist_.begin() != converterlist_.end()) {
264 ConverterList::iterator it = converterlist_.end() - 1;
265 it->From = formats.getFormat(it->from);
266 it->To = formats.getFormat(it->to);
271 void Converters::sort()
273 std::sort(converterlist_.begin(), converterlist_.end());
277 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
279 for (Graph::EdgePath::const_iterator cit = path.begin();
280 cit != path.end(); ++cit) {
281 Converter const & conv = converterlist_[*cit];
283 if (contains(conv.to, "pdf"))
284 return OutputParams::PDFLATEX;
286 return OutputParams::XML;
288 return OutputParams::LATEX;
292 bool Converters::convert(Buffer const * buffer,
293 FileName const & from_file, FileName const & to_file,
294 FileName const & orig_from,
295 string const & from_format, string const & to_format,
296 ErrorList & errorList, int conversionflags)
298 if (from_format == to_format)
299 return move(from_format, from_file, to_file, false);
301 if ((conversionflags & try_cache) &&
302 ConverterCache::get().inCache(orig_from, to_format))
303 return ConverterCache::get().copy(orig_from, to_format, to_file);
305 Graph::EdgePath edgepath = getPath(from_format, to_format);
306 if (edgepath.empty()) {
307 if (conversionflags & try_default) {
308 // if no special converter defined, then we take the
309 // default one from ImageMagic.
310 string const from_ext = from_format.empty() ?
311 getExtension(from_file.absFilename()) :
312 formats.extension(from_format);
313 string const to_ext = formats.extension(to_format);
314 string const command =
315 support::os::python() + ' ' +
316 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
318 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
320 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
321 LYXERR(Debug::FILES, "No converter defined! "
322 "I use convertDefault.py:\n\t" << command);
324 one.startscript(Systemcall::Wait, command);
325 if (to_file.isReadableFile()) {
326 if (conversionflags & try_cache)
327 ConverterCache::get().add(orig_from,
332 Alert::error(_("Cannot convert file"),
333 bformat(_("No information for converting %1$s "
334 "format files to %2$s.\n"
335 "Define a converter in the preferences."),
336 from_ascii(from_format), from_ascii(to_format)));
340 // buffer is only invalid for importing, and then runparams is not
342 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
343 runparams.flavor = getFlavor(edgepath);
345 // Some converters (e.g. lilypond) can only output files to the
346 // current directory, so we need to change the current directory.
347 // This has the added benefit that all other files that may be
348 // generated by the converter are deleted when LyX closes and do not
349 // clutter the real working directory.
350 string const path(onlyPath(from_file.absFilename()));
351 // Prevent the compiler from optimizing away p
353 support::PathChanger p(pp);
355 // empty the error list before any new conversion takes place.
358 bool run_latex = false;
359 string from_base = changeExtension(from_file.absFilename(), "");
360 string to_base = changeExtension(to_file.absFilename(), "");
362 FileName outfile = from_file;
363 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
364 cit != edgepath.end(); ++cit) {
365 Converter const & conv = converterlist_[*cit];
366 bool dummy = conv.To->dummy() && conv.to != "program";
368 LYXERR(Debug::FILES, "Converting from "
369 << conv.from << " to " << conv.to);
372 outfile = FileName(conv.result_dir.empty()
373 ? changeExtension(from_file.absFilename(), conv.To->extension())
374 : addName(subst(conv.result_dir,
375 token_base, from_base),
376 subst(conv.result_file,
377 token_base, onlyFilename(from_base))));
379 // if input and output files are equal, we use a
380 // temporary file as intermediary (JMarc)
381 FileName real_outfile;
382 if (outfile == infile) {
383 real_outfile = infile;
384 // when importing, a buffer does not necessarily exist
386 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
388 outfile = FileName(addName(package().temp_dir().absFilename(),
394 string const command = subst(conv.command, token_from, "");
395 LYXERR(Debug::FILES, "Running " << command);
396 if (!runLaTeX(*buffer, command, runparams, errorList))
399 if (conv.need_aux && !run_latex
400 && !latex_command_.empty()) {
401 LYXERR(Debug::FILES, "Running " << latex_command_
402 << " to update aux file");
403 runLaTeX(*buffer, latex_command_, runparams, errorList);
407 string const infile2 =
408 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
409 string const outfile2 =
410 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
412 string command = conv.command;
413 command = subst(command, token_from, quoteName(infile2));
414 command = subst(command, token_base, quoteName(from_base));
415 command = subst(command, token_to, quoteName(outfile2));
416 command = libScriptSearch(command);
418 if (!conv.parselog.empty())
419 command += " 2> " + quoteName(infile2 + ".out");
421 if (conv.from == "dvi" && conv.to == "ps")
422 command = add_options(command,
423 buffer->params().dvips_options());
424 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
425 command = add_options(command,
426 dvipdfm_options(buffer->params()));
428 LYXERR(Debug::FILES, "Calling " << command);
430 buffer->message(_("Executing command: ")
431 + from_utf8(command));
436 res = one.startscript(Systemcall::DontWait,
437 to_filesystem8bit(from_utf8(command)));
438 // We're not waiting for the result, so we can't do anything
441 res = one.startscript(Systemcall::Wait,
442 to_filesystem8bit(from_utf8(command)));
443 if (!real_outfile.empty()) {
444 Mover const & mover = getMover(conv.to);
445 if (!mover.rename(outfile, real_outfile))
448 LYXERR(Debug::FILES, "renaming file " << outfile
449 << " to " << real_outfile);
450 // Finally, don't forget to tell any future
451 // converters to use the renamed file...
452 outfile = real_outfile;
455 if (!conv.parselog.empty()) {
456 string const logfile = infile2 + ".log";
457 string const script = libScriptSearch(conv.parselog);
458 string const command2 = script +
459 " < " + quoteName(infile2 + ".out") +
460 " > " + quoteName(logfile);
461 one.startscript(Systemcall::Wait,
462 to_filesystem8bit(from_utf8(command2)));
463 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
469 if (conv.to == "program") {
470 Alert::error(_("Build errors"),
471 _("There were errors during the build process."));
473 // FIXME: this should go out of here. For example, here we cannot say if
474 // it is a document (.lyx) or something else. Same goes for elsewhere.
475 Alert::error(_("Cannot convert file"),
476 bformat(_("An error occurred whilst running %1$s"),
477 from_utf8(command.substr(0, 50))));
484 Converter const & conv = converterlist_[edgepath.back()];
485 if (conv.To->dummy())
488 if (!conv.result_dir.empty()) {
489 // The converter has put the file(s) in a directory.
490 // In this case we ignore the given to_file.
491 if (from_base != to_base) {
492 string const from = subst(conv.result_dir,
493 token_base, from_base);
494 string const to = subst(conv.result_dir,
495 token_base, to_base);
496 Mover const & mover = getMover(conv.from);
497 if (!mover.rename(FileName(from), FileName(to))) {
498 Alert::error(_("Cannot convert file"),
499 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
500 from_utf8(from), from_utf8(to)));
506 if (conversionflags & try_cache)
507 ConverterCache::get().add(orig_from, to_format, outfile);
508 return move(conv.to, outfile, to_file, conv.latex);
513 bool Converters::move(string const & fmt,
514 FileName const & from, FileName const & to, bool copy)
519 bool no_errors = true;
520 string const path = onlyPath(from.absFilename());
521 string const base = onlyFilename(removeExtension(from.absFilename()));
522 string const to_base = removeExtension(to.absFilename());
523 string const to_extension = getExtension(to.absFilename());
525 FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
526 for (FileNameList::const_iterator it = files.begin();
527 it != files.end(); ++it) {
528 string const from2 = it->absFilename();
529 string const file2 = onlyFilename(from2);
530 if (prefixIs(file2, base)) {
531 string const to2 = changeExtension(
532 to_base + file2.substr(base.length()),
534 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
536 Mover const & mover = getMover(fmt);
537 bool const moved = copy
538 ? mover.copy(*it, FileName(to2))
539 : mover.rename(*it, FileName(to2));
540 if (!moved && no_errors) {
541 Alert::error(_("Cannot convert file"),
543 _("Could not copy a temporary file from %1$s to %2$s.") :
544 _("Could not move a temporary file from %1$s to %2$s."),
545 from_utf8(from2), from_utf8(to2)));
554 bool Converters::formatIsUsed(string const & format)
556 ConverterList::const_iterator cit = converterlist_.begin();
557 ConverterList::const_iterator end = converterlist_.end();
558 for (; cit != end; ++cit) {
559 if (cit->from == format || cit->to == format)
566 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
567 FileName const & filename, ErrorList & errorList)
569 OutputParams runparams(0);
570 runparams.flavor = OutputParams::LATEX;
571 LaTeX latex("", runparams, filename);
573 int const result = latex.scanLogFile(terr);
575 if (result & LaTeX::ERRORS)
576 buffer.bufferErrors(terr, errorList);
585 : public boost::signals::trackable {
587 ShowMessage(Buffer const & b) : buffer_(b) {}
588 void operator()(docstring const & msg) const { buffer_.message(msg); }
590 Buffer const & buffer_;
596 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
597 OutputParams const & runparams, ErrorList & errorList)
599 buffer.setBusy(true);
600 buffer.message(_("Running LaTeX..."));
602 runparams.document_language = buffer.params().language->babel();
604 // do the LaTeX run(s)
605 string const name = buffer.latexName();
606 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
608 ShowMessage show(buffer);
609 latex.message.connect(show);
610 int const result = latex.run(terr);
612 if (result & LaTeX::ERRORS)
613 buffer.bufferErrors(terr, errorList);
615 // check return value from latex.run().
616 if ((result & LaTeX::NO_LOGFILE)) {
617 docstring const str =
618 bformat(_("LaTeX did not run successfully. "
619 "Additionally, LyX could not locate "
620 "the LaTeX log %1$s."), from_utf8(name));
621 Alert::error(_("LaTeX failed"), str);
622 } else if (result & LaTeX::NO_OUTPUT) {
623 Alert::warning(_("Output is empty"),
624 _("An empty output file was generated."));
628 buffer.setBusy(false);
630 int const ERROR_MASK =
635 return (result & ERROR_MASK) == 0;
641 void Converters::buildGraph()
643 G_.init(formats.size());
644 ConverterList::iterator beg = converterlist_.begin();
645 ConverterList::iterator const end = converterlist_.end();
646 for (ConverterList::iterator it = beg; it != end ; ++it) {
647 int const s = formats.getNumber(it->from);
648 int const t = formats.getNumber(it->to);
654 std::vector<Format const *> const
655 Converters::intToFormat(std::vector<int> const & input)
657 vector<Format const *> result(input.size());
659 vector<int>::const_iterator it = input.begin();
660 vector<int>::const_iterator const end = input.end();
661 vector<Format const *>::iterator rit = result.begin();
662 for ( ; it != end; ++it, ++rit) {
663 *rit = &formats.get(*it);
669 vector<Format const *> const
670 Converters::getReachableTo(string const & target, bool const clear_visited)
672 vector<int> const & reachablesto =
673 G_.getReachableTo(formats.getNumber(target), clear_visited);
675 return intToFormat(reachablesto);
679 vector<Format const *> const
680 Converters::getReachable(string const & from, bool const only_viewable,
681 bool const clear_visited)
683 vector<int> const & reachables =
684 G_.getReachable(formats.getNumber(from),
688 return intToFormat(reachables);
692 bool Converters::isReachable(string const & from, string const & to)
694 return G_.isReachable(formats.getNumber(from),
695 formats.getNumber(to));
699 Graph::EdgePath Converters::getPath(string const & from, string const & to)
701 return G_.getPath(formats.getNumber(from),
702 formats.getNumber(to));
706 vector<Format const *> Converters::importableFormats()
708 vector<string> l = loaders();
709 vector<Format const *> result = getReachableTo(l[0], true);
710 for (vector<string>::const_iterator it = l.begin() + 1;
711 it != l.end(); ++it) {
712 vector<Format const *> r = getReachableTo(*it, false);
713 result.insert(result.end(), r.begin(), r.end());
719 vector<string> Converters::loaders() const
724 v.push_back("textparagraph");