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"
25 #include "frontends/Alert.h"
27 #include "support/filetools.h"
28 #include "support/lyxlib.h"
29 #include "support/os.h"
30 #include "support/path.h"
31 #include "support/systemcall.h"
33 using lyx::support::addName;
34 using lyx::support::bformat;
35 using lyx::support::changeExtension;
36 using lyx::support::compare_ascii_no_case;
37 using lyx::support::contains;
38 using lyx::support::dirList;
39 using lyx::support::getExtension;
40 using lyx::support::isFileReadable;
41 using lyx::support::libFileSearch;
42 using lyx::support::libScriptSearch;
43 using lyx::support::makeRelPath;
44 using lyx::support::onlyFilename;
45 using lyx::support::onlyPath;
46 using lyx::support::Path;
47 using lyx::support::prefixIs;
48 using lyx::support::quoteName;
49 using lyx::support::split;
50 using lyx::support::subst;
51 using lyx::support::Systemcall;
61 namespace Alert = lyx::frontend::Alert;
66 string const token_from("$$i");
67 string const token_base("$$b");
68 string const token_to("$$o");
69 string const token_path("$$p");
73 string const add_options(string const & command, string const & options)
76 string const tail = split(command, head, ' ');
77 return head + ' ' + options + ' ' + tail;
81 string const dvipdfm_options(BufferParams const & bp)
85 if (bp.papersize != PAPER_CUSTOM) {
86 string const paper_size = bp.paperSizeName();
87 if (paper_size != "b5" && paper_size != "foolscap")
88 result = "-p "+ paper_size;
90 if (bp.orientation == ORIENTATION_LANDSCAPE)
98 class ConverterEqual : public std::binary_function<string, string, bool> {
100 ConverterEqual(string const & from, string const & to)
101 : from_(from), to_(to) {}
102 bool operator()(Converter const & c) const {
103 return c.from == from_ && c.to == to_;
113 Converter::Converter(string const & f, string const & t,
114 string const & c, string const & l)
115 : from(f), to(t), command(c), flags(l),
116 From(0), To(0), latex(false), xml(false),
117 original_dir(false), need_aux(false)
121 void Converter::readFlags()
123 string flag_list(flags);
124 while (!flag_list.empty()) {
125 string flag_name, flag_value;
126 flag_list = split(flag_list, flag_value, ',');
127 flag_value = split(flag_value, flag_name, '=');
128 if (flag_name == "latex")
130 else if (flag_name == "xml")
132 else if (flag_name == "originaldir")
134 else if (flag_name == "needaux")
136 else if (flag_name == "resultdir")
137 result_dir = (flag_value.empty())
138 ? token_base : flag_value;
139 else if (flag_name == "resultfile")
140 result_file = flag_value;
141 else if (flag_name == "parselog")
142 parselog = flag_value;
144 if (!result_dir.empty() && result_file.empty())
145 result_file = "index." + formats.extension(to);
146 //if (!contains(command, token_from))
151 bool operator<(Converter const & a, Converter const & b)
153 // use the compare_ascii_no_case instead of compare_no_case,
154 // because in turkish, 'i' is not the lowercase version of 'I',
155 // and thus turkish locale breaks parsing of tags.
156 int const i = compare_ascii_no_case(a.From->prettyname(),
157 b.From->prettyname());
159 return compare_ascii_no_case(a.To->prettyname(),
160 b.To->prettyname()) < 0;
166 Converter const * Converters::getConverter(string const & from,
167 string const & to) const
169 ConverterList::const_iterator const cit =
170 find_if(converterlist_.begin(), converterlist_.end(),
171 ConverterEqual(from, to));
172 if (cit != converterlist_.end())
179 int Converters::getNumber(string const & from, string const & to) const
181 ConverterList::const_iterator const cit =
182 find_if(converterlist_.begin(), converterlist_.end(),
183 ConverterEqual(from, to));
184 if (cit != converterlist_.end())
185 return distance(converterlist_.begin(), cit);
191 void Converters::add(string const & from, string const & to,
192 string const & command, string const & flags)
196 ConverterList::iterator it = find_if(converterlist_.begin(),
197 converterlist_.end(),
198 ConverterEqual(from , to));
200 Converter converter(from, to, command, flags);
201 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
203 converter.command = command;
204 converter.flags = flags;
206 converter.readFlags();
208 if (converter.latex && (latex_command_.empty() || to == "dvi"))
209 latex_command_ = subst(command, token_from, "");
210 // If we have both latex & pdflatex, we set latex_command to latex.
211 // The latex_command is used to update the .aux file when running
212 // a converter that uses it.
214 if (it == converterlist_.end()) {
215 converterlist_.push_back(converter);
217 converter.From = it->From;
218 converter.To = it->To;
224 void Converters::erase(string const & from, string const & to)
226 ConverterList::iterator const it =
227 find_if(converterlist_.begin(),
228 converterlist_.end(),
229 ConverterEqual(from, to));
230 if (it != converterlist_.end())
231 converterlist_.erase(it);
235 // This method updates the pointers From and To in all the converters.
236 // The code is not very efficient, but it doesn't matter as the number
237 // of formats and converters is small.
238 // Furthermore, this method is called only on startup, or after
239 // adding/deleting a format in FormPreferences (the latter calls can be
240 // eliminated if the formats in the Formats class are stored using a map or
241 // a list (instead of a vector), but this will cause other problems).
242 void Converters::update(Formats const & formats)
244 ConverterList::iterator it = converterlist_.begin();
245 ConverterList::iterator end = converterlist_.end();
246 for (; it != end; ++it) {
247 it->From = formats.getFormat(it->from);
248 it->To = formats.getFormat(it->to);
253 // This method updates the pointers From and To in the last converter.
254 // It is called when adding a new converter in FormPreferences
255 void Converters::updateLast(Formats const & formats)
257 if (converterlist_.begin() != converterlist_.end()) {
258 ConverterList::iterator it = converterlist_.end() - 1;
259 it->From = formats.getFormat(it->from);
260 it->To = formats.getFormat(it->to);
265 void Converters::sort()
267 std::sort(converterlist_.begin(), converterlist_.end());
271 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
273 for (Graph::EdgePath::const_iterator cit = path.begin();
274 cit != path.end(); ++cit) {
275 Converter const & conv = converterlist_[*cit];
277 if (contains(conv.to, "pdf"))
278 return OutputParams::PDFLATEX;
280 return OutputParams::XML;
282 return OutputParams::LATEX;
286 bool Converters::convert(Buffer const * buffer,
287 string const & from_file, string const & to_file_base,
288 string const & from_format, string const & to_format,
289 string & to_file, ErrorList & errorList, bool try_default)
291 string const to_ext = formats.extension(to_format);
292 to_file = changeExtension(to_file_base, to_ext);
294 if (from_format == to_format)
295 return move(from_format, from_file, to_file, false);
297 Graph::EdgePath edgepath = getPath(from_format, to_format);
298 if (edgepath.empty()) {
300 // if no special converter defined, then we take the
301 // default one from ImageMagic.
302 string const from_ext = from_format.empty() ?
303 getExtension(from_file) :
304 formats.extension(from_format);
305 string const command =
306 lyx::support::os::python() + ' ' +
307 quoteName(libFileSearch("scripts", "convertDefault.py")) +
309 quoteName(from_ext + ':' + from_file) +
311 quoteName(to_ext + ':' + to_file);
313 << "No converter defined! "
314 "I use convertDefault.py:\n\t"
317 one.startscript(Systemcall::Wait, command);
318 if (isFileReadable(to_file)) {
322 Alert::error(_("Cannot convert file"),
323 bformat(_("No information for converting %1$s "
324 "format files to %2$s.\n"
325 "Define a converter in the preferences."),
326 lyx::from_ascii(from_format), lyx::from_ascii(to_format)));
329 OutputParams runparams;
330 runparams.flavor = getFlavor(edgepath);
332 // Some converters (e.g. lilypond) can only output files to the
333 // current directory, so we need to change the current directory.
334 // This has the added benefit that all other files that may be
335 // generated by the converter are deleted when LyX closes and do not
336 // clutter the real working directory.
337 string path = onlyPath(from_file);
340 // empty the error list before any new conversion takes place.
343 bool run_latex = false;
344 string from_base = changeExtension(from_file, "");
345 string to_base = changeExtension(to_file, "");
347 string outfile = from_file;
348 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
349 cit != edgepath.end(); ++cit) {
350 Converter const & conv = converterlist_[*cit];
351 bool dummy = conv.To->dummy() && conv.to != "program";
353 lyxerr[Debug::FILES] << "Converting from "
354 << conv.from << " to " << conv.to << endl;
356 outfile = conv.result_dir.empty()
357 ? changeExtension(from_file, conv.To->extension())
358 : addName(subst(conv.result_dir,
359 token_base, from_base),
360 subst(conv.result_file,
361 token_base, onlyFilename(from_base)));
363 // if input and output files are equal, we use a
364 // temporary file as intermediary (JMarc)
366 if (outfile == infile) {
367 real_outfile = infile;
368 outfile = addName(buffer->temppath(), "tmpfile.out");
373 string const command = subst(conv.command, token_from, "");
374 lyxerr[Debug::FILES] << "Running " << command << endl;
375 if (!runLaTeX(*buffer, command, runparams, errorList))
378 if (conv.need_aux && !run_latex
379 && !latex_command_.empty()) {
381 << "Running " << latex_command_
382 << " to update aux file"<< endl;
383 runLaTeX(*buffer, latex_command_, runparams, errorList);
386 string const infile2 = (conv.original_dir)
387 ? infile : makeRelPath(infile, path);
388 string const outfile2 = (conv.original_dir)
389 ? outfile : makeRelPath(outfile, path);
391 string command = conv.command;
392 command = subst(command, token_from, quoteName(infile2));
393 command = subst(command, token_base, quoteName(from_base));
394 command = subst(command, token_to, quoteName(outfile2));
395 command = libScriptSearch(command);
397 if (!conv.parselog.empty())
398 command += " 2> " + quoteName(infile2 + ".out");
400 if (conv.from == "dvi" && conv.to == "ps")
401 command = add_options(command,
402 buffer->params().dvips_options());
403 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
404 command = add_options(command,
405 dvipdfm_options(buffer->params()));
407 lyxerr[Debug::FILES] << "Calling " << command << endl;
409 buffer->message(_("Executing command: ")
410 + lyx::from_utf8(command));
412 Systemcall::Starttype const type = (dummy)
413 ? Systemcall::DontWait : Systemcall::Wait;
416 if (conv.original_dir) {
417 Path p(buffer->filePath());
418 res = one.startscript(type, command);
420 res = one.startscript(type, command);
422 if (!real_outfile.empty()) {
423 Mover const & mover = movers(conv.to);
424 if (!mover.rename(outfile, real_outfile))
428 << "renaming file " << outfile
429 << " to " << real_outfile
431 // Finally, don't forget to tell any future
432 // converters to use the renamed file...
433 outfile = real_outfile;
436 if (!conv.parselog.empty()) {
437 string const logfile = infile2 + ".log";
438 string const script = libScriptSearch(conv.parselog);
439 string const command2 = script +
440 " < " + quoteName(infile2 + ".out") +
441 " > " + quoteName(logfile);
442 one.startscript(Systemcall::Wait, command2);
443 if (!scanLog(*buffer, command, logfile, errorList))
448 if (conv.to == "program") {
449 Alert::error(_("Build errors"),
450 _("There were errors during the build process."));
452 // FIXME: this should go out of here. For example, here we cannot say if
453 // it is a document (.lyx) or something else. Same goes for elsewhere.
454 Alert::error(_("Cannot convert file"),
455 bformat(_("An error occurred whilst running %1$s"),
456 lyx::from_ascii(command.substr(0, 50))));
463 Converter const & conv = converterlist_[edgepath.back()];
464 if (conv.To->dummy())
467 if (!conv.result_dir.empty()) {
468 to_file = addName(subst(conv.result_dir, token_base, to_base),
469 subst(conv.result_file,
470 token_base, onlyFilename(to_base)));
471 if (from_base != to_base) {
472 string const from = subst(conv.result_dir,
473 token_base, from_base);
474 string const to = subst(conv.result_dir,
475 token_base, to_base);
476 Mover const & mover = movers(conv.from);
477 if (!mover.rename(from, to)) {
478 Alert::error(_("Cannot convert file"),
479 bformat(_("Could not move a temporary file from %1$s to %2$s."),
480 lyx::from_ascii(from), lyx::from_ascii(to)));
486 return move(conv.to, outfile, to_file, conv.latex);
490 bool Converters::move(string const & fmt,
491 string const & from, string const & to, bool copy)
496 bool no_errors = true;
497 string const path = onlyPath(from);
498 string const base = onlyFilename(changeExtension(from, ""));
499 string const to_base = changeExtension(to, "");
500 string const to_extension = getExtension(to);
502 vector<string> files = dirList(onlyPath(from), getExtension(from));
503 for (vector<string>::const_iterator it = files.begin();
504 it != files.end(); ++it)
505 if (prefixIs(*it, base)) {
506 string const from2 = path + *it;
507 string to2 = to_base + it->substr(base.length());
508 to2 = changeExtension(to2, to_extension);
509 lyxerr[Debug::FILES] << "moving " << from2
510 << " to " << to2 << endl;
512 Mover const & mover = movers(fmt);
513 bool const moved = copy
514 ? mover.copy(from2, to2)
515 : mover.rename(from2, to2);
516 if (!moved && no_errors) {
517 Alert::error(_("Cannot convert file"),
519 _("Could not copy a temporary file from %1$s to %2$s.") :
520 _("Could not move a temporary file from %1$s to %2$s."),
521 lyx::from_ascii(from2), lyx::from_ascii(to2)));
529 bool Converters::convert(Buffer const * buffer,
530 string const & from_file, string const & to_file_base,
531 string const & from_format, string const & to_format,
532 ErrorList & errorList, bool try_default)
535 return convert(buffer, from_file, to_file_base, from_format, to_format,
536 to_file, errorList, try_default);
540 bool Converters::formatIsUsed(string const & format)
542 ConverterList::const_iterator cit = converterlist_.begin();
543 ConverterList::const_iterator end = converterlist_.end();
544 for (; cit != end; ++cit) {
545 if (cit->from == format || cit->to == format)
552 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
553 string const & filename, ErrorList & errorList)
555 OutputParams runparams;
556 runparams.flavor = OutputParams::LATEX;
557 LaTeX latex("", runparams, filename, "");
559 int const result = latex.scanLogFile(terr);
561 if (result & LaTeX::ERRORS)
562 bufferErrors(buffer, terr, errorList);
570 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
572 showMessage(Buffer const & b) : buffer_(b) {};
573 void operator()(docstring const & m) const
578 Buffer const & buffer_;
584 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
585 OutputParams const & runparams, ErrorList & errorList)
588 buffer.message(_("Running LaTeX..."));
590 runparams.document_language = buffer.params().language->babel();
592 // do the LaTeX run(s)
593 string const name = buffer.getLatexName();
594 LaTeX latex(command, runparams, name, buffer.filePath());
596 showMessage show(buffer);
597 latex.message.connect(show);
598 int const result = latex.run(terr);
600 if (result & LaTeX::ERRORS)
601 bufferErrors(buffer, terr, errorList);
603 // check return value from latex.run().
604 if ((result & LaTeX::NO_LOGFILE)) {
605 docstring const str =
606 bformat(_("LaTeX did not run successfully. "
607 "Additionally, LyX could not locate "
608 "the LaTeX log %1$s."), lyx::from_utf8(name));
609 Alert::error(_("LaTeX failed"), str);
610 } else if (result & LaTeX::NO_OUTPUT) {
611 Alert::warning(_("Output is empty"),
612 _("An empty output file was generated."));
618 int const ERROR_MASK =
623 return (result & ERROR_MASK) == 0;
629 void Converters::buildGraph()
631 G_.init(formats.size());
632 ConverterList::iterator beg = converterlist_.begin();
633 ConverterList::iterator const end = converterlist_.end();
634 for (ConverterList::iterator it = beg; it != end ; ++it) {
635 int const s = formats.getNumber(it->from);
636 int const t = formats.getNumber(it->to);
642 std::vector<Format const *> const
643 Converters::intToFormat(std::vector<int> const & input)
645 vector<Format const *> result(input.size());
647 vector<int>::const_iterator it = input.begin();
648 vector<int>::const_iterator const end = input.end();
649 vector<Format const *>::iterator rit = result.begin();
650 for ( ; it != end; ++it, ++rit) {
651 *rit = &formats.get(*it);
657 vector<Format const *> const
658 Converters::getReachableTo(string const & target, bool const clear_visited)
660 vector<int> const & reachablesto =
661 G_.getReachableTo(formats.getNumber(target), clear_visited);
663 return intToFormat(reachablesto);
667 vector<Format const *> const
668 Converters::getReachable(string const & from, bool const only_viewable,
669 bool const clear_visited)
671 vector<int> const & reachables =
672 G_.getReachable(formats.getNumber(from),
676 return intToFormat(reachables);
680 bool Converters::isReachable(string const & from, string const & to)
682 return G_.isReachable(formats.getNumber(from),
683 formats.getNumber(to));
687 Graph::EdgePath const
688 Converters::getPath(string const & from, string const & to)
690 return G_.getPath(formats.getNumber(from),
691 formats.getNumber(to));
695 /// The global instance
696 Converters converters;
698 // The global copy after reading lyxrc.defaults
699 Converters system_converters;