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