]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
Hack to display section symbol
[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                         BufferParams const & bparams = buffer ? buffer->params() : defaultBufferParams();
650                         command = subst(command, token_from, quoteName(infile2));
651                         command = subst(command, token_base, quoteName(from_base));
652                         command = subst(command, token_to, quoteName(outfile2));
653                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
654                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
655                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
656                         command = subst(command, token_textclass, quoteName(bparams.documentClass().name()));
657                         string modules = bparams.getModules().asString();
658                         // FIXME: remove when SystemCall uses QProcess with the list API.
659                         // Currently the QProcess parser is not able to encode an
660                         // empty argument as ""; work around this by passing a
661                         // single comma, that will be interpreted as a list of two
662                         // empty module names.
663                         if (modules.empty())
664                                 modules = ",";
665                         command = subst(command, token_modules, quoteName(modules));
666                         command = subst(command, token_encoding, quoteName(bparams.encoding().iconvName()));
667                         command = subst(command, token_python, os::python());
668
669                         if (!conv.parselog().empty())
670                                 command += " 2> " + quoteName(infile2 + ".out");
671
672                         // it is not actually not necessary to test for buffer here,
673                         // but it pleases coverity.
674                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
675                                 command = add_options(command,
676                                                       buffer->params().dvips_options());
677                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
678                                 command = add_options(command,
679                                                       dvipdfm_options(buffer->params()));
680
681                         LYXERR(Debug::FILES, "Calling " << command);
682                         if (buffer)
683                                 buffer->message(_("Executing command: ")
684                                 + from_utf8(command));
685
686                         Systemcall one;
687                         int res;
688                         if (dummy) {
689                                 res = one.startscript(Systemcall::DontWait,
690                                         to_filesystem8bit(from_utf8(command)),
691                                         buffer ? buffer->filePath() : string(),
692                                         buffer ? buffer->layoutPos() : string());
693                                 // We're not waiting for the result, so we can't do anything
694                                 // else here.
695                         } else {
696                                 Systemcall::Starttype starttype =
697                                                 (buffer && buffer->isClone()) ?
698                                                         Systemcall::WaitLoop : Systemcall::Wait;
699                                 res = one.startscript(starttype,
700                                                 to_filesystem8bit(from_utf8(command)),
701                                                 buffer ? buffer->filePath()
702                                                        : string(),
703                                                 buffer ? buffer->layoutPos()
704                                                        : string());
705                                 if (res == Systemcall::KILLED) {
706                                         frontend::Alert::warning(
707                                                 _("Converter killed"),
708                                                 bformat(_("The following converter was killed by the user.\n %1$s\n"),
709                                                         from_utf8(command)));
710                                         return KILLED;
711                                 }
712
713                                 if (!real_outfile.empty()) {
714                                         Mover const & mover = getMover(conv.to());
715                                         if (!mover.rename(outfile, real_outfile))
716                                                 res = -1;
717                                         else
718                                                 LYXERR(Debug::FILES, "renaming file " << outfile
719                                                         << " to " << real_outfile);
720                                         // Finally, don't forget to tell any future
721                                         // converters to use the renamed file...
722                                         outfile = real_outfile;
723                                 }
724
725                                 if (!conv.parselog().empty()) {
726                                         string const logfile =  infile2 + ".log";
727                                         string const command2 = conv.parselog() +
728                                                 " < " + quoteName(infile2 + ".out") +
729                                                 " > " + quoteName(logfile);
730                                         res = one.startscript(starttype,
731                                                 to_filesystem8bit(from_utf8(command2)),
732                                                 buffer ? buffer->filePath() : string(),
733                                                 buffer ? buffer->layoutPos() : string());
734                                         if (res == Systemcall::KILLED) {
735                                                 frontend::Alert::warning(
736                                                         _("Converter killed"),
737                                                         bformat(_("The following converter was killed by the user.\n %1$s\n"),
738                                                                 from_utf8(command)));
739                                                 return KILLED;
740                                         }
741                                         if (buffer && !scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
742                                                 return FAILURE;
743                                 }
744                         }
745
746                         if (res) {
747                                 if (res == Systemcall::KILLED) {
748                                         Alert::information(_("Process Killed"),
749                                                 bformat(_("The conversion process was killed while running:\n%1$s"),
750                                                         wrapParas(from_utf8(command))));
751                                         return KILLED;
752                                 }
753                                 if (res == Systemcall::TIMEOUT) {
754                                         Alert::information(_("Process Timed Out"),
755                                                 bformat(_("The conversion process:\n%1$s\ntimed out before completing."),
756                                                         wrapParas(from_utf8(command))));
757                                         return KILLED;
758                                 }
759                                 if (conv.to() == "program") {
760                                         Alert::error(_("Build errors"),
761                                                 _("There were errors during the build process."));
762                                 } else {
763 // FIXME: this should go out of here. For example, here we cannot say if
764 // it is a document (.lyx) or something else. Same goes for elsewhere.
765                                         Alert::error(_("Cannot convert file"),
766                                                 bformat(_("An error occurred while running:\n%1$s"),
767                                                 wrapParas(from_utf8(command))));
768                                 }
769                                 return FAILURE;
770                         }
771                 }
772         }
773
774         Converter const & conv = converterlist_[edgepath.back()];
775         if (conv.To()->dummy())
776                 return SUCCESS;
777
778         if (!conv.result_dir().empty()) {
779                 // The converter has put the file(s) in a directory.
780                 // In this case we ignore the given to_file.
781                 if (from_base != to_base) {
782                         string const from = subst(conv.result_dir(),
783                                             token_base, from_base);
784                         string const to = subst(conv.result_dir(),
785                                           token_base, to_base);
786                         Mover const & mover = getMover(conv.from());
787                         if (!mover.rename(FileName(from), FileName(to))) {
788                                 Alert::error(_("Cannot convert file"),
789                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
790                                                 from_utf8(from), from_utf8(to)));
791                                 return FAILURE;
792                         }
793                 }
794                 return SUCCESS;
795         } else {
796                 if (conversionflags & try_cache)
797                         ConverterCache::get().add(orig_from, to_format, outfile);
798                 return move(conv.to(), outfile, to_file, conv.latex()) ? SUCCESS : FAILURE;
799         }
800 }
801
802
803 bool Converters::move(string const & fmt,
804                       FileName const & from, FileName const & to, bool copy)
805 {
806         if (from == to)
807                 return true;
808
809         bool no_errors = true;
810         string const path = onlyPath(from.absFileName());
811         string const base = onlyFileName(removeExtension(from.absFileName()));
812         string const to_base = removeExtension(to.absFileName());
813         string const to_extension = getExtension(to.absFileName());
814
815         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
816         for (auto const & f : files) {
817                 string const from2 = f.absFileName();
818                 string const file2 = onlyFileName(from2);
819                 if (prefixIs(file2, base)) {
820                         string const to2 = changeExtension(
821                                 to_base + file2.substr(base.length()),
822                                 to_extension);
823                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
824
825                         Mover const & mover = getMover(fmt);
826                         bool const moved = copy
827                                 ? mover.copy(f, FileName(to2))
828                                 : mover.rename(f, FileName(to2));
829                         if (!moved && no_errors) {
830                                 Alert::error(_("Cannot convert file"),
831                                         bformat(copy ?
832                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
833                                                 _("Could not move a temporary file from %1$s to %2$s."),
834                                                 from_utf8(from2), from_utf8(to2)));
835                                 no_errors = false;
836                         }
837                 }
838         }
839         return no_errors;
840 }
841
842
843 bool Converters::formatIsUsed(string const & format) const
844 {
845         for (auto const & cvt : converterlist_) {
846                 if (cvt.from() == format || cvt.to() == format)
847                         return true;
848         }
849         return false;
850 }
851
852
853 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
854                          FileName const & filename, ErrorList & errorList)
855 {
856         OutputParams runparams(nullptr);
857         runparams.flavor = Flavor::LaTeX;
858         LaTeX latex("", runparams, filename);
859         TeXErrors terr;
860         int const result = latex.scanLogFile(terr);
861
862         if (result & LaTeX::ERRORS)
863                 buffer.bufferErrors(terr, errorList);
864
865         return true;
866 }
867
868
869 Converters::RetVal Converters::runLaTeX(Buffer const & buffer, string const & command,
870                           OutputParams const & runparams, ErrorList & errorList)
871 {
872         buffer.setBusy(true);
873         buffer.message(_("Running LaTeX..."));
874
875         // do the LaTeX run(s)
876         string const name = buffer.latexName();
877         LaTeX latex(command, runparams, makeAbsPath(name),
878                     buffer.filePath(), buffer.layoutPos(),
879                     buffer.isClone(), buffer.freshStartRequired());
880         TeXErrors terr;
881         // The connection closes itself at the end of the scope when latex is
882         // destroyed. One cannot close (and destroy) buffer while the converter is
883         // running.
884         latex.message.connect([&buffer](docstring const & msg){
885                         buffer.message(msg);
886                 });
887         int const result = latex.run(terr);
888
889         if (result == Systemcall::KILLED || result == Systemcall::TIMEOUT) {
890                 Alert::error(_("Export canceled"),
891                         _("The export process was terminated by the user."));
892                 return KILLED;
893         }
894
895         if (result & LaTeX::ERRORS)
896                 buffer.bufferErrors(terr, errorList);
897
898         if ((result & LaTeX::UNDEF_CIT) || (result & LaTeX::UNDEF_UNKNOWN_REF)) {
899                 buffer.bufferRefs(terr, errorList);
900                 if (errorList.empty())
901                         errorList.push_back(ErrorItem(_("Undefined reference"),
902                                 _("Undefined references or citations were found during the build.\n"
903                                   "Please check the warnings in the LaTeX log (Document > LaTeX Log)."),
904                                 &buffer));
905         }
906
907         if (!errorList.empty()) {
908           // We will show the LaTeX Errors GUI later which contains
909           // specific error messages so it would be repetitive to give
910           // e.g. the "finished with an error" dialog in addition.
911         }
912         else if (result & LaTeX::NO_LOGFILE) {
913                 docstring const str =
914                         bformat(_("LaTeX did not run successfully. "
915                                                "Additionally, LyX could not locate "
916                                                "the LaTeX log %1$s."), from_utf8(name));
917                 Alert::error(_("LaTeX failed"), str);
918         } else if (result & LaTeX::NONZERO_ERROR) {
919                 docstring const str =
920                         bformat(_( "The external program\n%1$s\n"
921                               "finished with an error. "
922                               "It is recommended you fix the cause of the external "
923                               "program's error (check the logs). "), from_utf8(command));
924                 Alert::error(_("LaTeX failed"), str);
925         } else if (result & LaTeX::NO_OUTPUT) {
926                 Alert::warning(_("Output is empty"),
927                                _("No output file was generated."));
928         }
929
930         buffer.setBusy(false);
931
932         int const ERROR_MASK =
933                         LaTeX::NO_LOGFILE |
934                         LaTeX::ERRORS |
935                         LaTeX::UNDEF_CIT |
936                         LaTeX::UNDEF_UNKNOWN_REF |
937                         LaTeX::NO_OUTPUT;
938
939         return (result & ERROR_MASK) == 0 ? SUCCESS : FAILURE;
940 }
941
942
943
944 void Converters::buildGraph()
945 {
946         // clear graph's data structures
947         G_.init(theFormats().size());
948         // each of the converters knows how to convert one format to another
949         // so, for each of them, we create an arrow on the graph, going from
950         // the one to the other
951         for (auto const & cvt : converterlist_) {
952                 int const from = theFormats().getNumber(cvt.from());
953                 int const to   = theFormats().getNumber(cvt.to());
954                 LASSERT(from >= 0, continue);
955                 LASSERT(to >= 0, continue);
956                 G_.addEdge(from, to);
957         }
958 }
959
960
961 FormatList const Converters::intToFormat(vector<int> const & input)
962 {
963         FormatList result(input.size());
964
965         vector<int>::const_iterator it = input.begin();
966         vector<int>::const_iterator const end = input.end();
967         FormatList::iterator rit = result.begin();
968         for ( ; it != end; ++it, ++rit) {
969                 *rit = &theFormats().get(*it);
970         }
971         return result;
972 }
973
974
975 FormatList const Converters::getReachableTo(string const & target,
976                 bool const clear_visited)
977 {
978         vector<int> const & reachablesto =
979                 G_.getReachableTo(theFormats().getNumber(target), clear_visited);
980
981         return intToFormat(reachablesto);
982 }
983
984
985 FormatList const Converters::getReachable(string const & from,
986                 bool const only_viewable, bool const clear_visited,
987                 set<string> const & excludes)
988 {
989         set<int> excluded_numbers;
990
991         for (auto const & ex : excludes)
992                 excluded_numbers.insert(theFormats().getNumber(ex));
993
994         vector<int> const & reachables =
995                 G_.getReachable(theFormats().getNumber(from),
996                                 only_viewable,
997                                 clear_visited,
998                                 excluded_numbers);
999
1000         return intToFormat(reachables);
1001 }
1002
1003
1004 bool Converters::isReachable(string const & from, string const & to)
1005 {
1006         return G_.isReachable(theFormats().getNumber(from),
1007                               theFormats().getNumber(to));
1008 }
1009
1010
1011 Graph::EdgePath Converters::getPath(string const & from, string const & to)
1012 {
1013         return G_.getPath(theFormats().getNumber(from),
1014                           theFormats().getNumber(to));
1015 }
1016
1017
1018 FormatList Converters::importableFormats()
1019 {
1020         vector<string> l = loaders();
1021         FormatList result = getReachableTo(l[0], true);
1022         vector<string>::const_iterator it = l.begin() + 1;
1023         vector<string>::const_iterator en = l.end();
1024         for (; it != en; ++it) {
1025                 FormatList r = getReachableTo(*it, false);
1026                 result.insert(result.end(), r.begin(), r.end());
1027         }
1028         return result;
1029 }
1030
1031
1032 FormatList Converters::exportableFormats(bool only_viewable)
1033 {
1034         vector<string> s = savers();
1035         FormatList result = getReachable(s[0], only_viewable, true);
1036         vector<string>::const_iterator it = s.begin() + 1;
1037         vector<string>::const_iterator en = s.end();
1038         for (; it != en; ++it) {
1039                  FormatList r = getReachable(*it, only_viewable, false);
1040                 result.insert(result.end(), r.begin(), r.end());
1041         }
1042         return result;
1043 }
1044
1045
1046 vector<string> Converters::loaders() const
1047 {
1048         vector<string> v;
1049         v.push_back("lyx");
1050         v.push_back("text");
1051         v.push_back("textparagraph");
1052         return v;
1053 }
1054
1055
1056 vector<string> Converters::savers() const
1057 {
1058         vector<string> v;
1059         v.push_back("docbook");
1060         v.push_back("latex");
1061         v.push_back("literate");
1062         v.push_back("luatex");
1063         v.push_back("dviluatex");
1064         v.push_back("lyx");
1065         v.push_back("xhtml");
1066         v.push_back("pdflatex");
1067         v.push_back("platex");
1068         v.push_back("text");
1069         v.push_back("xetex");
1070         return v;
1071 }
1072
1073
1074 } // namespace lyx