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