]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
Pedantic change of email only.
[lyx.git] / src / graphics / GraphicsConverter.C
1 /**
2  *  \file GraphicsConverter.C
3  *  Copyright 2002 the LyX Team
4  *  Read the file COPYING
5  *
6  *  \author Angus Leeming <leeming@lyx.org>
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "GraphicsConverter.h"
16
17 #include "converter.h"
18 #include "debug.h"
19
20 #include "support/filetools.h"
21 #include "support/forkedcall.h"
22 #include "support/lyxlib.h"
23
24 #include <boost/bind.hpp>
25 #include <boost/signals/trackable.hpp>
26
27 #include "Lsstream.h"
28 #include <fstream>
29 #include <sys/types.h> // needed for pid_t
30
31 using std::endl;
32
33 namespace grfx {
34
35 struct Converter::Impl : public boost::signals::trackable {
36         ///
37         Impl(Converter &,
38              string const &, string const &, string const &, string const &);
39
40         ///
41         void startConversion();
42
43         /** This method is connected to a signal passed to the forked call
44          *  class, passing control back here when the conversion is completed.
45          *  Cleans-up the temporary files, emits the finishedConversion
46          *  signal and removes the Converter from the list of all processes.
47          */
48         void converted(string const & cmd, pid_t pid, int retval);
49
50         ///
51         string script_command_;
52         ///
53         string script_file_;
54         ///
55         string to_file_;
56         ///
57         Converter & parent_;
58         ///
59         bool valid_process_;
60         ///
61         bool finished_;
62 };
63
64
65 Converter::Converter(string const & from_file,   string const & to_file_base,
66                      string const & from_format, string const & to_format)
67         : pimpl_(new Impl(*this,
68                           from_file, to_file_base, from_format, to_format))
69 {}
70
71
72 Converter::~Converter()
73 {}
74  
75
76 void Converter::startConversion()
77 {
78         pimpl_->startConversion();
79 }
80
81
82 bool Converter::isReachable(string const & from_format_name,
83                             string const & to_format_name)
84 {
85         return converters.isReachable(from_format_name, to_format_name);
86 }
87
88
89 string const & Converter::convertedFile() const
90 {
91         static string const empty;
92         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
93 }
94  
95 } // namespace grfx
96
97 //------------------------------
98 // Implementation details follow
99 //------------------------------
100
101 namespace {
102
103 /** Build the conversion script, returning true if able to build it.
104  *  The script is output to the ostringstream 'script'.
105  */
106 bool build_script(string const & from_file, string const & to_file_base,
107                   string const & from_format, string const & to_format,
108                   ostringstream & script);
109
110 } // namespace anon
111
112
113 namespace grfx {
114
115 Converter::Impl::Impl(Converter & p,
116                       string const & from_file,   string const & to_file_base,
117                       string const & from_format, string const & to_format)
118         : parent_(p), valid_process_(false), finished_(false)
119 {
120         lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
121                 << "\tfrom_file:      " << from_file
122                 << "\n\tto_file_base: " << to_file_base
123                 << "\n\tfrom_format:  " << from_format
124                 << "\n\tto_format:    " << to_format << endl;
125
126         // The conversion commands are stored in a stringstream
127         ostringstream script;
128         script << "#!/bin/sh\n";
129         bool const success = build_script(from_file, to_file_base,
130                                           from_format, to_format, script);
131
132         if (!success)
133                 return;
134
135         lyxerr[Debug::GRAPHICS] << "\tConversion script:"
136                                 << "\n--------------------------------------\n"
137                                 << script.str().c_str() 
138                                 << "\n--------------------------------------\n";
139
140         // Output the script to file.
141         static int counter = 0;
142         script_file_ = OnlyPath(to_file_base) + "lyxconvert" +
143                        tostr(counter++) + ".sh";
144
145         std::ofstream fs(script_file_.c_str());
146         if (!fs.good())
147                 return;
148
149         fs << script.str().c_str();
150         fs.close();
151
152         // The converted image is to be stored in this file
153         // We do not use ChangeExtension here because this is a
154         // basename, which may nevertheless contain a dot
155         to_file_ = to_file_base + '.' + formats.extension(to_format);
156
157         // The command needed to run the conversion process
158         // We create a dummy command for ease of understanding of the
159         // list of forked processes.
160         // Note that 'sh ' is absolutely essential, or execvp will fail.
161         script_command_ = "sh " + script_file_ + " " +
162                           OnlyFilename(from_file) + " " + to_format;
163
164         // All is ready to go
165         valid_process_ = true;
166 }
167
168
169 void Converter::Impl::startConversion()
170 {
171         if (!valid_process_) {
172                 converted(string(), 0, 1);
173                 return;
174         }
175                 
176         // Initiate the conversion
177         Forkedcall::SignalTypePtr convert_ptr;
178         convert_ptr.reset(new Forkedcall::SignalType);
179
180         convert_ptr->connect(
181                 boost::bind(&Impl::converted, this, _1, _2, _3));
182
183         Forkedcall call;
184         int retval = call.startscript(script_command_, convert_ptr);
185         if (retval > 0) {
186                 // Unable to even start the script, so clean-up the mess!
187                 converted(string(), 0, 1);
188         }
189 }
190
191
192 void Converter::Impl::converted(string const & /* cmd */,
193                                 pid_t /* pid */, int retval)
194 {
195         if (finished_)
196                 // We're done already!
197                 return;
198
199         finished_ = true;
200         // Clean-up behind ourselves
201         lyx::unlink(script_file_);
202
203         if (retval > 0) {
204                 lyx::unlink(to_file_);
205                 to_file_.erase();
206                 parent_.finishedConversion(false);
207         } else {
208                 parent_.finishedConversion(true);
209         }
210 }
211
212 } // namespace grfx
213
214 namespace {
215
216 string const move_file(string const & from_file, string const & to_file)
217 {
218         if (from_file == to_file)
219                 return string();
220
221         ostringstream command;
222         command << "fromfile=" << from_file << "\n"
223                 << "tofile="   << to_file << "\n\n"
224                 << "'mv' -f ${fromfile} ${tofile}\n"
225                 << "if [ $? -ne 0 ]; then\n"
226                 << "\t'cp' -f ${fromfile} ${tofile}\n"
227                 << "\tif [ $? -ne 0 ]; then\n"
228                 << "\t\texit 1\n"
229                 << "\tfi\n"
230                 << "\t'rm' -f ${fromfile}\n"
231                 << "fi\n";
232
233         return command.str().c_str();
234 }
235
236 bool build_script(string const & from_file,
237                   string const & to_file_base,
238                   string const & from_format,
239                   string const & to_format,
240                   ostringstream & script)
241 {
242         lyxerr[Debug::GRAPHICS] << "build_script ... ";
243         typedef Converters::EdgePath EdgePath;
244
245         string const to_file = ChangeExtension(to_file_base,
246                                                formats.extension(to_format));
247
248         if (from_format == to_format) {
249                 script << move_file(QuoteName(from_file), QuoteName(to_file));
250                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
251                 return true;
252         }
253
254         EdgePath edgepath = converters.getPath(from_format, to_format);
255
256         if (edgepath.empty()) {
257                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
258                 return false;
259         }
260
261         // Create a temporary base file-name for all intermediate steps.
262         // Remember to remove the temp file because we only want the name...
263         static int counter = 0;
264         string const tmp = "gconvert" + tostr(counter++);
265         string const to_base = lyx::tempName(string(), tmp);
266         lyx::unlink(to_base);
267
268         string outfile = from_file;
269
270         // The conversion commands may contain these tokens that need to be
271         // changed to infile, infile_base, outfile respectively.
272         string const token_from("$$i");
273         string const token_base("$$b");
274         string const token_to("$$o");
275
276         EdgePath::const_iterator it  = edgepath.begin();
277         EdgePath::const_iterator end = edgepath.end();
278         for (; it != end; ++it) {
279                 ::Converter const & conv = converters.get(*it);
280
281                 // Build the conversion command
282                 string const infile      = outfile;
283                 string const infile_base = ChangeExtension(infile, string());
284                 outfile = ChangeExtension(to_base, conv.To->extension());
285
286                 // Store these names in the shell script
287                 script << "infile="      << QuoteName(infile) << '\n'
288                        << "infile_base=" << QuoteName(infile_base) << '\n'
289                        << "outfile="     << QuoteName(outfile) << '\n';
290
291                 string command = conv.command;
292                 command = subst(command, token_from, "${infile}");
293                 command = subst(command, token_base, "${infile_base}");
294                 command = subst(command, token_to,   "${outfile}");
295
296                 // Store in the shell script
297                 script << "\n" << command << "\n\n";
298
299                 // Test that this was successful. If not, remove
300                 // ${outfile} and exit the shell script
301                 script << "if [ $? -ne 0 ]; then\n"
302                        << "\t'rm' -f ${outfile}\n"
303                        << "\texit 1\n"
304                        << "fi\n\n";
305
306                 // Test that the outfile exists.
307                 // ImageMagick's convert will often create ${outfile}.0,
308                 // ${outfile}.1.
309                 // If this occurs, move ${outfile}.0 to ${outfile}
310                 // and delete ${outfile}.?
311                 script << "if [ ! -f ${outfile} ]; then\n"
312                        << "\tif [ -f ${outfile}.0 ]; then\n"
313                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
314                        << "\t\t'rm' -f ${outfile}.?\n"
315                        << "\telse\n"
316                        << "\t\texit 1\n"
317                        << "\tfi\n"
318                        << "fi\n\n";
319
320                 // Delete the infile, if it isn't the original, from_file.
321                 if (infile != from_file) {
322                         script << "'rm' -f ${infile}\n\n";
323                 }
324         }
325
326         // Move the final outfile to to_file
327         script << move_file("${outfile}", QuoteName(to_file));
328         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
329
330         return true;
331 }
332  
333 } // namespace anon