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