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;
64 string const token_from("$$i");
65 string const token_base("$$b");
66 string const token_to("$$o");
67 string const token_path("$$p");
71 string const add_options(string const & command, string const & options)
74 string const tail = split(command, head, ' ');
75 return head + ' ' + options + ' ' + tail;
79 string const dvipdfm_options(BufferParams const & bp)
83 if (bp.papersize != PAPER_CUSTOM) {
84 string const paper_size = bp.paperSizeName();
85 if (paper_size != "b5" && paper_size != "foolscap")
86 result = "-p "+ paper_size;
88 if (bp.orientation == ORIENTATION_LANDSCAPE)
96 class ConverterEqual : public std::binary_function<string, string, bool> {
98 ConverterEqual(string const & from, string const & to)
99 : from_(from), to_(to) {}
100 bool operator()(Converter const & c) const {
101 return c.from == from_ && c.to == to_;
111 Converter::Converter(string const & f, string const & t,
112 string const & c, string const & l)
113 : from(f), to(t), command(c), flags(l),
114 From(0), To(0), latex(false), xml(false),
115 original_dir(false), need_aux(false)
119 void Converter::readFlags()
121 string flag_list(flags);
122 while (!flag_list.empty()) {
123 string flag_name, flag_value;
124 flag_list = split(flag_list, flag_value, ',');
125 flag_value = split(flag_value, flag_name, '=');
126 if (flag_name == "latex")
128 else if (flag_name == "xml")
130 else if (flag_name == "originaldir")
132 else if (flag_name == "needaux")
134 else if (flag_name == "resultdir")
135 result_dir = (flag_value.empty())
136 ? token_base : flag_value;
137 else if (flag_name == "resultfile")
138 result_file = flag_value;
139 else if (flag_name == "parselog")
140 parselog = flag_value;
142 if (!result_dir.empty() && result_file.empty())
143 result_file = "index." + formats.extension(to);
144 //if (!contains(command, token_from))
149 bool operator<(Converter const & a, Converter const & b)
151 // use the compare_ascii_no_case instead of compare_no_case,
152 // because in turkish, 'i' is not the lowercase version of 'I',
153 // and thus turkish locale breaks parsing of tags.
154 int const i = compare_ascii_no_case(a.From->prettyname(),
155 b.From->prettyname());
157 return compare_ascii_no_case(a.To->prettyname(),
158 b.To->prettyname()) < 0;
164 Converter const * Converters::getConverter(string const & from,
165 string const & to) const
167 ConverterList::const_iterator const cit =
168 find_if(converterlist_.begin(), converterlist_.end(),
169 ConverterEqual(from, to));
170 if (cit != converterlist_.end())
177 int Converters::getNumber(string const & from, string const & to) const
179 ConverterList::const_iterator const cit =
180 find_if(converterlist_.begin(), converterlist_.end(),
181 ConverterEqual(from, to));
182 if (cit != converterlist_.end())
183 return distance(converterlist_.begin(), cit);
189 void Converters::add(string const & from, string const & to,
190 string const & command, string const & flags)
194 ConverterList::iterator it = find_if(converterlist_.begin(),
195 converterlist_.end(),
196 ConverterEqual(from , to));
198 Converter converter(from, to, command, flags);
199 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
201 converter.command = command;
202 converter.flags = flags;
204 converter.readFlags();
206 if (converter.latex && (latex_command_.empty() || to == "dvi"))
207 latex_command_ = subst(command, token_from, "");
208 // If we have both latex & pdflatex, we set latex_command to latex.
209 // The latex_command is used to update the .aux file when running
210 // a converter that uses it.
212 if (it == converterlist_.end()) {
213 converterlist_.push_back(converter);
215 converter.From = it->From;
216 converter.To = it->To;
222 void Converters::erase(string const & from, string const & to)
224 ConverterList::iterator const it =
225 find_if(converterlist_.begin(),
226 converterlist_.end(),
227 ConverterEqual(from, to));
228 if (it != converterlist_.end())
229 converterlist_.erase(it);
233 // This method updates the pointers From and To in all the converters.
234 // The code is not very efficient, but it doesn't matter as the number
235 // of formats and converters is small.
236 // Furthermore, this method is called only on startup, or after
237 // adding/deleting a format in FormPreferences (the latter calls can be
238 // eliminated if the formats in the Formats class are stored using a map or
239 // a list (instead of a vector), but this will cause other problems).
240 void Converters::update(Formats const & formats)
242 ConverterList::iterator it = converterlist_.begin();
243 ConverterList::iterator end = converterlist_.end();
244 for (; it != end; ++it) {
245 it->From = formats.getFormat(it->from);
246 it->To = formats.getFormat(it->to);
251 // This method updates the pointers From and To in the last converter.
252 // It is called when adding a new converter in FormPreferences
253 void Converters::updateLast(Formats const & formats)
255 if (converterlist_.begin() != converterlist_.end()) {
256 ConverterList::iterator it = converterlist_.end() - 1;
257 it->From = formats.getFormat(it->from);
258 it->To = formats.getFormat(it->to);
263 void Converters::sort()
265 std::sort(converterlist_.begin(), converterlist_.end());
269 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
271 for (Graph::EdgePath::const_iterator cit = path.begin();
272 cit != path.end(); ++cit) {
273 Converter const & conv = converterlist_[*cit];
275 if (contains(conv.to, "pdf"))
276 return OutputParams::PDFLATEX;
278 return OutputParams::XML;
280 return OutputParams::LATEX;
284 bool Converters::convert(Buffer const * buffer,
285 string const & from_file, string const & to_file_base,
286 string const & from_format, string const & to_format,
287 string & to_file, ErrorList & errorList, bool try_default)
289 string const to_ext = formats.extension(to_format);
290 to_file = changeExtension(to_file_base, to_ext);
292 if (from_format == to_format)
293 return move(from_format, from_file, to_file, false);
295 Graph::EdgePath edgepath = getPath(from_format, to_format);
296 if (edgepath.empty()) {
298 // if no special converter defined, then we take the
299 // default one from ImageMagic.
300 string const from_ext = from_format.empty() ?
301 getExtension(from_file) :
302 formats.extension(from_format);
303 string const command =
304 lyx::support::os::python() + ' ' +
305 quoteName(libFileSearch("scripts", "convertDefault.py")) +
307 quoteName(from_ext + ':' + from_file) +
309 quoteName(to_ext + ':' + to_file);
311 << "No converter defined! "
312 "I use convertDefault.py:\n\t"
315 one.startscript(Systemcall::Wait, command);
316 if (isFileReadable(to_file)) {
320 Alert::error(_("Cannot convert file"),
321 bformat(_("No information for converting %1$s "
322 "format files to %2$s.\n"
323 "Define a convertor in the preferences."),
324 lyx::from_ascii(from_format), lyx::from_ascii(to_format)));
327 OutputParams runparams;
328 runparams.flavor = getFlavor(edgepath);
330 // Some converters (e.g. lilypond) can only output files to the
331 // current directory, so we need to change the current directory.
332 // This has the added benefit that all other files that may be
333 // generated by the converter are deleted when LyX closes and do not
334 // clutter the real working directory.
335 string path = onlyPath(from_file);
338 // empty the error list before any new conversion takes place.
341 bool run_latex = false;
342 string from_base = changeExtension(from_file, "");
343 string to_base = changeExtension(to_file, "");
345 string outfile = from_file;
346 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
347 cit != edgepath.end(); ++cit) {
348 Converter const & conv = converterlist_[*cit];
349 bool dummy = conv.To->dummy() && conv.to != "program";
351 lyxerr[Debug::FILES] << "Converting from "
352 << conv.from << " to " << conv.to << endl;
354 outfile = conv.result_dir.empty()
355 ? changeExtension(from_file, conv.To->extension())
356 : addName(subst(conv.result_dir,
357 token_base, from_base),
358 subst(conv.result_file,
359 token_base, onlyFilename(from_base)));
361 // if input and output files are equal, we use a
362 // temporary file as intermediary (JMarc)
364 if (outfile == infile) {
365 real_outfile = infile;
366 outfile = addName(buffer->temppath(), "tmpfile.out");
371 string const command = subst(conv.command, token_from, "");
372 lyxerr[Debug::FILES] << "Running " << command << endl;
373 if (!runLaTeX(*buffer, command, runparams, errorList))
376 if (conv.need_aux && !run_latex
377 && !latex_command_.empty()) {
379 << "Running " << latex_command_
380 << " to update aux file"<< endl;
381 runLaTeX(*buffer, latex_command_, runparams, errorList);
384 string const infile2 = (conv.original_dir)
385 ? infile : makeRelPath(infile, path);
386 string const outfile2 = (conv.original_dir)
387 ? outfile : makeRelPath(outfile, path);
389 string command = conv.command;
390 command = subst(command, token_from, quoteName(infile2));
391 command = subst(command, token_base, quoteName(from_base));
392 command = subst(command, token_to, quoteName(outfile2));
393 command = libScriptSearch(command);
395 if (!conv.parselog.empty())
396 command += " 2> " + quoteName(infile2 + ".out");
398 if (conv.from == "dvi" && conv.to == "ps")
399 command = add_options(command,
400 buffer->params().dvips_options());
401 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
402 command = add_options(command,
403 dvipdfm_options(buffer->params()));
405 lyxerr[Debug::FILES] << "Calling " << command << endl;
407 buffer->message(_("Executing command: ")
408 + lyx::from_utf8(command));
410 Systemcall::Starttype const type = (dummy)
411 ? Systemcall::DontWait : Systemcall::Wait;
414 if (conv.original_dir) {
415 Path p(buffer->filePath());
416 res = one.startscript(type, command);
418 res = one.startscript(type, command);
420 if (!real_outfile.empty()) {
421 Mover const & mover = movers(conv.to);
422 if (!mover.rename(outfile, real_outfile))
426 << "renaming file " << outfile
427 << " to " << real_outfile
429 // Finally, don't forget to tell any future
430 // converters to use the renamed file...
431 outfile = real_outfile;
434 if (!conv.parselog.empty()) {
435 string const logfile = infile2 + ".log";
436 string const script = libScriptSearch(conv.parselog);
437 string const command2 = script +
438 " < " + quoteName(infile2 + ".out") +
439 " > " + quoteName(logfile);
440 one.startscript(Systemcall::Wait, command2);
441 if (!scanLog(*buffer, command, logfile, errorList))
446 if (conv.to == "program") {
447 Alert::error(_("Build errors"),
448 _("There were errors during the build process."));
450 // FIXME: this should go out of here. For example, here we cannot say if
451 // it is a document (.lyx) or something else. Same goes for elsewhere.
452 Alert::error(_("Cannot convert file"),
453 bformat(_("An error occurred whilst running %1$s"),
454 lyx::from_ascii(command.substr(0, 50))));
461 Converter const & conv = converterlist_[edgepath.back()];
462 if (conv.To->dummy())
465 if (!conv.result_dir.empty()) {
466 to_file = addName(subst(conv.result_dir, token_base, to_base),
467 subst(conv.result_file,
468 token_base, onlyFilename(to_base)));
469 if (from_base != to_base) {
470 string const from = subst(conv.result_dir,
471 token_base, from_base);
472 string const to = subst(conv.result_dir,
473 token_base, to_base);
474 Mover const & mover = movers(conv.from);
475 if (!mover.rename(from, to)) {
476 Alert::error(_("Cannot convert file"),
477 bformat(_("Could not move a temporary file from %1$s to %2$s."),
478 lyx::from_ascii(from), lyx::from_ascii(to)));
484 return move(conv.to, outfile, to_file, conv.latex);
488 bool Converters::move(string const & fmt,
489 string const & from, string const & to, bool copy)
494 bool no_errors = true;
495 string const path = onlyPath(from);
496 string const base = onlyFilename(changeExtension(from, ""));
497 string const to_base = changeExtension(to, "");
498 string const to_extension = getExtension(to);
500 vector<string> files = dirList(onlyPath(from), getExtension(from));
501 for (vector<string>::const_iterator it = files.begin();
502 it != files.end(); ++it)
503 if (prefixIs(*it, base)) {
504 string const from2 = path + *it;
505 string to2 = to_base + it->substr(base.length());
506 to2 = changeExtension(to2, to_extension);
507 lyxerr[Debug::FILES] << "moving " << from2
508 << " to " << to2 << endl;
510 Mover const & mover = movers(fmt);
511 bool const moved = copy
512 ? mover.copy(from2, to2)
513 : mover.rename(from2, to2);
514 if (!moved && no_errors) {
515 Alert::error(_("Cannot convert file"),
517 _("Could not copy a temporary file from %1$s to %2$s.") :
518 _("Could not move a temporary file from %1$s to %2$s."),
519 lyx::from_ascii(from2), lyx::from_ascii(to2)));
527 bool Converters::convert(Buffer const * buffer,
528 string const & from_file, string const & to_file_base,
529 string const & from_format, string const & to_format,
530 ErrorList & errorList, bool try_default)
533 return convert(buffer, from_file, to_file_base, from_format, to_format,
534 to_file, errorList, try_default);
538 bool Converters::formatIsUsed(string const & format)
540 ConverterList::const_iterator cit = converterlist_.begin();
541 ConverterList::const_iterator end = converterlist_.end();
542 for (; cit != end; ++cit) {
543 if (cit->from == format || cit->to == format)
550 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
551 string const & filename, ErrorList & errorList)
553 OutputParams runparams;
554 runparams.flavor = OutputParams::LATEX;
555 LaTeX latex("", runparams, filename, "");
557 int const result = latex.scanLogFile(terr);
559 if (result & LaTeX::ERRORS)
560 bufferErrors(buffer, terr, errorList);
568 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
570 showMessage(Buffer const & b) : buffer_(b) {};
571 void operator()(docstring const & m) const
576 Buffer const & buffer_;
582 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
583 OutputParams const & runparams, ErrorList & errorList)
586 buffer.message(_("Running LaTeX..."));
588 runparams.document_language = buffer.params().language->babel();
590 // do the LaTeX run(s)
591 string const name = buffer.getLatexName();
592 LaTeX latex(command, runparams, name, buffer.filePath());
594 showMessage show(buffer);
595 latex.message.connect(show);
596 int const result = latex.run(terr);
598 if (result & LaTeX::ERRORS)
599 bufferErrors(buffer, terr, errorList);
601 // check return value from latex.run().
602 if ((result & LaTeX::NO_LOGFILE)) {
603 docstring const str =
604 bformat(_("LaTeX did not run successfully. "
605 "Additionally, LyX could not locate "
606 "the LaTeX log %1$s."), lyx::from_utf8(name));
607 Alert::error(_("LaTeX failed"), str);
608 } else if (result & LaTeX::NO_OUTPUT) {
609 Alert::warning(_("Output is empty"),
610 _("An empty output file was generated."));
616 int const ERROR_MASK =
621 return (result & ERROR_MASK) == 0;
627 void Converters::buildGraph()
629 G_.init(formats.size());
630 ConverterList::iterator beg = converterlist_.begin();
631 ConverterList::iterator const end = converterlist_.end();
632 for (ConverterList::iterator it = beg; it != end ; ++it) {
633 int const s = formats.getNumber(it->from);
634 int const t = formats.getNumber(it->to);
640 std::vector<Format const *> const
641 Converters::intToFormat(std::vector<int> const & input)
643 vector<Format const *> result(input.size());
645 vector<int>::const_iterator it = input.begin();
646 vector<int>::const_iterator const end = input.end();
647 vector<Format const *>::iterator rit = result.begin();
648 for ( ; it != end; ++it, ++rit) {
649 *rit = &formats.get(*it);
655 vector<Format const *> const
656 Converters::getReachableTo(string const & target, bool const clear_visited)
658 vector<int> const & reachablesto =
659 G_.getReachableTo(formats.getNumber(target), clear_visited);
661 return intToFormat(reachablesto);
665 vector<Format const *> const
666 Converters::getReachable(string const & from, bool const only_viewable,
667 bool const clear_visited)
669 vector<int> const & reachables =
670 G_.getReachable(formats.getNumber(from),
674 return intToFormat(reachables);
678 bool Converters::isReachable(string const & from, string const & to)
680 return G_.isReachable(formats.getNumber(from),
681 formats.getNumber(to));
685 Graph::EdgePath const
686 Converters::getPath(string const & from, string const & to)
688 return G_.getPath(formats.getNumber(from),
689 formats.getNumber(to));
693 /// The global instance
694 Converters converters;
696 // The global copy after reading lyxrc.defaults
697 Converters system_converters;