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