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 #ifndef CXX_GLOBAL_CSTD
48 string const token_from("$$i");
49 string const token_base("$$b");
50 string const token_to("$$o");
51 string const token_path("$$p");
55 string const add_options(string const & command, string const & options)
58 string const tail = split(command, head, ' ');
59 return head + ' ' + options + ' ' + tail;
65 Converter::Converter(string const & f, string const & t, string const & c,
66 string const & l): from(f), to(t), command(c), flags(l),
67 From(0), To(0), latex(false),
68 original_dir(false), need_aux(false)
72 void Converter::readFlags()
74 string flag_list(flags);
75 while (!flag_list.empty()) {
76 string flag_name, flag_value;
77 flag_list = split(flag_list, flag_value, ',');
78 flag_value = split(flag_value, flag_name, '=');
79 if (flag_name == "latex")
81 else if (flag_name == "originaldir")
83 else if (flag_name == "needaux")
85 else if (flag_name == "resultdir")
86 result_dir = (flag_value.empty())
87 ? token_base : flag_value;
88 else if (flag_name == "resultfile")
89 result_file = flag_value;
90 else if (flag_name == "parselog")
91 parselog = flag_value;
93 if (!result_dir.empty() && result_file.empty())
94 result_file = "index." + formats.extension(to);
95 //if (!contains(command, token_from))
100 bool operator<(Converter const & a, Converter const & b)
102 // use the compare_ascii_no_case instead of compare_no_case,
103 // because in turkish, 'i' is not the lowercase version of 'I',
104 // and thus turkish locale breaks parsing of tags.
105 int const i = compare_ascii_no_case(a.From->prettyname(),
106 b.From->prettyname());
108 return compare_ascii_no_case(a.To->prettyname(), b.To->prettyname())
116 class compare_Converter {
118 compare_Converter(string const & f, string const & t)
120 bool operator()(Converter const & c) {
121 return c.from == from && c.to == to;
130 Converter const * Converters::getConverter(string const & from,
133 ConverterList::const_iterator cit =
134 find_if(converterlist_.begin(), converterlist_.end(),
135 compare_Converter(from, to));
136 if (cit != converterlist_.end())
143 int Converters::getNumber(string const & from, string const & to)
145 ConverterList::const_iterator cit =
146 find_if(converterlist_.begin(), converterlist_.end(),
147 compare_Converter(from, to));
148 if (cit != converterlist_.end())
149 return cit - converterlist_.begin();
155 void Converters::add(string const & from, string const & to,
156 string const & command, string const & flags)
160 ConverterList::iterator it = find_if(converterlist_.begin(),
161 converterlist_.end(),
162 compare_Converter(from, to));
164 Converter converter(from, to, command, flags);
165 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
167 converter.command = command;
168 converter.flags = flags;
170 converter.readFlags();
172 if (converter.latex && (latex_command_.empty() || to == "dvi"))
173 latex_command_ = subst(command, token_from, "");
174 // If we have both latex & pdflatex, we set latex_command to latex.
175 // The latex_command is used to update the .aux file when running
176 // a converter that uses it.
178 if (it == converterlist_.end()) {
179 converterlist_.push_back(converter);
181 converter.From = it->From;
182 converter.To = it->To;
188 void Converters::erase(string const & from, string const & to)
190 ConverterList::iterator it = find_if(converterlist_.begin(),
191 converterlist_.end(),
192 compare_Converter(from, to));
193 if (it != converterlist_.end())
194 converterlist_.erase(it);
198 // This method updates the pointers From and To in all the converters.
199 // The code is not very efficient, but it doesn't matter as the number
200 // of formats and converters is small.
201 // Furthermore, this method is called only on startup, or after
202 // adding/deleting a format in FormPreferences (the latter calls can be
203 // eliminated if the formats in the Formats class are stored using a map or
204 // a list (instead of a vector), but this will cause other problems).
205 void Converters::update(Formats const & formats)
207 ConverterList::iterator it = converterlist_.begin();
208 ConverterList::iterator end = converterlist_.end();
209 for (; it != end; ++it) {
210 it->From = formats.getFormat(it->from);
211 it->To = formats.getFormat(it->to);
216 // This method updates the pointers From and To in the last converter.
217 // It is called when adding a new converter in FormPreferences
218 void Converters::updateLast(Formats const & formats)
220 if (converterlist_.begin() != converterlist_.end()) {
221 ConverterList::iterator it = converterlist_.end() - 1;
222 it->From = formats.getFormat(it->from);
223 it->To = formats.getFormat(it->to);
228 void Converters::sort()
230 std::sort(converterlist_.begin(), converterlist_.end());
234 bool Converters::usePdflatex(Graph::EdgePath const & path)
236 for (Graph::EdgePath::const_iterator cit = path.begin();
237 cit != path.end(); ++cit) {
238 Converter const & conv = converterlist_[*cit];
240 return contains(conv.to, "pdf");
246 bool Converters::convert(Buffer const * buffer,
247 string const & from_file, string const & to_file_base,
248 string const & from_format, string const & to_format,
251 to_file = ChangeExtension(to_file_base,
252 formats.extension(to_format));
254 if (from_format == to_format)
255 return move(from_file, to_file, false);
257 Graph::EdgePath edgepath = getPath(from_format, to_format);
258 if (edgepath.empty()) {
261 LatexRunParams runparams;
262 runparams.flavor = usePdflatex(edgepath) ?
263 LatexRunParams::PDFLATEX : LatexRunParams::LATEX;
265 string path = OnlyPath(from_file);
268 bool run_latex = false;
269 string from_base = ChangeExtension(from_file, "");
270 string to_base = ChangeExtension(to_file, "");
272 string outfile = from_file;
273 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
274 cit != edgepath.end(); ++cit) {
275 Converter const & conv = converterlist_[*cit];
276 bool dummy = conv.To->dummy() && conv.to != "program";
278 lyxerr[Debug::FILES] << "Converting from "
279 << conv.from << " to " << conv.to << endl;
281 outfile = conv.result_dir.empty()
282 ? ChangeExtension(from_file, conv.To->extension())
283 : AddName(subst(conv.result_dir,
284 token_base, from_base),
285 subst(conv.result_file,
286 token_base, OnlyFilename(from_base)));
288 // if input and output files are equal, we use a
289 // temporary file as intermediary (JMarc)
291 if (outfile == infile) {
292 real_outfile = infile;
293 outfile = AddName(buffer->tmppath, "tmpfile.out");
298 string command = subst(conv.command, token_from, "");
299 lyxerr[Debug::FILES] << "Running " << command << endl;
300 if (!runLaTeX(buffer, command, runparams))
303 if (conv.need_aux && !run_latex
304 && !latex_command_.empty()) {
306 << "Running " << latex_command_
307 << " to update aux file"<< endl;
308 runLaTeX(buffer, latex_command_, runparams);
311 string infile2 = (conv.original_dir)
312 ? infile : MakeRelPath(infile, path);
313 string outfile2 = (conv.original_dir)
314 ? outfile : MakeRelPath(outfile, path);
316 string command = conv.command;
317 command = subst(command, token_from, QuoteName(infile2));
318 command = subst(command, token_base, QuoteName(from_base));
319 command = subst(command, token_to, QuoteName(outfile2));
320 command = LibScriptSearch(command);
322 if (!conv.parselog.empty())
323 command += " 2> " + QuoteName(infile2 + ".out");
325 if (conv.from == "dvi" && conv.to == "ps")
326 command = add_options(command,
327 dvips_options(buffer));
328 else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
329 command = add_options(command,
330 dvipdfm_options(buffer));
332 lyxerr[Debug::FILES] << "Calling " << command << endl;
334 ShowMessage(buffer, _("Executing command:"), command);
336 Systemcall::Starttype type = (dummy)
337 ? Systemcall::DontWait : Systemcall::Wait;
340 if (conv.original_dir && buffer) {
341 Path p(buffer->filePath());
342 res = one.startscript(type, command);
344 res = one.startscript(type, command);
346 if (!real_outfile.empty()) {
347 if (!lyx::rename(outfile, real_outfile))
351 << "renaming file " << outfile
352 << " to " << real_outfile
356 if (!conv.parselog.empty()) {
357 string const logfile = infile2 + ".log";
358 string const script = LibScriptSearch(conv.parselog);
359 string const command2 = script +
360 " < " + QuoteName(infile2 + ".out") +
361 " > " + QuoteName(logfile);
362 one.startscript(Systemcall::Wait, command2);
363 if (!scanLog(buffer, command, logfile))
368 if (conv.to == "program") {
369 Alert::error(_("Build errors"),
370 _("There were errors during the build process."));
372 // FIXME: this should go out of here. For example, here we cannot say if
373 // it is a document (.lyx) or something else. Same goes for elsewhere.
374 Alert::error(_("Cannot convert file"),
375 bformat(_("An error occurred whilst running %1$s"),
376 command.substr(0, 50)));
383 Converter const & conv = converterlist_[edgepath.back()];
384 if (conv.To->dummy())
388 if (!conv.result_dir.empty()) {
389 to_file = AddName(subst(conv.result_dir, token_base, to_base),
390 subst(conv.result_file,
391 token_base, OnlyFilename(to_base)));
392 if (from_base != to_base) {
393 string from = subst(conv.result_dir,
394 token_base, from_base);
395 string to = subst(conv.result_dir,
396 token_base, to_base);
397 if (!lyx::rename(from, to)) {
398 Alert::error(_("Cannot convert file"),
399 bformat(_("Could not move a temporary file from %1$s to %2$s."),
406 return move(outfile, to_file, conv.latex);
410 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
411 // moves each /path/file*.ext file to /path2/file2*.ext2'
412 bool Converters::move(string const & from, string const & to, bool copy)
417 bool no_errors = true;
418 string const path = OnlyPath(from);
419 string const base = OnlyFilename(ChangeExtension(from, ""));
420 string const to_base = ChangeExtension(to, "");
421 string const to_extension = GetExtension(to);
423 vector<string> files = DirList(OnlyPath(from), GetExtension(from));
424 for (vector<string>::const_iterator it = files.begin();
425 it != files.end(); ++it)
426 if (prefixIs(*it, base)) {
427 string const from2 = path + *it;
428 string to2 = to_base + it->substr(base.length());
429 to2 = ChangeExtension(to2, to_extension);
430 lyxerr[Debug::FILES] << "moving " << from2
431 << " to " << to2 << endl;
432 bool const moved = (copy)
433 ? lyx::copy(from2, to2)
434 : lyx::rename(from2, to2);
435 if (!moved && no_errors) {
436 Alert::error(_("Cannot convert file"),
437 bformat(_("Could not move a temporary file from %1$s to %2$s."),
446 bool Converters::convert(Buffer const * buffer,
447 string const & from_file, string const & to_file_base,
448 string const & from_format, string const & to_format)
451 return convert(buffer, from_file, to_file_base, from_format, to_format,
456 bool Converters::formatIsUsed(string const & format)
458 ConverterList::const_iterator cit = converterlist_.begin();
459 ConverterList::const_iterator end = converterlist_.end();
460 for (; cit != end; ++cit) {
461 if (cit->from == format || cit->to == format)
468 bool Converters::scanLog(Buffer const * buffer, string const & /*command*/,
469 string const & filename)
474 BufferView * bv = buffer->getUser();
475 LatexRunParams runparams;
476 runparams.flavor = LatexRunParams::LATEX;
477 LaTeX latex("", runparams, filename, "");
479 int result = latex.scanLogFile(terr);
481 if (bv && (result & LaTeX::ERRORS))
482 parseErrors(*buffer, terr);
488 bool Converters::runLaTeX(Buffer const * buffer, string const & command,
489 LatexRunParams const & runparams)
494 BufferView * bv = buffer->getUser();
497 bv->owner()->busy(true);
498 bv->owner()->message(_("Running LaTeX..."));
499 // all the autoinsets have already been removed
502 // do the LaTeX run(s)
503 string name = buffer->getLatexName();
504 LaTeX latex(command, runparams, name, buffer->filePath());
506 int result = latex.run(terr,
507 bv ? &bv->owner()->getLyXFunc() : 0);
509 if (bv && (result & LaTeX::ERRORS))
510 parseErrors(*buffer, terr);
512 // check return value from latex.run().
513 if ((result & LaTeX::NO_LOGFILE)) {
514 string str = bformat(_("LaTeX did not run successfully. Additionally, LyX "
515 "could not locate the LaTeX log %1$s."), name);
516 Alert::error(_("LaTeX failed"), str);
517 } else if (result & LaTeX::NO_OUTPUT) {
518 Alert::warning(_("Output is empty"),
519 _("An empty output file was generated."));
523 bv->owner()->busy(false);
525 int const ERROR_MASK =
530 return (result & ERROR_MASK) == 0;
535 string const Converters::dvips_options(Buffer const * buffer)
541 if (buffer->params.use_geometry
542 && buffer->params.papersize2 == BufferParams::VM_PAPER_CUSTOM
543 && !lyxrc.print_paper_dimension_flag.empty()
544 && !buffer->params.paperwidth.empty()
545 && !buffer->params.paperheight.empty()) {
546 // using a custom papersize
547 result = lyxrc.print_paper_dimension_flag;
548 result += ' ' + buffer->params.paperwidth;
549 result += ',' + buffer->params.paperheight;
551 string const paper_option = papersize(buffer);
552 if (paper_option != "letter" ||
553 buffer->params.orientation != BufferParams::ORIENTATION_LANDSCAPE) {
554 // dvips won't accept -t letter -t landscape. In all other
555 // cases, include the paper size explicitly.
556 result = lyxrc.print_paper_flag;
557 result += ' ' + paper_option;
560 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE &&
561 buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM)
562 result += ' ' + lyxrc.print_landscape_flag;
567 string const Converters::dvipdfm_options(Buffer const * buffer)
573 if (buffer->params.papersize2 != BufferParams::VM_PAPER_CUSTOM) {
574 string const paper_size = papersize(buffer);
575 if (paper_size != "b5" && paper_size != "foolscap")
576 result = "-p "+ paper_size;
578 if (buffer->params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
586 void Converters::buildGraph()
588 G_.init(formats.size());
589 ConverterList::iterator beg = converterlist_.begin();
590 ConverterList::iterator end = converterlist_.end();
591 for (ConverterList::iterator it = beg; it != end ; ++it) {
592 int const s = formats.getNumber(it->from);
593 int const t = formats.getNumber(it->to);
599 std::vector<Format const *> const
600 Converters::intToFormat(std::vector<int> const & input)
602 vector<Format const *> result(input.size());
604 vector<int>::const_iterator it = input.begin();
605 vector<int>::const_iterator end = input.end();
606 vector<Format const *>::iterator rit = result.begin();
607 for ( ; it != end; ++it, ++rit) {
608 *rit = &formats.get(*it);
613 vector<Format const *> const
614 Converters::getReachableTo(string const & target, bool clear_visited)
616 vector<int> const & reachablesto =
617 G_.getReachableTo(formats.getNumber(target), clear_visited);
619 return intToFormat(reachablesto);
623 vector<Format const *> const
624 Converters::getReachable(string const & from, bool only_viewable,
627 vector<int> const & reachables =
628 G_.getReachable(formats.getNumber(from),
632 return intToFormat(reachables);
636 bool Converters::isReachable(string const & from, string const & to)
638 return G_.isReachable(formats.getNumber(from),
639 formats.getNumber(to));
643 Graph::EdgePath const
644 Converters::getPath(string const & from, string const & to)
646 return G_.getPath(formats.getNumber(from),
647 formats.getNumber(to));
651 /// The global instance
652 Converters converters;
654 // The global copy after reading lyxrc.defaults
655 Converters system_converters;