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)
91 Converter::Converter(string const & f, string const & t, string const & c,
92 string const & l): from(f), to(t), command(c), flags(l),
93 From(0), To(0), latex(false),
94 original_dir(false), need_aux(false)
98 void Converter::readFlags()
100 string flag_list(flags);
101 while (!flag_list.empty()) {
102 string flag_name, flag_value;
103 flag_list = split(flag_list, flag_value, ',');
104 flag_value = split(flag_value, flag_name, '=');
105 if (flag_name == "latex")
107 else if (flag_name == "originaldir")
109 else if (flag_name == "needaux")
111 else if (flag_name == "resultdir")
112 result_dir = (flag_value.empty())
113 ? token_base : flag_value;
114 else if (flag_name == "resultfile")
115 result_file = flag_value;
116 else if (flag_name == "parselog")
117 parselog = flag_value;
119 if (!result_dir.empty() && result_file.empty())
120 result_file = "index." + formats.extension(to);
121 //if (!contains(command, token_from))
126 bool operator<(Converter const & a, Converter const & b)
128 // use the compare_ascii_no_case instead of compare_no_case,
129 // because in turkish, 'i' is not the lowercase version of 'I',
130 // and thus turkish locale breaks parsing of tags.
131 int const i = compare_ascii_no_case(a.From->prettyname(),
132 b.From->prettyname());
134 return compare_ascii_no_case(a.To->prettyname(),
135 b.To->prettyname()) < 0;
141 class compare_Converter {
143 compare_Converter(string const & f, string const & t)
145 bool operator()(Converter const & c) {
146 return c.from == from && c.to == to;
155 Converter const * Converters::getConverter(string const & from,
158 ConverterList::const_iterator cit =
159 find_if(converterlist_.begin(), converterlist_.end(),
160 compare_Converter(from, to));
161 if (cit != converterlist_.end())
168 int Converters::getNumber(string const & from, string const & to)
170 ConverterList::const_iterator cit =
171 find_if(converterlist_.begin(), converterlist_.end(),
172 compare_Converter(from, to));
173 if (cit != converterlist_.end())
174 return cit - converterlist_.begin();
180 void Converters::add(string const & from, string const & to,
181 string const & command, string const & flags)
185 ConverterList::iterator it = find_if(converterlist_.begin(),
186 converterlist_.end(),
187 compare_Converter(from, to));
189 Converter converter(from, to, command, flags);
190 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
192 converter.command = command;
193 converter.flags = flags;
195 converter.readFlags();
197 if (converter.latex && (latex_command_.empty() || to == "dvi"))
198 latex_command_ = subst(command, token_from, "");
199 // If we have both latex & pdflatex, we set latex_command to latex.
200 // The latex_command is used to update the .aux file when running
201 // a converter that uses it.
203 if (it == converterlist_.end()) {
204 converterlist_.push_back(converter);
206 converter.From = it->From;
207 converter.To = it->To;
213 void Converters::erase(string const & from, string const & to)
215 ConverterList::iterator it = find_if(converterlist_.begin(),
216 converterlist_.end(),
217 compare_Converter(from, to));
218 if (it != converterlist_.end())
219 converterlist_.erase(it);
223 // This method updates the pointers From and To in all the converters.
224 // The code is not very efficient, but it doesn't matter as the number
225 // of formats and converters is small.
226 // Furthermore, this method is called only on startup, or after
227 // adding/deleting a format in FormPreferences (the latter calls can be
228 // eliminated if the formats in the Formats class are stored using a map or
229 // a list (instead of a vector), but this will cause other problems).
230 void Converters::update(Formats const & formats)
232 ConverterList::iterator it = converterlist_.begin();
233 ConverterList::iterator end = converterlist_.end();
234 for (; it != end; ++it) {
235 it->From = formats.getFormat(it->from);
236 it->To = formats.getFormat(it->to);
241 // This method updates the pointers From and To in the last converter.
242 // It is called when adding a new converter in FormPreferences
243 void Converters::updateLast(Formats const & formats)
245 if (converterlist_.begin() != converterlist_.end()) {
246 ConverterList::iterator it = converterlist_.end() - 1;
247 it->From = formats.getFormat(it->from);
248 it->To = formats.getFormat(it->to);
253 void Converters::sort()
255 std::sort(converterlist_.begin(), converterlist_.end());
259 bool Converters::usePdflatex(Graph::EdgePath const & path)
261 for (Graph::EdgePath::const_iterator cit = path.begin();
262 cit != path.end(); ++cit) {
263 Converter const & conv = converterlist_[*cit];
265 return contains(conv.to, "pdf");
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 LatexRunParams runparams;
287 runparams.flavor = usePdflatex(edgepath) ?
288 LatexRunParams::PDFLATEX : LatexRunParams::LATEX;
290 string path = OnlyPath(from_file);
293 bool run_latex = false;
294 string from_base = ChangeExtension(from_file, "");
295 string to_base = ChangeExtension(to_file, "");
297 string outfile = from_file;
298 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
299 cit != edgepath.end(); ++cit) {
300 Converter const & conv = converterlist_[*cit];
301 bool dummy = conv.To->dummy() && conv.to != "program";
303 lyxerr[Debug::FILES] << "Converting from "
304 << conv.from << " to " << conv.to << endl;
306 outfile = conv.result_dir.empty()
307 ? ChangeExtension(from_file, conv.To->extension())
308 : AddName(subst(conv.result_dir,
309 token_base, from_base),
310 subst(conv.result_file,
311 token_base, OnlyFilename(from_base)));
313 // if input and output files are equal, we use a
314 // temporary file as intermediary (JMarc)
316 if (outfile == infile) {
317 real_outfile = infile;
318 outfile = AddName(buffer->temppath(), "tmpfile.out");
323 string command = subst(conv.command, token_from, "");
324 lyxerr[Debug::FILES] << "Running " << command << endl;
325 if (!runLaTeX(*buffer, command, runparams))
328 if (conv.need_aux && !run_latex
329 && !latex_command_.empty()) {
331 << "Running " << latex_command_
332 << " to update aux file"<< endl;
333 runLaTeX(*buffer, latex_command_, runparams);
336 string infile2 = (conv.original_dir)
337 ? infile : MakeRelPath(infile, path);
338 string outfile2 = (conv.original_dir)
339 ? outfile : MakeRelPath(outfile, path);
341 string command = conv.command;
342 command = subst(command, token_from, QuoteName(infile2));
343 command = subst(command, token_base, QuoteName(from_base));
344 command = subst(command, token_to, QuoteName(outfile2));
345 command = LibScriptSearch(command);
347 if (!conv.parselog.empty())
348 command += " 2> " + QuoteName(infile2 + ".out");
350 if (conv.from == "dvi" && conv.to == "ps")
351 command = add_options(command,
352 buffer->params().dvips_options());
353 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
354 command = add_options(command,
355 dvipdfm_options(buffer->params()));
357 lyxerr[Debug::FILES] << "Calling " << command << endl;
358 buffer->message(_("Executing command: ") + command);
360 Systemcall::Starttype type = (dummy)
361 ? Systemcall::DontWait : Systemcall::Wait;
364 if (conv.original_dir) {
365 Path p(buffer->filePath());
366 res = one.startscript(type, command);
368 res = one.startscript(type, command);
370 if (!real_outfile.empty()) {
371 if (!rename(outfile, real_outfile))
375 << "renaming file " << outfile
376 << " to " << real_outfile
380 if (!conv.parselog.empty()) {
381 string const logfile = infile2 + ".log";
382 string const script = LibScriptSearch(conv.parselog);
383 string const command2 = script +
384 " < " + QuoteName(infile2 + ".out") +
385 " > " + QuoteName(logfile);
386 one.startscript(Systemcall::Wait, command2);
387 if (!scanLog(*buffer, command, logfile))
392 if (conv.to == "program") {
393 Alert::error(_("Build errors"),
394 _("There were errors during the build process."));
396 // FIXME: this should go out of here. For example, here we cannot say if
397 // it is a document (.lyx) or something else. Same goes for elsewhere.
398 Alert::error(_("Cannot convert file"),
399 bformat(_("An error occurred whilst running %1$s"),
400 command.substr(0, 50)));
407 Converter const & conv = converterlist_[edgepath.back()];
408 if (conv.To->dummy())
412 if (!conv.result_dir.empty()) {
413 to_file = AddName(subst(conv.result_dir, token_base, to_base),
414 subst(conv.result_file,
415 token_base, OnlyFilename(to_base)));
416 if (from_base != to_base) {
417 string from = subst(conv.result_dir,
418 token_base, from_base);
419 string to = subst(conv.result_dir,
420 token_base, to_base);
421 if (!rename(from, to)) {
422 Alert::error(_("Cannot convert file"),
423 bformat(_("Could not move a temporary file from %1$s to %2$s."),
430 return move(outfile, to_file, conv.latex);
434 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
435 // moves each /path/file*.ext file to /path2/file2*.ext2'
436 bool Converters::move(string const & from, string const & to, bool copy)
441 bool no_errors = true;
442 string const path = OnlyPath(from);
443 string const base = OnlyFilename(ChangeExtension(from, ""));
444 string const to_base = ChangeExtension(to, "");
445 string const to_extension = GetExtension(to);
447 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
448 for (vector<string>::const_iterator it = files.begin();
449 it != files.end(); ++it)
450 if (prefixIs(*it, base)) {
451 string const from2 = path + *it;
452 string to2 = to_base + it->substr(base.length());
453 to2 = ChangeExtension(to2, to_extension);
454 lyxerr[Debug::FILES] << "moving " << from2
455 << " to " << to2 << endl;
456 bool const moved = (copy)
457 ? lyx::support::copy(from2, to2)
458 : rename(from2, to2);
459 if (!moved && no_errors) {
460 Alert::error(_("Cannot convert file"),
461 bformat(_("Could not move a temporary file from %1$s to %2$s."),
470 bool Converters::convert(Buffer const * buffer,
471 string const & from_file, string const & to_file_base,
472 string const & from_format, string const & to_format)
475 return convert(buffer, from_file, to_file_base, from_format, to_format,
480 bool Converters::formatIsUsed(string const & format)
482 ConverterList::const_iterator cit = converterlist_.begin();
483 ConverterList::const_iterator end = converterlist_.end();
484 for (; cit != end; ++cit) {
485 if (cit->from == format || cit->to == format)
492 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
493 string const & filename)
495 LatexRunParams runparams;
496 runparams.flavor = LatexRunParams::LATEX;
497 LaTeX latex("", runparams, filename, "");
499 int result = latex.scanLogFile(terr);
501 if (result & LaTeX::ERRORS)
502 bufferErrors(buffer, terr);
509 class showMessage : public boost::signals::trackable {
511 showMessage(Buffer const & b) : buffer_(b) {};
512 void operator()(string const & m)
517 Buffer const & buffer_;
523 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
524 LatexRunParams const & runparams)
527 buffer.message(_("Running LaTeX..."));
529 // do the LaTeX run(s)
530 string name = buffer.getLatexName();
531 LaTeX latex(command, runparams, name, buffer.filePath());
533 showMessage show(buffer);
534 latex.message.connect(show);
535 int result = latex.run(terr);
537 if (result & LaTeX::ERRORS)
538 bufferErrors(buffer, terr);
540 // check return value from latex.run().
541 if ((result & LaTeX::NO_LOGFILE)) {
542 string str = bformat(_("LaTeX did not run successfully. "
543 "Additionally, LyX could not locate "
544 "the LaTeX log %1$s."), name);
545 Alert::error(_("LaTeX failed"), str);
546 } else if (result & LaTeX::NO_OUTPUT) {
547 Alert::warning(_("Output is empty"),
548 _("An empty output file was generated."));
554 int const ERROR_MASK =
559 return (result & ERROR_MASK) == 0;
565 void Converters::buildGraph()
567 G_.init(formats.size());
568 ConverterList::iterator beg = converterlist_.begin();
569 ConverterList::iterator end = converterlist_.end();
570 for (ConverterList::iterator it = beg; it != end ; ++it) {
571 int const s = formats.getNumber(it->from);
572 int const t = formats.getNumber(it->to);
578 std::vector<Format const *> const
579 Converters::intToFormat(std::vector<int> const & input)
581 vector<Format const *> result(input.size());
583 vector<int>::const_iterator it = input.begin();
584 vector<int>::const_iterator end = input.end();
585 vector<Format const *>::iterator rit = result.begin();
586 for ( ; it != end; ++it, ++rit) {
587 *rit = &formats.get(*it);
592 vector<Format const *> const
593 Converters::getReachableTo(string const & target, bool clear_visited)
595 vector<int> const & reachablesto =
596 G_.getReachableTo(formats.getNumber(target), clear_visited);
598 return intToFormat(reachablesto);
602 vector<Format const *> const
603 Converters::getReachable(string const & from, bool only_viewable,
606 vector<int> const & reachables =
607 G_.getReachable(formats.getNumber(from),
611 return intToFormat(reachables);
615 bool Converters::isReachable(string const & from, string const & to)
617 return G_.isReachable(formats.getNumber(from),
618 formats.getNumber(to));
622 Graph::EdgePath const
623 Converters::getPath(string const & from, string const & to)
625 return G_.getPath(formats.getNumber(from),
626 formats.getNumber(to));
630 /// The global instance
631 Converters converters;
633 // The global copy after reading lyxrc.defaults
634 Converters system_converters;