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