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