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 OutputParams::FLAVOR Converters::getFlavor(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 if (contains(conv.to, "pdf"))
266 return OutputParams::PDFLATEX;
268 return OutputParams::LATEX;
272 bool Converters::convert(Buffer const * buffer,
273 string const & from_file, string const & to_file_base,
274 string const & from_format, string const & to_format,
277 to_file = ChangeExtension(to_file_base,
278 formats.extension(to_format));
280 if (from_format == to_format)
281 return move(from_file, to_file, false);
283 Graph::EdgePath edgepath = getPath(from_format, to_format);
284 if (edgepath.empty()) {
287 OutputParams runparams;
288 runparams.flavor = getFlavor(edgepath);
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;
359 buffer->message(_("Executing command: ")
362 Systemcall::Starttype type = (dummy)
363 ? Systemcall::DontWait : Systemcall::Wait;
366 if (conv.original_dir) {
367 Path p(buffer->filePath());
368 res = one.startscript(type, command);
370 res = one.startscript(type, command);
372 if (!real_outfile.empty()) {
373 if (!rename(outfile, real_outfile))
377 << "renaming file " << outfile
378 << " to " << real_outfile
382 if (!conv.parselog.empty()) {
383 string const logfile = infile2 + ".log";
384 string const script = LibScriptSearch(conv.parselog);
385 string const command2 = script +
386 " < " + QuoteName(infile2 + ".out") +
387 " > " + QuoteName(logfile);
388 one.startscript(Systemcall::Wait, command2);
389 if (!scanLog(*buffer, command, logfile))
394 if (conv.to == "program") {
395 Alert::error(_("Build errors"),
396 _("There were errors during the build process."));
398 // FIXME: this should go out of here. For example, here we cannot say if
399 // it is a document (.lyx) or something else. Same goes for elsewhere.
400 Alert::error(_("Cannot convert file"),
401 bformat(_("An error occurred whilst running %1$s"),
402 command.substr(0, 50)));
409 Converter const & conv = converterlist_[edgepath.back()];
410 if (conv.To->dummy())
414 if (!conv.result_dir.empty()) {
415 to_file = AddName(subst(conv.result_dir, token_base, to_base),
416 subst(conv.result_file,
417 token_base, OnlyFilename(to_base)));
418 if (from_base != to_base) {
419 string from = subst(conv.result_dir,
420 token_base, from_base);
421 string to = subst(conv.result_dir,
422 token_base, to_base);
423 if (!rename(from, to)) {
424 Alert::error(_("Cannot convert file"),
425 bformat(_("Could not move a temporary file from %1$s to %2$s."),
432 return move(outfile, to_file, conv.latex);
436 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
437 // moves each /path/file*.ext file to /path2/file2*.ext2'
438 bool Converters::move(string const & from, string const & to, bool copy)
443 bool no_errors = true;
444 string const path = OnlyPath(from);
445 string const base = OnlyFilename(ChangeExtension(from, ""));
446 string const to_base = ChangeExtension(to, "");
447 string const to_extension = GetExtension(to);
449 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
450 for (vector<string>::const_iterator it = files.begin();
451 it != files.end(); ++it)
452 if (prefixIs(*it, base)) {
453 string const from2 = path + *it;
454 string to2 = to_base + it->substr(base.length());
455 to2 = ChangeExtension(to2, to_extension);
456 lyxerr[Debug::FILES] << "moving " << from2
457 << " to " << to2 << endl;
458 bool const moved = (copy)
459 ? lyx::support::copy(from2, to2)
460 : rename(from2, to2);
461 if (!moved && no_errors) {
462 Alert::error(_("Cannot convert file"),
463 bformat(_("Could not move a temporary file from %1$s to %2$s."),
472 bool Converters::convert(Buffer const * buffer,
473 string const & from_file, string const & to_file_base,
474 string const & from_format, string const & to_format)
477 return convert(buffer, from_file, to_file_base, from_format, to_format,
482 bool Converters::formatIsUsed(string const & format)
484 ConverterList::const_iterator cit = converterlist_.begin();
485 ConverterList::const_iterator end = converterlist_.end();
486 for (; cit != end; ++cit) {
487 if (cit->from == format || cit->to == format)
494 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
495 string const & filename)
497 OutputParams runparams;
498 runparams.flavor = OutputParams::LATEX;
499 LaTeX latex("", runparams, filename, "");
501 int result = latex.scanLogFile(terr);
503 if (result & LaTeX::ERRORS)
504 bufferErrors(buffer, terr);
511 class showMessage : public boost::signals::trackable {
513 showMessage(Buffer const & b) : buffer_(b) {};
514 void operator()(string const & m)
519 Buffer const & buffer_;
525 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
526 OutputParams const & runparams)
529 buffer.message(_("Running LaTeX..."));
531 // do the LaTeX run(s)
532 string name = buffer.getLatexName();
533 LaTeX latex(command, runparams, name, buffer.filePath());
535 showMessage show(buffer);
536 latex.message.connect(show);
537 int result = latex.run(terr);
539 if (result & LaTeX::ERRORS)
540 bufferErrors(buffer, terr);
542 // check return value from latex.run().
543 if ((result & LaTeX::NO_LOGFILE)) {
544 string str = bformat(_("LaTeX did not run successfully. "
545 "Additionally, LyX could not locate "
546 "the LaTeX log %1$s."), name);
547 Alert::error(_("LaTeX failed"), str);
548 } else if (result & LaTeX::NO_OUTPUT) {
549 Alert::warning(_("Output is empty"),
550 _("An empty output file was generated."));
556 int const ERROR_MASK =
561 return (result & ERROR_MASK) == 0;
567 void Converters::buildGraph()
569 G_.init(formats.size());
570 ConverterList::iterator beg = converterlist_.begin();
571 ConverterList::iterator end = converterlist_.end();
572 for (ConverterList::iterator it = beg; it != end ; ++it) {
573 int const s = formats.getNumber(it->from);
574 int const t = formats.getNumber(it->to);
580 std::vector<Format const *> const
581 Converters::intToFormat(std::vector<int> const & input)
583 vector<Format const *> result(input.size());
585 vector<int>::const_iterator it = input.begin();
586 vector<int>::const_iterator end = input.end();
587 vector<Format const *>::iterator rit = result.begin();
588 for ( ; it != end; ++it, ++rit) {
589 *rit = &formats.get(*it);
594 vector<Format const *> const
595 Converters::getReachableTo(string const & target, bool clear_visited)
597 vector<int> const & reachablesto =
598 G_.getReachableTo(formats.getNumber(target), clear_visited);
600 return intToFormat(reachablesto);
604 vector<Format const *> const
605 Converters::getReachable(string const & from, bool only_viewable,
608 vector<int> const & reachables =
609 G_.getReachable(formats.getNumber(from),
613 return intToFormat(reachables);
617 bool Converters::isReachable(string const & from, string const & to)
619 return G_.isReachable(formats.getNumber(from),
620 formats.getNumber(to));
624 Graph::EdgePath const
625 Converters::getPath(string const & from, string const & to)
627 return G_.getPath(formats.getNumber(from),
628 formats.getNumber(to));
632 /// The global instance
633 Converters converters;
635 // The global copy after reading lyxrc.defaults
636 Converters system_converters;