]> git.lyx.org Git - lyx.git/blob - src/converter.C
Replace 'using namespace abc;' with 'using abc::xyz;'
[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
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         LatexRunParams runparams;
287         runparams.flavor = usePdflatex(edgepath) ?
288                 LatexRunParams::PDFLATEX : LatexRunParams::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                         buffer->message(_("Executing command: ") + command);
359
360                         Systemcall::Starttype type = (dummy)
361                                 ? Systemcall::DontWait : Systemcall::Wait;
362                         Systemcall one;
363                         int res;
364                         if (conv.original_dir) {
365                                 Path p(buffer->filePath());
366                                 res = one.startscript(type, command);
367                         } else
368                                 res = one.startscript(type, command);
369
370                         if (!real_outfile.empty()) {
371                                 if (!rename(outfile, real_outfile))
372                                         res = -1;
373                                 else
374                                         lyxerr[Debug::FILES]
375                                                 << "renaming file " << outfile
376                                                 << " to " << real_outfile
377                                                 << endl;
378                         }
379
380                         if (!conv.parselog.empty()) {
381                                 string const logfile =  infile2 + ".log";
382                                 string const script = LibScriptSearch(conv.parselog);
383                                 string const command2 = script +
384                                         " < " + QuoteName(infile2 + ".out") +
385                                         " > " + QuoteName(logfile);
386                                 one.startscript(Systemcall::Wait, command2);
387                                 if (!scanLog(*buffer, command, logfile))
388                                         return false;
389                         }
390
391                         if (res) {
392                                 if (conv.to == "program") {
393                                         Alert::error(_("Build errors"),
394                                                 _("There were errors during the build process."));
395                                 } else {
396 // FIXME: this should go out of here. For example, here we cannot say if
397 // it is a document (.lyx) or something else. Same goes for elsewhere.
398                                 Alert::error(_("Cannot convert file"),
399                                         bformat(_("An error occurred whilst running %1$s"),
400                                                 command.substr(0, 50)));
401                                 }
402                                 return false;
403                         }
404                 }
405         }
406
407         Converter const & conv = converterlist_[edgepath.back()];
408         if (conv.To->dummy())
409                 return true;
410
411
412         if (!conv.result_dir.empty()) {
413                 to_file = AddName(subst(conv.result_dir, token_base, to_base),
414                                   subst(conv.result_file,
415                                         token_base, OnlyFilename(to_base)));
416                 if (from_base != to_base) {
417                         string from = subst(conv.result_dir,
418                                             token_base, from_base);
419                         string to = subst(conv.result_dir,
420                                           token_base, to_base);
421                         if (!rename(from, to)) {
422                                 Alert::error(_("Cannot convert file"),
423                                         bformat(_("Could not move a temporary file from %1$s to %2$s."),
424                                                 from, to));
425                                 return false;
426                         }
427                 }
428                 return true;
429         } else
430                 return move(outfile, to_file, conv.latex);
431 }
432
433
434 // If from = /path/file.ext and to = /path2/file2.ext2 then this method
435 // moves each /path/file*.ext file to /path2/file2*.ext2'
436 bool Converters::move(string const & from, string const & to, bool copy)
437 {
438         if (from == to)
439                 return true;
440
441         bool no_errors = true;
442         string const path = OnlyPath(from);
443         string const base = OnlyFilename(ChangeExtension(from, ""));
444         string const to_base = ChangeExtension(to, "");
445         string const to_extension = GetExtension(to);
446
447         vector<string> files = DirList(OnlyPath(from), GetExtension(from));
448         for (vector<string>::const_iterator it = files.begin();
449              it != files.end(); ++it)
450                 if (prefixIs(*it, base)) {
451                         string const from2 = path + *it;
452                         string to2 = to_base + it->substr(base.length());
453                         to2 = ChangeExtension(to2, to_extension);
454                         lyxerr[Debug::FILES] << "moving " << from2
455                                              << " to " << to2 << endl;
456                         bool const moved = (copy)
457                                 ? lyx::support::copy(from2, to2)
458                                 : rename(from2, to2);
459                         if (!moved && no_errors) {
460                                 Alert::error(_("Cannot convert file"),
461                                         bformat(_("Could not move a temporary file from %1$s to %2$s."),
462                                                 from2, to2));
463                                 no_errors = false;
464                         }
465                 }
466         return no_errors;
467 }
468
469
470 bool Converters::convert(Buffer const * buffer,
471                          string const & from_file, string const & to_file_base,
472                          string const & from_format, string const & to_format)
473 {
474         string to_file;
475         return convert(buffer, from_file, to_file_base, from_format, to_format,
476                        to_file);
477 }
478
479
480 bool Converters::formatIsUsed(string const & format)
481 {
482         ConverterList::const_iterator cit = converterlist_.begin();
483         ConverterList::const_iterator end = converterlist_.end();
484         for (; cit != end; ++cit) {
485                 if (cit->from == format || cit->to == format)
486                         return true;
487         }
488         return false;
489 }
490
491
492 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
493                          string const & filename)
494 {
495         LatexRunParams runparams;
496         runparams.flavor = LatexRunParams::LATEX;
497         LaTeX latex("", runparams, filename, "");
498         TeXErrors terr;
499         int result = latex.scanLogFile(terr);
500
501         if (result & LaTeX::ERRORS)
502                 bufferErrors(buffer, terr);
503
504         return true;
505 }
506
507 namespace {
508
509 class showMessage : public boost::signals::trackable {
510 public:
511         showMessage(Buffer const & b) : buffer_(b) {};
512         void operator()(string const & m)
513         {
514                 buffer_.message(m);
515         }
516 private:
517         Buffer const & buffer_;
518 };
519
520 }
521
522
523 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
524                           LatexRunParams const & runparams)
525 {
526         buffer.busy(true);
527         buffer.message(_("Running LaTeX..."));
528
529         // do the LaTeX run(s)
530         string name = buffer.getLatexName();
531         LaTeX latex(command, runparams, name, buffer.filePath());
532         TeXErrors terr;
533         showMessage show(buffer);
534         latex.message.connect(show);
535         int result = latex.run(terr);
536
537         if (result & LaTeX::ERRORS)
538                 bufferErrors(buffer, terr);
539
540         // check return value from latex.run().
541         if ((result & LaTeX::NO_LOGFILE)) {
542                 string str = bformat(_("LaTeX did not run successfully. "
543                                        "Additionally, LyX could not locate "
544                                        "the LaTeX log %1$s."), name);
545                 Alert::error(_("LaTeX failed"), str);
546         } else if (result & LaTeX::NO_OUTPUT) {
547                 Alert::warning(_("Output is empty"),
548                                _("An empty output file was generated."));
549         }
550
551
552         buffer.busy(false);
553
554         int const ERROR_MASK =
555                         LaTeX::NO_LOGFILE |
556                         LaTeX::ERRORS |
557                         LaTeX::NO_OUTPUT;
558
559         return (result & ERROR_MASK) == 0;
560
561 }
562
563
564
565 void Converters::buildGraph()
566 {
567         G_.init(formats.size());
568         ConverterList::iterator beg = converterlist_.begin();
569         ConverterList::iterator end = converterlist_.end();
570         for (ConverterList::iterator it = beg; it != end ; ++it) {
571                 int const s = formats.getNumber(it->from);
572                 int const t = formats.getNumber(it->to);
573                 G_.addEdge(s,t);
574         }
575 }
576
577
578 std::vector<Format const *> const
579 Converters::intToFormat(std::vector<int> const & input)
580 {
581         vector<Format const *> result(input.size());
582
583         vector<int>::const_iterator it = input.begin();
584         vector<int>::const_iterator end = input.end();
585         vector<Format const *>::iterator rit = result.begin();
586         for ( ; it != end; ++it, ++rit) {
587                 *rit = &formats.get(*it);
588         }
589         return result;
590 }
591
592 vector<Format const *> const
593 Converters::getReachableTo(string const & target, bool clear_visited)
594 {
595         vector<int> const & reachablesto =
596                 G_.getReachableTo(formats.getNumber(target), clear_visited);
597
598         return intToFormat(reachablesto);
599 }
600
601
602 vector<Format const *> const
603 Converters::getReachable(string const & from, bool only_viewable,
604                          bool clear_visited)
605 {
606         vector<int> const & reachables =
607                 G_.getReachable(formats.getNumber(from),
608                                 only_viewable,
609                                 clear_visited);
610
611         return intToFormat(reachables);
612 }
613
614
615 bool Converters::isReachable(string const & from, string const & to)
616 {
617         return G_.isReachable(formats.getNumber(from),
618                               formats.getNumber(to));
619 }
620
621
622 Graph::EdgePath const
623 Converters::getPath(string const & from, string const & to)
624 {
625         return G_.getPath(formats.getNumber(from),
626                           formats.getNumber(to));
627 }
628
629
630 /// The global instance
631 Converters converters;
632
633 // The global copy after reading lyxrc.defaults
634 Converters system_converters;