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