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