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