]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
a943857341cbda131d25edff70d4aaa4afb0a0de
[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 "debug.h"
20 #include "ErrorList.h"
21 #include "Format.h"
22 #include "gettext.h"
23 #include "Language.h"
24 #include "LaTeX.h"
25 #include "Mover.h"
26
27 #include "frontends/alert.h"
28
29 #include "support/filetools.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::dirList;
51 using support::FileName;
52 using support::getExtension;
53 using support::libFileSearch;
54 using support::libScriptSearch;
55 using support::makeAbsPath;
56 using support::makeRelPath;
57 using support::onlyFilename;
58 using support::onlyPath;
59 using support::package;
60 using support::prefixIs;
61 using support::quoteName;
62 using support::removeExtension;
63 using support::split;
64 using support::subst;
65 using support::Systemcall;
66
67 namespace Alert = lyx::frontend::Alert;
68
69
70 namespace {
71
72 string const token_from("$$i");
73 string const token_base("$$b");
74 string const token_to("$$o");
75 string const token_path("$$p");
76
77
78
79 string const add_options(string const & command, string const & options)
80 {
81         string head;
82         string const tail = split(command, head, ' ');
83         return head + ' ' + options + ' ' + tail;
84 }
85
86
87 string const dvipdfm_options(BufferParams const & bp)
88 {
89         string result;
90
91         if (bp.papersize != PAPER_CUSTOM) {
92                 string const paper_size = bp.paperSizeName();
93                 if (paper_size != "b5" && paper_size != "foolscap")
94                         result = "-p "+ paper_size;
95
96                 if (bp.orientation == ORIENTATION_LANDSCAPE)
97                         result += " -l";
98         }
99
100         return result;
101 }
102
103
104 class ConverterEqual {
105 public:
106         ConverterEqual(string const & from, string const & to)
107                 : from_(from), to_(to) {}
108         bool operator()(Converter const & c) const {
109                 return c.from == from_ && c.to == to_;
110         }
111 private:
112         string const from_;
113         string const to_;
114 };
115
116 } // namespace anon
117
118
119 Converter::Converter(string const & f, string const & t,
120                      string const & c, string const & l)
121         : from(f), to(t), command(c), flags(l),
122           From(0), To(0), latex(false), xml(false),
123           need_aux(false)
124 {}
125
126
127 void Converter::readFlags()
128 {
129         string flag_list(flags);
130         while (!flag_list.empty()) {
131                 string flag_name, flag_value;
132                 flag_list = split(flag_list, flag_value, ',');
133                 flag_value = split(flag_value, flag_name, '=');
134                 if (flag_name == "latex")
135                         latex = true;
136                 else if (flag_name == "xml")
137                         xml = 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, "No converter defined! "
320                                    "I use convertDefault.py:\n\t" << command);
321                         Systemcall one;
322                         one.startscript(Systemcall::Wait, command);
323                         if (to_file.isFileReadable()) {
324                                 if (conversionflags & try_cache)
325                                         ConverterCache::get().add(orig_from,
326                                                         to_format, to_file);
327                                 return true;
328                         }
329                 }
330                 Alert::error(_("Cannot convert file"),
331                              bformat(_("No information for converting %1$s "
332                                                     "format files to %2$s.\n"
333                                                     "Define a converter in the preferences."),
334                                                         from_ascii(from_format), from_ascii(to_format)));
335                 return false;
336         }
337
338         // buffer is only invalid for importing, and then runparams is not
339         // used anyway.
340         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
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 const path(onlyPath(from_file.absFilename()));
349         // Prevent the compiler from optimizing away p
350         FileName pp(path);
351         support::PathChanger p(pp);
352
353         // empty the error list before any new conversion takes place.
354         errorList.clear();
355
356         bool run_latex = false;
357         string from_base = changeExtension(from_file.absFilename(), "");
358         string to_base = changeExtension(to_file.absFilename(), "");
359         FileName infile;
360         FileName outfile = from_file;
361         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
362              cit != edgepath.end(); ++cit) {
363                 Converter const & conv = converterlist_[*cit];
364                 bool dummy = conv.To->dummy() && conv.to != "program";
365                 if (!dummy) {
366                         LYXERR(Debug::FILES, "Converting from  "
367                                << conv.from << " to " << conv.to);
368                 }
369                 infile = outfile;
370                 outfile = FileName(conv.result_dir.empty()
371                         ? changeExtension(from_file.absFilename(), conv.To->extension())
372                         : addName(subst(conv.result_dir,
373                                         token_base, from_base),
374                                   subst(conv.result_file,
375                                         token_base, onlyFilename(from_base))));
376
377                 // if input and output files are equal, we use a
378                 // temporary file as intermediary (JMarc)
379                 FileName real_outfile;
380                 if (outfile == infile) {
381                         real_outfile = infile;
382                         // when importing, a buffer does not necessarily exist
383                         if (buffer)
384                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
385                         else
386                                 outfile = FileName(addName(package().temp_dir().absFilename(),
387                                                    "tmpfile.out"));
388                 }
389
390                 if (conv.latex) {
391                         run_latex = true;
392                         string const command = subst(conv.command, token_from, "");
393                         LYXERR(Debug::FILES, "Running " << command);
394                         if (!runLaTeX(*buffer, command, runparams, errorList))
395                                 return false;
396                 } else {
397                         if (conv.need_aux && !run_latex
398                             && !latex_command_.empty()) {
399                                 LYXERR(Debug::FILES, "Running " << latex_command_
400                                         << " to update aux file");
401                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
402                         }
403
404                         // FIXME UNICODE
405                         string const infile2 = 
406                                 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
407                         string const outfile2 = 
408                                 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
409
410                         string command = conv.command;
411                         command = subst(command, token_from, quoteName(infile2));
412                         command = subst(command, token_base, quoteName(from_base));
413                         command = subst(command, token_to, quoteName(outfile2));
414                         command = libScriptSearch(command);
415
416                         if (!conv.parselog.empty())
417                                 command += " 2> " + quoteName(infile2 + ".out");
418
419                         if (conv.from == "dvi" && conv.to == "ps")
420                                 command = add_options(command,
421                                                       buffer->params().dvips_options());
422                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
423                                 command = add_options(command,
424                                                       dvipdfm_options(buffer->params()));
425
426                         LYXERR(Debug::FILES, "Calling " << command);
427                         if (buffer)
428                                 buffer->message(_("Executing command: ")
429                                 + from_utf8(command));
430
431                         Systemcall one;
432                         int res;
433                         if (dummy) {
434                                 res = one.startscript(Systemcall::DontWait,
435                                         to_filesystem8bit(from_utf8(command)));
436                                 // We're not waiting for the result, so we can't do anything
437                                 // else here.
438                         } else {
439                                 res = one.startscript(Systemcall::Wait,
440                                                 to_filesystem8bit(from_utf8(command)));
441                                 if (!real_outfile.empty()) {
442                                         Mover const & mover = getMover(conv.to);
443                                         if (!mover.rename(outfile, real_outfile))
444                                                 res = -1;
445                                         else
446                                                 LYXERR(Debug::FILES, "renaming file " << outfile
447                                                         << " to " << real_outfile);
448                                         // Finally, don't forget to tell any future
449                                         // converters to use the renamed file...
450                                         outfile = real_outfile;
451                                 }
452   
453                                 if (!conv.parselog.empty()) {
454                                         string const logfile =  infile2 + ".log";
455                                         string const script = libScriptSearch(conv.parselog);
456                                         string const command2 = script +
457                                                 " < " + quoteName(infile2 + ".out") +
458                                                 " > " + quoteName(logfile);
459                                         one.startscript(Systemcall::Wait,
460                                                 to_filesystem8bit(from_utf8(command2)));
461                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
462                                                 return false;
463                                 }
464                         }
465
466                         if (res) {
467                                 if (conv.to == "program") {
468                                         Alert::error(_("Build errors"),
469                                                 _("There were errors during the build process."));
470                                 } else {
471 // FIXME: this should go out of here. For example, here we cannot say if
472 // it is a document (.lyx) or something else. Same goes for elsewhere.
473                                         Alert::error(_("Cannot convert file"),
474                                                 bformat(_("An error occurred whilst running %1$s"),
475                                                 from_utf8(command.substr(0, 50))));
476                                 }
477                                 return false;
478                         }
479                 }
480         }
481
482         Converter const & conv = converterlist_[edgepath.back()];
483         if (conv.To->dummy())
484                 return true;
485
486         if (!conv.result_dir.empty()) {
487                 // The converter has put the file(s) in a directory.
488                 // In this case we ignore the given to_file.
489                 if (from_base != to_base) {
490                         string const from = subst(conv.result_dir,
491                                             token_base, from_base);
492                         string const to = subst(conv.result_dir,
493                                           token_base, to_base);
494                         Mover const & mover = getMover(conv.from);
495                         if (!mover.rename(FileName(from), FileName(to))) {
496                                 Alert::error(_("Cannot convert file"),
497                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
498                                                 from_utf8(from), from_utf8(to)));
499                                 return false;
500                         }
501                 }
502                 return true;
503         } else {
504                 if (conversionflags & try_cache)
505                         ConverterCache::get().add(orig_from, to_format, outfile);
506                 return move(conv.to, outfile, to_file, conv.latex);
507         }
508 }
509
510
511 bool Converters::move(string const & fmt,
512                       FileName const & from, FileName const & to, bool copy)
513 {
514         if (from == to)
515                 return true;
516
517         bool no_errors = true;
518         string const path = onlyPath(from.absFilename());
519         string const base = onlyFilename(removeExtension(from.absFilename()));
520         string const to_base = removeExtension(to.absFilename());
521         string const to_extension = getExtension(to.absFilename());
522
523         vector<FileName> const files = dirList(FileName(path),
524                         getExtension(from.absFilename()));
525         for (vector<FileName>::const_iterator it = files.begin();
526              it != files.end(); ++it) {
527                 string const from2 = it->absFilename();
528                 string const file2 = onlyFilename(from2);
529                 if (prefixIs(file2, base)) {
530                         string const to2 = changeExtension(
531                                 to_base + file2.substr(base.length()),
532                                 to_extension);
533                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
534
535                         Mover const & mover = getMover(fmt);
536                         bool const moved = copy
537                                 ? mover.copy(*it, FileName(to2))
538                                 : mover.rename(*it, FileName(to2));
539                         if (!moved && no_errors) {
540                                 Alert::error(_("Cannot convert file"),
541                                         bformat(copy ?
542                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
543                                                 _("Could not move a temporary file from %1$s to %2$s."),
544                                                 from_utf8(from2), from_utf8(to2)));
545                                 no_errors = false;
546                         }
547                 }
548         }
549         return no_errors;
550 }
551
552
553 bool Converters::formatIsUsed(string const & format)
554 {
555         ConverterList::const_iterator cit = converterlist_.begin();
556         ConverterList::const_iterator end = converterlist_.end();
557         for (; cit != end; ++cit) {
558                 if (cit->from == format || cit->to == format)
559                         return true;
560         }
561         return false;
562 }
563
564
565 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
566                          FileName const & filename, ErrorList & errorList)
567 {
568         OutputParams runparams(0);
569         runparams.flavor = OutputParams::LATEX;
570         LaTeX latex("", runparams, filename);
571         TeXErrors terr;
572         int const result = latex.scanLogFile(terr);
573
574         if (result & LaTeX::ERRORS)
575                 buffer.bufferErrors(terr, errorList);
576
577         return true;
578 }
579
580
581 namespace {
582
583 class ShowMessage
584         : public boost::signals::trackable {
585 public:
586         ShowMessage(Buffer const & b) : buffer_(b) {}
587         void operator()(docstring const & msg) const { buffer_.message(msg); }
588 private:
589         Buffer const & buffer_;
590 };
591
592 }
593
594
595 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
596                           OutputParams const & runparams, ErrorList & errorList)
597 {
598         buffer.setBusy(true);
599         buffer.message(_("Running LaTeX..."));
600
601         runparams.document_language = buffer.params().language->babel();
602
603         // do the LaTeX run(s)
604         string const name = buffer.latexName();
605         LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
606         TeXErrors terr;
607         ShowMessage show(buffer);
608         latex.message.connect(show);
609         int const result = latex.run(terr);
610
611         if (result & LaTeX::ERRORS)
612                 buffer.bufferErrors(terr, errorList);
613
614         // check return value from latex.run().
615         if ((result & LaTeX::NO_LOGFILE)) {
616                 docstring const str =
617                         bformat(_("LaTeX did not run successfully. "
618                                                "Additionally, LyX could not locate "
619                                                "the LaTeX log %1$s."), from_utf8(name));
620                 Alert::error(_("LaTeX failed"), str);
621         } else if (result & LaTeX::NO_OUTPUT) {
622                 Alert::warning(_("Output is empty"),
623                                _("An empty output file was generated."));
624         }
625
626
627         buffer.setBusy(false);
628
629         int const ERROR_MASK =
630                         LaTeX::NO_LOGFILE |
631                         LaTeX::ERRORS |
632                         LaTeX::NO_OUTPUT;
633
634         return (result & ERROR_MASK) == 0;
635
636 }
637
638
639
640 void Converters::buildGraph()
641 {
642         G_.init(formats.size());
643         ConverterList::iterator beg = converterlist_.begin();
644         ConverterList::iterator const end = converterlist_.end();
645         for (ConverterList::iterator it = beg; it != end ; ++it) {
646                 int const s = formats.getNumber(it->from);
647                 int const t = formats.getNumber(it->to);
648                 G_.addEdge(s,t);
649         }
650 }
651
652
653 std::vector<Format const *> const
654 Converters::intToFormat(std::vector<int> const & input)
655 {
656         vector<Format const *> result(input.size());
657
658         vector<int>::const_iterator it = input.begin();
659         vector<int>::const_iterator const end = input.end();
660         vector<Format const *>::iterator rit = result.begin();
661         for ( ; it != end; ++it, ++rit) {
662                 *rit = &formats.get(*it);
663         }
664         return result;
665 }
666
667
668 vector<Format const *> const
669 Converters::getReachableTo(string const & target, bool const clear_visited)
670 {
671         vector<int> const & reachablesto =
672                 G_.getReachableTo(formats.getNumber(target), clear_visited);
673
674         return intToFormat(reachablesto);
675 }
676
677
678 vector<Format const *> const
679 Converters::getReachable(string const & from, bool const only_viewable,
680                          bool const clear_visited)
681 {
682         vector<int> const & reachables =
683                 G_.getReachable(formats.getNumber(from),
684                                 only_viewable,
685                                 clear_visited);
686
687         return intToFormat(reachables);
688 }
689
690
691 bool Converters::isReachable(string const & from, string const & to)
692 {
693         return G_.isReachable(formats.getNumber(from),
694                               formats.getNumber(to));
695 }
696
697
698 Graph::EdgePath Converters::getPath(string const & from, string const & to)
699 {
700         return G_.getPath(formats.getNumber(from),
701                           formats.getNumber(to));
702 }
703
704
705 vector<Format const *> Converters::importableFormats()
706 {
707         vector<string> l = loaders();
708         vector<Format const *> result = getReachableTo(l[0], true);
709         for (vector<string>::const_iterator it = l.begin() + 1;
710              it != l.end(); ++it) {
711                 vector<Format const *> r = getReachableTo(*it, false);
712                 result.insert(result.end(), r.begin(), r.end());
713         }
714         return result;
715 }
716
717
718 vector<string> Converters::loaders() const
719 {
720         vector<string> v;
721         v.push_back("lyx");
722         v.push_back("text");
723         v.push_back("textparagraph");
724         return v;
725 }
726
727
728 } // namespace lyx