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);
329 string path = onlyPath(from_file);
331 // empty the error list before any new conversion takes place.
334 bool run_latex = false;
335 string from_base = changeExtension(from_file, "");
336 string to_base = changeExtension(to_file, "");
338 string outfile = from_file;
339 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
340 cit != edgepath.end(); ++cit) {
341 Converter const & conv = converterlist_[*cit];
342 bool dummy = conv.To->dummy() && conv.to != "program";
344 lyxerr[Debug::FILES] << "Converting from "
345 << conv.from << " to " << conv.to << endl;
347 outfile = conv.result_dir.empty()
348 ? changeExtension(from_file, 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)
357 if (outfile == infile) {
358 real_outfile = infile;
359 outfile = addName(buffer->temppath(), "tmpfile.out");
364 string const command = subst(conv.command, token_from, "");
365 lyxerr[Debug::FILES] << "Running " << command << endl;
366 if (!runLaTeX(*buffer, command, runparams, errorList))
369 if (conv.need_aux && !run_latex
370 && !latex_command_.empty()) {
372 << "Running " << latex_command_
373 << " to update aux file"<< endl;
374 runLaTeX(*buffer, latex_command_, runparams, errorList);
377 string const infile2 = (conv.original_dir)
378 ? infile : makeRelPath(infile, path);
379 string const outfile2 = (conv.original_dir)
380 ? outfile : makeRelPath(outfile, path);
382 string command = conv.command;
383 command = subst(command, token_from, quoteName(infile2));
384 command = subst(command, token_base, quoteName(from_base));
385 command = subst(command, token_to, quoteName(outfile2));
386 command = libScriptSearch(command);
388 if (!conv.parselog.empty())
389 command += " 2> " + quoteName(infile2 + ".out");
391 if (conv.from == "dvi" && conv.to == "ps")
392 command = add_options(command,
393 buffer->params().dvips_options());
394 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
395 command = add_options(command,
396 dvipdfm_options(buffer->params()));
398 lyxerr[Debug::FILES] << "Calling " << command << endl;
400 buffer->message(_("Executing command: ")
401 + lyx::from_utf8(command));
403 Systemcall::Starttype const type = (dummy)
404 ? Systemcall::DontWait : Systemcall::Wait;
407 if (conv.original_dir) {
408 Path p(buffer->filePath());
409 res = one.startscript(type, command);
411 res = one.startscript(type, command);
413 if (!real_outfile.empty()) {
414 Mover const & mover = movers(conv.to);
415 if (!mover.rename(outfile, real_outfile))
419 << "renaming file " << outfile
420 << " to " << real_outfile
422 // Finally, don't forget to tell any future
423 // converters to use the renamed file...
424 outfile = real_outfile;
427 if (!conv.parselog.empty()) {
428 string const logfile = infile2 + ".log";
429 string const script = libScriptSearch(conv.parselog);
430 string const command2 = script +
431 " < " + quoteName(infile2 + ".out") +
432 " > " + quoteName(logfile);
433 one.startscript(Systemcall::Wait, command2);
434 if (!scanLog(*buffer, command, logfile, errorList))
439 if (conv.to == "program") {
440 Alert::error(_("Build errors"),
441 _("There were errors during the build process."));
443 // FIXME: this should go out of here. For example, here we cannot say if
444 // it is a document (.lyx) or something else. Same goes for elsewhere.
445 Alert::error(_("Cannot convert file"),
446 bformat(_("An error occurred whilst running %1$s"),
447 lyx::from_ascii(command.substr(0, 50))));
454 Converter const & conv = converterlist_[edgepath.back()];
455 if (conv.To->dummy())
458 if (!conv.result_dir.empty()) {
459 to_file = addName(subst(conv.result_dir, token_base, to_base),
460 subst(conv.result_file,
461 token_base, onlyFilename(to_base)));
462 if (from_base != to_base) {
463 string const from = subst(conv.result_dir,
464 token_base, from_base);
465 string const to = subst(conv.result_dir,
466 token_base, to_base);
467 Mover const & mover = movers(conv.from);
468 if (!mover.rename(from, to)) {
469 Alert::error(_("Cannot convert file"),
470 bformat(_("Could not move a temporary file from %1$s to %2$s."),
471 lyx::from_ascii(from), lyx::from_ascii(to)));
477 return move(conv.to, outfile, to_file, conv.latex);
481 bool Converters::move(string const & fmt,
482 string const & from, string const & to, bool copy)
487 bool no_errors = true;
488 string const path = onlyPath(from);
489 string const base = onlyFilename(changeExtension(from, ""));
490 string const to_base = changeExtension(to, "");
491 string const to_extension = getExtension(to);
493 vector<string> files = dirList(onlyPath(from), getExtension(from));
494 for (vector<string>::const_iterator it = files.begin();
495 it != files.end(); ++it)
496 if (prefixIs(*it, base)) {
497 string const from2 = path + *it;
498 string to2 = to_base + it->substr(base.length());
499 to2 = changeExtension(to2, to_extension);
500 lyxerr[Debug::FILES] << "moving " << from2
501 << " to " << to2 << endl;
503 Mover const & mover = movers(fmt);
504 bool const moved = copy
505 ? mover.copy(from2, to2)
506 : mover.rename(from2, to2);
507 if (!moved && no_errors) {
508 Alert::error(_("Cannot convert file"),
510 _("Could not copy a temporary file from %1$s to %2$s.") :
511 _("Could not move a temporary file from %1$s to %2$s."),
512 lyx::from_ascii(from2), lyx::from_ascii(to2)));
520 bool Converters::convert(Buffer const * buffer,
521 string const & from_file, string const & to_file_base,
522 string const & from_format, string const & to_format,
523 ErrorList & errorList, bool try_default)
526 return convert(buffer, from_file, to_file_base, from_format, to_format,
527 to_file, errorList, try_default);
531 bool Converters::formatIsUsed(string const & format)
533 ConverterList::const_iterator cit = converterlist_.begin();
534 ConverterList::const_iterator end = converterlist_.end();
535 for (; cit != end; ++cit) {
536 if (cit->from == format || cit->to == format)
543 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
544 string const & filename, ErrorList & errorList)
546 OutputParams runparams;
547 runparams.flavor = OutputParams::LATEX;
548 LaTeX latex("", runparams, filename, "");
550 int const result = latex.scanLogFile(terr);
552 if (result & LaTeX::ERRORS)
553 bufferErrors(buffer, terr, errorList);
561 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
563 showMessage(Buffer const & b) : buffer_(b) {};
564 void operator()(docstring const & m) const
569 Buffer const & buffer_;
575 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
576 OutputParams const & runparams, ErrorList & errorList)
579 buffer.message(_("Running LaTeX..."));
581 runparams.document_language = buffer.params().language->babel();
583 // do the LaTeX run(s)
584 string const name = buffer.getLatexName();
585 LaTeX latex(command, runparams, name, buffer.filePath());
587 showMessage show(buffer);
588 latex.message.connect(show);
589 int const result = latex.run(terr);
591 if (result & LaTeX::ERRORS)
592 bufferErrors(buffer, terr, errorList);
594 // check return value from latex.run().
595 if ((result & LaTeX::NO_LOGFILE)) {
596 docstring const str =
597 bformat(_("LaTeX did not run successfully. "
598 "Additionally, LyX could not locate "
599 "the LaTeX log %1$s."), lyx::from_utf8(name));
600 Alert::error(_("LaTeX failed"), str);
601 } else if (result & LaTeX::NO_OUTPUT) {
602 Alert::warning(_("Output is empty"),
603 _("An empty output file was generated."));
609 int const ERROR_MASK =
614 return (result & ERROR_MASK) == 0;
620 void Converters::buildGraph()
622 G_.init(formats.size());
623 ConverterList::iterator beg = converterlist_.begin();
624 ConverterList::iterator const end = converterlist_.end();
625 for (ConverterList::iterator it = beg; it != end ; ++it) {
626 int const s = formats.getNumber(it->from);
627 int const t = formats.getNumber(it->to);
633 std::vector<Format const *> const
634 Converters::intToFormat(std::vector<int> const & input)
636 vector<Format const *> result(input.size());
638 vector<int>::const_iterator it = input.begin();
639 vector<int>::const_iterator const end = input.end();
640 vector<Format const *>::iterator rit = result.begin();
641 for ( ; it != end; ++it, ++rit) {
642 *rit = &formats.get(*it);
648 vector<Format const *> const
649 Converters::getReachableTo(string const & target, bool const clear_visited)
651 vector<int> const & reachablesto =
652 G_.getReachableTo(formats.getNumber(target), clear_visited);
654 return intToFormat(reachablesto);
658 vector<Format const *> const
659 Converters::getReachable(string const & from, bool const only_viewable,
660 bool const clear_visited)
662 vector<int> const & reachables =
663 G_.getReachable(formats.getNumber(from),
667 return intToFormat(reachables);
671 bool Converters::isReachable(string const & from, string const & to)
673 return G_.isReachable(formats.getNumber(from),
674 formats.getNumber(to));
678 Graph::EdgePath const
679 Converters::getPath(string const & from, string const & to)
681 return G_.getPath(formats.getNumber(from),
682 formats.getNumber(to));
686 /// The global instance
687 Converters converters;
689 // The global copy after reading lyxrc.defaults
690 Converters system_converters;