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"
20 #include "ErrorList.h"
27 #include "frontends/alert.h"
29 #include "support/filetools.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/Package.h"
33 #include "support/Path.h"
34 #include "support/Systemcall.h"
45 using support::addName;
46 using support::bformat;
47 using support::changeExtension;
48 using support::compare_ascii_no_case;
49 using support::contains;
50 using support::dirList;
51 using support::FileName;
52 using support::getExtension;
53 using support::libFileSearch;
54 using support::libScriptSearch;
55 using support::makeAbsPath;
56 using support::makeRelPath;
57 using support::onlyFilename;
58 using support::onlyPath;
59 using support::package;
60 using support::prefixIs;
61 using support::quoteName;
62 using support::removeExtension;
65 using support::Systemcall;
67 namespace Alert = lyx::frontend::Alert;
72 string const token_from("$$i");
73 string const token_base("$$b");
74 string const token_to("$$o");
75 string const token_path("$$p");
79 string const add_options(string const & command, string const & options)
82 string const tail = split(command, head, ' ');
83 return head + ' ' + options + ' ' + tail;
87 string const dvipdfm_options(BufferParams const & bp)
91 if (bp.papersize != PAPER_CUSTOM) {
92 string const paper_size = bp.paperSizeName();
93 if (paper_size != "b5" && paper_size != "foolscap")
94 result = "-p "+ paper_size;
96 if (bp.orientation == ORIENTATION_LANDSCAPE)
104 class ConverterEqual : public std::binary_function<string, string, bool> {
106 ConverterEqual(string const & from, string const & to)
107 : from_(from), to_(to) {}
108 bool operator()(Converter const & c) const {
109 return c.from == from_ && c.to == to_;
119 Converter::Converter(string const & f, string const & t,
120 string const & c, string const & l)
121 : from(f), to(t), command(c), flags(l),
122 From(0), To(0), latex(false), xml(false),
127 void Converter::readFlags()
129 string flag_list(flags);
130 while (!flag_list.empty()) {
131 string flag_name, flag_value;
132 flag_list = split(flag_list, flag_value, ',');
133 flag_value = split(flag_value, flag_name, '=');
134 if (flag_name == "latex")
136 else if (flag_name == "xml")
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 (to_file.isFileReadable()) {
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
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 << endl;
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 << endl;
396 if (!runLaTeX(*buffer, command, runparams, errorList))
399 if (conv.need_aux && !run_latex
400 && !latex_command_.empty()) {
402 << "Running " << latex_command_
403 << " to update aux file"<< endl;
404 runLaTeX(*buffer, latex_command_, runparams, errorList);
408 string const infile2 =
409 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
410 string const outfile2 =
411 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
413 string command = conv.command;
414 command = subst(command, token_from, quoteName(infile2));
415 command = subst(command, token_base, quoteName(from_base));
416 command = subst(command, token_to, quoteName(outfile2));
417 command = libScriptSearch(command);
419 if (!conv.parselog.empty())
420 command += " 2> " + quoteName(infile2 + ".out");
422 if (conv.from == "dvi" && conv.to == "ps")
423 command = add_options(command,
424 buffer->params().dvips_options());
425 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
426 command = add_options(command,
427 dvipdfm_options(buffer->params()));
429 LYXERR(Debug::FILES) << "Calling " << command << endl;
431 buffer->message(_("Executing command: ")
432 + from_utf8(command));
437 res = one.startscript(Systemcall::DontWait,
438 to_filesystem8bit(from_utf8(command)));
439 // We're not waiting for the result, so we can't do anything
442 res = one.startscript(Systemcall::Wait,
443 to_filesystem8bit(from_utf8(command)));
444 if (!real_outfile.empty()) {
445 Mover const & mover = getMover(conv.to);
446 if (!mover.rename(outfile, real_outfile))
450 << "renaming file " << outfile
451 << " to " << real_outfile
453 // Finally, don't forget to tell any future
454 // converters to use the renamed file...
455 outfile = real_outfile;
458 if (!conv.parselog.empty()) {
459 string const logfile = infile2 + ".log";
460 string const script = libScriptSearch(conv.parselog);
461 string const command2 = script +
462 " < " + quoteName(infile2 + ".out") +
463 " > " + quoteName(logfile);
464 one.startscript(Systemcall::Wait,
465 to_filesystem8bit(from_utf8(command2)));
466 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
472 if (conv.to == "program") {
473 Alert::error(_("Build errors"),
474 _("There were errors during the build process."));
476 // FIXME: this should go out of here. For example, here we cannot say if
477 // it is a document (.lyx) or something else. Same goes for elsewhere.
478 Alert::error(_("Cannot convert file"),
479 bformat(_("An error occurred whilst running %1$s"),
480 from_utf8(command.substr(0, 50))));
487 Converter const & conv = converterlist_[edgepath.back()];
488 if (conv.To->dummy())
491 if (!conv.result_dir.empty()) {
492 // The converter has put the file(s) in a directory.
493 // In this case we ignore the given to_file.
494 if (from_base != to_base) {
495 string const from = subst(conv.result_dir,
496 token_base, from_base);
497 string const to = subst(conv.result_dir,
498 token_base, to_base);
499 Mover const & mover = getMover(conv.from);
500 if (!mover.rename(FileName(from), FileName(to))) {
501 Alert::error(_("Cannot convert file"),
502 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
503 from_utf8(from), from_utf8(to)));
509 if (conversionflags & try_cache)
510 ConverterCache::get().add(orig_from, to_format, outfile);
511 return move(conv.to, outfile, to_file, conv.latex);
516 bool Converters::move(string const & fmt,
517 FileName const & from, FileName const & to, bool copy)
522 bool no_errors = true;
523 string const path = onlyPath(from.absFilename());
524 string const base = onlyFilename(removeExtension(from.absFilename()));
525 string const to_base = removeExtension(to.absFilename());
526 string const to_extension = getExtension(to.absFilename());
528 vector<FileName> const files = dirList(FileName(path),
529 getExtension(from.absFilename()));
530 for (vector<FileName>::const_iterator it = files.begin();
531 it != files.end(); ++it) {
532 string const from2 = it->absFilename();
533 string const file2 = onlyFilename(from2);
534 if (prefixIs(file2, base)) {
535 string const to2 = changeExtension(
536 to_base + file2.substr(base.length()),
538 LYXERR(Debug::FILES) << "moving " << from2
539 << " to " << to2 << endl;
541 Mover const & mover = getMover(fmt);
542 bool const moved = copy
543 ? mover.copy(*it, FileName(to2))
544 : mover.rename(*it, FileName(to2));
545 if (!moved && no_errors) {
546 Alert::error(_("Cannot convert file"),
548 _("Could not copy a temporary file from %1$s to %2$s.") :
549 _("Could not move a temporary file from %1$s to %2$s."),
550 from_utf8(from2), from_utf8(to2)));
559 bool Converters::formatIsUsed(string const & format)
561 ConverterList::const_iterator cit = converterlist_.begin();
562 ConverterList::const_iterator end = converterlist_.end();
563 for (; cit != end; ++cit) {
564 if (cit->from == format || cit->to == format)
571 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
572 FileName const & filename, ErrorList & errorList)
574 OutputParams runparams(0);
575 runparams.flavor = OutputParams::LATEX;
576 LaTeX latex("", runparams, filename);
578 int const result = latex.scanLogFile(terr);
580 if (result & LaTeX::ERRORS)
581 buffer.bufferErrors(terr, errorList);
590 : public boost::signals::trackable {
592 ShowMessage(Buffer const & b) : buffer_(b) {}
593 void operator()(docstring const & msg) const { buffer_.message(msg); }
595 Buffer const & buffer_;
601 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
602 OutputParams const & runparams, ErrorList & errorList)
604 buffer.setBusy(true);
605 buffer.message(_("Running LaTeX..."));
607 runparams.document_language = buffer.params().language->babel();
609 // do the LaTeX run(s)
610 string const name = buffer.latexName();
611 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
613 ShowMessage show(buffer);
614 latex.message.connect(show);
615 int const result = latex.run(terr);
617 if (result & LaTeX::ERRORS)
618 buffer.bufferErrors(terr, errorList);
620 // check return value from latex.run().
621 if ((result & LaTeX::NO_LOGFILE)) {
622 docstring const str =
623 bformat(_("LaTeX did not run successfully. "
624 "Additionally, LyX could not locate "
625 "the LaTeX log %1$s."), from_utf8(name));
626 Alert::error(_("LaTeX failed"), str);
627 } else if (result & LaTeX::NO_OUTPUT) {
628 Alert::warning(_("Output is empty"),
629 _("An empty output file was generated."));
633 buffer.setBusy(false);
635 int const ERROR_MASK =
640 return (result & ERROR_MASK) == 0;
646 void Converters::buildGraph()
648 G_.init(formats.size());
649 ConverterList::iterator beg = converterlist_.begin();
650 ConverterList::iterator const end = converterlist_.end();
651 for (ConverterList::iterator it = beg; it != end ; ++it) {
652 int const s = formats.getNumber(it->from);
653 int const t = formats.getNumber(it->to);
659 std::vector<Format const *> const
660 Converters::intToFormat(std::vector<int> const & input)
662 vector<Format const *> result(input.size());
664 vector<int>::const_iterator it = input.begin();
665 vector<int>::const_iterator const end = input.end();
666 vector<Format const *>::iterator rit = result.begin();
667 for ( ; it != end; ++it, ++rit) {
668 *rit = &formats.get(*it);
674 vector<Format const *> const
675 Converters::getReachableTo(string const & target, bool const clear_visited)
677 vector<int> const & reachablesto =
678 G_.getReachableTo(formats.getNumber(target), clear_visited);
680 return intToFormat(reachablesto);
684 vector<Format const *> const
685 Converters::getReachable(string const & from, bool const only_viewable,
686 bool const clear_visited)
688 vector<int> const & reachables =
689 G_.getReachable(formats.getNumber(from),
693 return intToFormat(reachables);
697 bool Converters::isReachable(string const & from, string const & to)
699 return G_.isReachable(formats.getNumber(from),
700 formats.getNumber(to));
704 Graph::EdgePath Converters::getPath(string const & from, string const & to)
706 return G_.getPath(formats.getNumber(from),
707 formats.getNumber(to));
711 vector<Format const *> Converters::importableFormats()
713 vector<string> l = loaders();
714 vector<Format const *> result = getReachableTo(l[0], true);
715 for (vector<string>::const_iterator it = l.begin() + 1;
716 it != l.end(); ++it) {
717 vector<Format const *> r = getReachableTo(*it, false);
718 result.insert(result.end(), r.begin(), r.end());
724 vector<string> Converters::loaders() const
729 v.push_back("textparagraph");