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