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