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