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"
19 #include "ErrorList.h"
25 #include "frontends/alert.h"
27 #include "support/debug.h"
28 #include "support/FileNameList.h"
29 #include "support/filetools.h"
30 #include "support/FileZipListDir.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33 #include "support/lyxlib.h"
34 #include "support/os.h"
35 #include "support/Package.h"
36 #include "support/Path.h"
37 #include "support/Systemcall.h"
40 using namespace lyx::support;
44 namespace Alert = lyx::frontend::Alert;
49 string const token_from("$$i");
50 string const token_base("$$b");
51 string const token_to("$$o");
52 string const token_path("$$p");
56 string const add_options(string const & command, string const & options)
59 string const tail = split(command, head, ' ');
60 return head + ' ' + options + ' ' + tail;
64 string const dvipdfm_options(BufferParams const & bp)
68 if (bp.papersize != PAPER_CUSTOM) {
69 string const paper_size = bp.paperSizeName();
70 if (paper_size != "b5" && paper_size != "foolscap")
71 result = "-p "+ paper_size;
73 if (bp.orientation == ORIENTATION_LANDSCAPE)
81 class ConverterEqual {
83 ConverterEqual(string const & from, string const & to)
84 : from_(from), to_(to) {}
85 bool operator()(Converter const & c) const {
86 return c.from == from_ && c.to == to_;
96 Converter::Converter(string const & f, string const & t,
97 string const & c, string const & l)
98 : from(f), to(t), command(c), flags(l),
99 From(0), To(0), latex(false), xml(false),
104 void Converter::readFlags()
106 string flag_list(flags);
107 while (!flag_list.empty()) {
108 string flag_name, flag_value;
109 flag_list = split(flag_list, flag_value, ',');
110 flag_value = split(flag_value, flag_name, '=');
111 if (flag_name == "latex")
113 else if (flag_name == "xml")
115 else if (flag_name == "needaux")
117 else if (flag_name == "resultdir")
118 result_dir = (flag_value.empty())
119 ? token_base : flag_value;
120 else if (flag_name == "resultfile")
121 result_file = flag_value;
122 else if (flag_name == "parselog")
123 parselog = flag_value;
125 if (!result_dir.empty() && result_file.empty())
126 result_file = "index." + formats.extension(to);
127 //if (!contains(command, token_from))
132 bool operator<(Converter const & a, Converter const & b)
134 // use the compare_ascii_no_case instead of compare_no_case,
135 // because in turkish, 'i' is not the lowercase version of 'I',
136 // and thus turkish locale breaks parsing of tags.
137 int const i = compare_ascii_no_case(a.From->prettyname(),
138 b.From->prettyname());
140 return compare_ascii_no_case(a.To->prettyname(),
141 b.To->prettyname()) < 0;
147 Converter const * Converters::getConverter(string const & from,
148 string const & to) const
150 ConverterList::const_iterator const cit =
151 find_if(converterlist_.begin(), converterlist_.end(),
152 ConverterEqual(from, to));
153 if (cit != converterlist_.end())
160 int Converters::getNumber(string const & from, string const & to) const
162 ConverterList::const_iterator const cit =
163 find_if(converterlist_.begin(), converterlist_.end(),
164 ConverterEqual(from, to));
165 if (cit != converterlist_.end())
166 return distance(converterlist_.begin(), cit);
172 void Converters::add(string const & from, string const & to,
173 string const & command, string const & flags)
177 ConverterList::iterator it = find_if(converterlist_.begin(),
178 converterlist_.end(),
179 ConverterEqual(from , to));
181 Converter converter(from, to, command, flags);
182 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
184 converter.command = command;
185 converter.flags = flags;
187 converter.readFlags();
189 if (converter.latex && (latex_command_.empty() || to == "dvi"))
190 latex_command_ = subst(command, token_from, "");
191 // If we have both latex & pdflatex, we set latex_command to latex.
192 // The latex_command is used to update the .aux file when running
193 // a converter that uses it.
195 if (it == converterlist_.end()) {
196 converterlist_.push_back(converter);
198 converter.From = it->From;
199 converter.To = it->To;
205 void Converters::erase(string const & from, string const & to)
207 ConverterList::iterator const it =
208 find_if(converterlist_.begin(),
209 converterlist_.end(),
210 ConverterEqual(from, to));
211 if (it != converterlist_.end())
212 converterlist_.erase(it);
216 // This method updates the pointers From and To in all the converters.
217 // The code is not very efficient, but it doesn't matter as the number
218 // of formats and converters is small.
219 // Furthermore, this method is called only on startup, or after
220 // adding/deleting a format in FormPreferences (the latter calls can be
221 // eliminated if the formats in the Formats class are stored using a map or
222 // a list (instead of a vector), but this will cause other problems).
223 void Converters::update(Formats const & formats)
225 ConverterList::iterator it = converterlist_.begin();
226 ConverterList::iterator end = converterlist_.end();
227 for (; it != end; ++it) {
228 it->From = formats.getFormat(it->from);
229 it->To = formats.getFormat(it->to);
234 // This method updates the pointers From and To in the last converter.
235 // It is called when adding a new converter in FormPreferences
236 void Converters::updateLast(Formats const & formats)
238 if (converterlist_.begin() != converterlist_.end()) {
239 ConverterList::iterator it = converterlist_.end() - 1;
240 it->From = formats.getFormat(it->from);
241 it->To = formats.getFormat(it->to);
246 void Converters::sort()
248 std::sort(converterlist_.begin(), converterlist_.end());
252 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
254 for (Graph::EdgePath::const_iterator cit = path.begin();
255 cit != path.end(); ++cit) {
256 Converter const & conv = converterlist_[*cit];
258 if (contains(conv.to, "pdf"))
259 return OutputParams::PDFLATEX;
261 return OutputParams::XML;
263 return OutputParams::LATEX;
267 bool Converters::convert(Buffer const * buffer,
268 FileName const & from_file, FileName const & to_file,
269 FileName const & orig_from,
270 string const & from_format, string const & to_format,
271 ErrorList & errorList, int conversionflags)
273 if (from_format == to_format)
274 return move(from_format, from_file, to_file, false);
276 if ((conversionflags & try_cache) &&
277 ConverterCache::get().inCache(orig_from, to_format))
278 return ConverterCache::get().copy(orig_from, to_format, to_file);
280 Graph::EdgePath edgepath = getPath(from_format, to_format);
281 if (edgepath.empty()) {
282 if (conversionflags & try_default) {
283 // if no special converter defined, then we take the
284 // default one from ImageMagic.
285 string const from_ext = from_format.empty() ?
286 getExtension(from_file.absFilename()) :
287 formats.extension(from_format);
288 string const to_ext = formats.extension(to_format);
289 string const command =
290 support::os::python() + ' ' +
291 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
293 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
295 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
296 LYXERR(Debug::FILES, "No converter defined! "
297 "I use convertDefault.py:\n\t" << command);
299 one.startscript(Systemcall::Wait, command);
300 if (to_file.isReadableFile()) {
301 if (conversionflags & try_cache)
302 ConverterCache::get().add(orig_from,
307 Alert::error(_("Cannot convert file"),
308 bformat(_("No information for converting %1$s "
309 "format files to %2$s.\n"
310 "Define a converter in the preferences."),
311 from_ascii(from_format), from_ascii(to_format)));
315 // buffer is only invalid for importing, and then runparams is not
317 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
318 runparams.flavor = getFlavor(edgepath);
320 // Some converters (e.g. lilypond) can only output files to the
321 // current directory, so we need to change the current directory.
322 // This has the added benefit that all other files that may be
323 // generated by the converter are deleted when LyX closes and do not
324 // clutter the real working directory.
325 string const path(onlyPath(from_file.absFilename()));
326 // Prevent the compiler from optimizing away p
328 support::PathChanger p(pp);
330 // empty the error list before any new conversion takes place.
333 bool run_latex = false;
334 string from_base = changeExtension(from_file.absFilename(), "");
335 string to_base = changeExtension(to_file.absFilename(), "");
337 FileName outfile = from_file;
338 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
339 cit != edgepath.end(); ++cit) {
340 Converter const & conv = converterlist_[*cit];
341 bool dummy = conv.To->dummy() && conv.to != "program";
343 LYXERR(Debug::FILES, "Converting from "
344 << conv.from << " to " << conv.to);
347 outfile = FileName(conv.result_dir.empty()
348 ? changeExtension(from_file.absFilename(), conv.To->extension())
349 : addName(subst(conv.result_dir,
350 token_base, from_base),
351 subst(conv.result_file,
352 token_base, onlyFilename(from_base))));
354 // if input and output files are equal, we use a
355 // temporary file as intermediary (JMarc)
356 FileName real_outfile;
357 if (outfile == infile) {
358 real_outfile = infile;
359 // when importing, a buffer does not necessarily exist
361 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
363 outfile = FileName(addName(package().temp_dir().absFilename(),
369 string const command = subst(conv.command, token_from, "");
370 LYXERR(Debug::FILES, "Running " << command);
371 if (!runLaTeX(*buffer, command, runparams, errorList))
374 if (conv.need_aux && !run_latex
375 && !latex_command_.empty()) {
376 LYXERR(Debug::FILES, "Running " << latex_command_
377 << " to update aux file");
378 runLaTeX(*buffer, latex_command_, runparams, errorList);
382 string const infile2 =
383 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
384 string const outfile2 =
385 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
387 string command = conv.command;
388 command = subst(command, token_from, quoteName(infile2));
389 command = subst(command, token_base, quoteName(from_base));
390 command = subst(command, token_to, quoteName(outfile2));
391 command = libScriptSearch(command);
393 if (!conv.parselog.empty())
394 command += " 2> " + quoteName(infile2 + ".out");
396 if (conv.from == "dvi" && conv.to == "ps")
397 command = add_options(command,
398 buffer->params().dvips_options());
399 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
400 command = add_options(command,
401 dvipdfm_options(buffer->params()));
403 LYXERR(Debug::FILES, "Calling " << command);
405 buffer->message(_("Executing command: ")
406 + from_utf8(command));
411 res = one.startscript(Systemcall::DontWait,
412 to_filesystem8bit(from_utf8(command)));
413 // We're not waiting for the result, so we can't do anything
416 res = one.startscript(Systemcall::Wait,
417 to_filesystem8bit(from_utf8(command)));
418 if (!real_outfile.empty()) {
419 Mover const & mover = getMover(conv.to);
420 if (!mover.rename(outfile, real_outfile))
423 LYXERR(Debug::FILES, "renaming file " << outfile
424 << " to " << real_outfile);
425 // Finally, don't forget to tell any future
426 // converters to use the renamed file...
427 outfile = real_outfile;
430 if (!conv.parselog.empty()) {
431 string const logfile = infile2 + ".log";
432 string const script = libScriptSearch(conv.parselog);
433 string const command2 = script +
434 " < " + quoteName(infile2 + ".out") +
435 " > " + quoteName(logfile);
436 one.startscript(Systemcall::Wait,
437 to_filesystem8bit(from_utf8(command2)));
438 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
444 if (conv.to == "program") {
445 Alert::error(_("Build errors"),
446 _("There were errors during the build process."));
448 // FIXME: this should go out of here. For example, here we cannot say if
449 // it is a document (.lyx) or something else. Same goes for elsewhere.
450 Alert::error(_("Cannot convert file"),
451 bformat(_("An error occurred whilst running %1$s"),
452 from_utf8(command.substr(0, 50))));
459 Converter const & conv = converterlist_[edgepath.back()];
460 if (conv.To->dummy())
463 if (!conv.result_dir.empty()) {
464 // The converter has put the file(s) in a directory.
465 // In this case we ignore the given to_file.
466 if (from_base != to_base) {
467 string const from = subst(conv.result_dir,
468 token_base, from_base);
469 string const to = subst(conv.result_dir,
470 token_base, to_base);
471 Mover const & mover = getMover(conv.from);
472 if (!mover.rename(FileName(from), FileName(to))) {
473 Alert::error(_("Cannot convert file"),
474 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
475 from_utf8(from), from_utf8(to)));
481 if (conversionflags & try_cache)
482 ConverterCache::get().add(orig_from, to_format, outfile);
483 return move(conv.to, outfile, to_file, conv.latex);
488 bool Converters::move(string const & fmt,
489 FileName const & from, FileName const & to, bool copy)
494 bool no_errors = true;
495 string const path = onlyPath(from.absFilename());
496 string const base = onlyFilename(removeExtension(from.absFilename()));
497 string const to_base = removeExtension(to.absFilename());
498 string const to_extension = getExtension(to.absFilename());
500 FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
501 for (FileNameList::const_iterator it = files.begin();
502 it != files.end(); ++it) {
503 string const from2 = it->absFilename();
504 string const file2 = onlyFilename(from2);
505 if (prefixIs(file2, base)) {
506 string const to2 = changeExtension(
507 to_base + file2.substr(base.length()),
509 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
511 Mover const & mover = getMover(fmt);
512 bool const moved = copy
513 ? mover.copy(*it, FileName(to2))
514 : mover.rename(*it, FileName(to2));
515 if (!moved && no_errors) {
516 Alert::error(_("Cannot convert file"),
518 _("Could not copy a temporary file from %1$s to %2$s.") :
519 _("Could not move a temporary file from %1$s to %2$s."),
520 from_utf8(from2), from_utf8(to2)));
529 bool Converters::formatIsUsed(string const & format)
531 ConverterList::const_iterator cit = converterlist_.begin();
532 ConverterList::const_iterator end = converterlist_.end();
533 for (; cit != end; ++cit) {
534 if (cit->from == format || cit->to == format)
541 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
542 FileName const & filename, ErrorList & errorList)
544 OutputParams runparams(0);
545 runparams.flavor = OutputParams::LATEX;
546 LaTeX latex("", runparams, filename);
548 int const result = latex.scanLogFile(terr);
550 if (result & LaTeX::ERRORS)
551 buffer.bufferErrors(terr, errorList);
560 : public boost::signals::trackable {
562 ShowMessage(Buffer const & b) : buffer_(b) {}
563 void operator()(docstring const & msg) const { buffer_.message(msg); }
565 Buffer const & buffer_;
571 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
572 OutputParams const & runparams, ErrorList & errorList)
574 buffer.setBusy(true);
575 buffer.message(_("Running LaTeX..."));
577 runparams.document_language = buffer.params().language->babel();
579 // do the LaTeX run(s)
580 string const name = buffer.latexName();
581 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
583 ShowMessage show(buffer);
584 latex.message.connect(show);
585 int const result = latex.run(terr);
587 if (result & LaTeX::ERRORS)
588 buffer.bufferErrors(terr, errorList);
590 // check return value from latex.run().
591 if ((result & LaTeX::NO_LOGFILE)) {
592 docstring const str =
593 bformat(_("LaTeX did not run successfully. "
594 "Additionally, LyX could not locate "
595 "the LaTeX log %1$s."), from_utf8(name));
596 Alert::error(_("LaTeX failed"), str);
597 } else if (result & LaTeX::NO_OUTPUT) {
598 Alert::warning(_("Output is empty"),
599 _("An empty output file was generated."));
603 buffer.setBusy(false);
605 int const ERROR_MASK =
610 return (result & ERROR_MASK) == 0;
616 void Converters::buildGraph()
618 G_.init(formats.size());
619 ConverterList::iterator beg = converterlist_.begin();
620 ConverterList::iterator const end = converterlist_.end();
621 for (ConverterList::iterator it = beg; it != end ; ++it) {
622 int const s = formats.getNumber(it->from);
623 int const t = formats.getNumber(it->to);
629 vector<Format const *> const
630 Converters::intToFormat(vector<int> const & input)
632 vector<Format const *> result(input.size());
634 vector<int>::const_iterator it = input.begin();
635 vector<int>::const_iterator const end = input.end();
636 vector<Format const *>::iterator rit = result.begin();
637 for ( ; it != end; ++it, ++rit) {
638 *rit = &formats.get(*it);
644 vector<Format const *> const
645 Converters::getReachableTo(string const & target, bool const clear_visited)
647 vector<int> const & reachablesto =
648 G_.getReachableTo(formats.getNumber(target), clear_visited);
650 return intToFormat(reachablesto);
654 vector<Format const *> const
655 Converters::getReachable(string const & from, bool const only_viewable,
656 bool const clear_visited)
658 vector<int> const & reachables =
659 G_.getReachable(formats.getNumber(from),
663 return intToFormat(reachables);
667 bool Converters::isReachable(string const & from, string const & to)
669 return G_.isReachable(formats.getNumber(from),
670 formats.getNumber(to));
674 Graph::EdgePath Converters::getPath(string const & from, string const & to)
676 return G_.getPath(formats.getNumber(from),
677 formats.getNumber(to));
681 vector<Format const *> Converters::importableFormats()
683 vector<string> l = loaders();
684 vector<Format const *> result = getReachableTo(l[0], true);
685 for (vector<string>::const_iterator it = l.begin() + 1;
686 it != l.end(); ++it) {
687 vector<Format const *> r = getReachableTo(*it, false);
688 result.insert(result.end(), r.begin(), r.end());
694 vector<string> Converters::loaders() const
699 v.push_back("textparagraph");