]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
e1a47db7cc081476aa0ca9bb7693dca2a900b24d
[lyx.git] / src / Converter.cpp
1 /**
2  * \file Converter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Dekel Tsur
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Converter.h"
14
15 #include "Buffer.h"
16 #include "buffer_funcs.h"
17 #include "BufferParams.h"
18 #include "ConverterCache.h"
19 #include "Encoding.h"
20 #include "ErrorList.h"
21 #include "Format.h"
22 #include "InsetList.h"
23 #include "Language.h"
24 #include "LaTeX.h"
25 #include "LyXRC.h"
26 #include "Mover.h"
27 #include "ParagraphList.h"
28 #include "Session.h"
29
30 #include "frontends/alert.h"
31
32 #include "insets/InsetInclude.h"
33
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"
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50 namespace Alert = lyx::frontend::Alert;
51
52
53 namespace {
54
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");
63
64
65 string const add_options(string const & command, string const & options)
66 {
67         string head;
68         string const tail = split(command, head, ' ');
69         return head + ' ' + options + ' ' + tail;
70 }
71
72
73 string const dvipdfm_options(BufferParams const & bp)
74 {
75         string result;
76
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;
81
82                 if (bp.orientation == ORIENTATION_LANDSCAPE)
83                         result += " -l";
84         }
85
86         return result;
87 }
88
89
90 class ConverterEqual {
91 public:
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_;
96         }
97 private:
98         string const from_;
99         string const to_;
100 };
101
102 } // namespace
103
104
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)
110 {}
111
112
113 void Converter::readFlags()
114 {
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") {
121                         latex_ = true;
122                         latex_flavor_ = flag_value.empty() ?
123                                 "latex" : flag_value;
124                 } else if (flag_name == "xml")
125                         xml_ = true;
126                 else if (flag_name == "needaux")
127                         need_aux_ = true;
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")
136                         nice_ = true;
137                 else if (flag_name == "needauth")
138                         need_auth_ = true;
139                 else if (flag_name == "hyperref-driver")
140                         href_driver_ = flag_value;
141         }
142         if (!result_dir_.empty() && result_file_.empty())
143                 result_file_ = "index." + theFormats().extension(to_);
144         //if (!contains(command, token_from))
145         //      latex = true;
146 }
147
148
149 Converter const * Converters::getConverter(string const & from,
150                                             string const & to) const
151 {
152         ConverterList::const_iterator const cit =
153                 find_if(converterlist_.begin(), converterlist_.end(),
154                         ConverterEqual(from, to));
155         if (cit != converterlist_.end())
156                 return &(*cit);
157         else
158                 return 0;
159 }
160
161
162 int Converters::getNumber(string const & from, string const & to) const
163 {
164         ConverterList::const_iterator const cit =
165                 find_if(converterlist_.begin(), converterlist_.end(),
166                         ConverterEqual(from, to));
167         if (cit != converterlist_.end())
168                 return distance(converterlist_.begin(), cit);
169         else
170                 return -1;
171 }
172
173
174 void Converters::add(string const & from, string const & to,
175                      string const & command, string const & flags)
176 {
177         theFormats().add(from);
178         theFormats().add(to);
179         ConverterList::iterator it = find_if(converterlist_.begin(),
180                                              converterlist_.end(),
181                                              ConverterEqual(from , to));
182
183         Converter converter(from, to, command, flags);
184         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
185                 converter = *it;
186                 converter.setCommand(command);
187                 converter.setFlags(flags);
188         }
189         converter.readFlags();
190
191         // The latex_command is used to update the .aux file when running
192         // a converter that uses it.
193         if (converter.latex()) {
194                 if (latex_command_.empty() ||
195                     converter.latex_flavor() == "latex")
196                         latex_command_ = subst(command, token_from, "");
197                 if (dvilualatex_command_.empty() ||
198                     converter.latex_flavor() == "dvilualatex")
199                         dvilualatex_command_ = subst(command, token_from, "");
200                 if (lualatex_command_.empty() ||
201                     converter.latex_flavor() == "lualatex")
202                         lualatex_command_ = subst(command, token_from, "");
203                 if (pdflatex_command_.empty() ||
204                     converter.latex_flavor() == "pdflatex")
205                         pdflatex_command_ = subst(command, token_from, "");
206                 if (xelatex_command_.empty() ||
207                     converter.latex_flavor() == "xelatex")
208                         xelatex_command_ = subst(command, token_from, "");
209         }
210
211         if (it == converterlist_.end()) {
212                 converterlist_.push_back(converter);
213         } else {
214                 converter.setFrom(it->From());
215                 converter.setTo(it->To());
216                 *it = converter;
217         }
218 }
219
220
221 void Converters::erase(string const & from, string const & to)
222 {
223         ConverterList::iterator const it =
224                 find_if(converterlist_.begin(),
225                         converterlist_.end(),
226                         ConverterEqual(from, to));
227         if (it != converterlist_.end())
228                 converterlist_.erase(it);
229 }
230
231
232 // This method updates the pointers From and To in all the converters.
233 // The code is not very efficient, but it doesn't matter as the number
234 // of formats and converters is small.
235 // Furthermore, this method is called only on startup, or after
236 // adding/deleting a format in FormPreferences (the latter calls can be
237 // eliminated if the formats in the Formats class are stored using a map or
238 // a list (instead of a vector), but this will cause other problems).
239 void Converters::update(Formats const & formats)
240 {
241         ConverterList::iterator it = converterlist_.begin();
242         ConverterList::iterator end = converterlist_.end();
243         for (; it != end; ++it) {
244                 it->setFrom(formats.getFormat(it->from()));
245                 it->setTo(formats.getFormat(it->to()));
246         }
247 }
248
249
250 // This method updates the pointers From and To in the last converter.
251 // It is called when adding a new converter in FormPreferences
252 void Converters::updateLast(Formats const & formats)
253 {
254         if (converterlist_.begin() != converterlist_.end()) {
255                 ConverterList::iterator it = converterlist_.end() - 1;
256                 it->setFrom(formats.getFormat(it->from()));
257                 it->setTo(formats.getFormat(it->to()));
258         }
259 }
260
261
262 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
263                                            Buffer const * buffer)
264 {
265         for (Graph::EdgePath::const_iterator cit = path.begin();
266              cit != path.end(); ++cit) {
267                 Converter const & conv = converterlist_[*cit];
268                 if (conv.latex()) {
269                         if (conv.latex_flavor() == "latex")
270                                 return OutputParams::LATEX;
271                         if (conv.latex_flavor() == "xelatex")
272                                 return OutputParams::XETEX;
273                         if (conv.latex_flavor() == "lualatex")
274                                 return OutputParams::LUATEX;
275                         if (conv.latex_flavor() == "dvilualatex")
276                                 return OutputParams::DVILUATEX;
277                         if (conv.latex_flavor() == "pdflatex")
278                                 return OutputParams::PDFLATEX;
279                 }
280                 if (conv.xml())
281                         return OutputParams::XML;
282         }
283         return buffer ? buffer->params().getOutputFlavor()
284                       : OutputParams::LATEX;
285 }
286
287
288 string Converters::getHyperrefDriver(Graph::EdgePath const & path)
289 {
290         for (Graph::EdgePath::const_iterator cit = path.begin();
291              cit != path.end(); ++cit) {
292                 Converter const & conv = converterlist_[*cit];
293                 if (!conv.hyperref_driver().empty())
294                         return conv.hyperref_driver();
295         }
296         return string();
297 }
298
299
300 bool Converters::checkAuth(Converter const & conv, string const & doc_fname,
301                            bool use_shell_escape)
302 {
303         string conv_command = conv.command();
304         bool const has_shell_escape = contains(conv_command, "-shell-escape")
305                                 || contains(conv_command, "-enable-write18");
306         if (conv.latex() && has_shell_escape && !use_shell_escape) {
307                 docstring const shellescape_warning =
308                       bformat(_("<p>The following LaTeX backend has been "
309                         "configured to allow execution of external programs "
310                         "for any document:</p>"
311                         "<center><p><tt>%1$s</tt></p></center>"
312                         "<p>This is a dangerous configuration. Please, "
313                         "consider using the support offered by LyX for "
314                         "allowing this privilege only to documents that "
315                         "actually need it, instead.</p>"),
316                         from_utf8(conv_command));
317                 frontend::Alert::error(_("Security Warning"),
318                                         shellescape_warning , false);
319         } else if (!conv.latex())
320                 use_shell_escape = false;
321         if (!conv.need_auth() && !use_shell_escape)
322                 return true;
323         size_t const token_pos = conv_command.find("$$");
324         bool const has_token = token_pos != string::npos;
325         string const command = use_shell_escape && !has_shell_escape
326                 ? (has_token ? conv_command.insert(token_pos, "-shell-escape ")
327                              : conv_command.append(" -shell-escape"))
328                 : conv_command;
329         docstring const security_warning = (use_shell_escape
330             ? bformat(_("<p>The following LaTeX backend has been requested "
331                 "to allow execution of external programs:</p>"
332                 "<center><p><tt>%1$s</tt></p></center>"
333                 "<p>The external programs can execute arbitrary commands on "
334                 "your system, including dangerous ones, if instructed to do "
335                 "so by a maliciously crafted LyX document.</p>"),
336               from_utf8(command))
337             : bformat(_("<p>The requested operation requires the use of a "
338                 "converter from %2$s to %3$s:</p>"
339                 "<blockquote><p><tt>%1$s</tt></p></blockquote>"
340                 "<p>This external program can execute arbitrary commands on "
341                 "your system, including dangerous ones, if instructed to do "
342                 "so by a maliciously crafted LyX document.</p>"),
343               from_utf8(command), from_utf8(conv.from()),
344               from_utf8(conv.to())));
345         if (lyxrc.use_converter_needauth_forbidden && !use_shell_escape) {
346                 frontend::Alert::error(
347                     _("An external converter is disabled for security reasons"),
348                     security_warning + _(
349                     "<p><b>Your current preference settings forbid its execution.</b></p>"
350                     "<p>(To change this setting, go to <i>Preferences &#x25b9; File "
351                     "Handling &#x25b9; Converters</i> and uncheck <i>Security &#x25b9; "
352                     "Forbid needauth converters</i>.)"), false);
353                 return false;
354         }
355         if (!lyxrc.use_converter_needauth && !use_shell_escape)
356                 return true;
357         docstring const security_title = use_shell_escape
358                 ? _("A LaTeX backend requires your authorization")
359                 : _("An external converter requires your authorization");
360         int choice;
361         docstring const security_warning2 = security_warning + (use_shell_escape
362                 ? _("<p>Should LaTeX backends be allowed to run external "
363                     "programs?</p><p><b>Allow them only if you trust the "
364                     "origin/sender of the LyX document!</b></p>")
365                 : _("<p>Would you like to run this converter?</p>"
366                     "<p><b>Only run if you trust the origin/sender of the LyX "
367                     "document!</b></p>"));
368         docstring const no = use_shell_escape
369                                 ? _("Do &not allow") : _("Do &not run");
370         docstring const yes = use_shell_escape ? _("A&llow") : _("&Run");
371         docstring const always = use_shell_escape
372                                         ? _("&Always allow for this document")
373                                         : _("&Always run for this document");
374         if (!doc_fname.empty()) {
375                 LYXERR(Debug::FILES, "looking up: " << doc_fname);
376                 bool authorized = use_shell_escape
377                         ? theSession().shellescapeFiles().findAuth(doc_fname)
378                         : theSession().authFiles().find(doc_fname);
379                 if (!authorized) {
380                         choice = frontend::Alert::prompt(security_title,
381                                                          security_warning2,
382                                                          0, 0, no, yes, always);
383                         if (choice == 2) {
384                                 if (use_shell_escape)
385                                         theSession().shellescapeFiles().insert(doc_fname, true);
386                                 else
387                                         theSession().authFiles().insert(doc_fname);
388                         }
389                 } else {
390                         choice = 1;
391                 }
392         } else {
393                 choice = frontend::Alert::prompt(security_title,
394                                                  security_warning2,
395                                                  0, 0, no, yes);
396         }
397         return choice != 0;
398 }
399
400
401 Converters::RetVal Converters::convert(Buffer const * buffer,
402                          FileName const & from_file, FileName const & to_file,
403                          FileName const & orig_from,
404                          string const & from_format, string const & to_format,
405                          ErrorList & errorList, int conversionflags)
406 {
407         if (from_format == to_format)
408                 return move(from_format, from_file, to_file, false) ?
409                       SUCCESS : FAILURE;
410
411         if ((conversionflags & try_cache) &&
412             ConverterCache::get().inCache(orig_from, to_format))
413                 return ConverterCache::get().copy(orig_from, to_format, to_file) ?
414                       SUCCESS : FAILURE;
415
416         Graph::EdgePath edgepath = getPath(from_format, to_format);
417         if (edgepath.empty()) {
418                 if (conversionflags & try_default) {
419                         // if no special converter defined, then we take the
420                         // default one from ImageMagic.
421                         string const from_ext = from_format.empty() ?
422                                 getExtension(from_file.absFileName()) :
423                                 theFormats().extension(from_format);
424                         string const to_ext = theFormats().extension(to_format);
425                         string const command =
426                                 os::python() + ' ' +
427                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
428                                 ' ' + from_ext + ' ' +
429                                 quoteName(from_file.toFilesystemEncoding()) +
430                                 ' ' + to_ext + ' ' +
431                                 quoteName(to_file.toFilesystemEncoding());
432                         LYXERR(Debug::FILES, "No converter defined! "
433                                    "I use convertDefault.py:\n\t" << command);
434                         Systemcall one;
435                         Systemcall::Starttype starttype =
436                                 (buffer && buffer->isClone()) ?
437                                         Systemcall::WaitLoop : Systemcall::Wait;
438                         int const exitval = one.startscript(starttype, command,
439                                         buffer ? buffer->filePath() : string(),
440                                         buffer ? buffer->layoutPos() : string());
441                         if (exitval == Systemcall::KILLED) {
442                                 frontend::Alert::warning(
443                                         _("Converter killed"),
444                                         bformat(_("The following converter was killed by the user.\n %1$s\n"),
445                                                 from_utf8(command)));
446                                 return KILLED;
447                         }
448                         if (to_file.isReadableFile()) {
449                                 if (conversionflags & try_cache)
450                                         ConverterCache::get().add(orig_from,
451                                                         to_format, to_file);
452                                 return SUCCESS;
453                         }
454                 }
455
456                 // only warn once per session and per file type
457                 static std::map<string, string> warned;
458                 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
459                         return FAILURE;
460                 }
461                 warned.insert(make_pair(from_format, to_format));
462
463                 Alert::error(_("Cannot convert file"),
464                              bformat(_("No information for converting %1$s "
465                                                     "format files to %2$s.\n"
466                                                     "Define a converter in the preferences."),
467                                                         from_ascii(from_format), from_ascii(to_format)));
468                 return FAILURE;
469         }
470
471         // buffer is only invalid for importing, and then runparams is not
472         // used anyway.
473         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
474         runparams.flavor = getFlavor(edgepath, buffer);
475
476         if (buffer) {
477                 runparams.use_japanese =
478                         (buffer->params().bufferFormat() == "latex"
479                          || suffixIs(buffer->params().bufferFormat(), "-ja"))
480                         && buffer->params().encoding().package() == Encoding::japanese;
481                 runparams.use_indices = buffer->params().use_indices;
482                 runparams.bibtex_command = buffer->params().bibtexCommand();
483                 runparams.index_command = (buffer->params().index_command == "default") ?
484                         string() : buffer->params().index_command;
485                 runparams.document_language = buffer->params().language->babel();
486                 runparams.only_childbibs = !buffer->params().useBiblatex()
487                                 && !buffer->params().useBibtopic()
488                                 && buffer->params().multibib == "child";
489         }
490
491         // Some converters (e.g. lilypond) can only output files to the
492         // current directory, so we need to change the current directory.
493         // This has the added benefit that all other files that may be
494         // generated by the converter are deleted when LyX closes and do not
495         // clutter the real working directory.
496         // FIXME: This does not work if path is an UNC path on windows
497         //        (bug 6127).
498         string const path(onlyPath(from_file.absFileName()));
499         // Prevent the compiler from optimizing away p
500         FileName pp(path);
501         PathChanger p(pp);
502
503         // empty the error list before any new conversion takes place.
504         errorList.clear();
505
506         bool run_latex = false;
507         string from_base = changeExtension(from_file.absFileName(), "");
508         string to_base = changeExtension(to_file.absFileName(), "");
509         FileName infile;
510         FileName outfile = from_file;
511         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
512              cit != edgepath.end(); ++cit) {
513                 Converter const & conv = converterlist_[*cit];
514                 bool dummy = conv.To()->dummy() && conv.to() != "program";
515                 if (!dummy) {
516                         LYXERR(Debug::FILES, "Converting from  "
517                                << conv.from() << " to " << conv.to());
518                 }
519                 infile = outfile;
520                 outfile = FileName(conv.result_file().empty()
521                         ? changeExtension(from_file.absFileName(), conv.To()->extension())
522                         : addName(subst(conv.result_dir(),
523                                         token_base, from_base),
524                                   subst(conv.result_file(),
525                                         token_base, onlyFileName(from_base))));
526
527                 // if input and output files are equal, we use a
528                 // temporary file as intermediary (JMarc)
529                 FileName real_outfile;
530                 if (!conv.result_file().empty())
531                         real_outfile = FileName(changeExtension(from_file.absFileName(),
532                                 conv.To()->extension()));
533                 if (outfile == infile) {
534                         real_outfile = infile;
535                         // when importing, a buffer does not necessarily exist
536                         if (buffer)
537                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
538                         else
539                                 outfile = FileName(addName(package().temp_dir().absFileName(),
540                                                    "tmpfile.out"));
541                 }
542
543                 if (buffer && buffer->params().use_minted
544                     && lyxrc.pygmentize_command.empty() && conv.latex()) {
545                         bool dowarn = false;
546                         // Warn only if listings insets are actually used
547                         for (Paragraph const & par : buffer->paragraphs()) {
548                                 InsetList const & insets = par.insetList();
549                                 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
550                                 pos_type incpos = insets.find(INCLUDE_CODE, 0);
551                                 if (incpos >= 0) {
552                                         InsetInclude const * include =
553                                                 static_cast<InsetInclude *>
554                                                         (insets.get(incpos));
555                                         if (include->params().getCmdName() !=
556                                                                 "inputminted") {
557                                                 incpos = -1;
558                                         }
559                                 }
560                                 if (lstpos >= 0 || incpos >= 0) {
561                                         dowarn = true;
562                                         break;
563                                 }
564                         }
565                         if (dowarn) {
566                                 Alert::warning(_("Pygments driver command not found!"),
567                                     _("The driver command necessary to use the minted package\n"
568                                       "(pygmentize) has not been found. Make sure you have\n"
569                                       "the python-pygments module installed or, if the driver\n"
570                                       "is named differently, to add the following line to the\n"
571                                       "document preamble:\n\n"
572                                       "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
573                                       "where 'driver' is name of the driver command."));
574                         }
575                 }
576
577                 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
578                                buffer && buffer->params().shell_escape))
579                         return FAILURE;
580
581                 if (conv.latex()) {
582                         // We are not importing, we have a buffer
583                         LATTEST(buffer);
584                         run_latex = true;
585                         string command = conv.command();
586                         command = subst(command, token_from, "");
587                         command = subst(command, token_latex_encoding,
588                                         buffer->params().encoding().latexName());
589                         if (buffer->params().shell_escape
590                             && !contains(command, "-shell-escape"))
591                                 command += " -shell-escape ";
592                         LYXERR(Debug::FILES, "Running " << command);
593                         // FIXME KILLED
594                         // Check changed return value here.
595                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
596                                 if (retval != SUCCESS)
597                                         return retval;
598                 } else {
599                         if (conv.need_aux() && !run_latex) {
600                                 // We are not importing, we have a buffer
601                                 LATTEST(buffer);
602                                 string command;
603                                 switch (runparams.flavor) {
604                                 case OutputParams::DVILUATEX:
605                                         command = dvilualatex_command_;
606                                         break;
607                                 case OutputParams::LUATEX:
608                                         command = lualatex_command_;
609                                         break;
610                                 case OutputParams::PDFLATEX:
611                                         command = pdflatex_command_;
612                                         break;
613                                 case OutputParams::XETEX:
614                                         command = xelatex_command_;
615                                         break;
616                                 default:
617                                         command = latex_command_;
618                                         break;
619                                 }
620                                 if (!command.empty()) {
621                                         LYXERR(Debug::FILES, "Running "
622                                                 << command
623                                                 << " to update aux file");
624                                         // FIXME KILLED
625                                         // Check changed return value here.
626                                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
627                                                 if (retval != SUCCESS)
628                                                         return retval;
629                                 }
630                         }
631
632                         // FIXME UNICODE
633                         string const infile2 =
634                                 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
635                         string const outfile2 =
636                                 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
637
638                         string command = conv.command();
639                         command = subst(command, token_from, quoteName(infile2));
640                         command = subst(command, token_base, quoteName(from_base));
641                         command = subst(command, token_to, quoteName(outfile2));
642                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
643                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
644                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
645                         command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
646
647                         if (!conv.parselog().empty())
648                                 command += " 2> " + quoteName(infile2 + ".out");
649
650                         // it is not actually not necessary to test for buffer here,
651                         // but it pleases coverity.
652                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
653                                 command = add_options(command,
654                                                       buffer->params().dvips_options());
655                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
656                                 command = add_options(command,
657                                                       dvipdfm_options(buffer->params()));
658
659                         LYXERR(Debug::FILES, "Calling " << command);
660                         if (buffer)
661                                 buffer->message(_("Executing command: ")
662                                 + from_utf8(command));
663
664                         Systemcall one;
665                         int res;
666                         if (dummy) {
667                                 res = one.startscript(Systemcall::DontWait,
668                                         to_filesystem8bit(from_utf8(command)),
669                                         buffer ? buffer->filePath() : string(),
670                                         buffer ? buffer->layoutPos() : string());
671                                 // We're not waiting for the result, so we can't do anything
672                                 // else here.
673                         } else {
674                                 Systemcall::Starttype starttype =
675                                                 (buffer && buffer->isClone()) ?
676                                                         Systemcall::WaitLoop : Systemcall::Wait;
677                                 res = one.startscript(starttype,
678                                                 to_filesystem8bit(from_utf8(command)),
679                                                 buffer ? buffer->filePath()
680                                                        : string(),
681                                                 buffer ? buffer->layoutPos()
682                                                        : string());
683                                 if (res == Systemcall::KILLED) {
684                                         frontend::Alert::warning(
685                                                 _("Converter killed"),
686                                                 bformat(_("The following converter was killed by the user.\n %1$s\n"), 
687                                                         from_utf8(command)));
688                                         return KILLED;
689                                 }
690                                 
691                                 if (!real_outfile.empty()) {
692                                         Mover const & mover = getMover(conv.to());
693                                         if (!mover.rename(outfile, real_outfile))
694                                                 res = -1;
695                                         else
696                                                 LYXERR(Debug::FILES, "renaming file " << outfile
697                                                         << " to " << real_outfile);
698                                         // Finally, don't forget to tell any future
699                                         // converters to use the renamed file...
700                                         outfile = real_outfile;
701                                 }
702
703                                 if (!conv.parselog().empty()) {
704                                         string const logfile =  infile2 + ".log";
705                                         string const command2 = conv.parselog() +
706                                                 " < " + quoteName(infile2 + ".out") +
707                                                 " > " + quoteName(logfile);
708                                         res = one.startscript(starttype,
709                                                 to_filesystem8bit(from_utf8(command2)),
710                                                 buffer->filePath(),
711                                                 buffer->layoutPos());
712                                         if (res == Systemcall::KILLED) {
713                                                 frontend::Alert::warning(
714                                                         _("Converter killed"),
715                                                         bformat(_("The following converter was killed by the user.\n %1$s\n"), 
716                                                                 from_utf8(command)));
717                                                 return KILLED;
718                                         }
719                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
720                                                 return FAILURE;
721                                 }
722                         }
723
724                         if (res) {
725                                 if (res == Systemcall::KILLED) {
726                                         Alert::information(_("Process Killed"),
727                                                 bformat(_("The conversion process was killed while running:\n%1$s"),
728                                                         wrapParas(from_utf8(command))));
729                                         return KILLED;
730                                 } 
731                                 if (res == Systemcall::TIMEOUT) {
732                                         Alert::information(_("Process Timed Out"),
733                                                 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
734                                                         wrapParas(from_utf8(command))));
735                                         return KILLED;
736                                 } 
737                                 if (conv.to() == "program") {
738                                         Alert::error(_("Build errors"),
739                                                 _("There were errors during the build process."));
740                                 } else {
741 // FIXME: this should go out of here. For example, here we cannot say if
742 // it is a document (.lyx) or something else. Same goes for elsewhere.
743                                         Alert::error(_("Cannot convert file"),
744                                                 bformat(_("An error occurred while running:\n%1$s"),
745                                                 wrapParas(from_utf8(command))));
746                                 }
747                                 return FAILURE;
748                         }
749                 }
750         }
751
752         Converter const & conv = converterlist_[edgepath.back()];
753         if (conv.To()->dummy())
754                 return SUCCESS;
755
756         if (!conv.result_dir().empty()) {
757                 // The converter has put the file(s) in a directory.
758                 // In this case we ignore the given to_file.
759                 if (from_base != to_base) {
760                         string const from = subst(conv.result_dir(),
761                                             token_base, from_base);
762                         string const to = subst(conv.result_dir(),
763                                           token_base, to_base);
764                         Mover const & mover = getMover(conv.from());
765                         if (!mover.rename(FileName(from), FileName(to))) {
766                                 Alert::error(_("Cannot convert file"),
767                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
768                                                 from_utf8(from), from_utf8(to)));
769                                 return FAILURE;
770                         }
771                 }
772                 return SUCCESS;
773         } else {
774                 if (conversionflags & try_cache)
775                         ConverterCache::get().add(orig_from, to_format, outfile);
776                 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
777         }
778 }
779
780
781 bool Converters::move(string const & fmt,
782                       FileName const & from, FileName const & to, bool copy)
783 {
784         if (from == to)
785                 return true;
786
787         bool no_errors = true;
788         string const path = onlyPath(from.absFileName());
789         string const base = onlyFileName(removeExtension(from.absFileName()));
790         string const to_base = removeExtension(to.absFileName());
791         string const to_extension = getExtension(to.absFileName());
792
793         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
794         for (support::FileNameList::const_iterator it = files.begin();
795              it != files.end(); ++it) {
796                 string const from2 = it->absFileName();
797                 string const file2 = onlyFileName(from2);
798                 if (prefixIs(file2, base)) {
799                         string const to2 = changeExtension(
800                                 to_base + file2.substr(base.length()),
801                                 to_extension);
802                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
803
804                         Mover const & mover = getMover(fmt);
805                         bool const moved = copy
806                                 ? mover.copy(*it, FileName(to2))
807                                 : mover.rename(*it, FileName(to2));
808                         if (!moved && no_errors) {
809                                 Alert::error(_("Cannot convert file"),
810                                         bformat(copy ?
811                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
812                                                 _("Could not move a temporary file from %1$s to %2$s."),
813                                                 from_utf8(from2), from_utf8(to2)));
814                                 no_errors = false;
815                         }
816                 }
817         }
818         return no_errors;
819 }
820
821
822 bool Converters::formatIsUsed(string const & format)
823 {
824         ConverterList::const_iterator cit = converterlist_.begin();
825         ConverterList::const_iterator end = converterlist_.end();
826         for (; cit != end; ++cit) {
827                 if (cit->from() == format || cit->to() == format)
828                         return true;
829         }
830         return false;
831 }
832
833
834 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
835                          FileName const & filename, ErrorList & errorList)
836 {
837         OutputParams runparams(0);
838         runparams.flavor = OutputParams::LATEX;
839         LaTeX latex("", runparams, filename);
840         TeXErrors terr;
841         int const result = latex.scanLogFile(terr);
842
843         if (result & LaTeX::ERRORS)
844                 buffer.bufferErrors(terr, errorList);
845
846         return true;
847 }
848
849
850 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
851                           OutputParams const & runparams, ErrorList & errorList)
852 {
853         buffer.setBusy(true);
854         buffer.message(_("Running LaTeX..."));
855
856         // do the LaTeX run(s)
857         string const name = buffer.latexName();
858         LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
859                     buffer.filePath(), buffer.layoutPos(),
860                     buffer.isClone(), buffer.lastPreviewError());
861         TeXErrors terr;
862         // The connection closes itself at the end of the scope when latex is
863         // destroyed. One cannot close (and destroy) buffer while the converter is
864         // running.
865         latex.message.connect([&buffer](docstring const & msg){
866                         buffer.message(msg);
867                 });
868         int const result = latex.run(terr);
869
870         if (result == Systemcall::KILLED) {
871                 Alert::error(_("Export canceled"),
872                         _("The export process was terminated by the user."));
873                 return KILLED;
874         }
875
876         if (result & LaTeX::ERRORS)
877                 buffer.bufferErrors(terr, errorList);
878
879         if (!errorList.empty()) {
880           // We will show the LaTeX Errors GUI later which contains
881           // specific error messages so it would be repetitive to give
882           // e.g. the "finished with an error" dialog in addition.
883         }
884         else if (result & LaTeX::NO_LOGFILE) {
885                 docstring const str =
886                         bformat(_("LaTeX did not run successfully. "
887                                                "Additionally, LyX could not locate "
888                                                "the LaTeX log %1$s."), from_utf8(name));
889                 Alert::error(_("LaTeX failed"), str);
890         } else if (result & LaTeX::NONZERO_ERROR) {
891                 docstring const str =
892                         bformat(_( "The external program\n%1$s\n"
893                               "finished with an error. "
894                               "It is recommended you fix the cause of the external "
895                               "program's error (check the logs). "), from_utf8(command));
896                 Alert::error(_("LaTeX failed"), str);
897         } else if (result & LaTeX::NO_OUTPUT) {
898                 Alert::warning(_("Output is empty"),
899                                _("No output file was generated."));
900         }
901
902         buffer.setBusy(false);
903
904         int const ERROR_MASK =
905                         LaTeX::NO_LOGFILE |
906                         LaTeX::ERRORS |
907                         LaTeX::NO_OUTPUT;
908
909         return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
910 }
911
912
913
914 void Converters::buildGraph()
915 {
916         // clear graph's data structures
917         G_.init(theFormats().size());
918         // each of the converters knows how to convert one format to another
919         // so, for each of them, we create an arrow on the graph, going from
920         // the one to the other
921         ConverterList::iterator it = converterlist_.begin();
922         ConverterList::iterator const end = converterlist_.end();
923         for (; it != end ; ++it) {
924                 int const from = theFormats().getNumber(it->from());
925                 int const to   = theFormats().getNumber(it->to());
926                 LASSERT(from >= 0, continue);
927                 LASSERT(to >= 0, continue);
928                 G_.addEdge(from, to);
929         }
930 }
931
932
933 FormatList const Converters::intToFormat(vector<int> const & input)
934 {
935         FormatList result(input.size());
936
937         vector<int>::const_iterator it = input.begin();
938         vector<int>::const_iterator const end = input.end();
939         FormatList::iterator rit = result.begin();
940         for ( ; it != end; ++it, ++rit) {
941                 *rit = &theFormats().get(*it);
942         }
943         return result;
944 }
945
946
947 FormatList const Converters::getReachableTo(string const & target,
948                 bool const clear_visited)
949 {
950         vector<int> const & reachablesto =
951                 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
952
953         return intToFormat(reachablesto);
954 }
955
956
957 FormatList const Converters::getReachable(string const & from,
958                 bool const only_viewable, bool const clear_visited,
959                 set<string> const & excludes)
960 {
961         set<int> excluded_numbers;
962
963         set<string>::const_iterator sit = excludes.begin();
964         set<string>::const_iterator const end = excludes.end();
965         for (; sit != end; ++sit)
966                 excluded_numbers.insert(theFormats().getNumber(*sit));
967
968         vector<int> const & reachables =
969                 G_.getReachable(theFormats().getNumber(from),
970                                 only_viewable,
971                                 clear_visited,
972                                 excluded_numbers);
973
974         return intToFormat(reachables);
975 }
976
977
978 bool Converters::isReachable(string const & from, string const & to)
979 {
980         return G_.isReachable(theFormats().getNumber(from),
981                               theFormats().getNumber(to));
982 }
983
984
985 Graph::EdgePath Converters::getPath(string const & from, string const & to)
986 {
987         return G_.getPath(theFormats().getNumber(from),
988                           theFormats().getNumber(to));
989 }
990
991
992 FormatList Converters::importableFormats()
993 {
994         vector<string> l = loaders();
995         FormatList result = getReachableTo(l[0], true);
996         vector<string>::const_iterator it = l.begin() + 1;
997         vector<string>::const_iterator en = l.end();
998         for (; it != en; ++it) {
999                 FormatList r = getReachableTo(*it, false);
1000                 result.insert(result.end(), r.begin(), r.end());
1001         }
1002         return result;
1003 }
1004
1005
1006 FormatList Converters::exportableFormats(bool only_viewable)
1007 {
1008         vector<string> s = savers();
1009         FormatList result = getReachable(s[0], only_viewable, true);
1010         vector<string>::const_iterator it = s.begin() + 1;
1011         vector<string>::const_iterator en = s.end();
1012         for (; it != en; ++it) {
1013                  FormatList r = getReachable(*it, only_viewable, false);
1014                 result.insert(result.end(), r.begin(), r.end());
1015         }
1016         return result;
1017 }
1018
1019
1020 vector<string> Converters::loaders() const
1021 {
1022         vector<string> v;
1023         v.push_back("lyx");
1024         v.push_back("text");
1025         v.push_back("textparagraph");
1026         return v;
1027 }
1028
1029
1030 vector<string> Converters::savers() const
1031 {
1032         vector<string> v;
1033         v.push_back("docbook");
1034         v.push_back("latex");
1035         v.push_back("literate");
1036         v.push_back("luatex");
1037         v.push_back("dviluatex");
1038         v.push_back("lyx");
1039         v.push_back("xhtml");
1040         v.push_back("pdflatex");
1041         v.push_back("platex");
1042         v.push_back("text");
1043         v.push_back("xetex");
1044         return v;
1045 }
1046
1047
1048 } // namespace lyx