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