]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
a157c2237d6f71813a6b1b6abde1b74095f19b75
[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.main_fontenc = buffer->params().main_font_encoding();
487                 runparams.only_childbibs = !buffer->params().useBiblatex()
488                                 && !buffer->params().useBibtopic()
489                                 && buffer->params().multibib == "child";
490         }
491
492         // Some converters (e.g. lilypond) can only output files to the
493         // current directory, so we need to change the current directory.
494         // This has the added benefit that all other files that may be
495         // generated by the converter are deleted when LyX closes and do not
496         // clutter the real working directory.
497         // FIXME: This does not work if path is an UNC path on windows
498         //        (bug 6127).
499         string const path(onlyPath(from_file.absFileName()));
500         // Prevent the compiler from optimizing away p
501         FileName pp(path);
502         PathChanger p(pp);
503
504         // empty the error list before any new conversion takes place.
505         errorList.clear();
506
507         bool run_latex = false;
508         string from_base = changeExtension(from_file.absFileName(), "");
509         string to_base = changeExtension(to_file.absFileName(), "");
510         FileName infile;
511         FileName outfile = from_file;
512         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
513              cit != edgepath.end(); ++cit) {
514                 Converter const & conv = converterlist_[*cit];
515                 bool dummy = conv.To()->dummy() && conv.to() != "program";
516                 if (!dummy) {
517                         LYXERR(Debug::FILES, "Converting from  "
518                                << conv.from() << " to " << conv.to());
519                 }
520                 infile = outfile;
521                 outfile = FileName(conv.result_file().empty()
522                         ? changeExtension(from_file.absFileName(), conv.To()->extension())
523                         : addName(subst(conv.result_dir(),
524                                         token_base, from_base),
525                                   subst(conv.result_file(),
526                                         token_base, onlyFileName(from_base))));
527
528                 // if input and output files are equal, we use a
529                 // temporary file as intermediary (JMarc)
530                 FileName real_outfile;
531                 if (!conv.result_file().empty())
532                         real_outfile = FileName(changeExtension(from_file.absFileName(),
533                                 conv.To()->extension()));
534                 if (outfile == infile) {
535                         real_outfile = infile;
536                         // when importing, a buffer does not necessarily exist
537                         if (buffer)
538                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
539                         else
540                                 outfile = FileName(addName(package().temp_dir().absFileName(),
541                                                    "tmpfile.out"));
542                 }
543
544                 if (buffer && buffer->params().use_minted
545                     && lyxrc.pygmentize_command.empty() && conv.latex()) {
546                         bool dowarn = false;
547                         // Warn only if listings insets are actually used
548                         for (Paragraph const & par : buffer->paragraphs()) {
549                                 InsetList const & insets = par.insetList();
550                                 pos_type lstpos = insets.find(LISTINGS_CODE, 0);
551                                 pos_type incpos = insets.find(INCLUDE_CODE, 0);
552                                 if (incpos >= 0) {
553                                         InsetInclude const * include =
554                                                 static_cast<InsetInclude *>
555                                                         (insets.get(incpos));
556                                         if (include->params().getCmdName() !=
557                                                                 "inputminted") {
558                                                 incpos = -1;
559                                         }
560                                 }
561                                 if (lstpos >= 0 || incpos >= 0) {
562                                         dowarn = true;
563                                         break;
564                                 }
565                         }
566                         if (dowarn) {
567                                 Alert::warning(_("Pygments driver command not found!"),
568                                     _("The driver command necessary to use the minted package\n"
569                                       "(pygmentize) has not been found. Make sure you have\n"
570                                       "the python-pygments module installed or, if the driver\n"
571                                       "is named differently, to add the following line to the\n"
572                                       "document preamble:\n\n"
573                                       "\\AtBeginDocument{\\renewcommand{\\MintedPygmentize}{driver}}\n\n"
574                                       "where 'driver' is name of the driver command."));
575                         }
576                 }
577
578                 if (!checkAuth(conv, buffer ? buffer->absFileName() : string(),
579                                buffer && buffer->params().shell_escape))
580                         return FAILURE;
581
582                 if (conv.latex()) {
583                         // We are not importing, we have a buffer
584                         LATTEST(buffer);
585                         run_latex = true;
586                         string command = conv.command();
587                         command = subst(command, token_from, "");
588                         command = subst(command, token_latex_encoding,
589                                         buffer->params().encoding().latexName());
590                         if (buffer->params().shell_escape
591                             && !contains(command, "-shell-escape"))
592                                 command += " -shell-escape ";
593                         LYXERR(Debug::FILES, "Running " << command);
594                         // FIXME KILLED
595                         // Check changed return value here.
596                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
597                                 if (retval != SUCCESS)
598                                         return retval;
599                 } else {
600                         if (conv.need_aux() && !run_latex) {
601                                 // We are not importing, we have a buffer
602                                 LATTEST(buffer);
603                                 string command;
604                                 switch (runparams.flavor) {
605                                 case OutputParams::DVILUATEX:
606                                         command = dvilualatex_command_;
607                                         break;
608                                 case OutputParams::LUATEX:
609                                         command = lualatex_command_;
610                                         break;
611                                 case OutputParams::PDFLATEX:
612                                         command = pdflatex_command_;
613                                         break;
614                                 case OutputParams::XETEX:
615                                         command = xelatex_command_;
616                                         break;
617                                 default:
618                                         command = latex_command_;
619                                         break;
620                                 }
621                                 if (!command.empty()) {
622                                         LYXERR(Debug::FILES, "Running "
623                                                 << command
624                                                 << " to update aux file");
625                                         // FIXME KILLED
626                                         // Check changed return value here.
627                                         RetVal const retval = runLaTeX(*buffer, command, runparams, errorList);
628                                                 if (retval != SUCCESS)
629                                                         return retval;
630                                 }
631                         }
632
633                         // FIXME UNICODE
634                         string const infile2 =
635                                 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
636                         string const outfile2 =
637                                 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
638
639                         string command = conv.command();
640                         command = subst(command, token_from, quoteName(infile2));
641                         command = subst(command, token_base, quoteName(from_base));
642                         command = subst(command, token_to, quoteName(outfile2));
643                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
644                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
645                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
646                         command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
647
648                         if (!conv.parselog().empty())
649                                 command += " 2> " + quoteName(infile2 + ".out");
650
651                         // it is not actually not necessary to test for buffer here,
652                         // but it pleases coverity.
653                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
654                                 command = add_options(command,
655                                                       buffer->params().dvips_options());
656                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
657                                 command = add_options(command,
658                                                       dvipdfm_options(buffer->params()));
659
660                         LYXERR(Debug::FILES, "Calling " << command);
661                         if (buffer)
662                                 buffer->message(_("Executing command: ")
663                                 + from_utf8(command));
664
665                         Systemcall one;
666                         int res;
667                         if (dummy) {
668                                 res = one.startscript(Systemcall::DontWait,
669                                         to_filesystem8bit(from_utf8(command)),
670                                         buffer ? buffer->filePath() : string(),
671                                         buffer ? buffer->layoutPos() : string());
672                                 // We're not waiting for the result, so we can't do anything
673                                 // else here.
674                         } else {
675                                 Systemcall::Starttype starttype =
676                                                 (buffer && buffer->isClone()) ?
677                                                         Systemcall::WaitLoop : Systemcall::Wait;
678                                 res = one.startscript(starttype,
679                                                 to_filesystem8bit(from_utf8(command)),
680                                                 buffer ? buffer->filePath()
681                                                        : string(),
682                                                 buffer ? buffer->layoutPos()
683                                                        : string());
684                                 if (res == Systemcall::KILLED) {
685                                         frontend::Alert::warning(
686                                                 _("Converter killed"),
687                                                 bformat(_("The following converter was killed by the user.\n %1$s\n"), 
688                                                         from_utf8(command)));
689                                         return KILLED;
690                                 }
691                                 
692                                 if (!real_outfile.empty()) {
693                                         Mover const & mover = getMover(conv.to());
694                                         if (!mover.rename(outfile, real_outfile))
695                                                 res = -1;
696                                         else
697                                                 LYXERR(Debug::FILES, "renaming file " << outfile
698                                                         << " to " << real_outfile);
699                                         // Finally, don't forget to tell any future
700                                         // converters to use the renamed file...
701                                         outfile = real_outfile;
702                                 }
703
704                                 if (!conv.parselog().empty()) {
705                                         string const logfile =  infile2 + ".log";
706                                         string const command2 = conv.parselog() +
707                                                 " < " + quoteName(infile2 + ".out") +
708                                                 " > " + quoteName(logfile);
709                                         res = one.startscript(starttype,
710                                                 to_filesystem8bit(from_utf8(command2)),
711                                                 buffer->filePath(),
712                                                 buffer->layoutPos());
713                                         if (res == Systemcall::KILLED) {
714                                                 frontend::Alert::warning(
715                                                         _("Converter killed"),
716                                                         bformat(_("The following converter was killed by the user.\n %1$s\n"), 
717                                                                 from_utf8(command)));
718                                                 return KILLED;
719                                         }
720                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
721                                                 return FAILURE;
722                                 }
723                         }
724
725                         if (res) {
726                                 if (res == Systemcall::KILLED) {
727                                         Alert::information(_("Process Killed"),
728                                                 bformat(_("The conversion process was killed while running:\n%1$s"),
729                                                         wrapParas(from_utf8(command))));
730                                         return KILLED;
731                                 } 
732                                 if (res == Systemcall::TIMEOUT) {
733                                         Alert::information(_("Process Timed Out"),
734                                                 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
735                                                         wrapParas(from_utf8(command))));
736                                         return KILLED;
737                                 } 
738                                 if (conv.to() == "program") {
739                                         Alert::error(_("Build errors"),
740                                                 _("There were errors during the build process."));
741                                 } else {
742 // FIXME: this should go out of here. For example, here we cannot say if
743 // it is a document (.lyx) or something else. Same goes for elsewhere.
744                                         Alert::error(_("Cannot convert file"),
745                                                 bformat(_("An error occurred while running:\n%1$s"),
746                                                 wrapParas(from_utf8(command))));
747                                 }
748                                 return FAILURE;
749                         }
750                 }
751         }
752
753         Converter const & conv = converterlist_[edgepath.back()];
754         if (conv.To()->dummy())
755                 return SUCCESS;
756
757         if (!conv.result_dir().empty()) {
758                 // The converter has put the file(s) in a directory.
759                 // In this case we ignore the given to_file.
760                 if (from_base != to_base) {
761                         string const from = subst(conv.result_dir(),
762                                             token_base, from_base);
763                         string const to = subst(conv.result_dir(),
764                                           token_base, to_base);
765                         Mover const & mover = getMover(conv.from());
766                         if (!mover.rename(FileName(from), FileName(to))) {
767                                 Alert::error(_("Cannot convert file"),
768                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
769                                                 from_utf8(from), from_utf8(to)));
770                                 return FAILURE;
771                         }
772                 }
773                 return SUCCESS;
774         } else {
775                 if (conversionflags & try_cache)
776                         ConverterCache::get().add(orig_from, to_format, outfile);
777                 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
778         }
779 }
780
781
782 bool Converters::move(string const & fmt,
783                       FileName const & from, FileName const & to, bool copy)
784 {
785         if (from == to)
786                 return true;
787
788         bool no_errors = true;
789         string const path = onlyPath(from.absFileName());
790         string const base = onlyFileName(removeExtension(from.absFileName()));
791         string const to_base = removeExtension(to.absFileName());
792         string const to_extension = getExtension(to.absFileName());
793
794         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
795         for (support::FileNameList::const_iterator it = files.begin();
796              it != files.end(); ++it) {
797                 string const from2 = it->absFileName();
798                 string const file2 = onlyFileName(from2);
799                 if (prefixIs(file2, base)) {
800                         string const to2 = changeExtension(
801                                 to_base + file2.substr(base.length()),
802                                 to_extension);
803                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
804
805                         Mover const & mover = getMover(fmt);
806                         bool const moved = copy
807                                 ? mover.copy(*it, FileName(to2))
808                                 : mover.rename(*it, FileName(to2));
809                         if (!moved && no_errors) {
810                                 Alert::error(_("Cannot convert file"),
811                                         bformat(copy ?
812                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
813                                                 _("Could not move a temporary file from %1$s to %2$s."),
814                                                 from_utf8(from2), from_utf8(to2)));
815                                 no_errors = false;
816                         }
817                 }
818         }
819         return no_errors;
820 }
821
822
823 bool Converters::formatIsUsed(string const & format)
824 {
825         ConverterList::const_iterator cit = converterlist_.begin();
826         ConverterList::const_iterator end = converterlist_.end();
827         for (; cit != end; ++cit) {
828                 if (cit->from() == format || cit->to() == format)
829                         return true;
830         }
831         return false;
832 }
833
834
835 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
836                          FileName const & filename, ErrorList & errorList)
837 {
838         OutputParams runparams(0);
839         runparams.flavor = OutputParams::LATEX;
840         LaTeX latex("", runparams, filename);
841         TeXErrors terr;
842         int const result = latex.scanLogFile(terr);
843
844         if (result & LaTeX::ERRORS)
845                 buffer.bufferErrors(terr, errorList);
846
847         return true;
848 }
849
850
851 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
852                           OutputParams const & runparams, ErrorList & errorList)
853 {
854         buffer.setBusy(true);
855         buffer.message(_("Running LaTeX..."));
856
857         // do the LaTeX run(s)
858         string const name = buffer.latexName();
859         LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
860                     buffer.filePath(), buffer.layoutPos(),
861                     buffer.isClone(), buffer.lastPreviewError());
862         TeXErrors terr;
863         // The connection closes itself at the end of the scope when latex is
864         // destroyed. One cannot close (and destroy) buffer while the converter is
865         // running.
866         latex.message.connect([&buffer](docstring const & msg){
867                         buffer.message(msg);
868                 });
869         int const result = latex.run(terr);
870
871         if (result == Systemcall::KILLED) {
872                 Alert::error(_("Export canceled"),
873                         _("The export process was terminated by the user."));
874                 return KILLED;
875         }
876
877         if (result & LaTeX::ERRORS)
878                 buffer.bufferErrors(terr, errorList);
879
880         if (!errorList.empty()) {
881           // We will show the LaTeX Errors GUI later which contains
882           // specific error messages so it would be repetitive to give
883           // e.g. the "finished with an error" dialog in addition.
884         }
885         else if (result & LaTeX::NO_LOGFILE) {
886                 docstring const str =
887                         bformat(_("LaTeX did not run successfully. "
888                                                "Additionally, LyX could not locate "
889                                                "the LaTeX log %1$s."), from_utf8(name));
890                 Alert::error(_("LaTeX failed"), str);
891         } else if (result & LaTeX::NONZERO_ERROR) {
892                 docstring const str =
893                         bformat(_( "The external program\n%1$s\n"
894                               "finished with an error. "
895                               "It is recommended you fix the cause of the external "
896                               "program's error (check the logs). "), from_utf8(command));
897                 Alert::error(_("LaTeX failed"), str);
898         } else if (result & LaTeX::NO_OUTPUT) {
899                 Alert::warning(_("Output is empty"),
900                                _("No output file was generated."));
901         }
902
903         buffer.setBusy(false);
904
905         int const ERROR_MASK =
906                         LaTeX::NO_LOGFILE |
907                         LaTeX::ERRORS |
908                         LaTeX::NO_OUTPUT;
909
910         return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
911 }
912
913
914
915 void Converters::buildGraph()
916 {
917         // clear graph's data structures
918         G_.init(theFormats().size());
919         // each of the converters knows how to convert one format to another
920         // so, for each of them, we create an arrow on the graph, going from
921         // the one to the other
922         ConverterList::iterator it = converterlist_.begin();
923         ConverterList::iterator const end = converterlist_.end();
924         for (; it != end ; ++it) {
925                 int const from = theFormats().getNumber(it->from());
926                 int const to   = theFormats().getNumber(it->to());
927                 LASSERT(from >= 0, continue);
928                 LASSERT(to >= 0, continue);
929                 G_.addEdge(from, to);
930         }
931 }
932
933
934 FormatList const Converters::intToFormat(vector<int> const & input)
935 {
936         FormatList result(input.size());
937
938         vector<int>::const_iterator it = input.begin();
939         vector<int>::const_iterator const end = input.end();
940         FormatList::iterator rit = result.begin();
941         for ( ; it != end; ++it, ++rit) {
942                 *rit = &theFormats().get(*it);
943         }
944         return result;
945 }
946
947
948 FormatList const Converters::getReachableTo(string const & target,
949                 bool const clear_visited)
950 {
951         vector<int> const & reachablesto =
952                 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
953
954         return intToFormat(reachablesto);
955 }
956
957
958 FormatList const Converters::getReachable(string const & from,
959                 bool const only_viewable, bool const clear_visited,
960                 set<string> const & excludes)
961 {
962         set<int> excluded_numbers;
963
964         set<string>::const_iterator sit = excludes.begin();
965         set<string>::const_iterator const end = excludes.end();
966         for (; sit != end; ++sit)
967                 excluded_numbers.insert(theFormats().getNumber(*sit));
968
969         vector<int> const & reachables =
970                 G_.getReachable(theFormats().getNumber(from),
971                                 only_viewable,
972                                 clear_visited,
973                                 excluded_numbers);
974
975         return intToFormat(reachables);
976 }
977
978
979 bool Converters::isReachable(string const & from, string const & to)
980 {
981         return G_.isReachable(theFormats().getNumber(from),
982                               theFormats().getNumber(to));
983 }
984
985
986 Graph::EdgePath Converters::getPath(string const & from, string const & to)
987 {
988         return G_.getPath(theFormats().getNumber(from),
989                           theFormats().getNumber(to));
990 }
991
992
993 FormatList Converters::importableFormats()
994 {
995         vector<string> l = loaders();
996         FormatList result = getReachableTo(l[0], true);
997         vector<string>::const_iterator it = l.begin() + 1;
998         vector<string>::const_iterator en = l.end();
999         for (; it != en; ++it) {
1000                 FormatList r = getReachableTo(*it, false);
1001                 result.insert(result.end(), r.begin(), r.end());
1002         }
1003         return result;
1004 }
1005
1006
1007 FormatList Converters::exportableFormats(bool only_viewable)
1008 {
1009         vector<string> s = savers();
1010         FormatList result = getReachable(s[0], only_viewable, true);
1011         vector<string>::const_iterator it = s.begin() + 1;
1012         vector<string>::const_iterator en = s.end();
1013         for (; it != en; ++it) {
1014                  FormatList r = getReachable(*it, only_viewable, false);
1015                 result.insert(result.end(), r.begin(), r.end());
1016         }
1017         return result;
1018 }
1019
1020
1021 vector<string> Converters::loaders() const
1022 {
1023         vector<string> v;
1024         v.push_back("lyx");
1025         v.push_back("text");
1026         v.push_back("textparagraph");
1027         return v;
1028 }
1029
1030
1031 vector<string> Converters::savers() const
1032 {
1033         vector<string> v;
1034         v.push_back("docbook");
1035         v.push_back("latex");
1036         v.push_back("literate");
1037         v.push_back("luatex");
1038         v.push_back("dviluatex");
1039         v.push_back("lyx");
1040         v.push_back("xhtml");
1041         v.push_back("pdflatex");
1042         v.push_back("platex");
1043         v.push_back("text");
1044         v.push_back("xetex");
1045         return v;
1046 }
1047
1048
1049 } // namespace lyx