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