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)));
340 OutputParams runparams;
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 path = onlyPath(from_file.absFilename());
351 // empty the error list before any new conversion takes place.
354 bool run_latex = false;
355 string from_base = changeExtension(from_file.absFilename(), "");
356 string to_base = changeExtension(to_file.absFilename(), "");
358 FileName outfile = from_file;
359 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
360 cit != edgepath.end(); ++cit) {
361 Converter const & conv = converterlist_[*cit];
362 bool dummy = conv.To->dummy() && conv.to != "program";
364 lyxerr[Debug::FILES] << "Converting from "
365 << conv.from << " to " << conv.to << endl;
367 outfile = FileName(conv.result_dir.empty()
368 ? changeExtension(from_file.absFilename(), conv.To->extension())
369 : addName(subst(conv.result_dir,
370 token_base, from_base),
371 subst(conv.result_file,
372 token_base, onlyFilename(from_base))));
374 // if input and output files are equal, we use a
375 // temporary file as intermediary (JMarc)
376 FileName real_outfile;
377 if (outfile == infile) {
378 real_outfile = infile;
379 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
384 string const command = subst(conv.command, token_from, "");
385 lyxerr[Debug::FILES] << "Running " << command << endl;
386 if (!runLaTeX(*buffer, command, runparams, errorList))
389 if (conv.need_aux && !run_latex
390 && !latex_command_.empty()) {
392 << "Running " << latex_command_
393 << " to update aux file"<< endl;
394 runLaTeX(*buffer, latex_command_, runparams, errorList);
397 string const infile2 = (conv.original_dir)
398 ? infile.absFilename() : makeRelPath(infile.absFilename(), path);
399 string const outfile2 = (conv.original_dir)
400 ? outfile.absFilename() : makeRelPath(outfile.absFilename(), path);
402 string command = conv.command;
403 command = subst(command, token_from, quoteName(infile2));
404 command = subst(command, token_base, quoteName(from_base));
405 command = subst(command, token_to, quoteName(outfile2));
406 command = libScriptSearch(command);
408 if (!conv.parselog.empty())
409 command += " 2> " + quoteName(infile2 + ".out");
411 if (conv.from == "dvi" && conv.to == "ps")
412 command = add_options(command,
413 buffer->params().dvips_options());
414 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
415 command = add_options(command,
416 dvipdfm_options(buffer->params()));
418 lyxerr[Debug::FILES] << "Calling " << command << endl;
420 buffer->message(_("Executing command: ")
421 + from_utf8(command));
423 Systemcall::Starttype const type = (dummy)
424 ? Systemcall::DontWait : Systemcall::Wait;
427 if (conv.original_dir) {
428 Path p(buffer->filePath());
429 res = one.startscript(type, command);
431 res = one.startscript(type, command);
433 if (!real_outfile.empty()) {
434 Mover const & mover = movers(conv.to);
435 if (!mover.rename(outfile, real_outfile))
439 << "renaming file " << outfile
440 << " to " << real_outfile
442 // Finally, don't forget to tell any future
443 // converters to use the renamed file...
444 outfile = real_outfile;
447 if (!conv.parselog.empty()) {
448 string const logfile = infile2 + ".log";
449 string const script = libScriptSearch(conv.parselog);
450 string const command2 = script +
451 " < " + quoteName(infile2 + ".out") +
452 " > " + quoteName(logfile);
453 one.startscript(Systemcall::Wait, command2);
454 if (!scanLog(*buffer, command, FileName(makeAbsPath(logfile, path)), errorList))
459 if (conv.to == "program") {
460 Alert::error(_("Build errors"),
461 _("There were errors during the build process."));
463 // FIXME: this should go out of here. For example, here we cannot say if
464 // it is a document (.lyx) or something else. Same goes for elsewhere.
465 Alert::error(_("Cannot convert file"),
466 bformat(_("An error occurred whilst running %1$s"),
467 from_ascii(command.substr(0, 50))));
474 Converter const & conv = converterlist_[edgepath.back()];
475 if (conv.To->dummy())
478 if (!conv.result_dir.empty()) {
479 // The converter has put the file(s) in a directory.
480 // In this case we ignore the given to_file.
481 if (from_base != to_base) {
482 string const from = subst(conv.result_dir,
483 token_base, from_base);
484 string const to = subst(conv.result_dir,
485 token_base, to_base);
486 Mover const & mover = movers(conv.from);
487 if (!mover.rename(FileName(from), FileName(to))) {
488 Alert::error(_("Cannot convert file"),
489 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
490 from_ascii(from), from_ascii(to)));
496 if (conversionflags & try_cache)
497 ConverterCache::get().add(orig_from, to_format, outfile);
498 return move(conv.to, outfile, to_file, conv.latex);
503 bool Converters::move(string const & fmt,
504 FileName const & from, FileName const & to, bool copy)
509 bool no_errors = true;
510 string const path = onlyPath(from.absFilename());
511 string const base = onlyFilename(removeExtension(from.absFilename()));
512 string const to_base = removeExtension(to.absFilename());
513 string const to_extension = getExtension(to.absFilename());
515 vector<string> const files = dirList(FileName(path),
516 getExtension(from.absFilename()));
517 for (vector<string>::const_iterator it = files.begin();
518 it != files.end(); ++it)
519 if (prefixIs(*it, base)) {
520 string const from2 = path + *it;
521 string to2 = to_base + it->substr(base.length());
522 to2 = changeExtension(to2, to_extension);
523 lyxerr[Debug::FILES] << "moving " << from2
524 << " to " << to2 << endl;
526 Mover const & mover = movers(fmt);
527 bool const moved = copy
528 ? mover.copy(FileName(from2), FileName(to2))
529 : mover.rename(FileName(from2), FileName(to2));
530 if (!moved && no_errors) {
531 Alert::error(_("Cannot convert file"),
533 _("Could not copy a temporary file from %1$s to %2$s.") :
534 _("Could not move a temporary file from %1$s to %2$s."),
535 from_ascii(from2), from_ascii(to2)));
543 bool Converters::formatIsUsed(string const & format)
545 ConverterList::const_iterator cit = converterlist_.begin();
546 ConverterList::const_iterator end = converterlist_.end();
547 for (; cit != end; ++cit) {
548 if (cit->from == format || cit->to == format)
555 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
556 FileName const & filename, ErrorList & errorList)
558 OutputParams runparams;
559 runparams.flavor = OutputParams::LATEX;
560 LaTeX latex("", runparams, filename);
562 int const result = latex.scanLogFile(terr);
564 if (result & LaTeX::ERRORS)
565 bufferErrors(buffer, terr, errorList);
573 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
575 showMessage(Buffer const & b) : buffer_(b) {};
576 void operator()(docstring const & m) const
581 Buffer const & buffer_;
587 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
588 OutputParams const & runparams, ErrorList & errorList)
591 buffer.message(_("Running LaTeX..."));
593 runparams.document_language = buffer.params().language->babel();
595 // do the LaTeX run(s)
596 string const name = buffer.getLatexName();
597 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
599 showMessage show(buffer);
600 latex.message.connect(show);
601 int const result = latex.run(terr);
603 if (result & LaTeX::ERRORS)
604 bufferErrors(buffer, terr, errorList);
606 // check return value from latex.run().
607 if ((result & LaTeX::NO_LOGFILE)) {
608 docstring const str =
609 bformat(_("LaTeX did not run successfully. "
610 "Additionally, LyX could not locate "
611 "the LaTeX log %1$s."), from_utf8(name));
612 Alert::error(_("LaTeX failed"), str);
613 } else if (result & LaTeX::NO_OUTPUT) {
614 Alert::warning(_("Output is empty"),
615 _("An empty output file was generated."));
621 int const ERROR_MASK =
626 return (result & ERROR_MASK) == 0;
632 void Converters::buildGraph()
634 G_.init(formats.size());
635 ConverterList::iterator beg = converterlist_.begin();
636 ConverterList::iterator const end = converterlist_.end();
637 for (ConverterList::iterator it = beg; it != end ; ++it) {
638 int const s = formats.getNumber(it->from);
639 int const t = formats.getNumber(it->to);
645 std::vector<Format const *> const
646 Converters::intToFormat(std::vector<int> const & input)
648 vector<Format const *> result(input.size());
650 vector<int>::const_iterator it = input.begin();
651 vector<int>::const_iterator const end = input.end();
652 vector<Format const *>::iterator rit = result.begin();
653 for ( ; it != end; ++it, ++rit) {
654 *rit = &formats.get(*it);
660 vector<Format const *> const
661 Converters::getReachableTo(string const & target, bool const clear_visited)
663 vector<int> const & reachablesto =
664 G_.getReachableTo(formats.getNumber(target), clear_visited);
666 return intToFormat(reachablesto);
670 vector<Format const *> const
671 Converters::getReachable(string const & from, bool const only_viewable,
672 bool const clear_visited)
674 vector<int> const & reachables =
675 G_.getReachable(formats.getNumber(from),
679 return intToFormat(reachables);
683 bool Converters::isReachable(string const & from, string const & to)
685 return G_.isReachable(formats.getNumber(from),
686 formats.getNumber(to));
690 Graph::EdgePath const
691 Converters::getPath(string const & from, string const & to)
693 return G_.getPath(formats.getNumber(from),
694 formats.getNumber(to));
698 /// The global instance
699 Converters converters;
701 // The global copy after reading lyxrc.defaults
702 Converters system_converters;