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