]> git.lyx.org Git - lyx.git/blob - src/converter.C
cleanup after svn hang-up, #undef CursorShape. Should be compilable ganin now.
[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         string path = onlyPath(from_file);
330         Path p(path);
331         // empty the error list before any new conversion takes place.
332         errorList.clear();
333
334         bool run_latex = false;
335         string from_base = changeExtension(from_file, "");
336         string to_base = changeExtension(to_file, "");
337         string infile;
338         string outfile = from_file;
339         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
340              cit != edgepath.end(); ++cit) {
341                 Converter const & conv = converterlist_[*cit];
342                 bool dummy = conv.To->dummy() && conv.to != "program";
343                 if (!dummy)
344                         lyxerr[Debug::FILES] << "Converting from  "
345                                << conv.from << " to " << conv.to << endl;
346                 infile = outfile;
347                 outfile = conv.result_dir.empty()
348                         ? changeExtension(from_file, conv.To->extension())
349                         : addName(subst(conv.result_dir,
350                                         token_base, from_base),
351                                   subst(conv.result_file,
352                                         token_base, onlyFilename(from_base)));
353
354                 // if input and output files are equal, we use a
355                 // temporary file as intermediary (JMarc)
356                 string real_outfile;
357                 if (outfile == infile) {
358                         real_outfile = infile;
359                         outfile = addName(buffer->temppath(), "tmpfile.out");
360                 }
361
362                 if (conv.latex) {
363                         run_latex = true;
364                         string const command = subst(conv.command, token_from, "");
365                         lyxerr[Debug::FILES] << "Running " << command << endl;
366                         if (!runLaTeX(*buffer, command, runparams, errorList))
367                                 return false;
368                 } else {
369                         if (conv.need_aux && !run_latex
370                             && !latex_command_.empty()) {
371                                 lyxerr[Debug::FILES]
372                                         << "Running " << latex_command_
373                                         << " to update aux file"<<  endl;
374                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
375                         }
376
377                         string const infile2 = (conv.original_dir)
378                                 ? infile : makeRelPath(infile, path);
379                         string const outfile2 = (conv.original_dir)
380                                 ? outfile : makeRelPath(outfile, path);
381
382                         string command = conv.command;
383                         command = subst(command, token_from, quoteName(infile2));
384                         command = subst(command, token_base, quoteName(from_base));
385                         command = subst(command, token_to, quoteName(outfile2));
386                         command = libScriptSearch(command);
387
388                         if (!conv.parselog.empty())
389                                 command += " 2> " + quoteName(infile2 + ".out");
390
391                         if (conv.from == "dvi" && conv.to == "ps")
392                                 command = add_options(command,
393                                                       buffer->params().dvips_options());
394                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
395                                 command = add_options(command,
396                                                       dvipdfm_options(buffer->params()));
397
398                         lyxerr[Debug::FILES] << "Calling " << command << endl;
399                         if (buffer)
400                                 buffer->message(_("Executing command: ")
401                                 + lyx::from_utf8(command));
402
403                         Systemcall::Starttype const type = (dummy)
404                                 ? Systemcall::DontWait : Systemcall::Wait;
405                         Systemcall one;
406                         int res;
407                         if (conv.original_dir) {
408                                 Path p(buffer->filePath());
409                                 res = one.startscript(type, command);
410                         } else
411                                 res = one.startscript(type, command);
412
413                         if (!real_outfile.empty()) {
414                                 Mover const & mover = movers(conv.to);
415                                 if (!mover.rename(outfile, real_outfile))
416                                         res = -1;
417                                 else
418                                         lyxerr[Debug::FILES]
419                                                 << "renaming file " << outfile
420                                                 << " to " << real_outfile
421                                                 << endl;
422                                 // Finally, don't forget to tell any future
423                                 // converters to use the renamed file...
424                                 outfile = real_outfile;
425                         }
426
427                         if (!conv.parselog.empty()) {
428                                 string const logfile =  infile2 + ".log";
429                                 string const script = libScriptSearch(conv.parselog);
430                                 string const command2 = script +
431                                         " < " + quoteName(infile2 + ".out") +
432                                         " > " + quoteName(logfile);
433                                 one.startscript(Systemcall::Wait, command2);
434                                 if (!scanLog(*buffer, command, logfile, errorList))
435                                         return false;
436                         }
437
438                         if (res) {
439                                 if (conv.to == "program") {
440                                         Alert::error(_("Build errors"),
441                                                 _("There were errors during the build process."));
442                                 } else {
443 // FIXME: this should go out of here. For example, here we cannot say if
444 // it is a document (.lyx) or something else. Same goes for elsewhere.
445                                 Alert::error(_("Cannot convert file"),
446                                         bformat(_("An error occurred whilst running %1$s"),
447                                         lyx::from_ascii(command.substr(0, 50))));
448                                 }
449                                 return false;
450                         }
451                 }
452         }
453
454         Converter const & conv = converterlist_[edgepath.back()];
455         if (conv.To->dummy())
456                 return true;
457
458         if (!conv.result_dir.empty()) {
459                 to_file = addName(subst(conv.result_dir, token_base, to_base),
460                                   subst(conv.result_file,
461                                         token_base, onlyFilename(to_base)));
462                 if (from_base != to_base) {
463                         string const from = subst(conv.result_dir,
464                                             token_base, from_base);
465                         string const to = subst(conv.result_dir,
466                                           token_base, to_base);
467                         Mover const & mover = movers(conv.from);
468                         if (!mover.rename(from, to)) {
469                                 Alert::error(_("Cannot convert file"),
470                                         bformat(_("Could not move a temporary file from %1$s to %2$s."),
471                                                 lyx::from_ascii(from), lyx::from_ascii(to)));
472                                 return false;
473                         }
474                 }
475                 return true;
476         } else
477                 return move(conv.to, outfile, to_file, conv.latex);
478 }
479
480
481 bool Converters::move(string const & fmt,
482                       string const & from, string const & to, bool copy)
483 {
484         if (from == to)
485                 return true;
486
487         bool no_errors = true;
488         string const path = onlyPath(from);
489         string const base = onlyFilename(changeExtension(from, ""));
490         string const to_base = changeExtension(to, "");
491         string const to_extension = getExtension(to);
492
493         vector<string> files = dirList(onlyPath(from), getExtension(from));
494         for (vector<string>::const_iterator it = files.begin();
495              it != files.end(); ++it)
496                 if (prefixIs(*it, base)) {
497                         string const from2 = path + *it;
498                         string to2 = to_base + it->substr(base.length());
499                         to2 = changeExtension(to2, to_extension);
500                         lyxerr[Debug::FILES] << "moving " << from2
501                                              << " to " << to2 << endl;
502
503                         Mover const & mover = movers(fmt);
504                         bool const moved = copy
505                                 ? mover.copy(from2, to2)
506                                 : mover.rename(from2, to2);
507                         if (!moved && no_errors) {
508                                 Alert::error(_("Cannot convert file"),
509                                         bformat(copy ?
510                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
511                                                 _("Could not move a temporary file from %1$s to %2$s."),
512                                                 lyx::from_ascii(from2), lyx::from_ascii(to2)));
513                                 no_errors = false;
514                         }
515                 }
516         return no_errors;
517 }
518
519
520 bool Converters::convert(Buffer const * buffer,
521                          string const & from_file, string const & to_file_base,
522                          string const & from_format, string const & to_format,
523                          ErrorList & errorList, bool try_default)
524 {
525         string to_file;
526         return convert(buffer, from_file, to_file_base, from_format, to_format,
527                        to_file, errorList, try_default);
528 }
529
530
531 bool Converters::formatIsUsed(string const & format)
532 {
533         ConverterList::const_iterator cit = converterlist_.begin();
534         ConverterList::const_iterator end = converterlist_.end();
535         for (; cit != end; ++cit) {
536                 if (cit->from == format || cit->to == format)
537                         return true;
538         }
539         return false;
540 }
541
542
543 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
544                          string const & filename, ErrorList & errorList)
545 {
546         OutputParams runparams;
547         runparams.flavor = OutputParams::LATEX;
548         LaTeX latex("", runparams, filename, "");
549         TeXErrors terr;
550         int const result = latex.scanLogFile(terr);
551
552         if (result & LaTeX::ERRORS)
553                 bufferErrors(buffer, terr, errorList);
554
555         return true;
556 }
557
558
559 namespace {
560
561 class showMessage : public std::unary_function<docstring, void>, public boost::signals::trackable {
562 public:
563         showMessage(Buffer const & b) : buffer_(b) {};
564         void operator()(docstring const & m) const
565         {
566                 buffer_.message(m);
567         }
568 private:
569         Buffer const & buffer_;
570 };
571
572 }
573
574
575 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
576                           OutputParams const & runparams, ErrorList & errorList)
577 {
578         buffer.busy(true);
579         buffer.message(_("Running LaTeX..."));
580
581         runparams.document_language = buffer.params().language->babel();
582
583         // do the LaTeX run(s)
584         string const name = buffer.getLatexName();
585         LaTeX latex(command, runparams, name, buffer.filePath());
586         TeXErrors terr;
587         showMessage show(buffer);
588         latex.message.connect(show);
589         int const result = latex.run(terr);
590
591         if (result & LaTeX::ERRORS)
592                 bufferErrors(buffer, terr, errorList);
593
594         // check return value from latex.run().
595         if ((result & LaTeX::NO_LOGFILE)) {
596                 docstring const str =
597                         bformat(_("LaTeX did not run successfully. "
598                                                "Additionally, LyX could not locate "
599                                                "the LaTeX log %1$s."), lyx::from_utf8(name));
600                 Alert::error(_("LaTeX failed"), str);
601         } else if (result & LaTeX::NO_OUTPUT) {
602                 Alert::warning(_("Output is empty"),
603                                _("An empty output file was generated."));
604         }
605
606
607         buffer.busy(false);
608
609         int const ERROR_MASK =
610                         LaTeX::NO_LOGFILE |
611                         LaTeX::ERRORS |
612                         LaTeX::NO_OUTPUT;
613
614         return (result & ERROR_MASK) == 0;
615
616 }
617
618
619
620 void Converters::buildGraph()
621 {
622         G_.init(formats.size());
623         ConverterList::iterator beg = converterlist_.begin();
624         ConverterList::iterator const end = converterlist_.end();
625         for (ConverterList::iterator it = beg; it != end ; ++it) {
626                 int const s = formats.getNumber(it->from);
627                 int const t = formats.getNumber(it->to);
628                 G_.addEdge(s,t);
629         }
630 }
631
632
633 std::vector<Format const *> const
634 Converters::intToFormat(std::vector<int> const & input)
635 {
636         vector<Format const *> result(input.size());
637
638         vector<int>::const_iterator it = input.begin();
639         vector<int>::const_iterator const end = input.end();
640         vector<Format const *>::iterator rit = result.begin();
641         for ( ; it != end; ++it, ++rit) {
642                 *rit = &formats.get(*it);
643         }
644         return result;
645 }
646
647
648 vector<Format const *> const
649 Converters::getReachableTo(string const & target, bool const clear_visited)
650 {
651         vector<int> const & reachablesto =
652                 G_.getReachableTo(formats.getNumber(target), clear_visited);
653
654         return intToFormat(reachablesto);
655 }
656
657
658 vector<Format const *> const
659 Converters::getReachable(string const & from, bool const only_viewable,
660                          bool const clear_visited)
661 {
662         vector<int> const & reachables =
663                 G_.getReachable(formats.getNumber(from),
664                                 only_viewable,
665                                 clear_visited);
666
667         return intToFormat(reachables);
668 }
669
670
671 bool Converters::isReachable(string const & from, string const & to)
672 {
673         return G_.isReachable(formats.getNumber(from),
674                               formats.getNumber(to));
675 }
676
677
678 Graph::EdgePath const
679 Converters::getPath(string const & from, string const & to)
680 {
681         return G_.getPath(formats.getNumber(from),
682                           formats.getNumber(to));
683 }
684
685
686 /// The global instance
687 Converters converters;
688
689 // The global copy after reading lyxrc.defaults
690 Converters system_converters;