]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
Asymptotic approach to a well-designed graphics loader.
[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 <a.leeming@ic.ac.uk>
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         to_file_ = ChangeExtension(to_file_base, formats.extension(to_format));
154
155         // The command needed to run the conversion process
156         // We create a dummy command for ease of understanding of the
157         // list of forked processes.
158         // Note that 'sh ' is absolutely essential, or execvp will fail.
159         script_command_ = "sh " + script_file_ + " " +
160                           OnlyFilename(from_file) + " " + to_format;
161
162         // All is ready to go
163         valid_process_ = true;
164 }
165
166
167 void Converter::Impl::startConversion()
168 {
169         if (!valid_process_) {
170                 converted(string(), 0, 1);
171                 return;
172         }
173                 
174         // Initiate the conversion
175         Forkedcall::SignalTypePtr convert_ptr;
176         convert_ptr.reset(new Forkedcall::SignalType);
177
178         convert_ptr->connect(
179                 boost::bind(&Impl::converted, this, _1, _2, _3));
180
181         Forkedcall call;
182         int retval = call.startscript(script_command_, convert_ptr);
183         if (retval > 0) {
184                 // Unable to even start the script, so clean-up the mess!
185                 converted(string(), 0, 1);
186         }
187 }
188
189
190 void Converter::Impl::converted(string const & /* cmd */,
191                                 pid_t /* pid */, int retval)
192 {
193         if (finished_)
194                 // We're done already!
195                 return;
196
197         finished_ = true;
198         // Clean-up behind ourselves
199         lyx::unlink(script_file_);
200
201         if (retval > 0) {
202                 lyx::unlink(to_file_);
203                 to_file_.erase();
204                 parent_.finishedConversion(false);
205         } else {
206                 parent_.finishedConversion(true);
207         }
208 }
209
210 } // namespace grfx
211
212 namespace {
213
214 string const move_file(string const & from_file, string const & to_file)
215 {
216         if (from_file == to_file)
217                 return string();
218
219         ostringstream command;
220         command << "fromfile=" << from_file << "\n"
221                 << "tofile="   << to_file << "\n\n"
222                 << "'mv' -f ${fromfile} ${tofile}\n"
223                 << "if [ $? -ne 0 ]; then\n"
224                 << "\t'cp' -f ${fromfile} ${tofile}\n"
225                 << "\tif [ $? -ne 0 ]; then\n"
226                 << "\t\texit 1\n"
227                 << "\tfi\n"
228                 << "\t'rm' -f ${fromfile}\n"
229                 << "fi\n";
230
231         return command.str().c_str();
232 }
233
234 bool build_script(string const & from_file,
235                   string const & to_file_base,
236                   string const & from_format,
237                   string const & to_format,
238                   ostringstream & script)
239 {
240         lyxerr[Debug::GRAPHICS] << "build_script ... ";
241         typedef Converters::EdgePath EdgePath;
242
243         string const to_file = ChangeExtension(to_file_base,
244                                                formats.extension(to_format));
245
246         if (from_format == to_format) {
247                 script << move_file(QuoteName(from_file), QuoteName(to_file));
248                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
249                 return true;
250         }
251
252         EdgePath edgepath = converters.getPath(from_format, to_format);
253
254         if (edgepath.empty()) {
255                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
256                 return false;
257         }
258
259         // Create a temporary base file-name for all intermediate steps.
260         // Remember to remove the temp file because we only want the name...
261         static int counter = 0;
262         string const tmp = "gconvert" + tostr(counter++);
263         string const to_base = lyx::tempName(string(), tmp);
264         lyx::unlink(to_base);
265
266         string outfile = from_file;
267
268         // The conversion commands may contain these tokens that need to be
269         // changed to infile, infile_base, outfile respectively.
270         string const token_from("$$i");
271         string const token_base("$$b");
272         string const token_to("$$o");
273
274         EdgePath::const_iterator it  = edgepath.begin();
275         EdgePath::const_iterator end = edgepath.end();
276         for (; it != end; ++it) {
277                 ::Converter const & conv = converters.get(*it);
278
279                 // Build the conversion command
280                 string const infile      = outfile;
281                 string const infile_base = ChangeExtension(infile, string());
282                 outfile = ChangeExtension(to_base, conv.To->extension());
283
284                 // Store these names in the shell script
285                 script << "infile="      << QuoteName(infile) << '\n'
286                        << "infile_base=" << QuoteName(infile_base) << '\n'
287                        << "outfile="     << QuoteName(outfile) << '\n';
288
289                 string command = conv.command;
290                 command = subst(command, token_from, "${infile}");
291                 command = subst(command, token_base, "${infile_base}");
292                 command = subst(command, token_to,   "${outfile}");
293
294                 // Store in the shell script
295                 script << "\n" << command << "\n\n";
296
297                 // Test that this was successful. If not, remove
298                 // ${outfile} and exit the shell script
299                 script << "if [ $? -ne 0 ]; then\n"
300                        << "\t'rm' -f ${outfile}\n"
301                        << "\texit 1\n"
302                        << "fi\n\n";
303
304                 // Test that the outfile exists.
305                 // ImageMagick's convert will often create ${outfile}.0,
306                 // ${outfile}.1.
307                 // If this occurs, move ${outfile}.0 to ${outfile}
308                 // and delete ${outfile}.?
309                 script << "if [ ! -f ${outfile} ]; then\n"
310                        << "\tif [ -f ${outfile}.0 ]; then\n"
311                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
312                        << "\t\t'rm' -f ${outfile}.?\n"
313                        << "\telse\n"
314                        << "\t\texit 1\n"
315                        << "\tfi\n"
316                        << "fi\n\n";
317
318                 // Delete the infile, if it isn't the original, from_file.
319                 if (infile != from_file) {
320                         script << "'rm' -f ${infile}\n\n";
321                 }
322         }
323
324         // Move the final outfile to to_file
325         script << move_file("${outfile}", QuoteName(to_file));
326         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
327
328         return true;
329 }
330  
331 } // namespace anon