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::absolutePath;
38 using support::addName;
39 using support::bformat;
40 using support::changeExtension;
41 using support::compare_ascii_no_case;
42 using support::contains;
43 using support::dirList;
44 using support::getExtension;
45 using support::isFileReadable;
46 using support::libFileSearch;
47 using support::libScriptSearch;
48 using support::makeRelPath;
49 using support::onlyFilename;
50 using support::onlyPath;
52 using support::prefixIs;
53 using support::quoteName;
56 using support::Systemcall;
64 namespace Alert = lyx::frontend::Alert;
69 string const token_from("$$i");
70 string const token_base("$$b");
71 string const token_to("$$o");
72 string const token_path("$$p");
76 string const add_options(string const & command, string const & options)
79 string const tail = split(command, head, ' ');
80 return head + ' ' + options + ' ' + tail;
84 string const dvipdfm_options(BufferParams const & bp)
88 if (bp.papersize != PAPER_CUSTOM) {
89 string const paper_size = bp.paperSizeName();
90 if (paper_size != "b5" && paper_size != "foolscap")
91 result = "-p "+ paper_size;
93 if (bp.orientation == ORIENTATION_LANDSCAPE)
101 class ConverterEqual : public std::binary_function<string, string, bool> {
103 ConverterEqual(string const & from, string const & to)
104 : from_(from), to_(to) {}
105 bool operator()(Converter const & c) const {
106 return c.from == from_ && c.to == to_;
116 Converter::Converter(string const & f, string const & t,
117 string const & c, string const & l)
118 : from(f), to(t), command(c), flags(l),
119 From(0), To(0), latex(false), xml(false),
120 original_dir(false), need_aux(false)
124 void Converter::readFlags()
126 string flag_list(flags);
127 while (!flag_list.empty()) {
128 string flag_name, flag_value;
129 flag_list = split(flag_list, flag_value, ',');
130 flag_value = split(flag_value, flag_name, '=');
131 if (flag_name == "latex")
133 else if (flag_name == "xml")
135 else if (flag_name == "originaldir")
137 else if (flag_name == "needaux")
139 else if (flag_name == "resultdir")
140 result_dir = (flag_value.empty())
141 ? token_base : flag_value;
142 else if (flag_name == "resultfile")
143 result_file = flag_value;
144 else if (flag_name == "parselog")
145 parselog = flag_value;
147 if (!result_dir.empty() && result_file.empty())
148 result_file = "index." + formats.extension(to);
149 //if (!contains(command, token_from))
154 bool operator<(Converter const & a, Converter const & b)
156 // use the compare_ascii_no_case instead of compare_no_case,
157 // because in turkish, 'i' is not the lowercase version of 'I',
158 // and thus turkish locale breaks parsing of tags.
159 int const i = compare_ascii_no_case(a.From->prettyname(),
160 b.From->prettyname());
162 return compare_ascii_no_case(a.To->prettyname(),
163 b.To->prettyname()) < 0;
169 Converter const * Converters::getConverter(string const & from,
170 string const & to) const
172 ConverterList::const_iterator const cit =
173 find_if(converterlist_.begin(), converterlist_.end(),
174 ConverterEqual(from, to));
175 if (cit != converterlist_.end())
182 int Converters::getNumber(string const & from, string const & to) const
184 ConverterList::const_iterator const cit =
185 find_if(converterlist_.begin(), converterlist_.end(),
186 ConverterEqual(from, to));
187 if (cit != converterlist_.end())
188 return distance(converterlist_.begin(), cit);
194 void Converters::add(string const & from, string const & to,
195 string const & command, string const & flags)
199 ConverterList::iterator it = find_if(converterlist_.begin(),
200 converterlist_.end(),
201 ConverterEqual(from , to));
203 Converter converter(from, to, command, flags);
204 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
206 converter.command = command;
207 converter.flags = flags;
209 converter.readFlags();
211 if (converter.latex && (latex_command_.empty() || to == "dvi"))
212 latex_command_ = subst(command, token_from, "");
213 // If we have both latex & pdflatex, we set latex_command to latex.
214 // The latex_command is used to update the .aux file when running
215 // a converter that uses it.
217 if (it == converterlist_.end()) {
218 converterlist_.push_back(converter);
220 converter.From = it->From;
221 converter.To = it->To;
227 void Converters::erase(string const & from, string const & to)
229 ConverterList::iterator const it =
230 find_if(converterlist_.begin(),
231 converterlist_.end(),
232 ConverterEqual(from, to));
233 if (it != converterlist_.end())
234 converterlist_.erase(it);
238 // This method updates the pointers From and To in all the converters.
239 // The code is not very efficient, but it doesn't matter as the number
240 // of formats and converters is small.
241 // Furthermore, this method is called only on startup, or after
242 // adding/deleting a format in FormPreferences (the latter calls can be
243 // eliminated if the formats in the Formats class are stored using a map or
244 // a list (instead of a vector), but this will cause other problems).
245 void Converters::update(Formats const & formats)
247 ConverterList::iterator it = converterlist_.begin();
248 ConverterList::iterator end = converterlist_.end();
249 for (; it != end; ++it) {
250 it->From = formats.getFormat(it->from);
251 it->To = formats.getFormat(it->to);
256 // This method updates the pointers From and To in the last converter.
257 // It is called when adding a new converter in FormPreferences
258 void Converters::updateLast(Formats const & formats)
260 if (converterlist_.begin() != converterlist_.end()) {
261 ConverterList::iterator it = converterlist_.end() - 1;
262 it->From = formats.getFormat(it->from);
263 it->To = formats.getFormat(it->to);
268 void Converters::sort()
270 std::sort(converterlist_.begin(), converterlist_.end());
274 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
276 for (Graph::EdgePath::const_iterator cit = path.begin();
277 cit != path.end(); ++cit) {
278 Converter const & conv = converterlist_[*cit];
280 if (contains(conv.to, "pdf"))
281 return OutputParams::PDFLATEX;
283 return OutputParams::XML;
285 return OutputParams::LATEX;
289 bool Converters::convert(Buffer const * buffer,
290 string const & from_file, string const & to_file,
291 string const & orig_from,
292 string const & from_format, string const & to_format,
293 ErrorList & errorList, int conversionflags)
295 BOOST_ASSERT(absolutePath(from_file));
296 BOOST_ASSERT(absolutePath(to_file));
297 BOOST_ASSERT(absolutePath(orig_from));
299 if (from_format == to_format)
300 return move(from_format, from_file, to_file, false);
302 if ((conversionflags & try_cache) &&
303 ConverterCache::get().inCache(orig_from, to_format))
304 return ConverterCache::get().copy(orig_from, to_format, to_file);
306 Graph::EdgePath edgepath = getPath(from_format, to_format);
307 if (edgepath.empty()) {
308 if (conversionflags & try_default) {
309 // if no special converter defined, then we take the
310 // default one from ImageMagic.
311 string const from_ext = from_format.empty() ?
312 getExtension(from_file) :
313 formats.extension(from_format);
314 string const to_ext = formats.extension(to_format);
315 string const command =
316 support::os::python() + ' ' +
317 quoteName(libFileSearch("scripts", "convertDefault.py")) +
319 quoteName(from_ext + ':' + from_file) +
321 quoteName(to_ext + ':' + to_file);
323 << "No converter defined! "
324 "I use convertDefault.py:\n\t"
327 one.startscript(Systemcall::Wait, command);
328 if (isFileReadable(to_file)) {
329 if (conversionflags & try_cache)
330 ConverterCache::get().add(orig_from,
335 Alert::error(_("Cannot convert file"),
336 bformat(_("No information for converting %1$s "
337 "format files to %2$s.\n"
338 "Define a converter in the preferences."),
339 from_ascii(from_format), from_ascii(to_format)));
342 OutputParams runparams;
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 path = onlyPath(from_file);
353 // empty the error list before any new conversion takes place.
356 bool run_latex = false;
357 string from_base = changeExtension(from_file, "");
358 string to_base = changeExtension(to_file, "");
360 string 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 << endl;
369 outfile = conv.result_dir.empty()
370 ? changeExtension(from_file, conv.To->extension())
371 : addName(subst(conv.result_dir,
372 token_base, from_base),
373 subst(conv.result_file,
374 token_base, onlyFilename(from_base)));
376 // if input and output files are equal, we use a
377 // temporary file as intermediary (JMarc)
379 if (outfile == infile) {
380 real_outfile = infile;
381 outfile = addName(buffer->temppath(), "tmpfile.out");
386 string const command = subst(conv.command, token_from, "");
387 lyxerr[Debug::FILES] << "Running " << command << endl;
388 if (!runLaTeX(*buffer, command, runparams, errorList))
391 if (conv.need_aux && !run_latex
392 && !latex_command_.empty()) {
394 << "Running " << latex_command_
395 << " to update aux file"<< endl;
396 runLaTeX(*buffer, latex_command_, runparams, errorList);
399 string const infile2 = (conv.original_dir)
400 ? infile : makeRelPath(infile, path);
401 string const outfile2 = (conv.original_dir)
402 ? outfile : makeRelPath(outfile, path);
404 string command = conv.command;
405 command = subst(command, token_from, quoteName(infile2));
406 command = subst(command, token_base, quoteName(from_base));
407 command = subst(command, token_to, quoteName(outfile2));
408 command = libScriptSearch(command);
410 if (!conv.parselog.empty())
411 command += " 2> " + quoteName(infile2 + ".out");
413 if (conv.from == "dvi" && conv.to == "ps")
414 command = add_options(command,
415 buffer->params().dvips_options());
416 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
417 command = add_options(command,
418 dvipdfm_options(buffer->params()));
420 lyxerr[Debug::FILES] << "Calling " << command << endl;
422 buffer->message(_("Executing command: ")
423 + from_utf8(command));
425 Systemcall::Starttype const type = (dummy)
426 ? Systemcall::DontWait : Systemcall::Wait;
429 if (conv.original_dir) {
430 Path p(buffer->filePath());
431 res = one.startscript(type, command);
433 res = one.startscript(type, command);
435 if (!real_outfile.empty()) {
436 Mover const & mover = movers(conv.to);
437 if (!mover.rename(outfile, real_outfile))
441 << "renaming file " << outfile
442 << " to " << real_outfile
444 // Finally, don't forget to tell any future
445 // converters to use the renamed file...
446 outfile = real_outfile;
449 if (!conv.parselog.empty()) {
450 string const logfile = infile2 + ".log";
451 string const script = libScriptSearch(conv.parselog);
452 string const command2 = script +
453 " < " + quoteName(infile2 + ".out") +
454 " > " + quoteName(logfile);
455 one.startscript(Systemcall::Wait, command2);
456 if (!scanLog(*buffer, command, logfile, errorList))
461 if (conv.to == "program") {
462 Alert::error(_("Build errors"),
463 _("There were errors during the build process."));
465 // FIXME: this should go out of here. For example, here we cannot say if
466 // it is a document (.lyx) or something else. Same goes for elsewhere.
467 Alert::error(_("Cannot convert file"),
468 bformat(_("An error occurred whilst running %1$s"),
469 from_ascii(command.substr(0, 50))));
476 Converter const & conv = converterlist_[edgepath.back()];
477 if (conv.To->dummy())
480 if (!conv.result_dir.empty()) {
481 // The converter has put the file(s) in a directory.
482 // In this case we ignore the given to_file.
483 if (from_base != to_base) {
484 string const from = subst(conv.result_dir,
485 token_base, from_base);
486 string const to = subst(conv.result_dir,
487 token_base, to_base);
488 Mover const & mover = movers(conv.from);
489 if (!mover.rename(from, to)) {
490 Alert::error(_("Cannot convert file"),
491 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
492 from_ascii(from), from_ascii(to)));
498 if (conversionflags & try_cache)
499 ConverterCache::get().add(orig_from, to_format, outfile);
500 return move(conv.to, outfile, to_file, conv.latex);
505 bool Converters::move(string const & fmt,
506 string const & from, string const & to, bool copy)
511 bool no_errors = true;
512 string const path = onlyPath(from);
513 string const base = onlyFilename(changeExtension(from, ""));
514 string const to_base = changeExtension(to, "");
515 string const to_extension = getExtension(to);
517 vector<string> files = dirList(onlyPath(from), getExtension(from));
518 for (vector<string>::const_iterator it = files.begin();
519 it != files.end(); ++it)
520 if (prefixIs(*it, base)) {
521 string const from2 = path + *it;
522 string to2 = to_base + it->substr(base.length());
523 to2 = changeExtension(to2, to_extension);
524 lyxerr[Debug::FILES] << "moving " << from2
525 << " to " << to2 << endl;
527 Mover const & mover = movers(fmt);
528 bool const moved = copy
529 ? mover.copy(from2, to2)
530 : mover.rename(from2, to2);
531 if (!moved && no_errors) {
532 Alert::error(_("Cannot convert file"),
534 _("Could not copy a temporary file from %1$s to %2$s.") :
535 _("Could not move a temporary file from %1$s to %2$s."),
536 from_ascii(from2), from_ascii(to2)));
544 bool Converters::formatIsUsed(string const & format)
546 ConverterList::const_iterator cit = converterlist_.begin();
547 ConverterList::const_iterator end = converterlist_.end();
548 for (; cit != end; ++cit) {
549 if (cit->from == format || cit->to == format)
556 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
557 string const & filename, ErrorList & errorList)
559 OutputParams runparams;
560 runparams.flavor = OutputParams::LATEX;
561 LaTeX latex("", runparams, filename, "");
563 int const result = latex.scanLogFile(terr);
565 if (result & LaTeX::ERRORS)
566 bufferErrors(buffer, terr, errorList);
574 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
576 showMessage(Buffer const & b) : buffer_(b) {};
577 void operator()(docstring const & m) const
582 Buffer const & buffer_;
588 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
589 OutputParams const & runparams, ErrorList & errorList)
592 buffer.message(_("Running LaTeX..."));
594 runparams.document_language = buffer.params().language->babel();
596 // do the LaTeX run(s)
597 string const name = buffer.getLatexName();
598 LaTeX latex(command, runparams, name, buffer.filePath());
600 showMessage show(buffer);
601 latex.message.connect(show);
602 int const result = latex.run(terr);
604 if (result & LaTeX::ERRORS)
605 bufferErrors(buffer, terr, errorList);
607 // check return value from latex.run().
608 if ((result & LaTeX::NO_LOGFILE)) {
609 docstring const str =
610 bformat(_("LaTeX did not run successfully. "
611 "Additionally, LyX could not locate "
612 "the LaTeX log %1$s."), from_utf8(name));
613 Alert::error(_("LaTeX failed"), str);
614 } else if (result & LaTeX::NO_OUTPUT) {
615 Alert::warning(_("Output is empty"),
616 _("An empty output file was generated."));
622 int const ERROR_MASK =
627 return (result & ERROR_MASK) == 0;
633 void Converters::buildGraph()
635 G_.init(formats.size());
636 ConverterList::iterator beg = converterlist_.begin();
637 ConverterList::iterator const end = converterlist_.end();
638 for (ConverterList::iterator it = beg; it != end ; ++it) {
639 int const s = formats.getNumber(it->from);
640 int const t = formats.getNumber(it->to);
646 std::vector<Format const *> const
647 Converters::intToFormat(std::vector<int> const & input)
649 vector<Format const *> result(input.size());
651 vector<int>::const_iterator it = input.begin();
652 vector<int>::const_iterator const end = input.end();
653 vector<Format const *>::iterator rit = result.begin();
654 for ( ; it != end; ++it, ++rit) {
655 *rit = &formats.get(*it);
661 vector<Format const *> const
662 Converters::getReachableTo(string const & target, bool const clear_visited)
664 vector<int> const & reachablesto =
665 G_.getReachableTo(formats.getNumber(target), clear_visited);
667 return intToFormat(reachablesto);
671 vector<Format const *> const
672 Converters::getReachable(string const & from, bool const only_viewable,
673 bool const clear_visited)
675 vector<int> const & reachables =
676 G_.getReachable(formats.getNumber(from),
680 return intToFormat(reachables);
684 bool Converters::isReachable(string const & from, string const & to)
686 return G_.isReachable(formats.getNumber(from),
687 formats.getNumber(to));
691 Graph::EdgePath const
692 Converters::getPath(string const & from, string const & to)
694 return G_.getPath(formats.getNumber(from),
695 formats.getNumber(to));
699 /// The global instance
700 Converters converters;
702 // The global copy after reading lyxrc.defaults
703 Converters system_converters;