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