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