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"
18 #include "bufferview_funcs.h"
20 #include "lyx_cb.h" // ShowMessage()
22 #include "BufferView.h"
25 #include "frontends/Alert.h"
26 #include "frontends/LyXView.h"
28 #include "support/filetools.h"
29 #include "support/lyxfunctional.h"
30 #include "support/path.h"
31 #include "support/tostr.h"
32 #include "support/systemcall.h"
36 #ifndef CXX_GLOBAL_CSTD
46 string const token_from("$$i");
47 string const token_base("$$b");
48 string const token_to("$$o");
49 string const token_path("$$p");
53 string const add_options(string const & command, string const & options)
56 string const tail = split(command, head, ' ');
57 return head + ' ' + options + ' ' + tail;
63 Converter::Converter(string const & f, string const & t, string const & c,
64 string const & l): from(f), to(t), command(c), flags(l),
65 From(0), To(0), latex(false),
66 original_dir(false), need_aux(false)
69 void Converter::readFlags()
71 string flag_list(flags);
72 while (!flag_list.empty()) {
73 string flag_name, flag_value;
74 flag_list = split(flag_list, flag_value, ',');
75 flag_value = split(flag_value, flag_name, '=');
76 if (flag_name == "latex")
78 else if (flag_name == "originaldir")
80 else if (flag_name == "needaux")
82 else if (flag_name == "resultdir")
83 result_dir = (flag_value.empty())
84 ? token_base : flag_value;
85 else if (flag_name == "resultfile")
86 result_file = flag_value;
87 else if (flag_name == "parselog")
88 parselog = flag_value;
90 if (!result_dir.empty() && result_file.empty())
91 result_file = "index." + formats.extension(to);
92 //if (!contains(command, token_from))
97 bool operator<(Converter const & a, Converter const & b)
99 // use the compare_ascii_no_case instead of compare_no_case,
100 // because in turkish, 'i' is not the lowercase version of 'I',
101 // and thus turkish locale breaks parsing of tags.
102 int const i = compare_ascii_no_case(a.From->prettyname(),
103 b.From->prettyname());
105 return compare_ascii_no_case(a.To->prettyname(), b.To->prettyname())
113 class compare_Converter {
115 compare_Converter(string const & f, string const & t)
117 bool operator()(Converter const & c) {
118 return c.from == from && c.to == to;
127 Converter const * Converters::getConverter(string const & from,
130 ConverterList::const_iterator cit =
131 find_if(converterlist_.begin(), converterlist_.end(),
132 compare_Converter(from, to));
133 if (cit != converterlist_.end())
140 int Converters::getNumber(string const & from, string const & to)
142 ConverterList::const_iterator cit =
143 find_if(converterlist_.begin(), converterlist_.end(),
144 compare_Converter(from, to));
145 if (cit != converterlist_.end())
146 return cit - converterlist_.begin();
152 void Converters::add(string const & from, string const & to,
153 string const & command, string const & flags)
157 ConverterList::iterator it = find_if(converterlist_.begin(),
158 converterlist_.end(),
159 compare_Converter(from, to));
161 Converter converter(from, to, command, flags);
162 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
164 converter.command = command;
165 converter.flags = flags;
167 converter.readFlags();
169 if (converter.latex && (latex_command_.empty() || to == "dvi"))
170 latex_command_ = subst(command, token_from, "");
171 // If we have both latex & pdflatex, we set latex_command to latex.
172 // The latex_command is used to update the .aux file when running
173 // a converter that uses it.
175 if (it == converterlist_.end()) {
176 converterlist_.push_back(converter);
178 converter.From = it->From;
179 converter.To = it->To;
185 void Converters::erase(string const & from, string const & to)
187 ConverterList::iterator it = find_if(converterlist_.begin(),
188 converterlist_.end(),
189 compare_Converter(from, to));
190 if (it != converterlist_.end())
191 converterlist_.erase(it);
195 // This method updates the pointers From and To in all the converters.
196 // The code is not very efficient, but it doesn't matter as the number
197 // of formats and converters is small.
198 // Furthermore, this method is called only on startup, or after
199 // adding/deleting a format in FormPreferences (the latter calls can be
200 // eliminated if the formats in the Formats class are stored using a map or
201 // a list (instead of a vector), but this will cause other problems).
202 void Converters::update(Formats const & formats)
204 ConverterList::iterator it = converterlist_.begin();
205 ConverterList::iterator end = converterlist_.end();
206 for (; it != end; ++it) {
207 it->From = formats.getFormat(it->from);
208 it->To = formats.getFormat(it->to);
213 // This method updates the pointers From and To in the last converter.
214 // It is called when adding a new converter in FormPreferences
215 void Converters::updateLast(Formats const & formats)
217 if (converterlist_.begin() != converterlist_.end()) {
218 ConverterList::iterator it = converterlist_.end() - 1;
219 it->From = formats.getFormat(it->from);
220 it->To = formats.getFormat(it->to);
225 void Converters::sort()
227 std::sort(converterlist_.begin(), converterlist_.end());
231 bool Converters::usePdflatex(Graph::EdgePath const & path)
233 for (Graph::EdgePath::const_iterator cit = path.begin();
234 cit != path.end(); ++cit) {
235 Converter const & conv = converterlist_[*cit];
237 return contains(conv.to, "pdf");
243 bool Converters::convert(Buffer const * buffer,
244 string const & from_file, string const & to_file_base,
245 string const & from_format, string const & to_format,
248 to_file = ChangeExtension(to_file_base,
249 formats.extension(to_format));
251 if (from_format == to_format)
252 return move(from_file, to_file, false);
254 Graph::EdgePath edgepath = getPath(from_format, to_format);
255 if (edgepath.empty()) {
259 string path = OnlyPath(from_file);
262 bool run_latex = false;
263 string from_base = ChangeExtension(from_file, "");
264 string to_base = ChangeExtension(to_file, "");
266 string outfile = from_file;
267 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
268 cit != edgepath.end(); ++cit) {
269 Converter const & conv = converterlist_[*cit];
270 bool dummy = conv.To->dummy() && conv.to != "program";
272 lyxerr[Debug::FILES] << "Converting from "
273 << conv.from << " to " << conv.to << endl;
275 outfile = conv.result_dir.empty()
276 ? ChangeExtension(from_file, conv.To->extension())
277 : AddName(subst(conv.result_dir,
278 token_base, from_base),
279 subst(conv.result_file,
280 token_base, OnlyFilename(from_base)));
282 // if input and output files are equal, we use a
283 // temporary file as intermediary (JMarc)
285 if (outfile == infile) {
286 real_outfile = infile;
287 outfile = AddName(buffer->tmppath, "tmpfile.out");
292 string command = subst(conv.command, token_from, "");
293 lyxerr[Debug::FILES] << "Running " << command << endl;
294 if (!runLaTeX(buffer, command))
297 if (conv.need_aux && !run_latex
298 && !latex_command_.empty()) {
300 << "Running " << latex_command_
301 << " to update aux file"<< endl;
302 runLaTeX(buffer, latex_command_);
305 string infile2 = (conv.original_dir)
306 ? infile : MakeRelPath(infile, path);
307 string outfile2 = (conv.original_dir)
308 ? outfile : MakeRelPath(outfile, path);
310 string command = conv.command;
311 command = subst(command, token_from, QuoteName(infile2));
312 command = subst(command, token_base, QuoteName(from_base));
313 command = subst(command, token_to, QuoteName(outfile2));
314 command = LibScriptSearch(command);
316 if (!conv.parselog.empty())
317 command += " 2> " + QuoteName(infile2 + ".out");
319 if (conv.from == "dvi" && conv.to == "ps")
320 command = add_options(command,
321 dvips_options(buffer));
322 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
323 command = add_options(command,
324 dvipdfm_options(buffer));
326 lyxerr[Debug::FILES] << "Calling " << command << endl;
328 ShowMessage(buffer, _("Executing command:"), command);
330 Systemcall::Starttype type = (dummy)
331 ? Systemcall::DontWait : Systemcall::Wait;
334 if (conv.original_dir && buffer) {
335 Path p(buffer->filePath());
336 res = one.startscript(type, command);
338 res = one.startscript(type, command);
340 if (!real_outfile.empty()) {
341 if (!lyx::rename(outfile, real_outfile))
345 << "renaming file " << outfile
346 << " to " << real_outfile
350 if (!conv.parselog.empty()) {
351 string const logfile = infile2 + ".log";
352 string const script = LibScriptSearch(conv.parselog);
353 string const command2 = script +
354 " < " + QuoteName(infile2 + ".out") +
355 " > " + QuoteName(logfile);
356 one.startscript(Systemcall::Wait, command2);
357 if (!scanLog(buffer, command, logfile))
362 if (conv.to == "program") {
363 Alert::error(_("Build errors"),
364 _("There were errors during the build process."));
366 // FIXME: this should go out of here. For example, here we cannot say if
367 // it is a document (.lyx) or something else. Same goes for elsewhere.
368 Alert::error(_("Cannot convert file"),
369 bformat(_("An error occurred whilst running %1$s"),
370 command.substr(0, 50)));
377 Converter const & conv = converterlist_[edgepath.back()];
378 if (conv.To->dummy())
382 if (!conv.result_dir.empty()) {
383 to_file = AddName(subst(conv.result_dir, token_base, to_base),
384 subst(conv.result_file,
385 token_base, OnlyFilename(to_base)));
386 if (from_base != to_base) {
387 string from = subst(conv.result_dir,
388 token_base, from_base);
389 string to = subst(conv.result_dir,
390 token_base, to_base);
391 if (!lyx::rename(from, to)) {
392 Alert::error(_("Cannot convert file"),
393 bformat(_("Could not move a temporary file from %1$s to %2$s."),
400 return move(outfile, to_file, conv.latex);
404 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
405 // moves each /path/file*.ext file to /path2/file2*.ext2'
406 bool Converters::move(string const & from, string const & to, bool copy)
411 bool no_errors = true;
412 string const path = OnlyPath(from);
413 string const base = OnlyFilename(ChangeExtension(from, ""));
414 string const to_base = ChangeExtension(to, "");
415 string const to_extension = GetExtension(to);
417 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
418 for (vector<string>::const_iterator it = files.begin();
419 it != files.end(); ++it)
420 if (prefixIs(*it, base)) {
421 string const from2 = path + *it;
422 string to2 = to_base + it->substr(base.length());
423 to2 = ChangeExtension(to2, to_extension);
424 lyxerr[Debug::FILES] << "moving " << from2
425 << " to " << to2 << endl;
426 bool const moved = (copy)
427 ? lyx::copy(from2, to2)
428 : lyx::rename(from2, to2);
429 if (!moved && no_errors) {
430 Alert::error(_("Cannot convert file"),
431 bformat(_("Could not move a temporary file from %1$s to %2$s."),
440 bool Converters::convert(Buffer const * buffer,
441 string const & from_file, string const & to_file_base,
442 string const & from_format, string const & to_format)
445 return convert(buffer, from_file, to_file_base, from_format, to_format,
450 bool Converters::formatIsUsed(string const & format)
452 ConverterList::const_iterator cit = converterlist_.begin();
453 ConverterList::const_iterator end = converterlist_.end();
454 for (; cit != end; ++cit) {
455 if (cit->from == format || cit->to == format)
464 void alertErrors(string const & prog, int nr_errors)
468 s = bformat(_("One error detected when running %1$s.\n"), prog);
470 s = bformat(_("%1$s errors detected when running %2$s.\n"),
471 prog, tostr(nr_errors));
472 Alert::error(_("Errors found"), s);
478 bool Converters::scanLog(Buffer const * buffer, string const & command,
479 string const & filename)
484 BufferView * bv = buffer->getUser();
486 bv->owner()->busy(true);
487 // all error insets should have been removed by now
490 LaTeX latex("", filename, "");
492 int result = latex.scanLogFile(terr);
494 if ((result & LaTeX::ERRORS)) {
495 // Insert all errors as errors boxes
496 bv->insertErrors(terr);
497 #warning repaint() or update() or nothing ?
501 bv->owner()->busy(false);
504 if ((result & LaTeX::ERRORS)) {
506 split(command, head, ' ');
507 alertErrors(head, latex.getNumErrors());
509 } else if (result & LaTeX::NO_OUTPUT) {
510 Alert::warning(_("Output is empty"),
511 _("An empty output file was generated."));
518 bool Converters::runLaTeX(Buffer const * buffer, string const & command)
523 BufferView * bv = buffer->getUser();
526 bv->owner()->busy(true);
527 bv->owner()->message(_("Running LaTeX..."));
528 // all the autoinsets have already been removed
531 // do the LaTeX run(s)
532 string name = buffer->getLatexName();
533 LaTeX latex(command, name, buffer->filePath());
535 int result = latex.run(terr,
536 bv ? &bv->owner()->getLyXFunc() : 0);
539 if ((result & LaTeX::ERRORS)) {
540 // Insert all errors as errors boxes
541 bv->insertErrors(terr);
542 #warning repaint() or update() or nothing ?
548 // check return value from latex.run().
549 if ((result & LaTeX::NO_LOGFILE)) {
550 string str = bformat(_("LaTeX did not run successfully. Additionally, LyX "
551 "could not locate the LaTeX log %1$s."), name);
552 Alert::error(_("LaTeX failed"), str);
553 } else if ((result & LaTeX::ERRORS)) {
554 alertErrors("LaTeX", latex.getNumErrors());
555 } else if (result & LaTeX::NO_OUTPUT) {
556 Alert::warning(_("Output is empty"),
557 _("An empty output file was generated."));
561 bv->owner()->busy(false);
563 int const ERROR_MASK =
568 return (result & ERROR_MASK) == 0;
573 string const Converters::dvips_options(Buffer const * buffer)
579 if (buffer->params.use_geometry
580 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
581 && !lyxrc.print_paper_dimension_flag.empty()
582 && !buffer->params.paperwidth.empty()
583 && !buffer->params.paperheight.empty()) {
584 // using a custom papersize
585 result = lyxrc.print_paper_dimension_flag;
586 result += ' ' + buffer->params.paperwidth;
587 result += ',' + buffer->params.paperheight;
589 string const paper_option = papersize(buffer);
590 if (paper_option != "letter" ||
591 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
592 // dvips won't accept -t letter -t landscape. In all other
593 // cases, include the paper size explicitly.
594 result = lyxrc.print_paper_flag;
595 result += ' ' + paper_option;
598 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
599 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
600 result += ' ' + lyxrc.print_landscape_flag;
605 string const Converters::dvipdfm_options(Buffer const * buffer)
611 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
612 string const paper_size = papersize(buffer);
613 if (paper_size != "b5" && paper_size != "foolscap")
614 result = "-p "+ paper_size;
616 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
623 void Converters::buildGraph()
625 G_.init(formats.size());
626 ConverterList::iterator beg = converterlist_.begin();
627 ConverterList::iterator end = converterlist_.end();
628 for (ConverterList::iterator it = beg; it != end ; ++it) {
629 int const s = formats.getNumber(it->from);
630 int const t = formats.getNumber(it->to);
635 vector<Format const *> const
636 Converters::intToFormat(std::vector<int> const & input)
638 vector<Format const *> result(input.size());
640 vector<int>::const_iterator it = input.begin();
641 vector<int>::const_iterator end = input.end();
642 vector<Format const *>::iterator rit = result.begin();
643 for ( ; it != end; ++it, ++rit) {
644 *rit = &formats.get(*it);
649 vector<Format const *> const
650 Converters::getReachableTo(string const & target, bool clear_visited)
652 vector<int> const & reachablesto =
653 G_.getReachableTo(formats.getNumber(target), clear_visited);
655 return intToFormat(reachablesto);
658 vector<Format const *> const
659 Converters::getReachable(string const & from, bool only_viewable,
662 vector<int> const & reachables =
663 G_.getReachable(formats.getNumber(from),
667 return intToFormat(reachables);
670 bool Converters::isReachable(string const & from, string const & to)
672 return G_.isReachable(formats.getNumber(from),
673 formats.getNumber(to));
676 Graph::EdgePath const
677 Converters::getPath(string const & from, string const & to)
679 return G_.getPath(formats.getNumber(from),
680 formats.getNumber(to));
683 /// The global instance
684 Converters converters;
686 // The global copy after reading lyxrc.defaults
687 Converters system_converters;