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"
23 #include "frontends/Alert.h"
25 #include "support/filetools.h"
26 #include "support/lyxlib.h"
27 #include "support/path.h"
28 #include "support/systemcall.h"
30 using lyx::support::AddName;
31 using lyx::support::bformat;
32 using lyx::support::ChangeExtension;
33 using lyx::support::compare_ascii_no_case;
34 using lyx::support::contains;
35 using lyx::support::DirList;
36 using lyx::support::GetExtension;
37 using lyx::support::LibScriptSearch;
38 using lyx::support::MakeRelPath;
39 using lyx::support::OnlyFilename;
40 using lyx::support::OnlyPath;
41 using lyx::support::Path;
42 using lyx::support::prefixIs;
43 using lyx::support::QuoteName;
44 using lyx::support::rename;
45 using lyx::support::split;
46 using lyx::support::subst;
47 using lyx::support::Systemcall;
57 string const token_from("$$i");
58 string const token_base("$$b");
59 string const token_to("$$o");
60 string const token_path("$$p");
64 string const add_options(string const & command, string const & options)
67 string const tail = split(command, head, ' ');
68 return head + ' ' + options + ' ' + tail;
72 string const dvipdfm_options(BufferParams const & bp)
76 if (bp.papersize2 != VM_PAPER_CUSTOM) {
77 string const paper_size = bp.paperSizeName();
78 if (paper_size != "b5" && paper_size != "foolscap")
79 result = "-p "+ paper_size;
81 if (bp.orientation == ORIENTATION_LANDSCAPE)
89 class ConverterEqual : public std::binary_function<string, string, bool> {
91 ConverterEqual(string const & from, string const & to)
92 : from_(from), to_(to) {}
93 bool operator()(Converter const & c) const {
94 return c.from == from_ && c.to == to_;
104 Converter::Converter(string const & f, string const & t, string const & c,
105 string const & l): from(f), to(t), command(c), flags(l),
106 From(0), To(0), latex(false),
107 original_dir(false), need_aux(false)
111 void Converter::readFlags()
113 string flag_list(flags);
114 while (!flag_list.empty()) {
115 string flag_name, flag_value;
116 flag_list = split(flag_list, flag_value, ',');
117 flag_value = split(flag_value, flag_name, '=');
118 if (flag_name == "latex")
120 else if (flag_name == "originaldir")
122 else if (flag_name == "needaux")
124 else if (flag_name == "resultdir")
125 result_dir = (flag_value.empty())
126 ? token_base : flag_value;
127 else if (flag_name == "resultfile")
128 result_file = flag_value;
129 else if (flag_name == "parselog")
130 parselog = flag_value;
132 if (!result_dir.empty() && result_file.empty())
133 result_file = "index." + formats.extension(to);
134 //if (!contains(command, token_from))
139 bool operator<(Converter const & a, Converter const & b)
141 // use the compare_ascii_no_case instead of compare_no_case,
142 // because in turkish, 'i' is not the lowercase version of 'I',
143 // and thus turkish locale breaks parsing of tags.
144 int const i = compare_ascii_no_case(a.From->prettyname(),
145 b.From->prettyname());
147 return compare_ascii_no_case(a.To->prettyname(),
148 b.To->prettyname()) < 0;
154 Converter const * Converters::getConverter(string const & from,
155 string const & to) const
157 ConverterList::const_iterator cit =
158 find_if(converterlist_.begin(), converterlist_.end(),
159 ConverterEqual(from, to));
160 if (cit != converterlist_.end())
167 int Converters::getNumber(string const & from, string const & to) const
169 ConverterList::const_iterator cit =
170 find_if(converterlist_.begin(), converterlist_.end(),
171 ConverterEqual(from, to));
172 if (cit != converterlist_.end())
173 return distance(converterlist_.begin(), cit);
179 void Converters::add(string const & from, string const & to,
180 string const & command, string const & flags)
184 ConverterList::iterator it = find_if(converterlist_.begin(),
185 converterlist_.end(),
186 ConverterEqual(from , to));
188 Converter converter(from, to, command, flags);
189 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
191 converter.command = command;
192 converter.flags = flags;
194 converter.readFlags();
196 if (converter.latex && (latex_command_.empty() || to == "dvi"))
197 latex_command_ = subst(command, token_from, "");
198 // If we have both latex & pdflatex, we set latex_command to latex.
199 // The latex_command is used to update the .aux file when running
200 // a converter that uses it.
202 if (it == converterlist_.end()) {
203 converterlist_.push_back(converter);
205 converter.From = it->From;
206 converter.To = it->To;
212 void Converters::erase(string const & from, string const & to)
214 ConverterList::iterator it = find_if(converterlist_.begin(),
215 converterlist_.end(),
216 ConverterEqual(from, to));
217 if (it != converterlist_.end())
218 converterlist_.erase(it);
222 // This method updates the pointers From and To in all the converters.
223 // The code is not very efficient, but it doesn't matter as the number
224 // of formats and converters is small.
225 // Furthermore, this method is called only on startup, or after
226 // adding/deleting a format in FormPreferences (the latter calls can be
227 // eliminated if the formats in the Formats class are stored using a map or
228 // a list (instead of a vector), but this will cause other problems).
229 void Converters::update(Formats const & formats)
231 ConverterList::iterator it = converterlist_.begin();
232 ConverterList::iterator end = converterlist_.end();
233 for (; it != end; ++it) {
234 it->From = formats.getFormat(it->from);
235 it->To = formats.getFormat(it->to);
240 // This method updates the pointers From and To in the last converter.
241 // It is called when adding a new converter in FormPreferences
242 void Converters::updateLast(Formats const & formats)
244 if (converterlist_.begin() != converterlist_.end()) {
245 ConverterList::iterator it = converterlist_.end() - 1;
246 it->From = formats.getFormat(it->from);
247 it->To = formats.getFormat(it->to);
252 void Converters::sort()
254 std::sort(converterlist_.begin(), converterlist_.end());
258 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
260 for (Graph::EdgePath::const_iterator cit = path.begin();
261 cit != path.end(); ++cit) {
262 Converter const & conv = converterlist_[*cit];
264 if (contains(conv.to, "pdf"))
265 return OutputParams::PDFLATEX;
267 return OutputParams::LATEX;
271 bool Converters::convert(Buffer const * buffer,
272 string const & from_file, string const & to_file_base,
273 string const & from_format, string const & to_format,
276 to_file = ChangeExtension(to_file_base,
277 formats.extension(to_format));
279 if (from_format == to_format)
280 return move(from_file, to_file, false);
282 Graph::EdgePath edgepath = getPath(from_format, to_format);
283 if (edgepath.empty()) {
286 OutputParams runparams;
287 runparams.flavor = getFlavor(edgepath);
289 string path = OnlyPath(from_file);
292 bool run_latex = false;
293 string from_base = ChangeExtension(from_file, "");
294 string to_base = ChangeExtension(to_file, "");
296 string outfile = from_file;
297 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
298 cit != edgepath.end(); ++cit) {
299 Converter const & conv = converterlist_[*cit];
300 bool dummy = conv.To->dummy() && conv.to != "program";
302 lyxerr[Debug::FILES] << "Converting from "
303 << conv.from << " to " << conv.to << endl;
305 outfile = conv.result_dir.empty()
306 ? ChangeExtension(from_file, conv.To->extension())
307 : AddName(subst(conv.result_dir,
308 token_base, from_base),
309 subst(conv.result_file,
310 token_base, OnlyFilename(from_base)));
312 // if input and output files are equal, we use a
313 // temporary file as intermediary (JMarc)
315 if (outfile == infile) {
316 real_outfile = infile;
317 outfile = AddName(buffer->temppath(), "tmpfile.out");
322 string command = subst(conv.command, token_from, "");
323 lyxerr[Debug::FILES] << "Running " << command << endl;
324 if (!runLaTeX(*buffer, command, runparams))
327 if (conv.need_aux && !run_latex
328 && !latex_command_.empty()) {
330 << "Running " << latex_command_
331 << " to update aux file"<< endl;
332 runLaTeX(*buffer, latex_command_, runparams);
335 string infile2 = (conv.original_dir)
336 ? infile : MakeRelPath(infile, path);
337 string outfile2 = (conv.original_dir)
338 ? outfile : MakeRelPath(outfile, path);
340 string command = conv.command;
341 command = subst(command, token_from, QuoteName(infile2));
342 command = subst(command, token_base, QuoteName(from_base));
343 command = subst(command, token_to, QuoteName(outfile2));
344 command = LibScriptSearch(command);
346 if (!conv.parselog.empty())
347 command += " 2> " + QuoteName(infile2 + ".out");
349 if (conv.from == "dvi" && conv.to == "ps")
350 command = add_options(command,
351 buffer->params().dvips_options());
352 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
353 command = add_options(command,
354 dvipdfm_options(buffer->params()));
356 lyxerr[Debug::FILES] << "Calling " << command << endl;
358 buffer->message(_("Executing command: ")
361 Systemcall::Starttype type = (dummy)
362 ? Systemcall::DontWait : Systemcall::Wait;
365 if (conv.original_dir) {
366 Path p(buffer->filePath());
367 res = one.startscript(type, command);
369 res = one.startscript(type, command);
371 if (!real_outfile.empty()) {
372 if (!rename(outfile, real_outfile))
376 << "renaming file " << outfile
377 << " to " << real_outfile
381 if (!conv.parselog.empty()) {
382 string const logfile = infile2 + ".log";
383 string const script = LibScriptSearch(conv.parselog);
384 string const command2 = script +
385 " < " + QuoteName(infile2 + ".out") +
386 " > " + QuoteName(logfile);
387 one.startscript(Systemcall::Wait, command2);
388 if (!scanLog(*buffer, command, logfile))
393 if (conv.to == "program") {
394 Alert::error(_("Build errors"),
395 _("There were errors during the build process."));
397 // FIXME: this should go out of here. For example, here we cannot say if
398 // it is a document (.lyx) or something else. Same goes for elsewhere.
399 Alert::error(_("Cannot convert file"),
400 bformat(_("An error occurred whilst running %1$s"),
401 command.substr(0, 50)));
408 Converter const & conv = converterlist_[edgepath.back()];
409 if (conv.To->dummy())
413 if (!conv.result_dir.empty()) {
414 to_file = AddName(subst(conv.result_dir, token_base, to_base),
415 subst(conv.result_file,
416 token_base, OnlyFilename(to_base)));
417 if (from_base != to_base) {
418 string from = subst(conv.result_dir,
419 token_base, from_base);
420 string to = subst(conv.result_dir,
421 token_base, to_base);
422 if (!rename(from, to)) {
423 Alert::error(_("Cannot convert file"),
424 bformat(_("Could not move a temporary file from %1$s to %2$s."),
431 return move(outfile, to_file, conv.latex);
435 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
436 // moves each /path/file*.ext file to /path2/file2*.ext2'
437 bool Converters::move(string const & from, string const & to, bool copy)
442 bool no_errors = true;
443 string const path = OnlyPath(from);
444 string const base = OnlyFilename(ChangeExtension(from, ""));
445 string const to_base = ChangeExtension(to, "");
446 string const to_extension = GetExtension(to);
448 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
449 for (vector<string>::const_iterator it = files.begin();
450 it != files.end(); ++it)
451 if (prefixIs(*it, base)) {
452 string const from2 = path + *it;
453 string to2 = to_base + it->substr(base.length());
454 to2 = ChangeExtension(to2, to_extension);
455 lyxerr[Debug::FILES] << "moving " << from2
456 << " to " << to2 << endl;
457 bool const moved = (copy)
458 ? lyx::support::copy(from2, to2)
459 : rename(from2, to2);
460 if (!moved && no_errors) {
461 Alert::error(_("Cannot convert file"),
462 bformat(_("Could not move a temporary file from %1$s to %2$s."),
471 bool Converters::convert(Buffer const * buffer,
472 string const & from_file, string const & to_file_base,
473 string const & from_format, string const & to_format)
476 return convert(buffer, from_file, to_file_base, from_format, to_format,
481 bool Converters::formatIsUsed(string const & format)
483 ConverterList::const_iterator cit = converterlist_.begin();
484 ConverterList::const_iterator end = converterlist_.end();
485 for (; cit != end; ++cit) {
486 if (cit->from == format || cit->to == format)
493 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
494 string const & filename)
496 OutputParams runparams;
497 runparams.flavor = OutputParams::LATEX;
498 LaTeX latex("", runparams, filename, "");
500 int result = latex.scanLogFile(terr);
502 if (result & LaTeX::ERRORS)
503 bufferErrors(buffer, terr);
510 class showMessage : public boost::signals::trackable {
512 showMessage(Buffer const & b) : buffer_(b) {};
513 void operator()(string const & m)
518 Buffer const & buffer_;
524 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
525 OutputParams const & runparams)
528 buffer.message(_("Running LaTeX..."));
530 // do the LaTeX run(s)
531 string name = buffer.getLatexName();
532 LaTeX latex(command, runparams, name, buffer.filePath());
534 showMessage show(buffer);
535 latex.message.connect(show);
536 int result = latex.run(terr);
538 if (result & LaTeX::ERRORS)
539 bufferErrors(buffer, terr);
541 // check return value from latex.run().
542 if ((result & LaTeX::NO_LOGFILE)) {
543 string str = bformat(_("LaTeX did not run successfully. "
544 "Additionally, LyX could not locate "
545 "the LaTeX log %1$s."), name);
546 Alert::error(_("LaTeX failed"), str);
547 } else if (result & LaTeX::NO_OUTPUT) {
548 Alert::warning(_("Output is empty"),
549 _("An empty output file was generated."));
555 int const ERROR_MASK =
560 return (result & ERROR_MASK) == 0;
566 void Converters::buildGraph()
568 G_.init(formats.size());
569 ConverterList::iterator beg = converterlist_.begin();
570 ConverterList::iterator end = converterlist_.end();
571 for (ConverterList::iterator it = beg; it != end ; ++it) {
572 int const s = formats.getNumber(it->from);
573 int const t = formats.getNumber(it->to);
579 std::vector<Format const *> const
580 Converters::intToFormat(std::vector<int> const & input)
582 vector<Format const *> result(input.size());
584 vector<int>::const_iterator it = input.begin();
585 vector<int>::const_iterator end = input.end();
586 vector<Format const *>::iterator rit = result.begin();
587 for ( ; it != end; ++it, ++rit) {
588 *rit = &formats.get(*it);
593 vector<Format const *> const
594 Converters::getReachableTo(string const & target, bool clear_visited)
596 vector<int> const & reachablesto =
597 G_.getReachableTo(formats.getNumber(target), clear_visited);
599 return intToFormat(reachablesto);
603 vector<Format const *> const
604 Converters::getReachable(string const & from, bool only_viewable,
607 vector<int> const & reachables =
608 G_.getReachable(formats.getNumber(from),
612 return intToFormat(reachables);
616 bool Converters::isReachable(string const & from, string const & to)
618 return G_.isReachable(formats.getNumber(from),
619 formats.getNumber(to));
623 Graph::EdgePath const
624 Converters::getPath(string const & from, string const & to)
626 return G_.getPath(formats.getNumber(from),
627 formats.getNumber(to));
631 /// The global instance
632 Converters converters;
634 // The global copy after reading lyxrc.defaults
635 Converters system_converters;