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