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