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