]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
a2e5e9be4938d50760f818528af4a11c46d93fb6
[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 "Language.h"
23 #include "LaTeX.h"
24 #include "LyXRC.h"
25 #include "Mover.h"
26
27 #include "frontends/alert.h"
28
29 #include "support/debug.h"
30 #include "support/FileNameList.h"
31 #include "support/filetools.h"
32 #include "support/gettext.h"
33 #include "support/lassert.h"
34 #include "support/lstrings.h"
35 #include "support/os.h"
36 #include "support/Package.h"
37 #include "support/PathChanger.h"
38 #include "support/Systemcall.h"
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 namespace Alert = lyx::frontend::Alert;
46
47
48 namespace {
49
50 string const token_from("$$i");
51 string const token_base("$$b");
52 string const token_to("$$o");
53 string const token_path("$$p");
54 string const token_orig_path("$$r");
55 string const token_orig_from("$$f");
56 string const token_encoding("$$e");
57 string const token_latex_encoding("$$E");
58
59
60 string const add_options(string const & command, string const & options)
61 {
62         string head;
63         string const tail = split(command, head, ' ');
64         return head + ' ' + options + ' ' + tail;
65 }
66
67
68 string const dvipdfm_options(BufferParams const & bp)
69 {
70         string result;
71
72         if (bp.papersize != PAPER_CUSTOM) {
73                 string const paper_size = bp.paperSizeName(BufferParams::DVIPDFM);
74                 if (!paper_size.empty())
75                         result = "-p "+ paper_size;
76
77                 if (bp.orientation == ORIENTATION_LANDSCAPE)
78                         result += " -l";
79         }
80
81         return result;
82 }
83
84
85 class ConverterEqual {
86 public:
87         ConverterEqual(string const & from, string const & to)
88                 : from_(from), to_(to) {}
89         bool operator()(Converter const & c) const {
90                 return c.from() == from_ && c.to() == to_;
91         }
92 private:
93         string const from_;
94         string const to_;
95 };
96
97 } // namespace anon
98
99
100 Converter::Converter(string const & f, string const & t,
101                      string const & c, string const & l)
102         : from_(f), to_(t), command_(c), flags_(l),
103           From_(0), To_(0), latex_(false), xml_(false),
104           need_aux_(false), nice_(false), need_auth_(false)
105 {}
106
107
108 void Converter::readFlags()
109 {
110         string flag_list(flags_);
111         while (!flag_list.empty()) {
112                 string flag_name, flag_value;
113                 flag_list = split(flag_list, flag_value, ',');
114                 flag_value = split(flag_value, flag_name, '=');
115                 if (flag_name == "latex") {
116                         latex_ = true;
117                         latex_flavor_ = flag_value.empty() ?
118                                 "latex" : flag_value;
119                 } else if (flag_name == "xml")
120                         xml_ = true;
121                 else if (flag_name == "needaux")
122                         need_aux_ = true;
123                 else if (flag_name == "resultdir")
124                         result_dir_ = (flag_value.empty())
125                                 ? token_base : flag_value;
126                 else if (flag_name == "resultfile")
127                         result_file_ = flag_value;
128                 else if (flag_name == "parselog")
129                         parselog_ = flag_value;
130                 else if (flag_name == "nice")
131                         nice_ = true;
132                 else if (flag_name == "needauth")
133                         need_auth_ = true;
134         }
135         if (!result_dir_.empty() && result_file_.empty())
136                 result_file_ = "index." + formats.extension(to_);
137         //if (!contains(command, token_from))
138         //      latex = true;
139 }
140
141
142 Converter const * Converters::getConverter(string const & from,
143                                             string const & to) const
144 {
145         ConverterList::const_iterator const cit =
146                 find_if(converterlist_.begin(), converterlist_.end(),
147                         ConverterEqual(from, to));
148         if (cit != converterlist_.end())
149                 return &(*cit);
150         else
151                 return 0;
152 }
153
154
155 int Converters::getNumber(string const & from, string const & to) const
156 {
157         ConverterList::const_iterator const cit =
158                 find_if(converterlist_.begin(), converterlist_.end(),
159                         ConverterEqual(from, to));
160         if (cit != converterlist_.end())
161                 return distance(converterlist_.begin(), cit);
162         else
163                 return -1;
164 }
165
166
167 void Converters::add(string const & from, string const & to,
168                      string const & command, string const & flags)
169 {
170         formats.add(from);
171         formats.add(to);
172         ConverterList::iterator it = find_if(converterlist_.begin(),
173                                              converterlist_.end(),
174                                              ConverterEqual(from , to));
175
176         Converter converter(from, to, command, flags);
177         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
178                 converter = *it;
179                 converter.setCommand(command);
180                 converter.setFlags(flags);
181         }
182         converter.readFlags();
183
184         // The latex_command is used to update the .aux file when running
185         // a converter that uses it.
186         if (converter.latex()) {
187                 if (latex_command_.empty() ||
188                     converter.latex_flavor() == "latex")
189                         latex_command_ = subst(command, token_from, "");
190                 if (dvilualatex_command_.empty() ||
191                     converter.latex_flavor() == "dvilualatex")
192                         dvilualatex_command_ = subst(command, token_from, "");
193                 if (lualatex_command_.empty() ||
194                     converter.latex_flavor() == "lualatex")
195                         lualatex_command_ = subst(command, token_from, "");
196                 if (pdflatex_command_.empty() ||
197                     converter.latex_flavor() == "pdflatex")
198                         pdflatex_command_ = subst(command, token_from, "");
199                 if (xelatex_command_.empty() ||
200                     converter.latex_flavor() == "xelatex")
201                         xelatex_command_ = subst(command, token_from, "");
202         }
203
204         if (it == converterlist_.end()) {
205                 converterlist_.push_back(converter);
206         } else {
207                 converter.setFrom(it->From());
208                 converter.setTo(it->To());
209                 *it = converter;
210         }
211 }
212
213
214 void Converters::erase(string const & from, string const & to)
215 {
216         ConverterList::iterator const it =
217                 find_if(converterlist_.begin(),
218                         converterlist_.end(),
219                         ConverterEqual(from, to));
220         if (it != converterlist_.end())
221                 converterlist_.erase(it);
222 }
223
224
225 // This method updates the pointers From and To in all the converters.
226 // The code is not very efficient, but it doesn't matter as the number
227 // of formats and converters is small.
228 // Furthermore, this method is called only on startup, or after
229 // adding/deleting a format in FormPreferences (the latter calls can be
230 // eliminated if the formats in the Formats class are stored using a map or
231 // a list (instead of a vector), but this will cause other problems).
232 void Converters::update(Formats const & formats)
233 {
234         ConverterList::iterator it = converterlist_.begin();
235         ConverterList::iterator end = converterlist_.end();
236         for (; it != end; ++it) {
237                 it->setFrom(formats.getFormat(it->from()));
238                 it->setTo(formats.getFormat(it->to()));
239         }
240 }
241
242
243 // This method updates the pointers From and To in the last converter.
244 // It is called when adding a new converter in FormPreferences
245 void Converters::updateLast(Formats const & formats)
246 {
247         if (converterlist_.begin() != converterlist_.end()) {
248                 ConverterList::iterator it = converterlist_.end() - 1;
249                 it->setFrom(formats.getFormat(it->from()));
250                 it->setTo(formats.getFormat(it->to()));
251         }
252 }
253
254
255 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path,
256                                            Buffer const * buffer)
257 {
258         for (Graph::EdgePath::const_iterator cit = path.begin();
259              cit != path.end(); ++cit) {
260                 Converter const & conv = converterlist_[*cit];
261                 if (conv.latex()) {
262                         if (conv.latex_flavor() == "latex")
263                                 return OutputParams::LATEX;
264                         if (conv.latex_flavor() == "xelatex")
265                                 return OutputParams::XETEX;
266                         if (conv.latex_flavor() == "lualatex")
267                                 return OutputParams::LUATEX;
268                         if (conv.latex_flavor() == "dvilualatex")
269                                 return OutputParams::DVILUATEX;
270                         if (conv.latex_flavor() == "pdflatex")
271                                 return OutputParams::PDFLATEX;
272                 }
273                 if (conv.xml())
274                         return OutputParams::XML;
275         }
276         return buffer ? buffer->params().getOutputFlavor()
277                       : OutputParams::LATEX;
278 }
279
280
281 bool Converters::checkAuth(Converter const & conv, string const & doc_fname)
282 {
283         if (!conv.need_auth())
284                 return true;
285         if (lyxrc.use_converter_needauth_forbidden) {
286                 frontend::Alert::warning(
287                         _("Potentially harmful external converters disabled"),
288                         _("Requested operation needs use of a potentially harmful external converter program,"
289                           "which is forbidden by default.\nThese converters are tagged by the 'needauth' option. "
290                           "In order to unlock execution of these converters,\nplease, go to "
291                           "Preferences->File Handling->Converters and uncheck "
292                           "Security->Forbid needauth converters."), true);
293                 return false;
294         }
295         if (!lyxrc.use_converter_needauth)
296                 return true;
297         static const docstring security_title = _("Launch of external converter needs user authorization");
298         static const char security_warning[] = "LyX is about to run converter '%1$s' which is launching an external program "
299                 "that normally acts as a picture/format converter. However, this external program is known to be able to "
300                 "execute arbitrary actions on the system on behalf of the user, including dangerous ones such as deleting "
301                 "files, if instructed to do so by a maliciously crafted .lyx document.\n\nWould you like to run the converter?\n\n"
302                 "ANSWER RUN ONLY IF YOU TRUST THE ORIGIN/SENDER OF THE LYX DOCUMENT!";
303         int choice;
304         if (!doc_fname.empty()) {
305                 LYXERR(Debug::FILES, "looking up: " << doc_fname);
306                 if (auth_files_.find(doc_fname) == auth_files_.end()) {
307                         choice = frontend::Alert::prompt(security_title,
308                                 bformat(_(security_warning), from_utf8(conv.command())),
309                                 0, 0, _("Do &NOT run"), _("&Run"), _("&Always run for this document"));
310                         if (choice == 2)
311                                 auth_files_.insert(doc_fname);
312                 } else {
313                         choice = 1;
314                 }
315         } else {
316                 choice = frontend::Alert::prompt(security_title,
317                         bformat(_(security_warning), from_utf8(conv.command())),
318                         0, 0, _("Do &NOT run"), _("&Run"));
319         }
320         return choice != 0;
321 }
322
323
324 bool Converters::convert(Buffer const * buffer,
325                          FileName const & from_file, FileName const & to_file,
326                          FileName const & orig_from,
327                          string const & from_format, string const & to_format,
328                          ErrorList & errorList, int conversionflags)
329 {
330         if (from_format == to_format)
331                 return move(from_format, from_file, to_file, false);
332
333         if ((conversionflags & try_cache) &&
334             ConverterCache::get().inCache(orig_from, to_format))
335                 return ConverterCache::get().copy(orig_from, to_format, to_file);
336
337         Graph::EdgePath edgepath = getPath(from_format, to_format);
338         if (edgepath.empty()) {
339                 if (conversionflags & try_default) {
340                         // if no special converter defined, then we take the
341                         // default one from ImageMagic.
342                         string const from_ext = from_format.empty() ?
343                                 getExtension(from_file.absFileName()) :
344                                 formats.extension(from_format);
345                         string const to_ext = formats.extension(to_format);
346                         string const command =
347                                 os::python() + ' ' +
348                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
349                                 ' ' + from_ext + ' ' +
350                                 quoteName(from_file.toFilesystemEncoding()) +
351                                 ' ' + to_ext + ' ' +
352                                 quoteName(to_file.toFilesystemEncoding());
353                         LYXERR(Debug::FILES, "No converter defined! "
354                                    "I use convertDefault.py:\n\t" << command);
355                         Systemcall one;
356                         one.startscript(Systemcall::Wait, command,
357                                         buffer ? buffer->filePath() : string(),
358                                         buffer ? buffer->layoutPos() : string());
359                         if (to_file.isReadableFile()) {
360                                 if (conversionflags & try_cache)
361                                         ConverterCache::get().add(orig_from,
362                                                         to_format, to_file);
363                                 return true;
364                         }
365                 }
366
367                 // only warn once per session and per file type
368                 static std::map<string, string> warned;
369                 if (warned.find(from_format) != warned.end() && warned.find(from_format)->second == to_format) {
370                         return false;
371                 }
372                 warned.insert(make_pair(from_format, to_format));
373
374                 Alert::error(_("Cannot convert file"),
375                              bformat(_("No information for converting %1$s "
376                                                     "format files to %2$s.\n"
377                                                     "Define a converter in the preferences."),
378                                                         from_ascii(from_format), from_ascii(to_format)));
379                 return false;
380         }
381
382         // buffer is only invalid for importing, and then runparams is not
383         // used anyway.
384         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
385         runparams.flavor = getFlavor(edgepath, buffer);
386
387         if (buffer) {
388                 runparams.use_japanese =
389                         buffer->params().bufferFormat() == "latex"
390                         && buffer->params().encoding().package() == Encoding::japanese;
391                 runparams.use_indices = buffer->params().use_indices;
392                 runparams.bibtex_command = (buffer->params().bibtex_command == "default") ?
393                         string() : buffer->params().bibtex_command;
394                 runparams.index_command = (buffer->params().index_command == "default") ?
395                         string() : buffer->params().index_command;
396                 runparams.document_language = buffer->params().language->babel();
397         }
398
399         // Some converters (e.g. lilypond) can only output files to the
400         // current directory, so we need to change the current directory.
401         // This has the added benefit that all other files that may be
402         // generated by the converter are deleted when LyX closes and do not
403         // clutter the real working directory.
404         // FIXME: This does not work if path is an UNC path on windows
405         //        (bug 6127).
406         string const path(onlyPath(from_file.absFileName()));
407         // Prevent the compiler from optimizing away p
408         FileName pp(path);
409         PathChanger p(pp);
410
411         // empty the error list before any new conversion takes place.
412         errorList.clear();
413
414         bool run_latex = false;
415         string from_base = changeExtension(from_file.absFileName(), "");
416         string to_base = changeExtension(to_file.absFileName(), "");
417         FileName infile;
418         FileName outfile = from_file;
419         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
420              cit != edgepath.end(); ++cit) {
421                 Converter const & conv = converterlist_[*cit];
422                 bool dummy = conv.To()->dummy() && conv.to() != "program";
423                 if (!dummy) {
424                         LYXERR(Debug::FILES, "Converting from  "
425                                << conv.from() << " to " << conv.to());
426                 }
427                 infile = outfile;
428                 outfile = FileName(conv.result_file().empty()
429                         ? changeExtension(from_file.absFileName(), conv.To()->extension())
430                         : addName(subst(conv.result_dir(),
431                                         token_base, from_base),
432                                   subst(conv.result_file(),
433                                         token_base, onlyFileName(from_base))));
434
435                 // if input and output files are equal, we use a
436                 // temporary file as intermediary (JMarc)
437                 FileName real_outfile;
438                 if (!conv.result_file().empty())
439                         real_outfile = FileName(changeExtension(from_file.absFileName(),
440                                 conv.To()->extension()));
441                 if (outfile == infile) {
442                         real_outfile = infile;
443                         // when importing, a buffer does not necessarily exist
444                         if (buffer)
445                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
446                         else
447                                 outfile = FileName(addName(package().temp_dir().absFileName(),
448                                                    "tmpfile.out"));
449                 }
450
451                 if (!checkAuth(conv, buffer->absFileName()))
452                         return false;
453
454                 if (conv.latex()) {
455                         run_latex = true;
456                         string command = conv.command();
457                         command = subst(command, token_from, "");
458                         command = subst(command, token_latex_encoding, buffer ?
459                                 buffer->params().encoding().latexName() : string());
460                         LYXERR(Debug::FILES, "Running " << command);
461                         if (!runLaTeX(*buffer, command, runparams, errorList))
462                                 return false;
463                 } else {
464                         if (conv.need_aux() && !run_latex) {
465                                 string command;
466                                 switch (runparams.flavor) {
467                                 case OutputParams::DVILUATEX:
468                                         command = dvilualatex_command_;
469                                         break;
470                                 case OutputParams::LUATEX:
471                                         command = lualatex_command_;
472                                         break;
473                                 case OutputParams::PDFLATEX:
474                                         command = pdflatex_command_;
475                                         break;
476                                 case OutputParams::XETEX:
477                                         command = xelatex_command_;
478                                         break;
479                                 default:
480                                         command = latex_command_;
481                                         break;
482                                 }
483                                 if (!command.empty()) {
484                                         LYXERR(Debug::FILES, "Running "
485                                                 << command
486                                                 << " to update aux file");
487                                         if (!runLaTeX(*buffer, command,
488                                                       runparams, errorList))
489                                                 return false;
490                                 }
491                         }
492
493                         // FIXME UNICODE
494                         string const infile2 =
495                                 to_utf8(makeRelPath(from_utf8(infile.absFileName()), from_utf8(path)));
496                         string const outfile2 =
497                                 to_utf8(makeRelPath(from_utf8(outfile.absFileName()), from_utf8(path)));
498
499                         string command = conv.command();
500                         command = subst(command, token_from, quoteName(infile2));
501                         command = subst(command, token_base, quoteName(from_base));
502                         command = subst(command, token_to, quoteName(outfile2));
503                         command = subst(command, token_path, quoteName(onlyPath(infile.absFileName())));
504                         command = subst(command, token_orig_path, quoteName(onlyPath(orig_from.absFileName())));
505                         command = subst(command, token_orig_from, quoteName(onlyFileName(orig_from.absFileName())));
506                         command = subst(command, token_encoding, buffer ? buffer->params().encoding().iconvName() : string());
507
508                         if (!conv.parselog().empty())
509                                 command += " 2> " + quoteName(infile2 + ".out");
510
511                         // it is not actually not necessary to test for buffer here,
512                         // but it pleases coverity.
513                         if (buffer && conv.from() == "dvi" && conv.to() == "ps")
514                                 command = add_options(command,
515                                                       buffer->params().dvips_options());
516                         else if (buffer && conv.from() == "dvi" && prefixIs(conv.to(), "pdf"))
517                                 command = add_options(command,
518                                                       dvipdfm_options(buffer->params()));
519
520                         LYXERR(Debug::FILES, "Calling " << command);
521                         if (buffer)
522                                 buffer->message(_("Executing command: ")
523                                 + from_utf8(command));
524
525                         Systemcall one;
526                         int res;
527                         if (dummy) {
528                                 res = one.startscript(Systemcall::DontWait,
529                                         to_filesystem8bit(from_utf8(command)),
530                                         buffer ? buffer->filePath() : string(),
531                                         buffer ? buffer->layoutPos() : string());
532                                 // We're not waiting for the result, so we can't do anything
533                                 // else here.
534                         } else {
535                                 res = one.startscript(Systemcall::Wait,
536                                                 to_filesystem8bit(from_utf8(command)),
537                                                 buffer ? buffer->filePath()
538                                                        : string(),
539                                                 buffer ? buffer->layoutPos()
540                                                        : string());
541                                 if (!real_outfile.empty()) {
542                                         Mover const & mover = getMover(conv.to());
543                                         if (!mover.rename(outfile, real_outfile))
544                                                 res = -1;
545                                         else
546                                                 LYXERR(Debug::FILES, "renaming file " << outfile
547                                                         << " to " << real_outfile);
548                                         // Finally, don't forget to tell any future
549                                         // converters to use the renamed file...
550                                         outfile = real_outfile;
551                                 }
552
553                                 if (!conv.parselog().empty()) {
554                                         string const logfile =  infile2 + ".log";
555                                         string const command2 = conv.parselog() +
556                                                 " < " + quoteName(infile2 + ".out") +
557                                                 " > " + quoteName(logfile);
558                                         one.startscript(Systemcall::Wait,
559                                                 to_filesystem8bit(from_utf8(command2)),
560                                                 buffer->filePath(),
561                                                 buffer->layoutPos());
562                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
563                                                 return false;
564                                 }
565                         }
566
567                         if (res) {
568                                 if (conv.to() == "program") {
569                                         Alert::error(_("Build errors"),
570                                                 _("There were errors during the build process."));
571                                 } else {
572 // FIXME: this should go out of here. For example, here we cannot say if
573 // it is a document (.lyx) or something else. Same goes for elsewhere.
574                                         Alert::error(_("Cannot convert file"),
575                                                 bformat(_("An error occurred while running:\n%1$s"),
576                                                 wrapParas(from_utf8(command))));
577                                 }
578                                 return false;
579                         }
580                 }
581         }
582
583         Converter const & conv = converterlist_[edgepath.back()];
584         if (conv.To()->dummy())
585                 return true;
586
587         if (!conv.result_dir().empty()) {
588                 // The converter has put the file(s) in a directory.
589                 // In this case we ignore the given to_file.
590                 if (from_base != to_base) {
591                         string const from = subst(conv.result_dir(),
592                                             token_base, from_base);
593                         string const to = subst(conv.result_dir(),
594                                           token_base, to_base);
595                         Mover const & mover = getMover(conv.from());
596                         if (!mover.rename(FileName(from), FileName(to))) {
597                                 Alert::error(_("Cannot convert file"),
598                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
599                                                 from_utf8(from), from_utf8(to)));
600                                 return false;
601                         }
602                 }
603                 return true;
604         } else {
605                 if (conversionflags & try_cache)
606                         ConverterCache::get().add(orig_from, to_format, outfile);
607                 return move(conv.to(), outfile, to_file, conv.latex());
608         }
609 }
610
611
612 bool Converters::move(string const & fmt,
613                       FileName const & from, FileName const & to, bool copy)
614 {
615         if (from == to)
616                 return true;
617
618         bool no_errors = true;
619         string const path = onlyPath(from.absFileName());
620         string const base = onlyFileName(removeExtension(from.absFileName()));
621         string const to_base = removeExtension(to.absFileName());
622         string const to_extension = getExtension(to.absFileName());
623
624         support::FileNameList const files = FileName(path).dirList(getExtension(from.absFileName()));
625         for (support::FileNameList::const_iterator it = files.begin();
626              it != files.end(); ++it) {
627                 string const from2 = it->absFileName();
628                 string const file2 = onlyFileName(from2);
629                 if (prefixIs(file2, base)) {
630                         string const to2 = changeExtension(
631                                 to_base + file2.substr(base.length()),
632                                 to_extension);
633                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
634
635                         Mover const & mover = getMover(fmt);
636                         bool const moved = copy
637                                 ? mover.copy(*it, FileName(to2))
638                                 : mover.rename(*it, FileName(to2));
639                         if (!moved && no_errors) {
640                                 Alert::error(_("Cannot convert file"),
641                                         bformat(copy ?
642                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
643                                                 _("Could not move a temporary file from %1$s to %2$s."),
644                                                 from_utf8(from2), from_utf8(to2)));
645                                 no_errors = false;
646                         }
647                 }
648         }
649         return no_errors;
650 }
651
652
653 bool Converters::formatIsUsed(string const & format)
654 {
655         ConverterList::const_iterator cit = converterlist_.begin();
656         ConverterList::const_iterator end = converterlist_.end();
657         for (; cit != end; ++cit) {
658                 if (cit->from() == format || cit->to() == format)
659                         return true;
660         }
661         return false;
662 }
663
664
665 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
666                          FileName const & filename, ErrorList & errorList)
667 {
668         OutputParams runparams(0);
669         runparams.flavor = OutputParams::LATEX;
670         LaTeX latex("", runparams, filename);
671         TeXErrors terr;
672         int const result = latex.scanLogFile(terr);
673
674         if (result & LaTeX::ERRORS)
675                 buffer.bufferErrors(terr, errorList);
676
677         return true;
678 }
679
680
681 namespace {
682
683 class ShowMessage
684         : public boost::signals2::trackable {
685 public:
686         ShowMessage(Buffer const & b) : buffer_(b) {}
687         void operator()(docstring const & msg) const { buffer_.message(msg); }
688 private:
689         Buffer const & buffer_;
690 };
691
692 }
693
694
695 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
696                           OutputParams const & runparams, ErrorList & errorList)
697 {
698         buffer.setBusy(true);
699         buffer.message(_("Running LaTeX..."));
700
701         // do the LaTeX run(s)
702         string const name = buffer.latexName();
703         LaTeX latex(command, runparams, FileName(makeAbsPath(name)),
704                     buffer.filePath(), buffer.layoutPos(),
705                     buffer.lastPreviewError());
706         TeXErrors terr;
707         ShowMessage show(buffer);
708         latex.message.connect(show);
709         int const result = latex.run(terr);
710
711         if (result & LaTeX::ERRORS)
712                 buffer.bufferErrors(terr, errorList);
713
714         if (!errorList.empty()) {
715           // We will show the LaTeX Errors GUI later which contains
716           // specific error messages so it would be repetitive to give
717           // e.g. the "finished with an error" dialog in addition.
718         }
719         else if (result & LaTeX::NO_LOGFILE) {
720                 docstring const str =
721                         bformat(_("LaTeX did not run successfully. "
722                                                "Additionally, LyX could not locate "
723                                                "the LaTeX log %1$s."), from_utf8(name));
724                 Alert::error(_("LaTeX failed"), str);
725         } else if (result & LaTeX::NONZERO_ERROR) {
726                 docstring const str =
727                         bformat(_( "The external program\n%1$s\n"
728                               "finished with an error. "
729                               "It is recommended you fix the cause of the external "
730                               "program's error (check the logs). "), from_utf8(command));
731                 Alert::error(_("LaTeX failed"), str);
732         } else if (result & LaTeX::NO_OUTPUT) {
733                 Alert::warning(_("Output is empty"),
734                                _("No output file was generated."));
735         }
736
737
738         buffer.setBusy(false);
739
740         int const ERROR_MASK =
741                         LaTeX::NO_LOGFILE |
742                         LaTeX::ERRORS |
743                         LaTeX::NO_OUTPUT;
744
745         return (result & ERROR_MASK) == 0;
746 }
747
748
749
750 void Converters::buildGraph()
751 {
752         // clear graph's data structures
753         G_.init(formats.size());
754         // each of the converters knows how to convert one format to another
755         // so, for each of them, we create an arrow on the graph, going from
756         // the one to the other
757         ConverterList::iterator it = converterlist_.begin();
758         ConverterList::iterator const end = converterlist_.end();
759         for (; it != end ; ++it) {
760                 int const from = formats.getNumber(it->from());
761                 int const to   = formats.getNumber(it->to());
762                 LASSERT(from >= 0, continue);
763                 LASSERT(to >= 0, continue);
764                 G_.addEdge(from, to);
765         }
766 }
767
768
769 FormatList const Converters::intToFormat(vector<int> const & input)
770 {
771         FormatList result(input.size());
772
773         vector<int>::const_iterator it = input.begin();
774         vector<int>::const_iterator const end = input.end();
775         FormatList::iterator rit = result.begin();
776         for ( ; it != end; ++it, ++rit) {
777                 *rit = &formats.get(*it);
778         }
779         return result;
780 }
781
782
783 FormatList const Converters::getReachableTo(string const & target, 
784                 bool const clear_visited)
785 {
786         vector<int> const & reachablesto =
787                 G_.getReachableTo(formats.getNumber(target), clear_visited);
788
789         return intToFormat(reachablesto);
790 }
791
792
793 FormatList const Converters::getReachable(string const & from, 
794                 bool const only_viewable, bool const clear_visited, 
795                 set<string> const & excludes)
796 {
797         set<int> excluded_numbers;
798
799         set<string>::const_iterator sit = excludes.begin();
800         set<string>::const_iterator const end = excludes.end();
801         for (; sit != end; ++sit)
802                 excluded_numbers.insert(formats.getNumber(*sit));
803
804         vector<int> const & reachables =
805                 G_.getReachable(formats.getNumber(from),
806                                 only_viewable,
807                                 clear_visited,
808                                 excluded_numbers);
809
810         return intToFormat(reachables);
811 }
812
813
814 bool Converters::isReachable(string const & from, string const & to)
815 {
816         return G_.isReachable(formats.getNumber(from),
817                               formats.getNumber(to));
818 }
819
820
821 Graph::EdgePath Converters::getPath(string const & from, string const & to)
822 {
823         return G_.getPath(formats.getNumber(from),
824                           formats.getNumber(to));
825 }
826
827
828 FormatList Converters::importableFormats()
829 {
830         vector<string> l = loaders();
831         FormatList result = getReachableTo(l[0], true);
832         vector<string>::const_iterator it = l.begin() + 1;
833         vector<string>::const_iterator en = l.end();
834         for (; it != en; ++it) {
835                 FormatList r = getReachableTo(*it, false);
836                 result.insert(result.end(), r.begin(), r.end());
837         }
838         return result;
839 }
840
841
842 FormatList Converters::exportableFormats(bool only_viewable)
843 {
844         vector<string> s = savers();
845         FormatList result = getReachable(s[0], only_viewable, true);
846         vector<string>::const_iterator it = s.begin() + 1;
847         vector<string>::const_iterator en = s.end();
848         for (; it != en; ++it) {
849                  FormatList r = getReachable(*it, only_viewable, false);
850                 result.insert(result.end(), r.begin(), r.end());
851         }
852         return result;
853 }
854
855
856 vector<string> Converters::loaders() const
857 {
858         vector<string> v;
859         v.push_back("lyx");
860         v.push_back("text");
861         v.push_back("textparagraph");
862         return v;
863 }
864
865
866 vector<string> Converters::savers() const
867 {
868         vector<string> v;
869         v.push_back("docbook");
870         v.push_back("latex");
871         v.push_back("literate");
872         v.push_back("luatex");
873         v.push_back("dviluatex");
874         v.push_back("lyx");
875         v.push_back("xhtml");
876         v.push_back("pdflatex");
877         v.push_back("platex");
878         v.push_back("text");
879         v.push_back("xetex");
880         return v;
881 }
882
883
884 } // namespace lyx