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