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 "buffer_funcs.h"
19 #include "bufferview_funcs.h"
20 #include "errorlist.h"
22 #include "lyx_cb.h" // ShowMessage()
24 #include "BufferView.h"
27 #include "frontends/Alert.h"
28 #include "frontends/LyXView.h"
30 #include "support/filetools.h"
31 #include "support/lyxfunctional.h"
32 #include "support/path.h"
33 #include "support/tostr.h"
34 #include "support/systemcall.h"
38 using namespace lyx::support;
40 #ifndef CXX_GLOBAL_CSTD
50 string const token_from("$$i");
51 string const token_base("$$b");
52 string const token_to("$$o");
53 string const token_path("$$p");
57 string const add_options(string const & command, string const & options)
60 string const tail = split(command, head, ' ');
61 return head + ' ' + options + ' ' + tail;
67 Converter::Converter(string const & f, string const & t, string const & c,
68 string const & l): from(f), to(t), command(c), flags(l),
69 From(0), To(0), latex(false),
70 original_dir(false), need_aux(false)
74 void Converter::readFlags()
76 string flag_list(flags);
77 while (!flag_list.empty()) {
78 string flag_name, flag_value;
79 flag_list = split(flag_list, flag_value, ',');
80 flag_value = split(flag_value, flag_name, '=');
81 if (flag_name == "latex")
83 else if (flag_name == "originaldir")
85 else if (flag_name == "needaux")
87 else if (flag_name == "resultdir")
88 result_dir = (flag_value.empty())
89 ? token_base : flag_value;
90 else if (flag_name == "resultfile")
91 result_file = flag_value;
92 else if (flag_name == "parselog")
93 parselog = flag_value;
95 if (!result_dir.empty() && result_file.empty())
96 result_file = "index." + formats.extension(to);
97 //if (!contains(command, token_from))
102 bool operator<(Converter const & a, Converter const & b)
104 // use the compare_ascii_no_case instead of compare_no_case,
105 // because in turkish, 'i' is not the lowercase version of 'I',
106 // and thus turkish locale breaks parsing of tags.
107 int const i = compare_ascii_no_case(a.From->prettyname(),
108 b.From->prettyname());
110 return compare_ascii_no_case(a.To->prettyname(), b.To->prettyname())
118 class compare_Converter {
120 compare_Converter(string const & f, string const & t)
122 bool operator()(Converter const & c) {
123 return c.from == from && c.to == to;
132 Converter const * Converters::getConverter(string const & from,
135 ConverterList::const_iterator cit =
136 find_if(converterlist_.begin(), converterlist_.end(),
137 compare_Converter(from, to));
138 if (cit != converterlist_.end())
145 int Converters::getNumber(string const & from, string const & to)
147 ConverterList::const_iterator cit =
148 find_if(converterlist_.begin(), converterlist_.end(),
149 compare_Converter(from, to));
150 if (cit != converterlist_.end())
151 return cit - converterlist_.begin();
157 void Converters::add(string const & from, string const & to,
158 string const & command, string const & flags)
162 ConverterList::iterator it = find_if(converterlist_.begin(),
163 converterlist_.end(),
164 compare_Converter(from, to));
166 Converter converter(from, to, command, flags);
167 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
169 converter.command = command;
170 converter.flags = flags;
172 converter.readFlags();
174 if (converter.latex && (latex_command_.empty() || to == "dvi"))
175 latex_command_ = subst(command, token_from, "");
176 // If we have both latex & pdflatex, we set latex_command to latex.
177 // The latex_command is used to update the .aux file when running
178 // a converter that uses it.
180 if (it == converterlist_.end()) {
181 converterlist_.push_back(converter);
183 converter.From = it->From;
184 converter.To = it->To;
190 void Converters::erase(string const & from, string const & to)
192 ConverterList::iterator it = find_if(converterlist_.begin(),
193 converterlist_.end(),
194 compare_Converter(from, to));
195 if (it != converterlist_.end())
196 converterlist_.erase(it);
200 // This method updates the pointers From and To in all the converters.
201 // The code is not very efficient, but it doesn't matter as the number
202 // of formats and converters is small.
203 // Furthermore, this method is called only on startup, or after
204 // adding/deleting a format in FormPreferences (the latter calls can be
205 // eliminated if the formats in the Formats class are stored using a map or
206 // a list (instead of a vector), but this will cause other problems).
207 void Converters::update(Formats const & formats)
209 ConverterList::iterator it = converterlist_.begin();
210 ConverterList::iterator end = converterlist_.end();
211 for (; it != end; ++it) {
212 it->From = formats.getFormat(it->from);
213 it->To = formats.getFormat(it->to);
218 // This method updates the pointers From and To in the last converter.
219 // It is called when adding a new converter in FormPreferences
220 void Converters::updateLast(Formats const & formats)
222 if (converterlist_.begin() != converterlist_.end()) {
223 ConverterList::iterator it = converterlist_.end() - 1;
224 it->From = formats.getFormat(it->from);
225 it->To = formats.getFormat(it->to);
230 void Converters::sort()
232 std::sort(converterlist_.begin(), converterlist_.end());
236 bool Converters::usePdflatex(Graph::EdgePath const & path)
238 for (Graph::EdgePath::const_iterator cit = path.begin();
239 cit != path.end(); ++cit) {
240 Converter const & conv = converterlist_[*cit];
242 return contains(conv.to, "pdf");
248 bool Converters::convert(Buffer const * buffer,
249 string const & from_file, string const & to_file_base,
250 string const & from_format, string const & to_format,
253 to_file = ChangeExtension(to_file_base,
254 formats.extension(to_format));
256 if (from_format == to_format)
257 return move(from_file, to_file, false);
259 Graph::EdgePath edgepath = getPath(from_format, to_format);
260 if (edgepath.empty()) {
263 LatexRunParams runparams;
264 runparams.flavor = usePdflatex(edgepath) ?
265 LatexRunParams::PDFLATEX : LatexRunParams::LATEX;
267 string path = OnlyPath(from_file);
270 bool run_latex = false;
271 string from_base = ChangeExtension(from_file, "");
272 string to_base = ChangeExtension(to_file, "");
274 string outfile = from_file;
275 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
276 cit != edgepath.end(); ++cit) {
277 Converter const & conv = converterlist_[*cit];
278 bool dummy = conv.To->dummy() && conv.to != "program";
280 lyxerr[Debug::FILES] << "Converting from "
281 << conv.from << " to " << conv.to << endl;
283 outfile = conv.result_dir.empty()
284 ? ChangeExtension(from_file, conv.To->extension())
285 : AddName(subst(conv.result_dir,
286 token_base, from_base),
287 subst(conv.result_file,
288 token_base, OnlyFilename(from_base)));
290 // if input and output files are equal, we use a
291 // temporary file as intermediary (JMarc)
293 if (outfile == infile) {
294 real_outfile = infile;
295 outfile = AddName(buffer->tmppath, "tmpfile.out");
300 string command = subst(conv.command, token_from, "");
301 lyxerr[Debug::FILES] << "Running " << command << endl;
302 if (!runLaTeX(buffer, command, runparams))
305 if (conv.need_aux && !run_latex
306 && !latex_command_.empty()) {
308 << "Running " << latex_command_
309 << " to update aux file"<< endl;
310 runLaTeX(buffer, latex_command_, runparams);
313 string infile2 = (conv.original_dir)
314 ? infile : MakeRelPath(infile, path);
315 string outfile2 = (conv.original_dir)
316 ? outfile : MakeRelPath(outfile, path);
318 string command = conv.command;
319 command = subst(command, token_from, QuoteName(infile2));
320 command = subst(command, token_base, QuoteName(from_base));
321 command = subst(command, token_to, QuoteName(outfile2));
322 command = LibScriptSearch(command);
324 if (!conv.parselog.empty())
325 command += " 2> " + QuoteName(infile2 + ".out");
327 if (conv.from == "dvi" && conv.to == "ps")
328 command = add_options(command,
329 dvips_options(buffer));
330 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
331 command = add_options(command,
332 dvipdfm_options(buffer));
334 lyxerr[Debug::FILES] << "Calling " << command << endl;
336 ShowMessage(buffer, _("Executing command:"), command);
338 Systemcall::Starttype type = (dummy)
339 ? Systemcall::DontWait : Systemcall::Wait;
342 if (conv.original_dir && buffer) {
343 Path p(buffer->filePath());
344 res = one.startscript(type, command);
346 res = one.startscript(type, command);
348 if (!real_outfile.empty()) {
349 if (!rename(outfile, real_outfile))
353 << "renaming file " << outfile
354 << " to " << real_outfile
358 if (!conv.parselog.empty()) {
359 string const logfile = infile2 + ".log";
360 string const script = LibScriptSearch(conv.parselog);
361 string const command2 = script +
362 " < " + QuoteName(infile2 + ".out") +
363 " > " + QuoteName(logfile);
364 one.startscript(Systemcall::Wait, command2);
365 if (!scanLog(buffer, command, logfile))
370 if (conv.to == "program") {
371 Alert::error(_("Build errors"),
372 _("There were errors during the build process."));
374 // FIXME: this should go out of here. For example, here we cannot say if
375 // it is a document (.lyx) or something else. Same goes for elsewhere.
376 Alert::error(_("Cannot convert file"),
377 bformat(_("An error occurred whilst running %1$s"),
378 command.substr(0, 50)));
385 Converter const & conv = converterlist_[edgepath.back()];
386 if (conv.To->dummy())
390 if (!conv.result_dir.empty()) {
391 to_file = AddName(subst(conv.result_dir, token_base, to_base),
392 subst(conv.result_file,
393 token_base, OnlyFilename(to_base)));
394 if (from_base != to_base) {
395 string from = subst(conv.result_dir,
396 token_base, from_base);
397 string to = subst(conv.result_dir,
398 token_base, to_base);
399 if (!rename(from, to)) {
400 Alert::error(_("Cannot convert file"),
401 bformat(_("Could not move a temporary file from %1$s to %2$s."),
408 return move(outfile, to_file, conv.latex);
412 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
413 // moves each /path/file*.ext file to /path2/file2*.ext2'
414 bool Converters::move(string const & from, string const & to, bool copy)
419 bool no_errors = true;
420 string const path = OnlyPath(from);
421 string const base = OnlyFilename(ChangeExtension(from, ""));
422 string const to_base = ChangeExtension(to, "");
423 string const to_extension = GetExtension(to);
425 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
426 for (vector<string>::const_iterator it = files.begin();
427 it != files.end(); ++it)
428 if (prefixIs(*it, base)) {
429 string const from2 = path + *it;
430 string to2 = to_base + it->substr(base.length());
431 to2 = ChangeExtension(to2, to_extension);
432 lyxerr[Debug::FILES] << "moving " << from2
433 << " to " << to2 << endl;
434 bool const moved = (copy)
435 ? lyx::support::copy(from2, to2)
436 : rename(from2, to2);
437 if (!moved && no_errors) {
438 Alert::error(_("Cannot convert file"),
439 bformat(_("Could not move a temporary file from %1$s to %2$s."),
448 bool Converters::convert(Buffer const * buffer,
449 string const & from_file, string const & to_file_base,
450 string const & from_format, string const & to_format)
453 return convert(buffer, from_file, to_file_base, from_format, to_format,
458 bool Converters::formatIsUsed(string const & format)
460 ConverterList::const_iterator cit = converterlist_.begin();
461 ConverterList::const_iterator end = converterlist_.end();
462 for (; cit != end; ++cit) {
463 if (cit->from == format || cit->to == format)
470 bool Converters::scanLog(Buffer const * buffer, string const & /*command*/,
471 string const & filename)
476 BufferView * bv = buffer->getUser();
477 LatexRunParams runparams;
478 runparams.flavor = LatexRunParams::LATEX;
479 LaTeX latex("", runparams, filename, "");
481 int result = latex.scanLogFile(terr);
483 if (bv && (result & LaTeX::ERRORS))
484 parseErrors(*buffer, terr);
490 bool Converters::runLaTeX(Buffer const * buffer, string const & command,
491 LatexRunParams const & runparams)
496 BufferView * bv = buffer->getUser();
499 bv->owner()->busy(true);
500 bv->owner()->message(_("Running LaTeX..."));
501 // all the autoinsets have already been removed
504 // do the LaTeX run(s)
505 string name = buffer->getLatexName();
506 LaTeX latex(command, runparams, name, buffer->filePath());
508 int result = latex.run(terr,
509 bv ? &bv->owner()->getLyXFunc() : 0);
511 if (bv && (result & LaTeX::ERRORS))
512 parseErrors(*buffer, terr);
514 // check return value from latex.run().
515 if ((result & LaTeX::NO_LOGFILE)) {
516 string str = bformat(_("LaTeX did not run successfully. Additionally, LyX "
517 "could not locate the LaTeX log %1$s."), name);
518 Alert::error(_("LaTeX failed"), str);
519 } else if (result & LaTeX::NO_OUTPUT) {
520 Alert::warning(_("Output is empty"),
521 _("An empty output file was generated."));
525 bv->owner()->busy(false);
527 int const ERROR_MASK =
532 return (result & ERROR_MASK) == 0;
537 string const Converters::dvips_options(Buffer const * buffer)
543 if (buffer->params.use_geometry
544 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
545 && !lyxrc.print_paper_dimension_flag.empty()
546 && !buffer->params.paperwidth.empty()
547 && !buffer->params.paperheight.empty()) {
548 // using a custom papersize
549 result = lyxrc.print_paper_dimension_flag;
550 result += ' ' + buffer->params.paperwidth;
551 result += ',' + buffer->params.paperheight;
553 string const paper_option = papersize(buffer);
554 if (paper_option != "letter" ||
555 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
556 // dvips won't accept -t letter -t landscape. In all other
557 // cases, include the paper size explicitly.
558 result = lyxrc.print_paper_flag;
559 result += ' ' + paper_option;
562 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
563 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
564 result += ' ' + lyxrc.print_landscape_flag;
569 string const Converters::dvipdfm_options(Buffer const * buffer)
575 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
576 string const paper_size = papersize(buffer);
577 if (paper_size != "b5" && paper_size != "foolscap")
578 result = "-p "+ paper_size;
580 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
588 void Converters::buildGraph()
590 G_.init(formats.size());
591 ConverterList::iterator beg = converterlist_.begin();
592 ConverterList::iterator end = converterlist_.end();
593 for (ConverterList::iterator it = beg; it != end ; ++it) {
594 int const s = formats.getNumber(it->from);
595 int const t = formats.getNumber(it->to);
601 std::vector<Format const *> const
602 Converters::intToFormat(std::vector<int> const & input)
604 vector<Format const *> result(input.size());
606 vector<int>::const_iterator it = input.begin();
607 vector<int>::const_iterator end = input.end();
608 vector<Format const *>::iterator rit = result.begin();
609 for ( ; it != end; ++it, ++rit) {
610 *rit = &formats.get(*it);
615 vector<Format const *> const
616 Converters::getReachableTo(string const & target, bool clear_visited)
618 vector<int> const & reachablesto =
619 G_.getReachableTo(formats.getNumber(target), clear_visited);
621 return intToFormat(reachablesto);
625 vector<Format const *> const
626 Converters::getReachable(string const & from, bool only_viewable,
629 vector<int> const & reachables =
630 G_.getReachable(formats.getNumber(from),
634 return intToFormat(reachables);
638 bool Converters::isReachable(string const & from, string const & to)
640 return G_.isReachable(formats.getNumber(from),
641 formats.getNumber(to));
645 Graph::EdgePath const
646 Converters::getPath(string const & from, string const & to)
648 return G_.getPath(formats.getNumber(from),
649 formats.getNumber(to));
653 /// The global instance
654 Converters converters;
656 // The global copy after reading lyxrc.defaults
657 Converters system_converters;