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"
21 #include "frontends/Alert.h"
23 #include "support/filetools.h"
24 #include "support/lyxlib.h"
25 #include "support/path.h"
26 #include "support/systemcall.h"
28 using namespace lyx::support;
38 string const token_from("$$i");
39 string const token_base("$$b");
40 string const token_to("$$o");
41 string const token_path("$$p");
45 string const add_options(string const & command, string const & options)
48 string const tail = split(command, head, ' ');
49 return head + ' ' + options + ' ' + tail;
53 string const dvipdfm_options(BufferParams const & bp)
57 if (bp.papersize2 != VM_PAPER_CUSTOM) {
58 string const paper_size = bp.paperSizeName();
59 if (paper_size != "b5" && paper_size != "foolscap")
60 result = "-p "+ paper_size;
62 if (bp.orientation == ORIENTATION_LANDSCAPE)
72 Converter::Converter(string const & f, string const & t, string const & c,
73 string const & l): from(f), to(t), command(c), flags(l),
74 From(0), To(0), latex(false),
75 original_dir(false), need_aux(false)
79 void Converter::readFlags()
81 string flag_list(flags);
82 while (!flag_list.empty()) {
83 string flag_name, flag_value;
84 flag_list = split(flag_list, flag_value, ',');
85 flag_value = split(flag_value, flag_name, '=');
86 if (flag_name == "latex")
88 else if (flag_name == "originaldir")
90 else if (flag_name == "needaux")
92 else if (flag_name == "resultdir")
93 result_dir = (flag_value.empty())
94 ? token_base : flag_value;
95 else if (flag_name == "resultfile")
96 result_file = flag_value;
97 else if (flag_name == "parselog")
98 parselog = flag_value;
100 if (!result_dir.empty() && result_file.empty())
101 result_file = "index." + formats.extension(to);
102 //if (!contains(command, token_from))
107 bool operator<(Converter const & a, Converter const & b)
109 // use the compare_ascii_no_case instead of compare_no_case,
110 // because in turkish, 'i' is not the lowercase version of 'I',
111 // and thus turkish locale breaks parsing of tags.
112 int const i = compare_ascii_no_case(a.From->prettyname(),
113 b.From->prettyname());
115 return compare_ascii_no_case(a.To->prettyname(),
116 b.To->prettyname()) < 0;
122 class compare_Converter {
124 compare_Converter(string const & f, string const & t)
126 bool operator()(Converter const & c) {
127 return c.from == from && c.to == to;
136 Converter const * Converters::getConverter(string const & from,
139 ConverterList::const_iterator cit =
140 find_if(converterlist_.begin(), converterlist_.end(),
141 compare_Converter(from, to));
142 if (cit != converterlist_.end())
149 int Converters::getNumber(string const & from, string const & to)
151 ConverterList::const_iterator cit =
152 find_if(converterlist_.begin(), converterlist_.end(),
153 compare_Converter(from, to));
154 if (cit != converterlist_.end())
155 return cit - converterlist_.begin();
161 void Converters::add(string const & from, string const & to,
162 string const & command, string const & flags)
166 ConverterList::iterator it = find_if(converterlist_.begin(),
167 converterlist_.end(),
168 compare_Converter(from, to));
170 Converter converter(from, to, command, flags);
171 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
173 converter.command = command;
174 converter.flags = flags;
176 converter.readFlags();
178 if (converter.latex && (latex_command_.empty() || to == "dvi"))
179 latex_command_ = subst(command, token_from, "");
180 // If we have both latex & pdflatex, we set latex_command to latex.
181 // The latex_command is used to update the .aux file when running
182 // a converter that uses it.
184 if (it == converterlist_.end()) {
185 converterlist_.push_back(converter);
187 converter.From = it->From;
188 converter.To = it->To;
194 void Converters::erase(string const & from, string const & to)
196 ConverterList::iterator it = find_if(converterlist_.begin(),
197 converterlist_.end(),
198 compare_Converter(from, to));
199 if (it != converterlist_.end())
200 converterlist_.erase(it);
204 // This method updates the pointers From and To in all the converters.
205 // The code is not very efficient, but it doesn't matter as the number
206 // of formats and converters is small.
207 // Furthermore, this method is called only on startup, or after
208 // adding/deleting a format in FormPreferences (the latter calls can be
209 // eliminated if the formats in the Formats class are stored using a map or
210 // a list (instead of a vector), but this will cause other problems).
211 void Converters::update(Formats const & formats)
213 ConverterList::iterator it = converterlist_.begin();
214 ConverterList::iterator end = converterlist_.end();
215 for (; it != end; ++it) {
216 it->From = formats.getFormat(it->from);
217 it->To = formats.getFormat(it->to);
222 // This method updates the pointers From and To in the last converter.
223 // It is called when adding a new converter in FormPreferences
224 void Converters::updateLast(Formats const & formats)
226 if (converterlist_.begin() != converterlist_.end()) {
227 ConverterList::iterator it = converterlist_.end() - 1;
228 it->From = formats.getFormat(it->from);
229 it->To = formats.getFormat(it->to);
234 void Converters::sort()
236 std::sort(converterlist_.begin(), converterlist_.end());
240 bool Converters::usePdflatex(Graph::EdgePath const & path)
242 for (Graph::EdgePath::const_iterator cit = path.begin();
243 cit != path.end(); ++cit) {
244 Converter const & conv = converterlist_[*cit];
246 return contains(conv.to, "pdf");
252 bool Converters::convert(Buffer const * buffer,
253 string const & from_file, string const & to_file_base,
254 string const & from_format, string const & to_format,
257 to_file = ChangeExtension(to_file_base,
258 formats.extension(to_format));
260 if (from_format == to_format)
261 return move(from_file, to_file, false);
263 Graph::EdgePath edgepath = getPath(from_format, to_format);
264 if (edgepath.empty()) {
267 LatexRunParams runparams;
268 runparams.flavor = usePdflatex(edgepath) ?
269 LatexRunParams::PDFLATEX : LatexRunParams::LATEX;
271 string path = OnlyPath(from_file);
274 bool run_latex = false;
275 string from_base = ChangeExtension(from_file, "");
276 string to_base = ChangeExtension(to_file, "");
278 string outfile = from_file;
279 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
280 cit != edgepath.end(); ++cit) {
281 Converter const & conv = converterlist_[*cit];
282 bool dummy = conv.To->dummy() && conv.to != "program";
284 lyxerr[Debug::FILES] << "Converting from "
285 << conv.from << " to " << conv.to << endl;
287 outfile = conv.result_dir.empty()
288 ? ChangeExtension(from_file, conv.To->extension())
289 : AddName(subst(conv.result_dir,
290 token_base, from_base),
291 subst(conv.result_file,
292 token_base, OnlyFilename(from_base)));
294 // if input and output files are equal, we use a
295 // temporary file as intermediary (JMarc)
297 if (outfile == infile) {
298 real_outfile = infile;
299 outfile = AddName(buffer->temppath(), "tmpfile.out");
304 string command = subst(conv.command, token_from, "");
305 lyxerr[Debug::FILES] << "Running " << command << endl;
306 if (!runLaTeX(*buffer, command, runparams))
309 if (conv.need_aux && !run_latex
310 && !latex_command_.empty()) {
312 << "Running " << latex_command_
313 << " to update aux file"<< endl;
314 runLaTeX(*buffer, latex_command_, runparams);
317 string infile2 = (conv.original_dir)
318 ? infile : MakeRelPath(infile, path);
319 string outfile2 = (conv.original_dir)
320 ? outfile : MakeRelPath(outfile, path);
322 string command = conv.command;
323 command = subst(command, token_from, QuoteName(infile2));
324 command = subst(command, token_base, QuoteName(from_base));
325 command = subst(command, token_to, QuoteName(outfile2));
326 command = LibScriptSearch(command);
328 if (!conv.parselog.empty())
329 command += " 2> " + QuoteName(infile2 + ".out");
331 if (conv.from == "dvi" && conv.to == "ps")
332 command = add_options(command,
333 buffer->params().dvips_options());
334 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
335 command = add_options(command,
336 dvipdfm_options(buffer->params()));
338 lyxerr[Debug::FILES] << "Calling " << command << endl;
339 buffer->message(_("Executing command: ") + command);
341 Systemcall::Starttype type = (dummy)
342 ? Systemcall::DontWait : Systemcall::Wait;
345 if (conv.original_dir) {
346 Path p(buffer->filePath());
347 res = one.startscript(type, command);
349 res = one.startscript(type, command);
351 if (!real_outfile.empty()) {
352 if (!rename(outfile, real_outfile))
356 << "renaming file " << outfile
357 << " to " << real_outfile
361 if (!conv.parselog.empty()) {
362 string const logfile = infile2 + ".log";
363 string const script = LibScriptSearch(conv.parselog);
364 string const command2 = script +
365 " < " + QuoteName(infile2 + ".out") +
366 " > " + QuoteName(logfile);
367 one.startscript(Systemcall::Wait, command2);
368 if (!scanLog(*buffer, command, logfile))
373 if (conv.to == "program") {
374 Alert::error(_("Build errors"),
375 _("There were errors during the build process."));
377 // FIXME: this should go out of here. For example, here we cannot say if
378 // it is a document (.lyx) or something else. Same goes for elsewhere.
379 Alert::error(_("Cannot convert file"),
380 bformat(_("An error occurred whilst running %1$s"),
381 command.substr(0, 50)));
388 Converter const & conv = converterlist_[edgepath.back()];
389 if (conv.To->dummy())
393 if (!conv.result_dir.empty()) {
394 to_file = AddName(subst(conv.result_dir, token_base, to_base),
395 subst(conv.result_file,
396 token_base, OnlyFilename(to_base)));
397 if (from_base != to_base) {
398 string from = subst(conv.result_dir,
399 token_base, from_base);
400 string to = subst(conv.result_dir,
401 token_base, to_base);
402 if (!rename(from, to)) {
403 Alert::error(_("Cannot convert file"),
404 bformat(_("Could not move a temporary file from %1$s to %2$s."),
411 return move(outfile, to_file, conv.latex);
415 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
416 // moves each /path/file*.ext file to /path2/file2*.ext2'
417 bool Converters::move(string const & from, string const & to, bool copy)
422 bool no_errors = true;
423 string const path = OnlyPath(from);
424 string const base = OnlyFilename(ChangeExtension(from, ""));
425 string const to_base = ChangeExtension(to, "");
426 string const to_extension = GetExtension(to);
428 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
429 for (vector<string>::const_iterator it = files.begin();
430 it != files.end(); ++it)
431 if (prefixIs(*it, base)) {
432 string const from2 = path + *it;
433 string to2 = to_base + it->substr(base.length());
434 to2 = ChangeExtension(to2, to_extension);
435 lyxerr[Debug::FILES] << "moving " << from2
436 << " to " << to2 << endl;
437 bool const moved = (copy)
438 ? lyx::support::copy(from2, to2)
439 : rename(from2, to2);
440 if (!moved && no_errors) {
441 Alert::error(_("Cannot convert file"),
442 bformat(_("Could not move a temporary file from %1$s to %2$s."),
451 bool Converters::convert(Buffer const * buffer,
452 string const & from_file, string const & to_file_base,
453 string const & from_format, string const & to_format)
456 return convert(buffer, from_file, to_file_base, from_format, to_format,
461 bool Converters::formatIsUsed(string const & format)
463 ConverterList::const_iterator cit = converterlist_.begin();
464 ConverterList::const_iterator end = converterlist_.end();
465 for (; cit != end; ++cit) {
466 if (cit->from == format || cit->to == format)
473 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
474 string const & filename)
476 LatexRunParams runparams;
477 runparams.flavor = LatexRunParams::LATEX;
478 LaTeX latex("", runparams, filename, "");
480 int result = latex.scanLogFile(terr);
482 if (result & LaTeX::ERRORS)
483 bufferErrors(buffer, terr);
490 class showMessage : public boost::signals::trackable {
492 showMessage(Buffer const & b) : buffer_(b) {};
493 void operator()(string const & m)
498 Buffer const & buffer_;
504 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
505 LatexRunParams const & runparams)
508 buffer.message(_("Running LaTeX..."));
510 // do the LaTeX run(s)
511 string name = buffer.getLatexName();
512 LaTeX latex(command, runparams, name, buffer.filePath());
514 showMessage show(buffer);
515 latex.message.connect(show);
516 int result = latex.run(terr);
518 if (result & LaTeX::ERRORS)
519 bufferErrors(buffer, terr);
521 // check return value from latex.run().
522 if ((result & LaTeX::NO_LOGFILE)) {
523 string str = bformat(_("LaTeX did not run successfully. "
524 "Additionally, LyX could not locate "
525 "the LaTeX log %1$s."), name);
526 Alert::error(_("LaTeX failed"), str);
527 } else if (result & LaTeX::NO_OUTPUT) {
528 Alert::warning(_("Output is empty"),
529 _("An empty output file was generated."));
535 int const ERROR_MASK =
540 return (result & ERROR_MASK) == 0;
546 void Converters::buildGraph()
548 G_.init(formats.size());
549 ConverterList::iterator beg = converterlist_.begin();
550 ConverterList::iterator end = converterlist_.end();
551 for (ConverterList::iterator it = beg; it != end ; ++it) {
552 int const s = formats.getNumber(it->from);
553 int const t = formats.getNumber(it->to);
559 std::vector<Format const *> const
560 Converters::intToFormat(std::vector<int> const & input)
562 vector<Format const *> result(input.size());
564 vector<int>::const_iterator it = input.begin();
565 vector<int>::const_iterator end = input.end();
566 vector<Format const *>::iterator rit = result.begin();
567 for ( ; it != end; ++it, ++rit) {
568 *rit = &formats.get(*it);
573 vector<Format const *> const
574 Converters::getReachableTo(string const & target, bool clear_visited)
576 vector<int> const & reachablesto =
577 G_.getReachableTo(formats.getNumber(target), clear_visited);
579 return intToFormat(reachablesto);
583 vector<Format const *> const
584 Converters::getReachable(string const & from, bool only_viewable,
587 vector<int> const & reachables =
588 G_.getReachable(formats.getNumber(from),
592 return intToFormat(reachables);
596 bool Converters::isReachable(string const & from, string const & to)
598 return G_.isReachable(formats.getNumber(from),
599 formats.getNumber(to));
603 Graph::EdgePath const
604 Converters::getPath(string const & from, string const & to)
606 return G_.getPath(formats.getNumber(from),
607 formats.getNumber(to));
611 /// The global instance
612 Converters converters;
614 // The global copy after reading lyxrc.defaults
615 Converters system_converters;