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