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