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