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