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"
14 #include "bufferparams.h"
17 #include "buffer_funcs.h"
22 #include "frontends/Alert.h"
24 #include "support/filetools.h"
25 #include "support/lyxlib.h"
26 #include "support/path.h"
27 #include "support/systemcall.h"
29 using namespace lyx::support;
39 string const token_from("$$i");
40 string const token_base("$$b");
41 string const token_to("$$o");
42 string const token_path("$$p");
46 string const add_options(string const & command, string const & options)
49 string const tail = split(command, head, ' ');
50 return head + ' ' + options + ' ' + tail;
54 string const dvipdfm_options(BufferParams const & bp)
58 if (bp.papersize2 != VM_PAPER_CUSTOM) {
59 string const paper_size = bp.paperSizeName();
60 if (paper_size != "b5" && paper_size != "foolscap")
61 result = "-p "+ paper_size;
63 if (bp.orientation == ORIENTATION_LANDSCAPE)
73 Converter::Converter(string const & f, string const & t, string const & c,
74 string const & l): from(f), to(t), command(c), flags(l),
75 From(0), To(0), latex(false),
76 original_dir(false), need_aux(false)
80 void Converter::readFlags()
82 string flag_list(flags);
83 while (!flag_list.empty()) {
84 string flag_name, flag_value;
85 flag_list = split(flag_list, flag_value, ',');
86 flag_value = split(flag_value, flag_name, '=');
87 if (flag_name == "latex")
89 else if (flag_name == "originaldir")
91 else if (flag_name == "needaux")
93 else if (flag_name == "resultdir")
94 result_dir = (flag_value.empty())
95 ? token_base : flag_value;
96 else if (flag_name == "resultfile")
97 result_file = flag_value;
98 else if (flag_name == "parselog")
99 parselog = flag_value;
101 if (!result_dir.empty() && result_file.empty())
102 result_file = "index." + formats.extension(to);
103 //if (!contains(command, token_from))
108 bool operator<(Converter const & a, Converter const & b)
110 // use the compare_ascii_no_case instead of compare_no_case,
111 // because in turkish, 'i' is not the lowercase version of 'I',
112 // and thus turkish locale breaks parsing of tags.
113 int const i = compare_ascii_no_case(a.From->prettyname(),
114 b.From->prettyname());
116 return compare_ascii_no_case(a.To->prettyname(),
117 b.To->prettyname()) < 0;
123 class compare_Converter {
125 compare_Converter(string const & f, string const & t)
127 bool operator()(Converter const & c) {
128 return c.from == from && c.to == to;
137 Converter const * Converters::getConverter(string const & from,
140 ConverterList::const_iterator cit =
141 find_if(converterlist_.begin(), converterlist_.end(),
142 compare_Converter(from, to));
143 if (cit != converterlist_.end())
150 int Converters::getNumber(string const & from, string const & to)
152 ConverterList::const_iterator cit =
153 find_if(converterlist_.begin(), converterlist_.end(),
154 compare_Converter(from, to));
155 if (cit != converterlist_.end())
156 return cit - converterlist_.begin();
162 void Converters::add(string const & from, string const & to,
163 string const & command, string const & flags)
167 ConverterList::iterator it = find_if(converterlist_.begin(),
168 converterlist_.end(),
169 compare_Converter(from, to));
171 Converter converter(from, to, command, flags);
172 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
174 converter.command = command;
175 converter.flags = flags;
177 converter.readFlags();
179 if (converter.latex && (latex_command_.empty() || to == "dvi"))
180 latex_command_ = subst(command, token_from, "");
181 // If we have both latex & pdflatex, we set latex_command to latex.
182 // The latex_command is used to update the .aux file when running
183 // a converter that uses it.
185 if (it == converterlist_.end()) {
186 converterlist_.push_back(converter);
188 converter.From = it->From;
189 converter.To = it->To;
195 void Converters::erase(string const & from, string const & to)
197 ConverterList::iterator it = find_if(converterlist_.begin(),
198 converterlist_.end(),
199 compare_Converter(from, to));
200 if (it != converterlist_.end())
201 converterlist_.erase(it);
205 // This method updates the pointers From and To in all the converters.
206 // The code is not very efficient, but it doesn't matter as the number
207 // of formats and converters is small.
208 // Furthermore, this method is called only on startup, or after
209 // adding/deleting a format in FormPreferences (the latter calls can be
210 // eliminated if the formats in the Formats class are stored using a map or
211 // a list (instead of a vector), but this will cause other problems).
212 void Converters::update(Formats const & formats)
214 ConverterList::iterator it = converterlist_.begin();
215 ConverterList::iterator end = converterlist_.end();
216 for (; it != end; ++it) {
217 it->From = formats.getFormat(it->from);
218 it->To = formats.getFormat(it->to);
223 // This method updates the pointers From and To in the last converter.
224 // It is called when adding a new converter in FormPreferences
225 void Converters::updateLast(Formats const & formats)
227 if (converterlist_.begin() != converterlist_.end()) {
228 ConverterList::iterator it = converterlist_.end() - 1;
229 it->From = formats.getFormat(it->from);
230 it->To = formats.getFormat(it->to);
235 void Converters::sort()
237 std::sort(converterlist_.begin(), converterlist_.end());
241 bool Converters::usePdflatex(Graph::EdgePath const & path)
243 for (Graph::EdgePath::const_iterator cit = path.begin();
244 cit != path.end(); ++cit) {
245 Converter const & conv = converterlist_[*cit];
247 return contains(conv.to, "pdf");
253 bool Converters::convert(Buffer const * buffer,
254 string const & from_file, string const & to_file_base,
255 string const & from_format, string const & to_format,
258 to_file = ChangeExtension(to_file_base,
259 formats.extension(to_format));
261 if (from_format == to_format)
262 return move(from_file, to_file, false);
264 Graph::EdgePath edgepath = getPath(from_format, to_format);
265 if (edgepath.empty()) {
268 LatexRunParams runparams;
269 runparams.flavor = usePdflatex(edgepath) ?
270 LatexRunParams::PDFLATEX : LatexRunParams::LATEX;
272 string path = OnlyPath(from_file);
275 bool run_latex = false;
276 string from_base = ChangeExtension(from_file, "");
277 string to_base = ChangeExtension(to_file, "");
279 string outfile = from_file;
280 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
281 cit != edgepath.end(); ++cit) {
282 Converter const & conv = converterlist_[*cit];
283 bool dummy = conv.To->dummy() && conv.to != "program";
285 lyxerr[Debug::FILES] << "Converting from "
286 << conv.from << " to " << conv.to << endl;
288 outfile = conv.result_dir.empty()
289 ? ChangeExtension(from_file, conv.To->extension())
290 : AddName(subst(conv.result_dir,
291 token_base, from_base),
292 subst(conv.result_file,
293 token_base, OnlyFilename(from_base)));
295 // if input and output files are equal, we use a
296 // temporary file as intermediary (JMarc)
298 if (outfile == infile) {
299 real_outfile = infile;
300 outfile = AddName(buffer->temppath(), "tmpfile.out");
305 string command = subst(conv.command, token_from, "");
306 lyxerr[Debug::FILES] << "Running " << command << endl;
307 if (!runLaTeX(*buffer, command, runparams))
310 if (conv.need_aux && !run_latex
311 && !latex_command_.empty()) {
313 << "Running " << latex_command_
314 << " to update aux file"<< endl;
315 runLaTeX(*buffer, latex_command_, runparams);
318 string infile2 = (conv.original_dir)
319 ? infile : MakeRelPath(infile, path);
320 string outfile2 = (conv.original_dir)
321 ? outfile : MakeRelPath(outfile, path);
323 string command = conv.command;
324 command = subst(command, token_from, QuoteName(infile2));
325 command = subst(command, token_base, QuoteName(from_base));
326 command = subst(command, token_to, QuoteName(outfile2));
327 command = LibScriptSearch(command);
329 if (!conv.parselog.empty())
330 command += " 2> " + QuoteName(infile2 + ".out");
332 if (conv.from == "dvi" && conv.to == "ps")
333 command = add_options(command,
334 buffer->params().dvips_options());
335 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
336 command = add_options(command,
337 dvipdfm_options(buffer->params()));
339 lyxerr[Debug::FILES] << "Calling " << command << endl;
340 buffer->message(_("Executing command: ") + command);
342 Systemcall::Starttype type = (dummy)
343 ? Systemcall::DontWait : Systemcall::Wait;
346 if (conv.original_dir) {
347 Path p(buffer->filePath());
348 res = one.startscript(type, command);
350 res = one.startscript(type, command);
352 if (!real_outfile.empty()) {
353 if (!rename(outfile, real_outfile))
357 << "renaming file " << outfile
358 << " to " << real_outfile
362 if (!conv.parselog.empty()) {
363 string const logfile = infile2 + ".log";
364 string const script = LibScriptSearch(conv.parselog);
365 string const command2 = script +
366 " < " + QuoteName(infile2 + ".out") +
367 " > " + QuoteName(logfile);
368 one.startscript(Systemcall::Wait, command2);
369 if (!scanLog(*buffer, command, logfile))
374 if (conv.to == "program") {
375 Alert::error(_("Build errors"),
376 _("There were errors during the build process."));
378 // FIXME: this should go out of here. For example, here we cannot say if
379 // it is a document (.lyx) or something else. Same goes for elsewhere.
380 Alert::error(_("Cannot convert file"),
381 bformat(_("An error occurred whilst running %1$s"),
382 command.substr(0, 50)));
389 Converter const & conv = converterlist_[edgepath.back()];
390 if (conv.To->dummy())
394 if (!conv.result_dir.empty()) {
395 to_file = AddName(subst(conv.result_dir, token_base, to_base),
396 subst(conv.result_file,
397 token_base, OnlyFilename(to_base)));
398 if (from_base != to_base) {
399 string from = subst(conv.result_dir,
400 token_base, from_base);
401 string to = subst(conv.result_dir,
402 token_base, to_base);
403 if (!rename(from, to)) {
404 Alert::error(_("Cannot convert file"),
405 bformat(_("Could not move a temporary file from %1$s to %2$s."),
412 return move(outfile, to_file, conv.latex);
416 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
417 // moves each /path/file*.ext file to /path2/file2*.ext2'
418 bool Converters::move(string const & from, string const & to, bool copy)
423 bool no_errors = true;
424 string const path = OnlyPath(from);
425 string const base = OnlyFilename(ChangeExtension(from, ""));
426 string const to_base = ChangeExtension(to, "");
427 string const to_extension = GetExtension(to);
429 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
430 for (vector<string>::const_iterator it = files.begin();
431 it != files.end(); ++it)
432 if (prefixIs(*it, base)) {
433 string const from2 = path + *it;
434 string to2 = to_base + it->substr(base.length());
435 to2 = ChangeExtension(to2, to_extension);
436 lyxerr[Debug::FILES] << "moving " << from2
437 << " to " << to2 << endl;
438 bool const moved = (copy)
439 ? lyx::support::copy(from2, to2)
440 : rename(from2, to2);
441 if (!moved && no_errors) {
442 Alert::error(_("Cannot convert file"),
443 bformat(_("Could not move a temporary file from %1$s to %2$s."),
452 bool Converters::convert(Buffer const * buffer,
453 string const & from_file, string const & to_file_base,
454 string const & from_format, string const & to_format)
457 return convert(buffer, from_file, to_file_base, from_format, to_format,
462 bool Converters::formatIsUsed(string const & format)
464 ConverterList::const_iterator cit = converterlist_.begin();
465 ConverterList::const_iterator end = converterlist_.end();
466 for (; cit != end; ++cit) {
467 if (cit->from == format || cit->to == format)
474 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
475 string const & filename)
477 LatexRunParams runparams;
478 runparams.flavor = LatexRunParams::LATEX;
479 LaTeX latex("", runparams, filename, "");
481 int result = latex.scanLogFile(terr);
483 if (result & LaTeX::ERRORS)
484 bufferErrors(buffer, terr);
491 class showMessage : public boost::signals::trackable {
493 showMessage(Buffer const & b) : buffer_(b) {};
494 void operator()(string const & m)
499 Buffer const & buffer_;
505 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
506 LatexRunParams const & runparams)
509 buffer.message(_("Running LaTeX..."));
511 // do the LaTeX run(s)
512 string name = buffer.getLatexName();
513 LaTeX latex(command, runparams, name, buffer.filePath());
515 showMessage show(buffer);
516 latex.message.connect(show);
517 int result = latex.run(terr);
519 if (result & LaTeX::ERRORS)
520 bufferErrors(buffer, terr);
522 // check return value from latex.run().
523 if ((result & LaTeX::NO_LOGFILE)) {
524 string str = bformat(_("LaTeX did not run successfully. "
525 "Additionally, LyX could not locate "
526 "the LaTeX log %1$s."), name);
527 Alert::error(_("LaTeX failed"), str);
528 } else if (result & LaTeX::NO_OUTPUT) {
529 Alert::warning(_("Output is empty"),
530 _("An empty output file was generated."));
536 int const ERROR_MASK =
541 return (result & ERROR_MASK) == 0;
547 void Converters::buildGraph()
549 G_.init(formats.size());
550 ConverterList::iterator beg = converterlist_.begin();
551 ConverterList::iterator end = converterlist_.end();
552 for (ConverterList::iterator it = beg; it != end ; ++it) {
553 int const s = formats.getNumber(it->from);
554 int const t = formats.getNumber(it->to);
560 std::vector<Format const *> const
561 Converters::intToFormat(std::vector<int> const & input)
563 vector<Format const *> result(input.size());
565 vector<int>::const_iterator it = input.begin();
566 vector<int>::const_iterator end = input.end();
567 vector<Format const *>::iterator rit = result.begin();
568 for ( ; it != end; ++it, ++rit) {
569 *rit = &formats.get(*it);
574 vector<Format const *> const
575 Converters::getReachableTo(string const & target, bool clear_visited)
577 vector<int> const & reachablesto =
578 G_.getReachableTo(formats.getNumber(target), clear_visited);
580 return intToFormat(reachablesto);
584 vector<Format const *> const
585 Converters::getReachable(string const & from, bool only_viewable,
588 vector<int> const & reachables =
589 G_.getReachable(formats.getNumber(from),
593 return intToFormat(reachables);
597 bool Converters::isReachable(string const & from, string const & to)
599 return G_.isReachable(formats.getNumber(from),
600 formats.getNumber(to));
604 Graph::EdgePath const
605 Converters::getPath(string const & from, string const & to)
607 return G_.getPath(formats.getNumber(from),
608 formats.getNumber(to));
612 /// The global instance
613 Converters converters;
615 // The global copy after reading lyxrc.defaults
616 Converters system_converters;