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;
57 using support::Systemcall;
65 namespace Alert = lyx::frontend::Alert;
70 string const token_from("$$i");
71 string const token_base("$$b");
72 string const token_to("$$o");
73 string const token_path("$$p");
77 string const add_options(string const & command, string const & options)
80 string const tail = split(command, head, ' ');
81 return head + ' ' + options + ' ' + tail;
85 string const dvipdfm_options(BufferParams const & bp)
89 if (bp.papersize != PAPER_CUSTOM) {
90 string const paper_size = bp.paperSizeName();
91 if (paper_size != "b5" && paper_size != "foolscap")
92 result = "-p "+ paper_size;
94 if (bp.orientation == ORIENTATION_LANDSCAPE)
102 class ConverterEqual : public std::binary_function<string, string, bool> {
104 ConverterEqual(string const & from, string const & to)
105 : from_(from), to_(to) {}
106 bool operator()(Converter const & c) const {
107 return c.from == from_ && c.to == to_;
117 Converter::Converter(string const & f, string const & t,
118 string const & c, string const & l)
119 : from(f), to(t), command(c), flags(l),
120 From(0), To(0), latex(false), xml(false),
121 original_dir(false), need_aux(false)
125 void Converter::readFlags()
127 string flag_list(flags);
128 while (!flag_list.empty()) {
129 string flag_name, flag_value;
130 flag_list = split(flag_list, flag_value, ',');
131 flag_value = split(flag_value, flag_name, '=');
132 if (flag_name == "latex")
134 else if (flag_name == "xml")
136 else if (flag_name == "originaldir")
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());
320 << "No converter defined! "
321 "I use convertDefault.py:\n\t"
324 one.startscript(Systemcall::Wait, command);
325 if (isFileReadable(to_file)) {
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)));
339 OutputParams runparams;
340 runparams.flavor = getFlavor(edgepath);
342 // Some converters (e.g. lilypond) can only output files to the
343 // current directory, so we need to change the current directory.
344 // This has the added benefit that all other files that may be
345 // generated by the converter are deleted when LyX closes and do not
346 // clutter the real working directory.
347 string path = onlyPath(from_file.absFilename());
350 // empty the error list before any new conversion takes place.
353 bool run_latex = false;
354 string from_base = changeExtension(from_file.absFilename(), "");
355 string to_base = changeExtension(to_file.absFilename(), "");
357 FileName outfile = from_file;
358 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
359 cit != edgepath.end(); ++cit) {
360 Converter const & conv = converterlist_[*cit];
361 bool dummy = conv.To->dummy() && conv.to != "program";
363 lyxerr[Debug::FILES] << "Converting from "
364 << conv.from << " to " << conv.to << endl;
366 outfile = FileName(conv.result_dir.empty()
367 ? changeExtension(from_file.absFilename(), conv.To->extension())
368 : addName(subst(conv.result_dir,
369 token_base, from_base),
370 subst(conv.result_file,
371 token_base, onlyFilename(from_base))));
373 // if input and output files are equal, we use a
374 // temporary file as intermediary (JMarc)
375 FileName real_outfile;
376 if (outfile == infile) {
377 real_outfile = infile;
378 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
383 string const command = subst(conv.command, token_from, "");
384 lyxerr[Debug::FILES] << "Running " << command << endl;
385 if (!runLaTeX(*buffer, command, runparams, errorList))
388 if (conv.need_aux && !run_latex
389 && !latex_command_.empty()) {
391 << "Running " << latex_command_
392 << " to update aux file"<< endl;
393 runLaTeX(*buffer, latex_command_, runparams, errorList);
396 string const infile2 = (conv.original_dir)
397 ? infile.absFilename() : makeRelPath(infile.absFilename(), path);
398 string const outfile2 = (conv.original_dir)
399 ? outfile.absFilename() : makeRelPath(outfile.absFilename(), path);
401 string command = conv.command;
402 command = subst(command, token_from, quoteName(infile2));
403 command = subst(command, token_base, quoteName(from_base));
404 command = subst(command, token_to, quoteName(outfile2));
405 command = libScriptSearch(command);
407 if (!conv.parselog.empty())
408 command += " 2> " + quoteName(infile2 + ".out");
410 if (conv.from == "dvi" && conv.to == "ps")
411 command = add_options(command,
412 buffer->params().dvips_options());
413 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
414 command = add_options(command,
415 dvipdfm_options(buffer->params()));
417 lyxerr[Debug::FILES] << "Calling " << command << endl;
419 buffer->message(_("Executing command: ")
420 + from_utf8(command));
422 Systemcall::Starttype const type = (dummy)
423 ? Systemcall::DontWait : Systemcall::Wait;
426 if (conv.original_dir) {
427 Path p(buffer->filePath());
428 res = one.startscript(type, command);
430 res = one.startscript(type, command);
432 if (!real_outfile.empty()) {
433 Mover const & mover = movers(conv.to);
434 if (!mover.rename(outfile, real_outfile))
438 << "renaming file " << outfile
439 << " to " << real_outfile
441 // Finally, don't forget to tell any future
442 // converters to use the renamed file...
443 outfile = real_outfile;
446 if (!conv.parselog.empty()) {
447 string const logfile = infile2 + ".log";
448 string const script = libScriptSearch(conv.parselog);
449 string const command2 = script +
450 " < " + quoteName(infile2 + ".out") +
451 " > " + quoteName(logfile);
452 one.startscript(Systemcall::Wait, command2);
453 if (!scanLog(*buffer, command, FileName(makeAbsPath(logfile, path)), errorList))
458 if (conv.to == "program") {
459 Alert::error(_("Build errors"),
460 _("There were errors during the build process."));
462 // FIXME: this should go out of here. For example, here we cannot say if
463 // it is a document (.lyx) or something else. Same goes for elsewhere.
464 Alert::error(_("Cannot convert file"),
465 bformat(_("An error occurred whilst running %1$s"),
466 from_ascii(command.substr(0, 50))));
473 Converter const & conv = converterlist_[edgepath.back()];
474 if (conv.To->dummy())
477 if (!conv.result_dir.empty()) {
478 // The converter has put the file(s) in a directory.
479 // In this case we ignore the given to_file.
480 if (from_base != to_base) {
481 string const from = subst(conv.result_dir,
482 token_base, from_base);
483 string const to = subst(conv.result_dir,
484 token_base, to_base);
485 Mover const & mover = movers(conv.from);
486 if (!mover.rename(FileName(from), FileName(to))) {
487 Alert::error(_("Cannot convert file"),
488 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
489 from_ascii(from), from_ascii(to)));
495 if (conversionflags & try_cache)
496 ConverterCache::get().add(orig_from, to_format, outfile);
497 return move(conv.to, outfile, to_file, conv.latex);
502 bool Converters::move(string const & fmt,
503 FileName const & from, FileName const & to, bool copy)
508 bool no_errors = true;
509 string const path = onlyPath(from.absFilename());
510 string const base = onlyFilename(changeExtension(from.absFilename(), string()));
511 string const to_base = changeExtension(to.absFilename(), string());
512 string const to_extension = getExtension(to.absFilename());
514 vector<string> const files = dirList(
515 FileName(onlyPath(from.absFilename())),
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;