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"
18 #include "ConverterCache.h"
20 #include "ErrorList.h"
22 #include "InsetList.h"
27 #include "ParagraphList.h"
30 #include "frontends/alert.h"
32 #include "insets/InsetInclude.h"
34 #include "support/debug.h"
35 #include "support/FileNameList.h"
36 #include "support/filetools.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
40 #include "support/os.h"
41 #include "support/Package.h"
42 #include "support/PathChanger.h"
43 #include "support/Systemcall.h"
46 using namespace lyx::support;
50 namespace Alert = lyx::frontend::Alert;
55 string const token_from("$$i");
56 string const token_base("$$b");
57 string const token_to("$$o");
58 string const token_path("$$p");
59 string const token_orig_path("$$r");
60 string const token_orig_from("$$f");
61 string const token_encoding("$$e");
62 string const token_latex_encoding("$$E");
65 string const add_options(string const & command, string const & options)
68 string const tail = split(command, head, ' ');
69 return head + ' ' + options + ' ' + tail;
73 string const dvipdfm_options(BufferParams const & bp)
77 if (bp.papersize != PAPER_CUSTOM) {
78 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
79 if (!paper_size.empty())
80 result = "-p "+ paper_size;
82 if (bp.orientation == ORIENTATION_LANDSCAPE)
90 class ConverterEqual {
92 ConverterEqual(string const & from, string const & to)
93 : from_(from), to_(to) {}
94 bool operator()(Converter const & c) const {
95 return c.from() == from_ && c.to() == to_;
105 Converter::Converter(string const & f, string const & t,
106 string const & c, string const & l)
107 : from_(f), to_(t), command_(c), flags_(l),
108 From_(0), To_(0), latex_(false), xml_(false),
109 need_aux_(false), nice_(false), need_auth_(false)
113 void Converter::readFlags()
115 string flag_list(flags_);
116 while (!flag_list.empty()) {
117 string flag_name, flag_value;
118 flag_list = split(flag_list, flag_value, ',');
119 flag_value = split(flag_value, flag_name, '=');
120 if (flag_name == "latex") {
122 latex_flavor_ = flag_value.empty() ?
123 "latex" : flag_value;
124 } else if (flag_name == "xml")
126 else if (flag_name == "needaux")
128 else if (flag_name == "resultdir")
129 result_dir_ = (flag_value.empty())
130 ? token_base : flag_value;
131 else if (flag_name == "resultfile")
132 result_file_ = flag_value;
133 else if (flag_name == "parselog")
134 parselog_ = flag_value;
135 else if (flag_name == "nice")
137 else if (flag_name == "needauth")
140 if (!result_dir_.empty() && result_file_.empty())
141 result_file_ = "index." + theFormats().extension(to_);
142 //if (!contains(command, token_from))
147 Converter const * Converters::getConverter(string const & from,
148 string const & to) const
150 ConverterList::const_iterator const cit =
151 find_if(converterlist_.begin(), converterlist_.end(),
152 ConverterEqual(from, to));
153 if (cit != converterlist_.end())
160 int Converters::getNumber(string const & from, string const & to) const
162 ConverterList::const_iterator const cit =
163 find_if(converterlist_.begin(), converterlist_.end(),
164 ConverterEqual(from, to));
165 if (cit != converterlist_.end())
166 return distance(converterlist_.begin(), cit);
172 void Converters::add(string const & from, string const & to,
173 string const & command, string const & flags)
175 theFormats().add(from);
176 theFormats().add(to);
177 ConverterList::iterator it = find_if(converterlist_.begin(),
178 converterlist_.end(),
179 ConverterEqual(from , to));
181 Converter converter(from, to, command, flags);
182 if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
184 converter.setCommand(command);
185 converter.setFlags(flags);
187 converter.readFlags();
189 // The latex_command is used to update the .aux file when running
190 // a converter that uses it.
191 if (converter.latex()) {
192 if (latex_command_.empty() ||
193 converter.latex_flavor() == "latex")
194 latex_command_ = subst(command, token_from, "");
195 if (dvilualatex_command_.empty() ||
196 converter.latex_flavor() == "dvilualatex")
197 dvilualatex_command_ = subst(command, token_from, "");
198 if (lualatex_command_.empty() ||
199 converter.latex_flavor() == "lualatex")
200 lualatex_command_ = subst(command, token_from, "");
201 if (pdflatex_command_.empty() ||
202 converter.latex_flavor() == "pdflatex")
203 pdflatex_command_ = subst(command, token_from, "");
204 if (xelatex_command_.empty() ||
205 converter.latex_flavor() == "xelatex")
206 xelatex_command_ = subst(command, token_from, "");
209 if (it == converterlist_.end()) {
210 converterlist_.push_back(converter);
212 converter.setFrom(it->From());
213 converter.setTo(it->To());
219 void Converters::erase(string const & from, string const & to)
221 ConverterList::iterator const it =
222 find_if(converterlist_.begin(),
223 converterlist_.end(),
224 ConverterEqual(from, to));
225 if (it != converterlist_.end())
226 converterlist_.erase(it);
230 // This method updates the pointers From and To in all the converters.
231 // The code is not very efficient, but it doesn't matter as the number
232 // of formats and converters is small.
233 // Furthermore, this method is called only on startup, or after
234 // adding/deleting a format in FormPreferences (the latter calls can be
235 // eliminated if the formats in the Formats class are stored using a map or
236 // a list (instead of a vector), but this will cause other problems).
237 void Converters::update(Formats const & formats)
239 ConverterList::iterator it = converterlist_.begin();
240 ConverterList::iterator end = converterlist_.end();
241 for (; it != end; ++it) {
242 it->setFrom(formats.getFormat(it->from()));
243 it->setTo(formats.getFormat(it->to()));
248 // This method updates the pointers From and To in the last converter.
249 // It is called when adding a new converter in FormPreferences
250 void Converters::updateLast(Formats const & formats)
252 if (converterlist_.begin() != converterlist_.end()) {
253 ConverterList::iterator it = converterlist_.end() - 1;
254 it->setFrom(formats.getFormat(it->from()));
255 it->setTo(formats.getFormat(it->to()));
260 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
261 Buffer const * buffer)
263 for (Graph::EdgePath::const_iterator cit = path.begin();
264 cit != path.end(); ++cit) {
265 Converter const & conv = converterlist_[*cit];
267 if (conv.latex_flavor() == "latex")
268 return OutputParams::LATEX;
269 if (conv.latex_flavor() == "xelatex")
270 return OutputParams::XETEX;
271 if (conv.latex_flavor() == "lualatex")
272 return OutputParams::LUATEX;
273 if (conv.latex_flavor() == "dvilualatex")
274 return OutputParams::DVILUATEX;
275 if (conv.latex_flavor() == "pdflatex")
276 return OutputParams::PDFLATEX;
279 return OutputParams::XML;
281 return buffer ? buffer->params().getOutputFlavor()
282 : OutputParams::LATEX;
286 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
287 bool use_shell_escape)
289 string conv_command = conv.command();
290 bool const has_shell_escape = contains(conv_command, "-shell-escape")
291 || contains(conv_command, "-enable-write18");
292 if (conv.latex() && has_shell_escape && !use_shell_escape) {
293 docstring const shellescape_warning =
294 bformat(_("<p>The following LaTeX backend has been "
295 "configured to allow execution of external programs "
296 "for any document:</p>"
297 "<center><p><tt>%1$s</tt></p></center>"
298 "<p>This is a dangerous configuration. Please, "
299 "consider using the support offered by LyX for "
300 "allowing this privilege only to documents that "
301 "actually need it, instead.</p>"),
302 from_utf8(conv_command));
303 frontend::Alert::error(_("Security Warning"),
304 shellescape_warning , false);
305 } else if (!conv.latex())
306 use_shell_escape = false;
307 if (!conv.need_auth() && !use_shell_escape)
309 size_t const token_pos = conv_command.find("$$");
310 bool const has_token = token_pos != string::npos;
311 string const command = use_shell_escape && !has_shell_escape
312 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
313 : conv_command.append(" -shell-escape"))
315 docstring const security_warning = (use_shell_escape
316 ? bformat(_("<p>The following LaTeX backend has been requested "
317 "to allow execution of external programs:</p>"
318 "<center><p><tt>%1$s</tt></p></center>"
319 "<p>The external programs can execute arbitrary commands on "
320 "your system, including dangerous ones, if instructed to do "
321 "so by a maliciously crafted LyX document.</p>"),
323 : bformat(_("<p>The requested operation requires the use of a "
324 "converter from %2$s to %3$s:</p>"
325 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
326 "<p>This external program can execute arbitrary commands on "
327 "your system, including dangerous ones, if instructed to do "
328 "so by a maliciously crafted LyX document.</p>"),
329 from_utf8(command), from_utf8(conv.from()),
330 from_utf8(conv.to())));
331 if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
332 frontend::Alert::error(
333 _("An external converter is disabled for security reasons"),
334 security_warning + _(
335 "<p><b>Your current preference settings forbid its execution.</b></p>"
336 "<p>(To change this setting, go to <i>Preferences ▹ File "
337 "Handling ▹ Converters</i> and uncheck <i>Security ▹ "
338 "Forbid needauth converters</i>.)"), false);
341 if (!lyxrc.use_converter_needauth && !use_shell_escape)
343 docstring const security_title = use_shell_escape
344 ? _("A LaTeX backend requires your authorization")
345 : _("An external converter requires your authorization");
347 docstring const security_warning2 = security_warning + (use_shell_escape
348 ? _("<p>Should LaTeX backends be allowed to run external "
349 "programs?</p><p><b>Allow them only if you trust the "
350 "origin/sender of the LyX document!</b></p>")
351 : _("<p>Would you like to run this converter?</p>"
352 "<p><b>Only run if you trust the origin/sender of the LyX "
353 "document!</b></p>"));
354 docstring const no = use_shell_escape
355 ? _("Do ¬ allow") : _("Do ¬ run");
356 docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
357 docstring const always = use_shell_escape
358 ? _("&Always allow for this document")
359 : _("&Always run for this document");
360 if (!doc_fname.empty()) {
361 LYXERR(Debug::FILES, "looking up: " << doc_fname);
362 bool authorized = use_shell_escape
363 ? theSession().shellescapeFiles().findAuth(doc_fname)
364 : theSession().authFiles().find(doc_fname);
366 choice = frontend::Alert::prompt(security_title,
368 0, 0, no, yes, always);
370 if (use_shell_escape)
371 theSession().shellescapeFiles().insert(doc_fname, true);
373 theSession().authFiles().insert(doc_fname);
379 choice = frontend::Alert::prompt(security_title,
387 bool Converters::convert(Buffer const * buffer,
388 FileName const & from_file, FileName const & to_file,
389 FileName const & orig_from,
390 string const & from_format, string const & to_format,
391 ErrorList & errorList, int conversionflags)
393 if (from_format == to_format)
394 return move(from_format, from_file, to_file, false);
396 if ((conversionflags & try_cache) &&
397 ConverterCache::get().inCache(orig_from, to_format))
398 return ConverterCache::get().copy(orig_from, to_format, to_file);
400 Graph::EdgePath edgepath = getPath(from_format, to_format);
401 if (edgepath.empty()) {
402 if (conversionflags & try_default) {
403 // if no special converter defined, then we take the
404 // default one from ImageMagic.
405 string const from_ext = from_format.empty() ?
406 getExtension(from_file.absFileName()) :
407 theFormats().extension(from_format);
408 string const to_ext = theFormats().extension(to_format);
409 string const command =
411 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
412 ' ' + from_ext + ' ' +
413 quoteName(from_file.toFilesystemEncoding()) +
415 quoteName(to_file.toFilesystemEncoding());
416 LYXERR(Debug::FILES, "No converter defined! "
417 "I use convertDefault.py:\n\t" << command);
419 Systemcall::Starttype starttype =
420 (buffer && buffer->isClone()) ?
421 Systemcall::WaitLoop : Systemcall::Wait;
422 int const exitval = one.startscript(starttype, command,
423 buffer ? buffer->filePath() : string(),
424 buffer ? buffer->layoutPos() : string());
425 if (exitval == Systemcall::KILLED) {
426 frontend::Alert::warning(
427 _("Converter killed"),
428 bformat(_("The running converter\n %1$s\nwas killed by the user."),
429 from_utf8(command)));
432 if (to_file.isReadableFile()) {
433 if (conversionflags & try_cache)
434 ConverterCache::get().add(orig_from,
440 // only warn once per session and per file type
441 static std::map<string, string> warned;
442 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
445 warned.insert(make_pair(from_format, to_format));
447 Alert::error(_("Cannot convert file"),
448 bformat(_("No information for converting %1$s "
449 "format files to %2$s.\n"
450 "Define a converter in the preferences."),
451 from_ascii(from_format), from_ascii(to_format)));
455 // buffer is only invalid for importing, and then runparams is not
457 OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
458 runparams.flavor = getFlavor(edgepath, buffer);
461 runparams.use_japanese =
462 (buffer->params().bufferFormat() == "latex"
463 || suffixIs(buffer->params().bufferFormat(), "-ja"))
464 && buffer->params().encoding().package() == Encoding::japanese;
465 runparams.use_indices = buffer->params().use_indices;
466 runparams.bibtex_command = buffer->params().bibtexCommand();
467 runparams.index_command = (buffer->params().index_command == "default") ?
468 string() : buffer->params().index_command;
469 runparams.document_language = buffer->params().language->babel();
470 runparams.only_childbibs = !buffer->params().useBiblatex()
471 && !buffer->params().useBibtopic()
472 && buffer->params().multibib == "child";
475 // Some converters (e.g. lilypond) can only output files to the
476 // current directory, so we need to change the current directory.
477 // This has the added benefit that all other files that may be
478 // generated by the converter are deleted when LyX closes and do not
479 // clutter the real working directory.
480 // FIXME: This does not work if path is an UNC path on windows
482 string const path(onlyPath(from_file.absFileName()));
483 // Prevent the compiler from optimizing away p
487 // empty the error list before any new conversion takes place.
490 bool run_latex = false;
491 string from_base = changeExtension(from_file.absFileName(), "");
492 string to_base = changeExtension(to_file.absFileName(), "");
494 FileName outfile = from_file;
495 for (Graph::EdgePath::const_iterator cit = edgepath.begin();
496 cit != edgepath.end(); ++cit) {
497 Converter const & conv = converterlist_[*cit];
498 bool dummy = conv.To()->dummy() && conv.to() != "program";
500 LYXERR(Debug::FILES, "Converting from "
501 << conv.from() << " to " << conv.to());
504 outfile = FileName(conv.result_file().empty()
505 ? changeExtension(from_file.absFileName(), conv.To()->extension())
506 : addName(subst(conv.result_dir(),
507 token_base, from_base),
508 subst(conv.result_file(),
509 token_base, onlyFileName(from_base))));
511 // if input and output files are equal, we use a
512 // temporary file as intermediary (JMarc)
513 FileName real_outfile;
514 if (!conv.result_file().empty())
515 real_outfile = FileName(changeExtension(from_file.absFileName(),
516 conv.To()->extension()));
517 if (outfile == infile) {
518 real_outfile = infile;
519 // when importing, a buffer does not necessarily exist
521 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
523 outfile = FileName(addName(package().temp_dir().absFileName(),
527 if (buffer && buffer->params().use_minted
528 && lyxrc.pygmentize_command.empty() && conv.latex()) {
530 // Warn only if listings insets are actually used
531 for (Paragraph const & par : buffer->paragraphs()) {
532 InsetList const & insets = par.insetList();
533 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
534 pos_type incpos = insets.find(INCLUDE_CODE, 0);
536 InsetInclude const * include =
537 static_cast<InsetInclude *>
538 (insets.get(incpos));
539 if (include->params().getCmdName() !=
544 if (lstpos >= 0 || incpos >= 0) {
550 Alert::warning(_("Pygments driver command not found!"),
551 _("The driver command necessary to use the minted package\n"
552 "(pygmentize) has not been found. Make sure you have\n"
553 "the python-pygments module installed or, if the driver\n"
554 "is named differently, to add the following line to the\n"
555 "document preamble:\n\n"
556 "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
557 "where 'driver' is name of the driver command."));
561 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
562 buffer && buffer->params().shell_escape))
566 // We are not importing, we have a buffer
569 string command = conv.command();
570 command = subst(command, token_from, "");
571 command = subst(command, token_latex_encoding,
572 buffer->params().encoding().latexName());
573 if (buffer->params().shell_escape
574 && !contains(command, "-shell-escape"))
575 command += " -shell-escape ";
576 LYXERR(Debug::FILES, "Running " << command);
578 // Check changed return value here.
579 if (!runLaTeX(*buffer, command, runparams, errorList))
582 if (conv.need_aux() && !run_latex) {
583 // We are not importing, we have a buffer
586 switch (runparams.flavor) {
587 case OutputParams::DVILUATEX:
588 command = dvilualatex_command_;
590 case OutputParams::LUATEX:
591 command = lualatex_command_;
593 case OutputParams::PDFLATEX:
594 command = pdflatex_command_;
596 case OutputParams::XETEX:
597 command = xelatex_command_;
600 command = latex_command_;
603 if (!command.empty()) {
604 LYXERR(Debug::FILES, "Running "
606 << " to update aux file");
608 // Check changed return value here.
609 if (!runLaTeX(*buffer, command,
610 runparams, errorList))
616 string const infile2 =
617 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
618 string const outfile2 =
619 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
621 string command = conv.command();
622 command = subst(command, token_from, quoteName(infile2));
623 command = subst(command, token_base, quoteName(from_base));
624 command = subst(command, token_to, quoteName(outfile2));
625 command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
626 command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
627 command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
628 command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
630 if (!conv.parselog().empty())
631 command += " 2> " + quoteName(infile2 + ".out");
633 // it is not actually not necessary to test for buffer here,
634 // but it pleases coverity.
635 if (buffer && conv.from() == "dvi" && conv.to() == "ps")
636 command = add_options(command,
637 buffer->params().dvips_options());
638 else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
639 command = add_options(command,
640 dvipdfm_options(buffer->params()));
642 LYXERR(Debug::FILES, "Calling " << command);
644 buffer->message(_("Executing command: ")
645 + from_utf8(command));
650 res = one.startscript(Systemcall::DontWait,
651 to_filesystem8bit(from_utf8(command)),
652 buffer ? buffer->filePath() : string(),
653 buffer ? buffer->layoutPos() : string());
654 // We're not waiting for the result, so we can't do anything
657 Systemcall::Starttype starttype =
658 (buffer && buffer->isClone()) ?
659 Systemcall::WaitLoop : Systemcall::Wait;
660 res = one.startscript(starttype,
661 to_filesystem8bit(from_utf8(command)),
662 buffer ? buffer->filePath()
664 buffer ? buffer->layoutPos()
666 if (res == Systemcall::KILLED) {
667 frontend::Alert::warning(
668 _("Converter killed"),
669 bformat(_("The running converter\n %1$s\nwas killed by the user."),
670 from_utf8(command)));
674 if (!real_outfile.empty()) {
675 Mover const & mover = getMover(conv.to());
676 if (!mover.rename(outfile, real_outfile))
679 LYXERR(Debug::FILES, "renaming file " << outfile
680 << " to " << real_outfile);
681 // Finally, don't forget to tell any future
682 // converters to use the renamed file...
683 outfile = real_outfile;
686 if (!conv.parselog().empty()) {
687 string const logfile = infile2 + ".log";
688 string const command2 = conv.parselog() +
689 " < " + quoteName(infile2 + ".out") +
690 " > " + quoteName(logfile);
691 res = one.startscript(starttype,
692 to_filesystem8bit(from_utf8(command2)),
694 buffer->layoutPos());
695 if (res == Systemcall::KILLED) {
696 frontend::Alert::warning(
697 _("Converter killed"),
698 bformat(_("The running converter\n %1$s\nwas killed by the user."),
699 from_utf8(command)));
702 if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
708 if (res == Systemcall::KILLED) {
709 Alert::information(_("Process Killed"),
710 bformat(_("The conversion process was killed while running:\n%1$s"),
711 wrapParas(from_utf8(command))));
712 } else if (res == Systemcall::TIMEOUT) {
713 Alert::information(_("Process Timed Out"),
714 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
715 wrapParas(from_utf8(command))));
716 } else if (conv.to() == "program") {
717 Alert::error(_("Build errors"),
718 _("There were errors during the build process."));
720 // FIXME: this should go out of here. For example, here we cannot say if
721 // it is a document (.lyx) or something else. Same goes for elsewhere.
722 Alert::error(_("Cannot convert file"),
723 bformat(_("An error occurred while running:\n%1$s"),
724 wrapParas(from_utf8(command))));
731 Converter const & conv = converterlist_[edgepath.back()];
732 if (conv.To()->dummy())
735 if (!conv.result_dir().empty()) {
736 // The converter has put the file(s) in a directory.
737 // In this case we ignore the given to_file.
738 if (from_base != to_base) {
739 string const from = subst(conv.result_dir(),
740 token_base, from_base);
741 string const to = subst(conv.result_dir(),
742 token_base, to_base);
743 Mover const & mover = getMover(conv.from());
744 if (!mover.rename(FileName(from), FileName(to))) {
745 Alert::error(_("Cannot convert file"),
746 bformat(_("Could not move a temporary directory from %1$s to %2$s."),
747 from_utf8(from), from_utf8(to)));
753 if (conversionflags & try_cache)
754 ConverterCache::get().add(orig_from, to_format, outfile);
755 return move(conv.to(), outfile, to_file, conv.latex());
760 bool Converters::move(string const & fmt,
761 FileName const & from, FileName const & to, bool copy)
766 bool no_errors = true;
767 string const path = onlyPath(from.absFileName());
768 string const base = onlyFileName(removeExtension(from.absFileName()));
769 string const to_base = removeExtension(to.absFileName());
770 string const to_extension = getExtension(to.absFileName());
772 support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
773 for (support::FileNameList::const_iterator it = files.begin();
774 it != files.end(); ++it) {
775 string const from2 = it->absFileName();
776 string const file2 = onlyFileName(from2);
777 if (prefixIs(file2, base)) {
778 string const to2 = changeExtension(
779 to_base + file2.substr(base.length()),
781 LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
783 Mover const & mover = getMover(fmt);
784 bool const moved = copy
785 ? mover.copy(*it, FileName(to2))
786 : mover.rename(*it, FileName(to2));
787 if (!moved && no_errors) {
788 Alert::error(_("Cannot convert file"),
790 _("Could not copy a temporary file from %1$s to %2$s.") :
791 _("Could not move a temporary file from %1$s to %2$s."),
792 from_utf8(from2), from_utf8(to2)));
801 bool Converters::formatIsUsed(string const & format)
803 ConverterList::const_iterator cit = converterlist_.begin();
804 ConverterList::const_iterator end = converterlist_.end();
805 for (; cit != end; ++cit) {
806 if (cit->from() == format || cit->to() == format)
813 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
814 FileName const & filename, ErrorList & errorList)
816 OutputParams runparams(0);
817 runparams.flavor = OutputParams::LATEX;
818 LaTeX latex("", runparams, filename);
820 int const result = latex.scanLogFile(terr);
822 if (result & LaTeX::ERRORS)
823 buffer.bufferErrors(terr, errorList);
830 // Probably need to return an INT here
831 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
832 OutputParams const & runparams, ErrorList & errorList)
834 buffer.setBusy(true);
835 buffer.message(_("Running LaTeX..."));
837 // do the LaTeX run(s)
838 string const name = buffer.latexName();
839 LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
840 buffer.filePath(), buffer.layoutPos(),
841 buffer.isClone(), buffer.lastPreviewError());
843 // The connection closes itself at the end of the scope when latex is
844 // destroyed. One cannot close (and destroy) buffer while the converter is
846 latex.message.connect([&buffer](docstring const & msg){
849 int const result = latex.run(terr);
851 if (result == Systemcall::KILLED) {
852 Alert::error(_("Export canceled"),
853 _("The export process was terminated by the user."));
857 if (result & LaTeX::ERRORS)
858 buffer.bufferErrors(terr, errorList);
860 if (!errorList.empty()) {
861 // We will show the LaTeX Errors GUI later which contains
862 // specific error messages so it would be repetitive to give
863 // e.g. the "finished with an error" dialog in addition.
865 else if (result & LaTeX::NO_LOGFILE) {
866 docstring const str =
867 bformat(_("LaTeX did not run successfully. "
868 "Additionally, LyX could not locate "
869 "the LaTeX log %1$s."), from_utf8(name));
870 Alert::error(_("LaTeX failed"), str);
871 } else if (result & LaTeX::NONZERO_ERROR) {
872 docstring const str =
873 bformat(_( "The external program\n%1$s\n"
874 "finished with an error. "
875 "It is recommended you fix the cause of the external "
876 "program's error (check the logs). "), from_utf8(command));
877 Alert::error(_("LaTeX failed"), str);
878 } else if (result & LaTeX::NO_OUTPUT) {
879 Alert::warning(_("Output is empty"),
880 _("No output file was generated."));
884 buffer.setBusy(false);
886 int const ERROR_MASK =
891 return (result & ERROR_MASK) == 0;
896 void Converters::buildGraph()
898 // clear graph's data structures
899 G_.init(theFormats().size());
900 // each of the converters knows how to convert one format to another
901 // so, for each of them, we create an arrow on the graph, going from
902 // the one to the other
903 ConverterList::iterator it = converterlist_.begin();
904 ConverterList::iterator const end = converterlist_.end();
905 for (; it != end ; ++it) {
906 int const from = theFormats().getNumber(it->from());
907 int const to = theFormats().getNumber(it->to());
908 LASSERT(from >= 0, continue);
909 LASSERT(to >= 0, continue);
910 G_.addEdge(from, to);
915 FormatList const Converters::intToFormat(vector<int> const & input)
917 FormatList result(input.size());
919 vector<int>::const_iterator it = input.begin();
920 vector<int>::const_iterator const end = input.end();
921 FormatList::iterator rit = result.begin();
922 for ( ; it != end; ++it, ++rit) {
923 *rit = &theFormats().get(*it);
929 FormatList const Converters::getReachableTo(string const & target,
930 bool const clear_visited)
932 vector<int> const & reachablesto =
933 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
935 return intToFormat(reachablesto);
939 FormatList const Converters::getReachable(string const & from,
940 bool const only_viewable, bool const clear_visited,
941 set<string> const & excludes)
943 set<int> excluded_numbers;
945 set<string>::const_iterator sit = excludes.begin();
946 set<string>::const_iterator const end = excludes.end();
947 for (; sit != end; ++sit)
948 excluded_numbers.insert(theFormats().getNumber(*sit));
950 vector<int> const & reachables =
951 G_.getReachable(theFormats().getNumber(from),
956 return intToFormat(reachables);
960 bool Converters::isReachable(string const & from, string const & to)
962 return G_.isReachable(theFormats().getNumber(from),
963 theFormats().getNumber(to));
967 Graph::EdgePath Converters::getPath(string const & from, string const & to)
969 return G_.getPath(theFormats().getNumber(from),
970 theFormats().getNumber(to));
974 FormatList Converters::importableFormats()
976 vector<string> l = loaders();
977 FormatList result = getReachableTo(l[0], true);
978 vector<string>::const_iterator it = l.begin() + 1;
979 vector<string>::const_iterator en = l.end();
980 for (; it != en; ++it) {
981 FormatList r = getReachableTo(*it, false);
982 result.insert(result.end(), r.begin(), r.end());
988 FormatList Converters::exportableFormats(bool only_viewable)
990 vector<string> s = savers();
991 FormatList result = getReachable(s[0], only_viewable, true);
992 vector<string>::const_iterator it = s.begin() + 1;
993 vector<string>::const_iterator en = s.end();
994 for (; it != en; ++it) {
995 FormatList r = getReachable(*it, only_viewable, false);
996 result.insert(result.end(), r.begin(), r.end());
1002 vector<string> Converters::loaders() const
1006 v.push_back("text");
1007 v.push_back("textparagraph");
1012 vector<string> Converters::savers() const
1015 v.push_back("docbook");
1016 v.push_back("latex");
1017 v.push_back("literate");
1018 v.push_back("luatex");
1019 v.push_back("dviluatex");
1021 v.push_back("xhtml");
1022 v.push_back("pdflatex");
1023 v.push_back("platex");
1024 v.push_back("text");
1025 v.push_back("xetex");