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