]> git.lyx.org Git - lyx.git/blob - src/Converter.cpp
Further cleanup of InsetFlex, InsetCollapsable and InsetLayout:
[lyx.git] / src / Converter.cpp
1 /**
2  * \file Converter.cpp
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 "ConverterCache.h"
16 #include "Buffer.h"
17 #include "buffer_funcs.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "ErrorList.h"
21 #include "Format.h"
22 #include "gettext.h"
23 #include "Language.h"
24 #include "LaTeX.h"
25 #include "Mover.h"
26
27 #include "frontends/alert.h"
28
29 #include "support/filetools.h"
30 #include "support/lyxlib.h"
31 #include "support/os.h"
32 #include "support/Package.h"
33 #include "support/Path.h"
34 #include "support/Systemcall.h"
35
36 using std::endl;
37 using std::find_if;
38 using std::string;
39 using std::vector;
40 using std::distance;
41
42
43 namespace lyx {
44
45 using support::addName;
46 using support::bformat;
47 using support::changeExtension;
48 using support::compare_ascii_no_case;
49 using support::contains;
50 using support::dirList;
51 using support::FileName;
52 using support::getExtension;
53 using support::libFileSearch;
54 using support::libScriptSearch;
55 using support::makeAbsPath;
56 using support::makeRelPath;
57 using support::onlyFilename;
58 using support::onlyPath;
59 using support::package;
60 using support::prefixIs;
61 using support::quoteName;
62 using support::removeExtension;
63 using support::split;
64 using support::subst;
65 using support::Systemcall;
66
67 namespace Alert = lyx::frontend::Alert;
68
69
70 namespace {
71
72 string const token_from("$$i");
73 string const token_base("$$b");
74 string const token_to("$$o");
75 string const token_path("$$p");
76
77
78
79 string const add_options(string const & command, string const & options)
80 {
81         string head;
82         string const tail = split(command, head, ' ');
83         return head + ' ' + options + ' ' + tail;
84 }
85
86
87 string const dvipdfm_options(BufferParams const & bp)
88 {
89         string result;
90
91         if (bp.papersize != PAPER_CUSTOM) {
92                 string const paper_size = bp.paperSizeName();
93                 if (paper_size != "b5" && paper_size != "foolscap")
94                         result = "-p "+ paper_size;
95
96                 if (bp.orientation == ORIENTATION_LANDSCAPE)
97                         result += " -l";
98         }
99
100         return result;
101 }
102
103
104 class ConverterEqual : public std::binary_function<string, string, bool> {
105 public:
106         ConverterEqual(string const & from, string const & to)
107                 : from_(from), to_(to) {}
108         bool operator()(Converter const & c) const {
109                 return c.from == from_ && c.to == to_;
110         }
111 private:
112         string const from_;
113         string const to_;
114 };
115
116 } // namespace anon
117
118
119 Converter::Converter(string const & f, string const & t,
120                      string const & c, string const & l)
121         : from(f), to(t), command(c), flags(l),
122           From(0), To(0), latex(false), xml(false),
123           need_aux(false)
124 {}
125
126
127 void Converter::readFlags()
128 {
129         string flag_list(flags);
130         while (!flag_list.empty()) {
131                 string flag_name, flag_value;
132                 flag_list = split(flag_list, flag_value, ',');
133                 flag_value = split(flag_value, flag_name, '=');
134                 if (flag_name == "latex")
135                         latex = true;
136                 else if (flag_name == "xml")
137                         xml = true;
138                 else if (flag_name == "needaux")
139                         need_aux = true;
140                 else if (flag_name == "resultdir")
141                         result_dir = (flag_value.empty())
142                                 ? token_base : flag_value;
143                 else if (flag_name == "resultfile")
144                         result_file = flag_value;
145                 else if (flag_name == "parselog")
146                         parselog = flag_value;
147         }
148         if (!result_dir.empty() && result_file.empty())
149                 result_file = "index." + formats.extension(to);
150         //if (!contains(command, token_from))
151         //      latex = true;
152 }
153
154
155 bool operator<(Converter const & a, Converter const & b)
156 {
157         // use the compare_ascii_no_case instead of compare_no_case,
158         // because in turkish, 'i' is not the lowercase version of 'I',
159         // and thus turkish locale breaks parsing of tags.
160         int const i = compare_ascii_no_case(a.From->prettyname(),
161                                             b.From->prettyname());
162         if (i == 0)
163                 return compare_ascii_no_case(a.To->prettyname(),
164                                              b.To->prettyname()) < 0;
165         else
166                 return i < 0;
167 }
168
169
170 Converter const * Converters::getConverter(string const & from,
171                                             string const & to) const
172 {
173         ConverterList::const_iterator const cit =
174                 find_if(converterlist_.begin(), converterlist_.end(),
175                         ConverterEqual(from, to));
176         if (cit != converterlist_.end())
177                 return &(*cit);
178         else
179                 return 0;
180 }
181
182
183 int Converters::getNumber(string const & from, string const & to) const
184 {
185         ConverterList::const_iterator const cit =
186                 find_if(converterlist_.begin(), converterlist_.end(),
187                         ConverterEqual(from, to));
188         if (cit != converterlist_.end())
189                 return distance(converterlist_.begin(), cit);
190         else
191                 return -1;
192 }
193
194
195 void Converters::add(string const & from, string const & to,
196                      string const & command, string const & flags)
197 {
198         formats.add(from);
199         formats.add(to);
200         ConverterList::iterator it = find_if(converterlist_.begin(),
201                                              converterlist_.end(),
202                                              ConverterEqual(from , to));
203
204         Converter converter(from, to, command, flags);
205         if (it != converterlist_.end() && !flags.empty() && flags[0] == '*') {
206                 converter = *it;
207                 converter.command = command;
208                 converter.flags = flags;
209         }
210         converter.readFlags();
211
212         if (converter.latex && (latex_command_.empty() || to == "dvi"))
213                 latex_command_ = subst(command, token_from, "");
214         // If we have both latex & pdflatex, we set latex_command to latex.
215         // The latex_command is used to update the .aux file when running
216         // a converter that uses it.
217
218         if (it == converterlist_.end()) {
219                 converterlist_.push_back(converter);
220         } else {
221                 converter.From = it->From;
222                 converter.To = it->To;
223                 *it = converter;
224         }
225 }
226
227
228 void Converters::erase(string const & from, string const & to)
229 {
230         ConverterList::iterator const it =
231                 find_if(converterlist_.begin(),
232                         converterlist_.end(),
233                         ConverterEqual(from, to));
234         if (it != converterlist_.end())
235                 converterlist_.erase(it);
236 }
237
238
239 // This method updates the pointers From and To in all the converters.
240 // The code is not very efficient, but it doesn't matter as the number
241 // of formats and converters is small.
242 // Furthermore, this method is called only on startup, or after
243 // adding/deleting a format in FormPreferences (the latter calls can be
244 // eliminated if the formats in the Formats class are stored using a map or
245 // a list (instead of a vector), but this will cause other problems).
246 void Converters::update(Formats const & formats)
247 {
248         ConverterList::iterator it = converterlist_.begin();
249         ConverterList::iterator end = converterlist_.end();
250         for (; it != end; ++it) {
251                 it->From = formats.getFormat(it->from);
252                 it->To = formats.getFormat(it->to);
253         }
254 }
255
256
257 // This method updates the pointers From and To in the last converter.
258 // It is called when adding a new converter in FormPreferences
259 void Converters::updateLast(Formats const & formats)
260 {
261         if (converterlist_.begin() != converterlist_.end()) {
262                 ConverterList::iterator it = converterlist_.end() - 1;
263                 it->From = formats.getFormat(it->from);
264                 it->To = formats.getFormat(it->to);
265         }
266 }
267
268
269 void Converters::sort()
270 {
271         std::sort(converterlist_.begin(), converterlist_.end());
272 }
273
274
275 OutputParams::FLAVOR Converters::getFlavor(Graph::EdgePath const & path)
276 {
277         for (Graph::EdgePath::const_iterator cit = path.begin();
278              cit != path.end(); ++cit) {
279                 Converter const & conv = converterlist_[*cit];
280                 if (conv.latex)
281                         if (contains(conv.to, "pdf"))
282                                 return OutputParams::PDFLATEX;
283                 if (conv.xml)
284                         return OutputParams::XML;
285         }
286         return OutputParams::LATEX;
287 }
288
289
290 bool Converters::convert(Buffer const * buffer,
291                          FileName const & from_file, FileName const & to_file,
292                          FileName const & orig_from,
293                          string const & from_format, string const & to_format,
294                          ErrorList & errorList, int conversionflags)
295 {
296         if (from_format == to_format)
297                 return move(from_format, from_file, to_file, false);
298
299         if ((conversionflags & try_cache) &&
300             ConverterCache::get().inCache(orig_from, to_format))
301                 return ConverterCache::get().copy(orig_from, to_format, to_file);
302
303         Graph::EdgePath edgepath = getPath(from_format, to_format);
304         if (edgepath.empty()) {
305                 if (conversionflags & try_default) {
306                         // if no special converter defined, then we take the
307                         // default one from ImageMagic.
308                         string const from_ext = from_format.empty() ?
309                                 getExtension(from_file.absFilename()) :
310                                 formats.extension(from_format);
311                         string const to_ext = formats.extension(to_format);
312                         string const command =
313                                 support::os::python() + ' ' +
314                                 quoteName(libFileSearch("scripts", "convertDefault.py").toFilesystemEncoding()) +
315                                 ' ' +
316                                 quoteName(from_ext + ':' + from_file.toFilesystemEncoding()) +
317                                 ' ' +
318                                 quoteName(to_ext + ':' + to_file.toFilesystemEncoding());
319                         LYXERR(Debug::FILES)
320                                 << "No converter defined! "
321                                    "I use convertDefault.py:\n\t"
322                                 << command << endl;
323                         Systemcall one;
324                         one.startscript(Systemcall::Wait, command);
325                         if (to_file.isFileReadable()) {
326                                 if (conversionflags & try_cache)
327                                         ConverterCache::get().add(orig_from,
328                                                         to_format, to_file);
329                                 return true;
330                         }
331                 }
332                 Alert::error(_("Cannot convert file"),
333                              bformat(_("No information for converting %1$s "
334                                                     "format files to %2$s.\n"
335                                                     "Define a converter in the preferences."),
336                                                         from_ascii(from_format), from_ascii(to_format)));
337                 return false;
338         }
339
340         // buffer is only invalid for importing, and then runparams is not
341         // used anyway.
342         OutputParams runparams(buffer ? &buffer->params().encoding() : 0);
343         runparams.flavor = getFlavor(edgepath);
344
345         // Some converters (e.g. lilypond) can only output files to the
346         // current directory, so we need to change the current directory.
347         // This has the added benefit that all other files that may be
348         // generated by the converter are deleted when LyX closes and do not
349         // clutter the real working directory.
350         string const path(onlyPath(from_file.absFilename()));
351         // Prevent the compiler from optimizing away p
352         FileName pp(path);
353         support::Path p(pp);
354
355         // empty the error list before any new conversion takes place.
356         errorList.clear();
357
358         bool run_latex = false;
359         string from_base = changeExtension(from_file.absFilename(), "");
360         string to_base = changeExtension(to_file.absFilename(), "");
361         FileName infile;
362         FileName outfile = from_file;
363         for (Graph::EdgePath::const_iterator cit = edgepath.begin();
364              cit != edgepath.end(); ++cit) {
365                 Converter const & conv = converterlist_[*cit];
366                 bool dummy = conv.To->dummy() && conv.to != "program";
367                 if (!dummy) {
368                         LYXERR(Debug::FILES) << "Converting from  "
369                                << conv.from << " to " << conv.to << endl;
370                 }
371                 infile = outfile;
372                 outfile = FileName(conv.result_dir.empty()
373                         ? changeExtension(from_file.absFilename(), conv.To->extension())
374                         : addName(subst(conv.result_dir,
375                                         token_base, from_base),
376                                   subst(conv.result_file,
377                                         token_base, onlyFilename(from_base))));
378
379                 // if input and output files are equal, we use a
380                 // temporary file as intermediary (JMarc)
381                 FileName real_outfile;
382                 if (outfile == infile) {
383                         real_outfile = infile;
384                         // when importing, a buffer does not necessarily exist
385                         if (buffer)
386                                 outfile = FileName(addName(buffer->temppath(), "tmpfile.out"));
387                         else
388                                 outfile = FileName(addName(package().temp_dir().absFilename(),
389                                                    "tmpfile.out"));
390                 }
391
392                 if (conv.latex) {
393                         run_latex = true;
394                         string const command = subst(conv.command, token_from, "");
395                         LYXERR(Debug::FILES) << "Running " << command << endl;
396                         if (!runLaTeX(*buffer, command, runparams, errorList))
397                                 return false;
398                 } else {
399                         if (conv.need_aux && !run_latex
400                             && !latex_command_.empty()) {
401                                 LYXERR(Debug::FILES)
402                                         << "Running " << latex_command_
403                                         << " to update aux file"<<  endl;
404                                 runLaTeX(*buffer, latex_command_, runparams, errorList);
405                         }
406
407                         // FIXME UNICODE
408                         string const infile2 = 
409                                 to_utf8(makeRelPath(from_utf8(infile.absFilename()), from_utf8(path)));
410                         string const outfile2 = 
411                                 to_utf8(makeRelPath(from_utf8(outfile.absFilename()), from_utf8(path)));
412
413                         string command = conv.command;
414                         command = subst(command, token_from, quoteName(infile2));
415                         command = subst(command, token_base, quoteName(from_base));
416                         command = subst(command, token_to, quoteName(outfile2));
417                         command = libScriptSearch(command);
418
419                         if (!conv.parselog.empty())
420                                 command += " 2> " + quoteName(infile2 + ".out");
421
422                         if (conv.from == "dvi" && conv.to == "ps")
423                                 command = add_options(command,
424                                                       buffer->params().dvips_options());
425                         else if (conv.from == "dvi" && prefixIs(conv.to, "pdf"))
426                                 command = add_options(command,
427                                                       dvipdfm_options(buffer->params()));
428
429                         LYXERR(Debug::FILES) << "Calling " << command << endl;
430                         if (buffer)
431                                 buffer->message(_("Executing command: ")
432                                 + from_utf8(command));
433
434                         Systemcall one;
435                         int res;
436                         if (dummy) {
437                                 res = one.startscript(Systemcall::DontWait,
438                                         to_filesystem8bit(from_utf8(command)));
439                                 // We're not waiting for the result, so we can't do anything
440                                 // else here.
441                         } else {
442                                 res = one.startscript(Systemcall::Wait,
443                                                 to_filesystem8bit(from_utf8(command)));
444                                 if (!real_outfile.empty()) {
445                                         Mover const & mover = getMover(conv.to);
446                                         if (!mover.rename(outfile, real_outfile))
447                                                 res = -1;
448                                         else
449                                                 LYXERR(Debug::FILES)
450                                                         << "renaming file " << outfile
451                                                         << " to " << real_outfile
452                                                         << endl;
453                                         // Finally, don't forget to tell any future
454                                         // converters to use the renamed file...
455                                         outfile = real_outfile;
456                                 }
457   
458                                 if (!conv.parselog.empty()) {
459                                         string const logfile =  infile2 + ".log";
460                                         string const script = libScriptSearch(conv.parselog);
461                                         string const command2 = script +
462                                                 " < " + quoteName(infile2 + ".out") +
463                                                 " > " + quoteName(logfile);
464                                         one.startscript(Systemcall::Wait,
465                                                 to_filesystem8bit(from_utf8(command2)));
466                                         if (!scanLog(*buffer, command, makeAbsPath(logfile, path), errorList))
467                                                 return false;
468                                 }
469                         }
470
471                         if (res) {
472                                 if (conv.to == "program") {
473                                         Alert::error(_("Build errors"),
474                                                 _("There were errors during the build process."));
475                                 } else {
476 // FIXME: this should go out of here. For example, here we cannot say if
477 // it is a document (.lyx) or something else. Same goes for elsewhere.
478                                         Alert::error(_("Cannot convert file"),
479                                                 bformat(_("An error occurred whilst running %1$s"),
480                                                 from_utf8(command.substr(0, 50))));
481                                 }
482                                 return false;
483                         }
484                 }
485         }
486
487         Converter const & conv = converterlist_[edgepath.back()];
488         if (conv.To->dummy())
489                 return true;
490
491         if (!conv.result_dir.empty()) {
492                 // The converter has put the file(s) in a directory.
493                 // In this case we ignore the given to_file.
494                 if (from_base != to_base) {
495                         string const from = subst(conv.result_dir,
496                                             token_base, from_base);
497                         string const to = subst(conv.result_dir,
498                                           token_base, to_base);
499                         Mover const & mover = getMover(conv.from);
500                         if (!mover.rename(FileName(from), FileName(to))) {
501                                 Alert::error(_("Cannot convert file"),
502                                         bformat(_("Could not move a temporary directory from %1$s to %2$s."),
503                                                 from_utf8(from), from_utf8(to)));
504                                 return false;
505                         }
506                 }
507                 return true;
508         } else {
509                 if (conversionflags & try_cache)
510                         ConverterCache::get().add(orig_from, to_format, outfile);
511                 return move(conv.to, outfile, to_file, conv.latex);
512         }
513 }
514
515
516 bool Converters::move(string const & fmt,
517                       FileName const & from, FileName const & to, bool copy)
518 {
519         if (from == to)
520                 return true;
521
522         bool no_errors = true;
523         string const path = onlyPath(from.absFilename());
524         string const base = onlyFilename(removeExtension(from.absFilename()));
525         string const to_base = removeExtension(to.absFilename());
526         string const to_extension = getExtension(to.absFilename());
527
528         vector<FileName> const files = dirList(FileName(path),
529                         getExtension(from.absFilename()));
530         for (vector<FileName>::const_iterator it = files.begin();
531              it != files.end(); ++it) {
532                 string const from2 = it->absFilename();
533                 string const file2 = onlyFilename(from2);
534                 if (prefixIs(file2, base)) {
535                         string const to2 = changeExtension(
536                                 to_base + file2.substr(base.length()),
537                                 to_extension);
538                         LYXERR(Debug::FILES) << "moving " << from2
539                                              << " to " << to2 << endl;
540
541                         Mover const & mover = getMover(fmt);
542                         bool const moved = copy
543                                 ? mover.copy(*it, FileName(to2))
544                                 : mover.rename(*it, FileName(to2));
545                         if (!moved && no_errors) {
546                                 Alert::error(_("Cannot convert file"),
547                                         bformat(copy ?
548                                                 _("Could not copy a temporary file from %1$s to %2$s.") :
549                                                 _("Could not move a temporary file from %1$s to %2$s."),
550                                                 from_utf8(from2), from_utf8(to2)));
551                                 no_errors = false;
552                         }
553                 }
554         }
555         return no_errors;
556 }
557
558
559 bool Converters::formatIsUsed(string const & format)
560 {
561         ConverterList::const_iterator cit = converterlist_.begin();
562         ConverterList::const_iterator end = converterlist_.end();
563         for (; cit != end; ++cit) {
564                 if (cit->from == format || cit->to == format)
565                         return true;
566         }
567         return false;
568 }
569
570
571 bool Converters::scanLog(Buffer const & buffer, string const & /*command*/,
572                          FileName const & filename, ErrorList & errorList)
573 {
574         OutputParams runparams(0);
575         runparams.flavor = OutputParams::LATEX;
576         LaTeX latex("", runparams, filename);
577         TeXErrors terr;
578         int const result = latex.scanLogFile(terr);
579
580         if (result & LaTeX::ERRORS)
581                 buffer.bufferErrors(terr, errorList);
582
583         return true;
584 }
585
586
587 namespace {
588
589 class ShowMessage
590         : public boost::signals::trackable {
591 public:
592         ShowMessage(Buffer const & b) : buffer_(b) {}
593         void operator()(docstring const & msg) const { buffer_.message(msg); }
594 private:
595         Buffer const & buffer_;
596 };
597
598 }
599
600
601 bool Converters::runLaTeX(Buffer const & buffer, string const & command,
602                           OutputParams const & runparams, ErrorList & errorList)
603 {
604         buffer.setBusy(true);
605         buffer.message(_("Running LaTeX..."));
606
607         runparams.document_language = buffer.params().language->babel();
608
609         // do the LaTeX run(s)
610         string const name = buffer.latexName();
611         LaTeX latex(command, runparams, FileName(makeAbsPath(name)));
612         TeXErrors terr;
613         ShowMessage show(buffer);
614         latex.message.connect(show);
615         int const result = latex.run(terr);
616
617         if (result & LaTeX::ERRORS)
618                 buffer.bufferErrors(terr, errorList);
619
620         // check return value from latex.run().
621         if ((result & LaTeX::NO_LOGFILE)) {
622                 docstring const str =
623                         bformat(_("LaTeX did not run successfully. "
624                                                "Additionally, LyX could not locate "
625                                                "the LaTeX log %1$s."), from_utf8(name));
626                 Alert::error(_("LaTeX failed"), str);
627         } else if (result & LaTeX::NO_OUTPUT) {
628                 Alert::warning(_("Output is empty"),
629                                _("An empty output file was generated."));
630         }
631
632
633         buffer.setBusy(false);
634
635         int const ERROR_MASK =
636                         LaTeX::NO_LOGFILE |
637                         LaTeX::ERRORS |
638                         LaTeX::NO_OUTPUT;
639
640         return (result & ERROR_MASK) == 0;
641
642 }
643
644
645
646 void Converters::buildGraph()
647 {
648         G_.init(formats.size());
649         ConverterList::iterator beg = converterlist_.begin();
650         ConverterList::iterator const end = converterlist_.end();
651         for (ConverterList::iterator it = beg; it != end ; ++it) {
652                 int const s = formats.getNumber(it->from);
653                 int const t = formats.getNumber(it->to);
654                 G_.addEdge(s,t);
655         }
656 }
657
658
659 std::vector<Format const *> const
660 Converters::intToFormat(std::vector<int> const & input)
661 {
662         vector<Format const *> result(input.size());
663
664         vector<int>::const_iterator it = input.begin();
665         vector<int>::const_iterator const end = input.end();
666         vector<Format const *>::iterator rit = result.begin();
667         for ( ; it != end; ++it, ++rit) {
668                 *rit = &formats.get(*it);
669         }
670         return result;
671 }
672
673
674 vector<Format const *> const
675 Converters::getReachableTo(string const & target, bool const clear_visited)
676 {
677         vector<int> const & reachablesto =
678                 G_.getReachableTo(formats.getNumber(target), clear_visited);
679
680         return intToFormat(reachablesto);
681 }
682
683
684 vector<Format const *> const
685 Converters::getReachable(string const & from, bool const only_viewable,
686                          bool const clear_visited)
687 {
688         vector<int> const & reachables =
689                 G_.getReachable(formats.getNumber(from),
690                                 only_viewable,
691                                 clear_visited);
692
693         return intToFormat(reachables);
694 }
695
696
697 bool Converters::isReachable(string const & from, string const & to)
698 {
699         return G_.isReachable(formats.getNumber(from),
700                               formats.getNumber(to));
701 }
702
703
704 Graph::EdgePath Converters::getPath(string const & from, string const & to)
705 {
706         return G_.getPath(formats.getNumber(from),
707                           formats.getNumber(to));
708 }
709
710
711 vector<Format const *> Converters::importableFormats()
712 {
713         vector<string> l = loaders();
714         vector<Format const *> result = getReachableTo(l[0], true);
715         for (vector<string>::const_iterator it = l.begin() + 1;
716              it != l.end(); ++it) {
717                 vector<Format const *> r = getReachableTo(*it, false);
718                 result.insert(result.end(), r.begin(), r.end());
719         }
720         return result;
721 }
722
723
724 vector<string> Converters::loaders() const
725 {
726         vector<string> v;
727         v.push_back("lyx");
728         v.push_back("text");
729         v.push_back("textparagraph");
730         return v;
731 }
732
733
734 } // namespace lyx