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