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