]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
cosmetics
[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/os.h"
34 #include "support/Package.h"
35 #include "support/Path.h"
36 #include "support/Systemcall.h"
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 namespace Alert = lyx::frontend::Alert;
44
45
46 namespace {
47
48 string const token_from("$$i");
49 string const token_base("$$b");
50 string const token_to("$$o");
51 string const token_path("$$p");
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.to, "pdf"))
258                                 return OutputParams::PDFLATEX;
259                 if (conv.xml)
260                         return OutputParams::XML;
261         }
262         return OutputParams::LATEX;
263 }
264
265
266 bool Converters::convert(Buffer const * buffer,
267                          FileName const & from_file, FileName const & to_file,
268                          FileName const & orig_from,
269                          string const & from_format, string const & to_format,
270                          ErrorList & errorList, int conversionflags)
271 {
272         if (from_format == to_format)
273                 return move(from_format, from_file, to_file, false);
274
275         if ((conversionflags & try_cache) &&
276             ConverterCache::get().inCache(orig_from, to_format))
277                 return ConverterCache::get().copy(orig_from, to_format, to_file);
278
279         Graph::EdgePath edgepath = getPath(from_format, to_format);
280         if (edgepath.empty()) {
281                 if (conversionflags & try_default) {
282                         // if no special converter defined, then we take the
283                         // default one from ImageMagic.
284                         string const from_ext = from_format.empty() ?
285                                 getExtension(from_file.absFilename()) :
286                                 formats.extension(from_format);
287                         string const to_ext = formats.extension(to_format);
288                         string const command =
289                                 os::python() + ' ' +
290                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
291                                 ' ' +
292                                 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
293                                 ' ' +
294                                 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
295                         LYXERR(Debug::FILES, "No converter defined! "
296                                    "I use convertDefault.py:\n\t" << command);
297                         Systemcall one;
298                         one.startscript(Systemcall::Wait, command);
299                         if (to_file.isReadableFile()) {
300                                 if (conversionflags & try_cache)
301                                         ConverterCache::get().add(orig_from,
302                                                         to_format, to_file);
303                                 return true;
304                         }
305                 }
306                 Alert::error(_("Cannot convert file"),
307                              bformat(_("No information for converting %1$s "
308                                                     "format files to %2$s.\n"
309                                                     "Define a converter in the preferences."),
310                                                         from_ascii(from_format), from_ascii(to_format)));
311                 return false;
312         }
313
314         // buffer is only invalid for importing, and then runparams is not
315         // used anyway.
316         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
317         runparams.flavor = getFlavor(edgepath);
318
319         // Some converters (e.g. lilypond) can only output files to the
320         // current directory, so we need to change the current directory.
321         // This has the added benefit that all other files that may be
322         // generated by the converter are deleted when LyX closes and do not
323         // clutter the real working directory.
324         string const path(onlyPath(from_file.absFilename()));
325         // Prevent the compiler from optimizing away p
326         FileName pp(path);
327         PathChanger p(pp);
328
329         // empty the error list before any new conversion takes place.
330         errorList.clear();
331
332         bool run_latex = false;
333         string from_base = changeExtension(from_file.absFilename(), "");
334         string to_base = changeExtension(to_file.absFilename(), "");
335         FileName infile;
336         FileName outfile = from_file;
337         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
338              cit != edgepath.end(); ++cit) {
339                 Converter const & conv = converterlist_[*cit];
340                 bool dummy = conv.To->dummy() && conv.to != "program";
341                 if (!dummy) {
342                         LYXERR(Debug::FILES, "Converting from  "
343                                << conv.from << " to " << conv.to);
344                 }
345                 infile = outfile;
346                 outfile = FileName(conv.result_dir.empty()
347                         ? changeExtension(from_file.absFilename(), conv.To->extension())
348                         : addName(subst(conv.result_dir,
349                                         token_base, from_base),
350                                   subst(conv.result_file,
351                                         token_base, onlyFilename(from_base))));
352
353                 // if input and output files are equal, we use a
354                 // temporary file as intermediary (JMarc)
355                 FileName real_outfile;
356                 if (outfile == infile) {
357                         real_outfile = infile;
358                         // when importing, a buffer does not necessarily exist
359                         if (buffer)
360                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
361                         else
362                                 outfile = FileName(addName(package().temp_dir().absFilename(),
363                                                    "tmpfile.out"));
364                 }
365
366                 if (conv.latex) {
367                         run_latex = true;
368                         string const command = subst(conv.command, token_from, "");
369                         LYXERR(Debug::FILES, "Running " << command);
370                         if (!runLaTeX(*buffer, command, runparams, errorList))
371                                 return false;
372                 } else {
373                         if (conv.need_aux && !run_latex
374                             && !latex_command_.empty()) {
375                                 LYXERR(Debug::FILES, "Running " << latex_command_
376                                         << " to update aux file");
377                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
378                         }
379
380                         // FIXME UNICODE
381                         string const infile2 = 
382                                 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
383                         string const outfile2 = 
384                                 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
385
386                         string command = conv.command;
387                         command = subst(command, token_from, quoteName(infile2));
388                         command = subst(command, token_base, quoteName(from_base));
389                         command = subst(command, token_to, quoteName(outfile2));
390                         command = libScriptSearch(command);
391
392                         if (!conv.parselog.empty())
393                                 command += " 2> " + quoteName(infile2 + ".out");
394
395                         if (conv.from == "dvi" && conv.to == "ps")
396                                 command = add_options(command,
397                                                       buffer->params().dvips_options());
398                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
399                                 command = add_options(command,
400                                                       dvipdfm_options(buffer->params()));
401
402                         LYXERR(Debug::FILES, "Calling " << command);
403                         if (buffer)
404                                 buffer->message(_("Executing command: ")
405                                 + from_utf8(command));
406
407                         Systemcall one;
408                         int res;
409                         if (dummy) {
410                                 res = one.startscript(Systemcall::DontWait,
411                                         to_filesystem8bit(from_utf8(command)));
412                                 // We're not waiting for the result, so we can't do anything
413                                 // else here.
414                         } else {
415                                 res = one.startscript(Systemcall::Wait,
416                                                 to_filesystem8bit(from_utf8(command)));
417                                 if (!real_outfile.empty()) {
418                                         Mover const & mover = getMover(conv.to);
419                                         if (!mover.rename(outfile, real_outfile))
420                                                 res = -1;
421                                         else
422                                                 LYXERR(Debug::FILES, "renaming file " << outfile
423                                                         << " to " << real_outfile);
424                                         // Finally, don't forget to tell any future
425                                         // converters to use the renamed file...
426                                         outfile = real_outfile;
427                                 }
428   
429                                 if (!conv.parselog.empty()) {
430                                         string const logfile =  infile2 + ".log";
431                                         string const script = libScriptSearch(conv.parselog);
432                                         string const command2 = script +
433                                                 " < " + quoteName(infile2 + ".out") +
434                                                 " > " + quoteName(logfile);
435                                         one.startscript(Systemcall::Wait,
436                                                 to_filesystem8bit(from_utf8(command2)));
437                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
438                                                 return false;
439                                 }
440                         }
441
442                         if (res) {
443                                 if (conv.to == "program") {
444                                         Alert::error(_("Build errors"),
445                                                 _("There were errors during the build process."));
446                                 } else {
447 // FIXME: this should go out of here. For example, here we cannot say if
448 // it is a document (.lyx) or something else. Same goes for elsewhere.
449                                         Alert::error(_("Cannot convert file"),
450                                                 bformat(_("An error occurred whilst running %1$s"),
451                                                 from_utf8(command.substr(0, 50))));
452                                 }
453                                 return false;
454                         }
455                 }
456         }
457
458         Converter const & conv = converterlist_[edgepath.back()];
459         if (conv.To->dummy())
460                 return true;
461
462         if (!conv.result_dir.empty()) {
463                 // The converter has put the file(s) in a directory.
464                 // In this case we ignore the given to_file.
465                 if (from_base != to_base) {
466                         string const from = subst(conv.result_dir,
467                                             token_base, from_base);
468                         string const to = subst(conv.result_dir,
469                                           token_base, to_base);
470                         Mover const & mover = getMover(conv.from);
471                         if (!mover.rename(FileName(from), FileName(to))) {
472                                 Alert::error(_("Cannot convert file"),
473                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
474                                                 from_utf8(from), from_utf8(to)));
475                                 return false;
476                         }
477                 }
478                 return true;
479         } else {
480                 if (conversionflags & try_cache)
481                         ConverterCache::get().add(orig_from, to_format, outfile);
482                 return move(conv.to, outfile, to_file, conv.latex);
483         }
484 }
485
486
487 bool Converters::move(string const & fmt,
488                       FileName const & from, FileName const & to, bool copy)
489 {
490         if (from == to)
491                 return true;
492
493         bool no_errors = true;
494         string const path = onlyPath(from.absFilename());
495         string const base = onlyFilename(removeExtension(from.absFilename()));
496         string const to_base = removeExtension(to.absFilename());
497         string const to_extension = getExtension(to.absFilename());
498
499         FileNameList const files = FileName(path).dirList(getExtension(from.absFilename()));
500         for (FileNameList::const_iterator it = files.begin();
501              it != files.end(); ++it) {
502                 string const from2 = it->absFilename();
503                 string const file2 = onlyFilename(from2);
504                 if (prefixIs(file2, base)) {
505                         string const to2 = changeExtension(
506                                 to_base + file2.substr(base.length()),
507                                 to_extension);
508                         LYXERR(Debug::FILES, "moving " << from2 << " to " << to2);
509
510                         Mover const & mover = getMover(fmt);
511                         bool const moved = copy
512                                 ? mover.copy(*it, FileName(to2))
513                                 : mover.rename(*it, FileName(to2));
514                         if (!moved && no_errors) {
515                                 Alert::error(_("Cannot convert file"),
516                                         bformat(copy ?
517                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
518                                                 _("Could not move a temporary file from %1$s to %2$s."),
519                                                 from_utf8(from2), from_utf8(to2)));
520                                 no_errors = false;
521                         }
522                 }
523         }
524         return no_errors;
525 }
526
527
528 bool Converters::formatIsUsed(string const & format)
529 {
530         ConverterList::const_iterator cit = converterlist_.begin();
531         ConverterList::const_iterator end = converterlist_.end();
532         for (; cit != end; ++cit) {
533                 if (cit->from == format || cit->to == format)
534                         return true;
535         }
536         return false;
537 }
538
539
540 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
541                          FileName const & filename, ErrorList & errorList)
542 {
543         OutputParams runparams(0);
544         runparams.flavor = OutputParams::LATEX;
545         LaTeX latex("", runparams, filename);
546         TeXErrors terr;
547         int const result = latex.scanLogFile(terr);
548
549         if (result & LaTeX::ERRORS)
550                 buffer.bufferErrors(terr, errorList);
551
552         return true;
553 }
554
555
556 namespace {
557
558 class ShowMessage
559         : public boost::signals::trackable {
560 public:
561         ShowMessage(Buffer const & b) : buffer_(b) {}
562         void operator()(docstring const & msg) const { buffer_.message(msg); }
563 private:
564         Buffer const & buffer_;
565 };
566
567 }
568
569
570 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
571                           OutputParams const & runparams, ErrorList & errorList)
572 {
573         buffer.setBusy(true);
574         buffer.message(_("Running LaTeX..."));
575
576         runparams.document_language = buffer.params().language->babel();
577
578         // do the LaTeX run(s)
579         string const name = buffer.latexName();
580         LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
581         TeXErrors terr;
582         ShowMessage show(buffer);
583         latex.message.connect(show);
584         int const result = latex.run(terr);
585
586         if (result & LaTeX::ERRORS)
587                 buffer.bufferErrors(terr, errorList);
588
589         // check return value from latex.run().
590         if ((result & LaTeX::NO_LOGFILE)) {
591                 docstring const str =
592                         bformat(_("LaTeX did not run successfully. "
593                                                "Additionally, LyX could not locate "
594                                                "the LaTeX log %1$s."), from_utf8(name));
595                 Alert::error(_("LaTeX failed"), str);
596         } else if (result & LaTeX::NO_OUTPUT) {
597                 Alert::warning(_("Output is empty"),
598                                _("An empty output file was generated."));
599         }
600
601
602         buffer.setBusy(false);
603
604         int const ERROR_MASK =
605                         LaTeX::NO_LOGFILE |
606                         LaTeX::ERRORS |
607                         LaTeX::NO_OUTPUT;
608
609         return (result & ERROR_MASK) == 0;
610
611 }
612
613
614
615 void Converters::buildGraph()
616 {
617         G_.init(formats.size());
618         ConverterList::iterator beg = converterlist_.begin();
619         ConverterList::iterator const end = converterlist_.end();
620         for (ConverterList::iterator it = beg; it != end ; ++it) {
621                 int const s = formats.getNumber(it->from);
622                 int const t = formats.getNumber(it->to);
623                 G_.addEdge(s,t);
624         }
625 }
626
627
628 vector<Format const *> const
629 Converters::intToFormat(vector<int> const & input)
630 {
631         vector<Format const *> result(input.size());
632
633         vector<int>::const_iterator it = input.begin();
634         vector<int>::const_iterator const end = input.end();
635         vector<Format const *>::iterator rit = result.begin();
636         for ( ; it != end; ++it, ++rit) {
637                 *rit = &formats.get(*it);
638         }
639         return result;
640 }
641
642
643 vector<Format const *> const
644 Converters::getReachableTo(string const & target, bool const clear_visited)
645 {
646         vector<int> const & reachablesto =
647                 G_.getReachableTo(formats.getNumber(target), clear_visited);
648
649         return intToFormat(reachablesto);
650 }
651
652
653 vector<Format const *> const
654 Converters::getReachable(string const & from, bool const only_viewable,
655                          bool const clear_visited)
656 {
657         vector<int> const & reachables =
658                 G_.getReachable(formats.getNumber(from),
659                                 only_viewable,
660                                 clear_visited);
661
662         return intToFormat(reachables);
663 }
664
665
666 bool Converters::isReachable(string const & from, string const & to)
667 {
668         return G_.isReachable(formats.getNumber(from),
669                               formats.getNumber(to));
670 }
671
672
673 Graph::EdgePath Converters::getPath(string const & from, string const & to)
674 {
675         return G_.getPath(formats.getNumber(from),
676                           formats.getNumber(to));
677 }
678
679
680 vector<Format const *> Converters::importableFormats()
681 {
682         vector<string> l = loaders();
683         vector<Format const *> result = getReachableTo(l[0], true);
684         for (vector<string>::const_iterator it = l.begin() + 1;
685              it != l.end(); ++it) {
686                 vector<Format const *> r = getReachableTo(*it, false);
687                 result.insert(result.end(), r.begin(), r.end());
688         }
689         return result;
690 }
691
692
693 vector<string> Converters::loaders() const
694 {
695         vector<string> v;
696         v.push_back("lyx");
697         v.push_back("text");
698         v.push_back("textparagraph");
699         return v;
700 }
701
702
703 } // namespace lyx