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;
62 string const token_from("$$i");
63 string const token_base("$$b");
64 string const token_to("$$o");
65 string const token_path("$$p");
69 string const add_options(string const & command, string const & options)
72 string const tail = split(command, head, ' ');
73 return head + ' ' + options + ' ' + tail;
77 string const dvipdfm_options(BufferParams const & bp)
81 if (bp.papersize != PAPER_CUSTOM) {
82 string const paper_size = bp.paperSizeName();
83 if (paper_size != "b5" && paper_size != "foolscap")
84 result = "-p "+ paper_size;
86 if (bp.orientation == ORIENTATION_LANDSCAPE)
94 class ConverterEqual : public std::binary_function<string, string, bool> {
96 ConverterEqual(string const & from, string const & to)
97 : from_(from), to_(to) {}
98 bool operator()(Converter const & c) const {
99 return c.from == from_ && c.to == to_;
109 Converter::Converter(string const & f, string const & t,
110 string const & c, string const & l)
111 : from(f), to(t), command(c), flags(l),
112 From(0), To(0), latex(false), xml(false),
113 original_dir(false), need_aux(false)
117 void Converter::readFlags()
119 string flag_list(flags);
120 while (!flag_list.empty()) {
121 string flag_name, flag_value;
122 flag_list = split(flag_list, flag_value, ',');
123 flag_value = split(flag_value, flag_name, '=');
124 if (flag_name == "latex")
126 else if (flag_name == "xml")
128 else if (flag_name == "originaldir")
130 else if (flag_name == "needaux")
132 else if (flag_name == "resultdir")
133 result_dir = (flag_value.empty())
134 ? token_base : flag_value;
135 else if (flag_name == "resultfile")
136 result_file = flag_value;
137 else if (flag_name == "parselog")
138 parselog = flag_value;
140 if (!result_dir.empty() && result_file.empty())
141 result_file = "index." + formats.extension(to);
142 //if (!contains(command, token_from))
147 bool operator<(Converter const & a, Converter const & b)
149 // use the compare_ascii_no_case instead of compare_no_case,
150 // because in turkish, 'i' is not the lowercase version of 'I',
151 // and thus turkish locale breaks parsing of tags.
152 int const i = compare_ascii_no_case(a.From->prettyname(),
153 b.From->prettyname());
155 return compare_ascii_no_case(a.To->prettyname(),
156 b.To->prettyname()) < 0;
162 Converter const * Converters::getConverter(string const & from,
163 string const & to) const
165 ConverterList::const_iterator const cit =
166 find_if(converterlist_.begin(), converterlist_.end(),
167 ConverterEqual(from, to));
168 if (cit != converterlist_.end())
175 int Converters::getNumber(string const & from, string const & to) const
177 ConverterList::const_iterator const cit =
178 find_if(converterlist_.begin(), converterlist_.end(),
179 ConverterEqual(from, to));
180 if (cit != converterlist_.end())
181 return distance(converterlist_.begin(), cit);
187 void Converters::add(string const & from, string const & to,
188 string const & command, string const & flags)
192 ConverterList::iterator it = find_if(converterlist_.begin(),
193 converterlist_.end(),
194 ConverterEqual(from , to));
196 Converter converter(from, to, command, flags);
197 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
199 converter.command = command;
200 converter.flags = flags;
202 converter.readFlags();
204 if (converter.latex && (latex_command_.empty() || to == "dvi"))
205 latex_command_ = subst(command, token_from, "");
206 // If we have both latex & pdflatex, we set latex_command to latex.
207 // The latex_command is used to update the .aux file when running
208 // a converter that uses it.
210 if (it == converterlist_.end()) {
211 converterlist_.push_back(converter);
213 converter.From = it->From;
214 converter.To = it->To;
220 void Converters::erase(string const & from, string const & to)
222 ConverterList::iterator const it =
223 find_if(converterlist_.begin(),
224 converterlist_.end(),
225 ConverterEqual(from, to));
226 if (it != converterlist_.end())
227 converterlist_.erase(it);
231 // This method updates the pointers From and To in all the converters.
232 // The code is not very efficient, but it doesn't matter as the number
233 // of formats and converters is small.
234 // Furthermore, this method is called only on startup, or after
235 // adding/deleting a format in FormPreferences (the latter calls can be
236 // eliminated if the formats in the Formats class are stored using a map or
237 // a list (instead of a vector), but this will cause other problems).
238 void Converters::update(Formats const & formats)
240 ConverterList::iterator it = converterlist_.begin();
241 ConverterList::iterator end = converterlist_.end();
242 for (; it != end; ++it) {
243 it->From = formats.getFormat(it->from);
244 it->To = formats.getFormat(it->to);
249 // This method updates the pointers From and To in the last converter.
250 // It is called when adding a new converter in FormPreferences
251 void Converters::updateLast(Formats const & formats)
253 if (converterlist_.begin() != converterlist_.end()) {
254 ConverterList::iterator it = converterlist_.end() - 1;
255 it->From = formats.getFormat(it->from);
256 it->To = formats.getFormat(it->to);
261 void Converters::sort()
263 std::sort(converterlist_.begin(), converterlist_.end());
267 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
269 for (Graph::EdgePath::const_iterator cit = path.begin();
270 cit != path.end(); ++cit) {
271 Converter const & conv = converterlist_[*cit];
273 if (contains(conv.to, "pdf"))
274 return OutputParams::PDFLATEX;
276 return OutputParams::XML;
278 return OutputParams::LATEX;
282 bool Converters::convert(Buffer const * buffer,
283 string const & from_file, string const & to_file_base,
284 string const & from_format, string const & to_format,
285 string & to_file, bool try_default)
287 string const to_ext = formats.extension(to_format);
288 to_file = changeExtension(to_file_base, to_ext);
290 if (from_format == to_format)
291 return move(from_format, from_file, to_file, false);
293 Graph::EdgePath edgepath = getPath(from_format, to_format);
294 if (edgepath.empty()) {
296 // if no special converter defined, then we take the
297 // default one from ImageMagic.
298 string const from_ext = from_format.empty() ?
299 getExtension(from_file) :
300 formats.extension(from_format);
301 string const command =
302 lyx::support::os::python() + ' ' +
303 quoteName(libFileSearch("scripts", "convertDefault.py")) +
305 quoteName(from_ext + ':' + from_file) +
307 quoteName(to_ext + ':' + to_file);
309 << "No converter defined! "
310 "I use convertDefault.py:\n\t"
313 one.startscript(Systemcall::Wait, command);
314 if (isFileReadable(to_file)) {
318 Alert::error(_("Cannot convert file"),
319 bformat(_("No information for converting %1$s "
320 "format files to %2$s.\n"
321 "Define a convertor in the preferences."),
322 from_format, to_format));
325 OutputParams runparams;
326 runparams.flavor = getFlavor(edgepath);
327 string path = onlyPath(from_file);
330 bool run_latex = false;
331 string from_base = changeExtension(from_file, "");
332 string to_base = changeExtension(to_file, "");
334 string outfile = from_file;
335 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
336 cit != edgepath.end(); ++cit) {
337 Converter const & conv = converterlist_[*cit];
338 bool dummy = conv.To->dummy() && conv.to != "program";
340 lyxerr[Debug::FILES] << "Converting from "
341 << conv.from << " to " << conv.to << endl;
343 outfile = conv.result_dir.empty()
344 ? changeExtension(from_file, conv.To->extension())
345 : addName(subst(conv.result_dir,
346 token_base, from_base),
347 subst(conv.result_file,
348 token_base, onlyFilename(from_base)));
350 // if input and output files are equal, we use a
351 // temporary file as intermediary (JMarc)
353 if (outfile == infile) {
354 real_outfile = infile;
355 outfile = addName(buffer->temppath(), "tmpfile.out");
360 string const command = subst(conv.command, token_from, "");
361 lyxerr[Debug::FILES] << "Running " << command << endl;
362 if (!runLaTeX(*buffer, command, runparams))
365 if (conv.need_aux && !run_latex
366 && !latex_command_.empty()) {
368 << "Running " << latex_command_
369 << " to update aux file"<< endl;
370 runLaTeX(*buffer, latex_command_, runparams);
373 string const infile2 = (conv.original_dir)
374 ? infile : makeRelPath(infile, path);
375 string const outfile2 = (conv.original_dir)
376 ? outfile : makeRelPath(outfile, path);
378 string command = conv.command;
379 command = subst(command, token_from, quoteName(infile2));
380 command = subst(command, token_base, quoteName(from_base));
381 command = subst(command, token_to, quoteName(outfile2));
382 command = libScriptSearch(command);
384 if (!conv.parselog.empty())
385 command += " 2> " + quoteName(infile2 + ".out");
387 if (conv.from == "dvi" && conv.to == "ps")
388 command = add_options(command,
389 buffer->params().dvips_options());
390 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
391 command = add_options(command,
392 dvipdfm_options(buffer->params()));
394 lyxerr[Debug::FILES] << "Calling " << command << endl;
396 buffer->message(_("Executing command: ")
399 Systemcall::Starttype const type = (dummy)
400 ? Systemcall::DontWait : Systemcall::Wait;
403 if (conv.original_dir) {
404 Path p(buffer->filePath());
405 res = one.startscript(type, command);
407 res = one.startscript(type, command);
409 if (!real_outfile.empty()) {
410 Mover const & mover = movers(conv.to);
411 if (!mover.rename(outfile, real_outfile))
415 << "renaming file " << outfile
416 << " to " << real_outfile
418 // Finally, don't forget to tell any future
419 // converters to use the renamed file...
420 outfile = real_outfile;
423 if (!conv.parselog.empty()) {
424 string const logfile = infile2 + ".log";
425 string const script = libScriptSearch(conv.parselog);
426 string const command2 = script +
427 " < " + quoteName(infile2 + ".out") +
428 " > " + quoteName(logfile);
429 one.startscript(Systemcall::Wait, command2);
430 if (!scanLog(*buffer, command, logfile))
435 if (conv.to == "program") {
436 Alert::error(_("Build errors"),
437 _("There were errors during the build process."));
439 // FIXME: this should go out of here. For example, here we cannot say if
440 // it is a document (.lyx) or something else. Same goes for elsewhere.
441 Alert::error(_("Cannot convert file"),
442 bformat(_("An error occurred whilst running %1$s"),
443 command.substr(0, 50)));
450 Converter const & conv = converterlist_[edgepath.back()];
451 if (conv.To->dummy())
454 if (!conv.result_dir.empty()) {
455 to_file = addName(subst(conv.result_dir, token_base, to_base),
456 subst(conv.result_file,
457 token_base, onlyFilename(to_base)));
458 if (from_base != to_base) {
459 string const from = subst(conv.result_dir,
460 token_base, from_base);
461 string const to = subst(conv.result_dir,
462 token_base, to_base);
463 Mover const & mover = movers(conv.from);
464 if (!mover.rename(from, to)) {
465 Alert::error(_("Cannot convert file"),
466 bformat(_("Could not move a temporary file from %1$s to %2$s."),
473 return move(conv.to, outfile, to_file, conv.latex);
477 bool Converters::move(string const & fmt,
478 string const & from, string const & to, bool copy)
483 bool no_errors = true;
484 string const path = onlyPath(from);
485 string const base = onlyFilename(changeExtension(from, ""));
486 string const to_base = changeExtension(to, "");
487 string const to_extension = getExtension(to);
489 vector<string> files = dirList(onlyPath(from), getExtension(from));
490 for (vector<string>::const_iterator it = files.begin();
491 it != files.end(); ++it)
492 if (prefixIs(*it, base)) {
493 string const from2 = path + *it;
494 string to2 = to_base + it->substr(base.length());
495 to2 = changeExtension(to2, to_extension);
496 lyxerr[Debug::FILES] << "moving " << from2
497 << " to " << to2 << endl;
499 Mover const & mover = movers(fmt);
500 bool const moved = copy
501 ? mover.copy(from2, to2)
502 : mover.rename(from2, to2);
503 if (!moved && no_errors) {
504 Alert::error(_("Cannot convert file"),
506 _("Could not copy a temporary file from %1$s to %2$s.") :
507 _("Could not move a temporary file from %1$s to %2$s."),
516 bool Converters::convert(Buffer const * buffer,
517 string const & from_file, string const & to_file_base,
518 string const & from_format, string const & to_format,
522 return convert(buffer, from_file, to_file_base, from_format, to_format,
523 to_file, try_default);
527 bool Converters::formatIsUsed(string const & format)
529 ConverterList::const_iterator cit = converterlist_.begin();
530 ConverterList::const_iterator end = converterlist_.end();
531 for (; cit != end; ++cit) {
532 if (cit->from == format || cit->to == format)
539 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
540 string const & filename)
542 OutputParams runparams;
543 runparams.flavor = OutputParams::LATEX;
544 LaTeX latex("", runparams, filename, "");
546 int const result = latex.scanLogFile(terr);
548 if (result & LaTeX::ERRORS)
549 bufferErrors(buffer, terr);
557 class showMessage : public std::unary_function<string, void>, public boost::signals::trackable {
559 showMessage(Buffer const & b) : buffer_(b) {};
560 void operator()(string const & m) const
565 Buffer const & buffer_;
571 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
572 OutputParams const & runparams)
575 buffer.message(_("Running LaTeX..."));
577 runparams.document_language = buffer.params().language->babel();
579 // do the LaTeX run(s)
580 string const name = buffer.getLatexName();
581 LaTeX latex(command, runparams, name, buffer.filePath());
583 showMessage show(buffer);
584 latex.message.connect(show);
585 int const result = latex.run(terr);
587 if (result & LaTeX::ERRORS)
588 bufferErrors(buffer, terr);
590 // check return value from latex.run().
591 if ((result & LaTeX::NO_LOGFILE)) {
593 bformat(_("LaTeX did not run successfully. "
594 "Additionally, LyX could not locate "
595 "the LaTeX log %1$s."), 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."));
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 std::vector<Format const *> const
630 Converters::intToFormat(std::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 const
675 Converters::getPath(string const & from, string const & to)
677 return G_.getPath(formats.getNumber(from),
678 formats.getNumber(to));
682 /// The global instance
683 Converters converters;
685 // The global copy after reading lyxrc.defaults
686 Converters system_converters;