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