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