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"
26 #include "frontends/Alert.h"
28 #include "support/filetools.h"
29 #include "support/lyxlib.h"
30 #include "support/os.h"
31 #include "support/path.h"
32 #include "support/systemcall.h"
37 using support::addName;
38 using support::bformat;
39 using support::changeExtension;
40 using support::compare_ascii_no_case;
41 using support::contains;
42 using support::dirList;
43 using support::FileName;
44 using support::getExtension;
45 using support::isFileReadable;
46 using support::libFileSearch;
47 using support::libScriptSearch;
48 using support::makeAbsPath;
49 using support::makeRelPath;
50 using support::onlyFilename;
51 using support::onlyPath;
53 using support::prefixIs;
54 using support::quoteName;
55 using support::removeExtension;
58 using support::Systemcall;
66 namespace Alert = lyx::frontend::Alert;
71 string const token_from("$$i");
72 string const token_base("$$b");
73 string const token_to("$$o");
74 string const token_path("$$p");
78 string const add_options(string const & command, string const & options)
81 string const tail = split(command, head, ' ');
82 return head + ' ' + options + ' ' + tail;
86 string const dvipdfm_options(BufferParams const & bp)
90 if (bp.papersize != PAPER_CUSTOM) {
91 string const paper_size = bp.paperSizeName();
92 if (paper_size != "b5" && paper_size != "foolscap")
93 result = "-p "+ paper_size;
95 if (bp.orientation == ORIENTATION_LANDSCAPE)
103 class ConverterEqual : public std::binary_function<string, string, bool> {
105 ConverterEqual(string const & from, string const & to)
106 : from_(from), to_(to) {}
107 bool operator()(Converter const & c) const {
108 return c.from == from_ && c.to == to_;
118 Converter::Converter(string const & f, string const & t,
119 string const & c, string const & l)
120 : from(f), to(t), command(c), flags(l),
121 From(0), To(0), latex(false), xml(false),
122 original_dir(false), need_aux(false)
126 void Converter::readFlags()
128 string flag_list(flags);
129 while (!flag_list.empty()) {
130 string flag_name, flag_value;
131 flag_list = split(flag_list, flag_value, ',');
132 flag_value = split(flag_value, flag_name, '=');
133 if (flag_name == "latex")
135 else if (flag_name == "xml")
137 else if (flag_name == "originaldir")
139 else if (flag_name == "needaux")
141 else if (flag_name == "resultdir")
142 result_dir = (flag_value.empty())
143 ? token_base : flag_value;
144 else if (flag_name == "resultfile")
145 result_file = flag_value;
146 else if (flag_name == "parselog")
147 parselog = flag_value;
149 if (!result_dir.empty() && result_file.empty())
150 result_file = "index." + formats.extension(to);
151 //if (!contains(command, token_from))
156 bool operator<(Converter const & a, Converter const & b)
158 // use the compare_ascii_no_case instead of compare_no_case,
159 // because in turkish, 'i' is not the lowercase version of 'I',
160 // and thus turkish locale breaks parsing of tags.
161 int const i = compare_ascii_no_case(a.From->prettyname(),
162 b.From->prettyname());
164 return compare_ascii_no_case(a.To->prettyname(),
165 b.To->prettyname()) < 0;
171 Converter const * Converters::getConverter(string const & from,
172 string const & to) const
174 ConverterList::const_iterator const cit =
175 find_if(converterlist_.begin(), converterlist_.end(),
176 ConverterEqual(from, to));
177 if (cit != converterlist_.end())
184 int Converters::getNumber(string const & from, string const & to) const
186 ConverterList::const_iterator const cit =
187 find_if(converterlist_.begin(), converterlist_.end(),
188 ConverterEqual(from, to));
189 if (cit != converterlist_.end())
190 return distance(converterlist_.begin(), cit);
196 void Converters::add(string const & from, string const & to,
197 string const & command, string const & flags)
201 ConverterList::iterator it = find_if(converterlist_.begin(),
202 converterlist_.end(),
203 ConverterEqual(from , to));
205 Converter converter(from, to, command, flags);
206 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
208 converter.command = command;
209 converter.flags = flags;
211 converter.readFlags();
213 if (converter.latex && (latex_command_.empty() || to == "dvi"))
214 latex_command_ = subst(command, token_from, "");
215 // If we have both latex & pdflatex, we set latex_command to latex.
216 // The latex_command is used to update the .aux file when running
217 // a converter that uses it.
219 if (it == converterlist_.end()) {
220 converterlist_.push_back(converter);
222 converter.From = it->From;
223 converter.To = it->To;
229 void Converters::erase(string const & from, string const & to)
231 ConverterList::iterator const it =
232 find_if(converterlist_.begin(),
233 converterlist_.end(),
234 ConverterEqual(from, to));
235 if (it != converterlist_.end())
236 converterlist_.erase(it);
240 // This method updates the pointers From and To in all the converters.
241 // The code is not very efficient, but it doesn't matter as the number
242 // of formats and converters is small.
243 // Furthermore, this method is called only on startup, or after
244 // adding/deleting a format in FormPreferences (the latter calls can be
245 // eliminated if the formats in the Formats class are stored using a map or
246 // a list (instead of a vector), but this will cause other problems).
247 void Converters::update(Formats const & formats)
249 ConverterList::iterator it = converterlist_.begin();
250 ConverterList::iterator end = converterlist_.end();
251 for (; it != end; ++it) {
252 it->From = formats.getFormat(it->from);
253 it->To = formats.getFormat(it->to);
258 // This method updates the pointers From and To in the last converter.
259 // It is called when adding a new converter in FormPreferences
260 void Converters::updateLast(Formats const & formats)
262 if (converterlist_.begin() != converterlist_.end()) {
263 ConverterList::iterator it = converterlist_.end() - 1;
264 it->From = formats.getFormat(it->from);
265 it->To = formats.getFormat(it->to);
270 void Converters::sort()
272 std::sort(converterlist_.begin(), converterlist_.end());
276 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
278 for (Graph::EdgePath::const_iterator cit = path.begin();
279 cit != path.end(); ++cit) {
280 Converter const & conv = converterlist_[*cit];
282 if (contains(conv.to, "pdf"))
283 return OutputParams::PDFLATEX;
285 return OutputParams::XML;
287 return OutputParams::LATEX;
291 bool Converters::convert(Buffer const * buffer,
292 FileName const & from_file, FileName const & to_file,
293 FileName const & orig_from,
294 string const & from_format, string const & to_format,
295 ErrorList & errorList, int conversionflags)
297 if (from_format == to_format)
298 return move(from_format, from_file, to_file, false);
300 if ((conversionflags & try_cache) &&
301 ConverterCache::get().inCache(orig_from, to_format))
302 return ConverterCache::get().copy(orig_from, to_format, to_file);
304 Graph::EdgePath edgepath = getPath(from_format, to_format);
305 if (edgepath.empty()) {
306 if (conversionflags & try_default) {
307 // if no special converter defined, then we take the
308 // default one from ImageMagic.
309 string const from_ext = from_format.empty() ?
310 getExtension(from_file.absFilename()) :
311 formats.extension(from_format);
312 string const to_ext = formats.extension(to_format);
313 string const command =
314 support::os::python() + ' ' +
315 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
317 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
319 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
321 << "No converter defined! "
322 "I use convertDefault.py:\n\t"
325 one.startscript(Systemcall::Wait, command);
326 if (isFileReadable(to_file)) {
327 if (conversionflags & try_cache)
328 ConverterCache::get().add(orig_from,
333 Alert::error(_("Cannot convert file"),
334 bformat(_("No information for converting %1$s "
335 "format files to %2$s.\n"
336 "Define a converter in the preferences."),
337 from_ascii(from_format), from_ascii(to_format)));
341 // buffer is only invalid for importing, and then runparams is not
343 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
344 runparams.flavor = getFlavor(edgepath);
346 // Some converters (e.g. lilypond) can only output files to the
347 // current directory, so we need to change the current directory.
348 // This has the added benefit that all other files that may be
349 // generated by the converter are deleted when LyX closes and do not
350 // clutter the real working directory.
351 string path = onlyPath(from_file.absFilename());
354 // empty the error list before any new conversion takes place.
357 bool run_latex = false;
358 string from_base = changeExtension(from_file.absFilename(), "");
359 string to_base = changeExtension(to_file.absFilename(), "");
361 FileName outfile = from_file;
362 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
363 cit != edgepath.end(); ++cit) {
364 Converter const & conv = converterlist_[*cit];
365 bool dummy = conv.To->dummy() && conv.to != "program";
367 lyxerr[Debug::FILES] << "Converting from "
368 << conv.from << " to " << conv.to << endl;
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 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
387 string const command = subst(conv.command, token_from, "");
388 lyxerr[Debug::FILES] << "Running " << command << endl;
389 if (!runLaTeX(*buffer, command, runparams, errorList))
392 if (conv.need_aux && !run_latex
393 && !latex_command_.empty()) {
395 << "Running " << latex_command_
396 << " to update aux file"<< endl;
397 runLaTeX(*buffer, latex_command_, runparams, errorList);
401 string const infile2 = (conv.original_dir)
402 ? infile.absFilename() : to_utf8(makeRelPath(from_utf8(infile.absFilename()),
404 string const outfile2 = (conv.original_dir)
405 ? outfile.absFilename() : to_utf8(makeRelPath(from_utf8(outfile.absFilename()),
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 << endl;
426 buffer->message(_("Executing command: ")
427 + from_utf8(command));
429 Systemcall::Starttype const type = (dummy)
430 ? Systemcall::DontWait : Systemcall::Wait;
433 if (conv.original_dir) {
434 Path p(buffer->filePath());
435 res = one.startscript(type,
436 to_filesystem8bit(from_utf8(command)));
438 res = one.startscript(type,
439 to_filesystem8bit(from_utf8(command)));
441 if (!real_outfile.empty()) {
442 Mover const & mover = getMover(conv.to);
443 if (!mover.rename(outfile, real_outfile))
447 << "renaming file " << outfile
448 << " 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))
468 if (conv.to == "program") {
469 Alert::error(_("Build errors"),
470 _("There were errors during the build process."));
472 // FIXME: this should go out of here. For example, here we cannot say if
473 // it is a document (.lyx) or something else. Same goes for elsewhere.
474 Alert::error(_("Cannot convert file"),
475 bformat(_("An error occurred whilst running %1$s"),
476 from_utf8(command.substr(0, 50))));
483 Converter const & conv = converterlist_[edgepath.back()];
484 if (conv.To->dummy())
487 if (!conv.result_dir.empty()) {
488 // The converter has put the file(s) in a directory.
489 // In this case we ignore the given to_file.
490 if (from_base != to_base) {
491 string const from = subst(conv.result_dir,
492 token_base, from_base);
493 string const to = subst(conv.result_dir,
494 token_base, to_base);
495 Mover const & mover = getMover(conv.from);
496 if (!mover.rename(FileName(from), FileName(to))) {
497 Alert::error(_("Cannot convert file"),
498 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
499 from_utf8(from), from_utf8(to)));
505 if (conversionflags & try_cache)
506 ConverterCache::get().add(orig_from, to_format, outfile);
507 return move(conv.to, outfile, to_file, conv.latex);
512 bool Converters::move(string const & fmt,
513 FileName const & from, FileName const & to, bool copy)
518 bool no_errors = true;
519 string const path = onlyPath(from.absFilename());
520 string const base = onlyFilename(removeExtension(from.absFilename()));
521 string const to_base = removeExtension(to.absFilename());
522 string const to_extension = getExtension(to.absFilename());
524 vector<FileName> const files = dirList(FileName(path),
525 getExtension(from.absFilename()));
526 for (vector<FileName>::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
535 << " to " << to2 << endl;
537 Mover const & mover = getMover(fmt);
538 bool const moved = copy
539 ? mover.copy(*it, FileName(to2))
540 : mover.rename(*it, FileName(to2));
541 if (!moved && no_errors) {
542 Alert::error(_("Cannot convert file"),
544 _("Could not copy a temporary file from %1$s to %2$s.") :
545 _("Could not move a temporary file from %1$s to %2$s."),
546 from_utf8(from2), from_utf8(to2)));
555 bool Converters::formatIsUsed(string const & format)
557 ConverterList::const_iterator cit = converterlist_.begin();
558 ConverterList::const_iterator end = converterlist_.end();
559 for (; cit != end; ++cit) {
560 if (cit->from == format || cit->to == format)
567 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
568 FileName const & filename, ErrorList & errorList)
570 OutputParams runparams(0);
571 runparams.flavor = OutputParams::LATEX;
572 LaTeX latex("", runparams, filename);
574 int const result = latex.scanLogFile(terr);
576 if (result & LaTeX::ERRORS)
577 bufferErrors(buffer, terr, errorList);
585 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
587 showMessage(Buffer const & b) : buffer_(b) {};
588 void operator()(docstring const & m) const
593 Buffer const & buffer_;
599 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
600 OutputParams const & runparams, ErrorList & errorList)
603 buffer.message(_("Running LaTeX..."));
605 runparams.document_language = buffer.params().language->babel();
607 // do the LaTeX run(s)
608 string const name = buffer.getLatexName();
609 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
611 showMessage show(buffer);
612 latex.message.connect(show);
613 int const result = latex.run(terr);
615 if (result & LaTeX::ERRORS)
616 bufferErrors(buffer, terr, errorList);
618 // check return value from latex.run().
619 if ((result & LaTeX::NO_LOGFILE)) {
620 docstring const str =
621 bformat(_("LaTeX did not run successfully. "
622 "Additionally, LyX could not locate "
623 "the LaTeX log %1$s."), from_utf8(name));
624 Alert::error(_("LaTeX failed"), str);
625 } else if (result & LaTeX::NO_OUTPUT) {
626 Alert::warning(_("Output is empty"),
627 _("An empty output file was generated."));
633 int const ERROR_MASK =
638 return (result & ERROR_MASK) == 0;
644 void Converters::buildGraph()
646 G_.init(formats.size());
647 ConverterList::iterator beg = converterlist_.begin();
648 ConverterList::iterator const end = converterlist_.end();
649 for (ConverterList::iterator it = beg; it != end ; ++it) {
650 int const s = formats.getNumber(it->from);
651 int const t = formats.getNumber(it->to);
657 std::vector<Format const *> const
658 Converters::intToFormat(std::vector<int> const & input)
660 vector<Format const *> result(input.size());
662 vector<int>::const_iterator it = input.begin();
663 vector<int>::const_iterator const end = input.end();
664 vector<Format const *>::iterator rit = result.begin();
665 for ( ; it != end; ++it, ++rit) {
666 *rit = &formats.get(*it);
672 vector<Format const *> const
673 Converters::getReachableTo(string const & target, bool const clear_visited)
675 vector<int> const & reachablesto =
676 G_.getReachableTo(formats.getNumber(target), clear_visited);
678 return intToFormat(reachablesto);
682 vector<Format const *> const
683 Converters::getReachable(string const & from, bool const only_viewable,
684 bool const clear_visited)
686 vector<int> const & reachables =
687 G_.getReachable(formats.getNumber(from),
691 return intToFormat(reachables);
695 bool Converters::isReachable(string const & from, string const & to)
697 return G_.isReachable(formats.getNumber(from),
698 formats.getNumber(to));
702 Graph::EdgePath const
703 Converters::getPath(string const & from, string const & to)
705 return G_.getPath(formats.getNumber(from),
706 formats.getNumber(to));