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