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