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