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