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