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"
16 #include "buffer_funcs.h"
17 #include "BufferParams.h"
18 #include "ConverterCache.h"
20 #include "ErrorList.h"
26 #include "frontends/alert.h"
28 #include "support/debug.h"
29 #include "support/FileNameList.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33 #include "support/os.h"
34 #include "support/Package.h"
35 #include "support/Path.h"
36 #include "support/Systemcall.h"
39 using namespace lyx::support;
43 namespace Alert = lyx::frontend::Alert;
48 string const token_from("$$i");
49 string const token_base("$$b");
50 string const token_to("$$o");
51 string const token_path("$$p");
52 string const token_orig_path("$$r");
53 string const token_encoding("$$e");
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(BufferParams::DVIPDFM);
70 if (!paper_size.empty())
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.from, "xetex"))
259 return OutputParams::XETEX;
260 if (contains(conv.to, "pdf"))
261 return OutputParams::PDFLATEX;
263 return OutputParams::XML;
265 return OutputParams::LATEX;
269 bool Converters::convert(Buffer const * buffer,
270 FileName const & from_file, FileName const & to_file,
271 FileName const & orig_from,
272 string const & from_format, string const & to_format,
273 ErrorList & errorList, int conversionflags)
275 if (from_format == to_format)
276 return move(from_format, from_file, to_file, false);
278 if ((conversionflags & try_cache) &&
279 ConverterCache::get().inCache(orig_from, to_format))
280 return ConverterCache::get().copy(orig_from, to_format, to_file);
282 Graph::EdgePath edgepath = getPath(from_format, to_format);
283 if (edgepath.empty()) {
284 if (conversionflags & try_default) {
285 // if no special converter defined, then we take the
286 // default one from ImageMagic.
287 string const from_ext = from_format.empty() ?
288 getExtension(from_file.absFileName()) :
289 formats.extension(from_format);
290 string const to_ext = formats.extension(to_format);
291 string const command =
293 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
295 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
297 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
298 LYXERR(Debug::FILES, "No converter defined! "
299 "I use convertDefault.py:\n\t" << command);
301 one.startscript(Systemcall::Wait, command);
302 if (to_file.isReadableFile()) {
303 if (conversionflags & try_cache)
304 ConverterCache::get().add(orig_from,
310 // only warn once per session and per file type
311 static std::map<string, string> warned;
312 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
315 warned.insert(make_pair(from_format, to_format));
317 Alert::error(_("Cannot convert file"),
318 bformat(_("No information for converting %1$s "
319 "format files to %2$s.\n"
320 "Define a converter in the preferences."),
321 from_ascii(from_format), from_ascii(to_format)));
325 // buffer is only invalid for importing, and then runparams is not
327 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
328 runparams.flavor = getFlavor(edgepath);
331 runparams.use_japanese = buffer->bufferFormat() == "platex";
332 runparams.use_indices = buffer->params().use_indices;
333 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
334 string() : buffer->params().bibtex_command;
335 runparams.index_command = (buffer->params().index_command == "default") ?
336 string() : buffer->params().index_command;
339 // Some converters (e.g. lilypond) can only output files to the
340 // current directory, so we need to change the current directory.
341 // This has the added benefit that all other files that may be
342 // generated by the converter are deleted when LyX closes and do not
343 // clutter the real working directory.
344 string const path(onlyPath(from_file.absFileName()));
345 // Prevent the compiler from optimizing away p
349 // empty the error list before any new conversion takes place.
352 bool run_latex = false;
353 string from_base = changeExtension(from_file.absFileName(), "");
354 string to_base = changeExtension(to_file.absFileName(), "");
356 FileName outfile = from_file;
357 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
358 cit != edgepath.end(); ++cit) {
359 Converter const & conv = converterlist_[*cit];
360 bool dummy = conv.To->dummy() && conv.to != "program";
362 LYXERR(Debug::FILES, "Converting from "
363 << conv.from << " to " << conv.to);
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 // when importing, a buffer does not necessarily exist
380 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
382 outfile = FileName(addName(package().temp_dir().absFileName(),
388 string const command = subst(conv.command, token_from, "");
389 LYXERR(Debug::FILES, "Running " << command);
390 if (!runLaTeX(*buffer, command, runparams, errorList))
393 if (conv.need_aux && !run_latex
394 && !latex_command_.empty()) {
395 LYXERR(Debug::FILES, "Running " << latex_command_
396 << " to update aux file");
397 runLaTeX(*buffer, latex_command_, runparams, errorList);
401 string const infile2 =
402 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
403 string const outfile2 =
404 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
406 string command = conv.command;
407 command = subst(command, token_from, quoteName(infile2));
408 command = subst(command, token_base, quoteName(from_base));
409 command = subst(command, token_to, quoteName(outfile2));
410 command = subst(command, token_path, quoteName(infile.onlyPath().absFileName()));
411 command = subst(command, token_orig_path, quoteName(orig_from.onlyPath().absFileName()));
412 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
413 command = libScriptSearch(command);
415 if (!conv.parselog.empty())
416 command += " 2> " + quoteName(infile2 + ".out");
418 if (conv.from == "dvi" && conv.to == "ps")
419 command = add_options(command,
420 buffer->params().dvips_options());
421 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
422 command = add_options(command,
423 dvipdfm_options(buffer->params()));
425 LYXERR(Debug::FILES, "Calling " << command);
427 buffer->message(_("Executing command: ")
428 + from_utf8(command));
433 res = one.startscript(Systemcall::DontWait,
434 to_filesystem8bit(from_utf8(command)));
435 // We're not waiting for the result, so we can't do anything
438 res = one.startscript(Systemcall::Wait,
439 to_filesystem8bit(from_utf8(command)));
440 if (!real_outfile.empty()) {
441 Mover const & mover = getMover(conv.to);
442 if (!mover.rename(outfile, real_outfile))
445 LYXERR(Debug::FILES, "renaming file " << outfile
446 << " to " << real_outfile);
447 // Finally, don't forget to tell any future
448 // converters to use the renamed file...
449 outfile = real_outfile;
452 if (!conv.parselog.empty()) {
453 string const logfile = infile2 + ".log";
454 string const script = libScriptSearch(conv.parselog);
455 string const command2 = script +
456 " < " + quoteName(infile2 + ".out") +
457 " > " + quoteName(logfile);
458 one.startscript(Systemcall::Wait,
459 to_filesystem8bit(from_utf8(command2)));
460 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
466 if (conv.to == "program") {
467 Alert::error(_("Build errors"),
468 _("There were errors during the build process."));
470 // FIXME: this should go out of here. For example, here we cannot say if
471 // it is a document (.lyx) or something else. Same goes for elsewhere.
472 Alert::error(_("Cannot convert file"),
473 bformat(_("An error occurred whilst running %1$s"),
474 from_utf8(command.substr(0, 50))));
481 Converter const & conv = converterlist_[edgepath.back()];
482 if (conv.To->dummy())
485 if (!conv.result_dir.empty()) {
486 // The converter has put the file(s) in a directory.
487 // In this case we ignore the given to_file.
488 if (from_base != to_base) {
489 string const from = subst(conv.result_dir,
490 token_base, from_base);
491 string const to = subst(conv.result_dir,
492 token_base, to_base);
493 Mover const & mover = getMover(conv.from);
494 if (!mover.rename(FileName(from), FileName(to))) {
495 Alert::error(_("Cannot convert file"),
496 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
497 from_utf8(from), from_utf8(to)));
503 if (conversionflags & try_cache)
504 ConverterCache::get().add(orig_from, to_format, outfile);
505 return move(conv.to, outfile, to_file, conv.latex);
510 bool Converters::move(string const & fmt,
511 FileName const & from, FileName const & to, bool copy)
516 bool no_errors = true;
517 string const path = onlyPath(from.absFileName());
518 string const base = onlyFileName(removeExtension(from.absFileName()));
519 string const to_base = removeExtension(to.absFileName());
520 string const to_extension = getExtension(to.absFileName());
522 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
523 for (support::FileNameList::const_iterator it = files.begin();
524 it != files.end(); ++it) {
525 string const from2 = it->absFileName();
526 string const file2 = onlyFileName(from2);
527 if (prefixIs(file2, base)) {
528 string const to2 = changeExtension(
529 to_base + file2.substr(base.length()),
531 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
533 Mover const & mover = getMover(fmt);
534 bool const moved = copy
535 ? mover.copy(*it, FileName(to2))
536 : mover.rename(*it, FileName(to2));
537 if (!moved && no_errors) {
538 Alert::error(_("Cannot convert file"),
540 _("Could not copy a temporary file from %1$s to %2$s.") :
541 _("Could not move a temporary file from %1$s to %2$s."),
542 from_utf8(from2), from_utf8(to2)));
551 bool Converters::formatIsUsed(string const & format)
553 ConverterList::const_iterator cit = converterlist_.begin();
554 ConverterList::const_iterator end = converterlist_.end();
555 for (; cit != end; ++cit) {
556 if (cit->from == format || cit->to == format)
563 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
564 FileName const & filename, ErrorList & errorList)
566 OutputParams runparams(0);
567 runparams.flavor = OutputParams::LATEX;
568 LaTeX latex("", runparams, filename);
570 int const result = latex.scanLogFile(terr);
572 if (result & LaTeX::ERRORS)
573 buffer.bufferErrors(terr, errorList);
582 : public boost::signals::trackable {
584 ShowMessage(Buffer const & b) : buffer_(b) {}
585 void operator()(docstring const & msg) const { buffer_.message(msg); }
587 Buffer const & buffer_;
593 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
594 OutputParams const & runparams, ErrorList & errorList)
596 buffer.setBusy(true);
597 buffer.message(_("Running LaTeX..."));
599 runparams.document_language = buffer.params().language->babel();
601 // do the LaTeX run(s)
602 string const name = buffer.latexName();
603 LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
605 ShowMessage show(buffer);
606 latex.message.connect(show);
607 int const result = latex.run(terr);
609 if (result & LaTeX::ERRORS)
610 buffer.bufferErrors(terr, errorList);
612 // check return value from latex.run().
613 if ((result & LaTeX::NO_LOGFILE) && !buffer.isClone()) {
614 docstring const str =
615 bformat(_("LaTeX did not run successfully. "
616 "Additionally, LyX could not locate "
617 "the LaTeX log %1$s."), from_utf8(name));
618 Alert::error(_("LaTeX failed"), str);
619 } else if ((result & LaTeX::NO_OUTPUT) && !buffer.isClone()) {
620 Alert::warning(_("Output is empty"),
621 _("An empty output file was generated."));
625 buffer.setBusy(false);
627 int const ERROR_MASK =
632 return (result & ERROR_MASK) == 0;
638 void Converters::buildGraph()
640 // clear graph's data structures
641 G_.init(formats.size());
642 // each of the converters knows how to convert one format to another
643 // so, for each of them, we create an arrow on the graph, going from
644 // the one to the other
645 ConverterList::iterator it = converterlist_.begin();
646 ConverterList::iterator const end = converterlist_.end();
647 for (; it != end ; ++it) {
648 int const from = formats.getNumber(it->from);
649 int const to = formats.getNumber(it->to);
650 G_.addEdge(from, to);
655 vector<Format const *> const
656 Converters::intToFormat(vector<int> const & input)
658 vector<Format const *> result(input.size());
660 vector<int>::const_iterator it = input.begin();
661 vector<int>::const_iterator const end = input.end();
662 vector<Format const *>::iterator rit = result.begin();
663 for ( ; it != end; ++it, ++rit) {
664 *rit = &formats.get(*it);
670 vector<Format const *> const
671 Converters::getReachableTo(string const & target, bool const clear_visited)
673 vector<int> const & reachablesto =
674 G_.getReachableTo(formats.getNumber(target), clear_visited);
676 return intToFormat(reachablesto);
680 vector<Format const *> const
681 Converters::getReachable(string const & from, bool const only_viewable,
682 bool const clear_visited)
684 vector<int> const & reachables =
685 G_.getReachable(formats.getNumber(from),
689 return intToFormat(reachables);
693 bool Converters::isReachable(string const & from, string const & to)
695 return G_.isReachable(formats.getNumber(from),
696 formats.getNumber(to));
700 Graph::EdgePath Converters::getPath(string const & from, string const & to)
702 return G_.getPath(formats.getNumber(from),
703 formats.getNumber(to));
707 vector<Format const *> Converters::importableFormats()
709 vector<string> l = loaders();
710 vector<Format const *> result = getReachableTo(l[0], true);
711 for (vector<string>::const_iterator it = l.begin() + 1;
712 it != l.end(); ++it) {
713 vector<Format const *> r = getReachableTo(*it, false);
714 result.insert(result.end(), r.begin(), r.end());
720 vector<Format const *> Converters::exportableFormats(bool only_viewable)
722 vector<string> s = savers();
723 vector<Format const *> result = getReachable(s[0], only_viewable, true);
724 for (vector<string>::const_iterator it = s.begin() + 1;
725 it != s.end(); ++it) {
726 vector<Format const *> r =
727 getReachable(*it, only_viewable, false);
728 result.insert(result.end(), r.begin(), r.end());
734 vector<string> Converters::loaders() const
739 v.push_back("textparagraph");
744 vector<string> Converters::savers() const
747 v.push_back("docbook");
748 v.push_back("latex");
749 v.push_back("literate");
751 v.push_back("xhtml");
752 v.push_back("pdflatex");
753 v.push_back("platex");
755 v.push_back("xetex");