]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
Alfredo's forkedcall queue.
[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 #include "GraphicsConverter.h"
14
15 #include "converter.h"
16 #include "debug.h"
17
18 #include "support/filetools.h"
19 #include "support/forkedcall.h"
20 #include "support/forkedcallqueue.h"
21 #include "support/lyxlib.h"
22
23 #include <boost/bind.hpp>
24 #include <boost/signals/trackable.hpp>
25
26 #include "Lsstream.h"
27 #include "support/LOstream.h"
28 #include <fstream>
29 #include <sys/types.h> // needed for pid_t
30
31 using std::endl;
32 using std::ostream;
33
34 namespace grfx {
35
36 struct Converter::Impl : public boost::signals::trackable {
37         ///
38         Impl(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(pid_t pid, int retval);
49
50         /** At the end of the conversion process inform the outside world
51          *  by emitting a signal.
52          */
53         typedef boost::signal1<void, bool> SignalType;
54         ///
55         SignalType finishedConversion;
56
57         ///
58         string script_command_;
59         ///
60         string script_file_;
61         ///
62         string to_file_;
63         ///
64         bool valid_process_;
65         ///
66         bool finished_;
67 };
68
69
70 bool Converter::isReachable(string const & from_format_name,
71                             string const & to_format_name)
72 {
73         return converters.isReachable(from_format_name, to_format_name);
74 }
75
76
77 Converter::Converter(string const & from_file,   string const & to_file_base,
78                      string const & from_format, string const & to_format)
79         : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
80 {}
81
82
83 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
84 Converter::~Converter()
85 {}
86
87
88 void Converter::startConversion() const
89 {
90         pimpl_->startConversion();
91 }
92
93
94 boost::signals::connection Converter::connect(slot_type const & slot) const
95 {
96         return pimpl_->finishedConversion.connect(slot);
97 }
98
99
100 string const & Converter::convertedFile() const
101 {
102         static string const empty;
103         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
104 }
105
106 } // namespace grfx
107
108 //------------------------------
109 // Implementation details follow
110 //------------------------------
111
112 namespace {
113
114 /** Build the conversion script, returning true if able to build it.
115  *  The script is output to the ostringstream 'script'.
116  */
117 bool build_script(string const & from_file, string const & to_file_base,
118                   string const & from_format, string const & to_format,
119                   ostream & script);
120
121 } // namespace anon
122
123
124 namespace grfx {
125
126 Converter::Impl::Impl(string const & from_file,   string const & to_file_base,
127                       string const & from_format, string const & to_format)
128         : valid_process_(false), finished_(false)
129 {
130         lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
131                 << "\tfrom_file:      " << from_file
132                 << "\n\tto_file_base: " << to_file_base
133                 << "\n\tfrom_format:  " << from_format
134                 << "\n\tto_format:    " << to_format << endl;
135
136         // The converted image is to be stored in this file (we do not
137         // use ChangeExtension because this is a basename which may
138         // nevertheless contain a '.')
139         to_file_ = 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                                 << STRCONV(script.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 << STRCONV(script.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(0, 1);
192                 return;
193         }
194
195         Forkedcall::SignalTypePtr 
196                 ptr = ForkedCallQueue::get().add(script_command_);
197
198         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
199
200 }
201
202 void Converter::Impl::converted(pid_t /* pid */, int retval)
203 {
204         if (finished_)
205                 // We're done already!
206                 return;
207
208         finished_ = true;
209         // Clean-up behind ourselves
210         lyx::unlink(script_file_);
211
212         if (retval > 0) {
213                 lyx::unlink(to_file_);
214                 to_file_.erase();
215                 finishedConversion(false);
216         } else {
217                 finishedConversion(true);
218         }
219 }
220
221 } // namespace grfx
222
223 namespace {
224
225 string const move_file(string const & from_file, string const & to_file)
226 {
227         if (from_file == to_file)
228                 return string();
229
230         ostringstream command;
231         command << "fromfile=" << from_file << "\n"
232                 << "tofile="   << to_file << "\n\n"
233                 << "'mv' -f ${fromfile} ${tofile} ||\n"
234                 << "{\n"
235                 << "\t'cp' -f ${fromfile} ${tofile} ||\n"
236                 << "\t{\n"
237                 << "\t\texit 1\n"
238                 << "\t}\n"
239                 << "\t'rm' -f ${fromfile}\n"
240                 << "}\n";
241
242         return STRCONV(command.str());
243 }
244
245
246 bool build_script(string const & from_file,
247                   string const & to_file_base,
248                   string const & from_format,
249                   string const & to_format,
250                   ostream & script)
251 {
252         lyxerr[Debug::GRAPHICS] << "build_script ... ";
253         typedef Converters::EdgePath EdgePath;
254
255         // we do not use ChangeExtension because this is a basename
256         // which may nevertheless contain a '.'
257         string const to_file = to_file_base + '.'
258                 + formats.extension(to_format);
259
260         if (from_format == to_format) {
261                 script << move_file(QuoteName(from_file), QuoteName(to_file));
262                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
263                 return true;
264         }
265
266         EdgePath edgepath = converters.getPath(from_format, to_format);
267
268         if (edgepath.empty()) {
269                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
270                 return false;
271         }
272
273         // Create a temporary base file-name for all intermediate steps.
274         // Remember to remove the temp file because we only want the name...
275         static int counter = 0;
276         string const tmp = "gconvert" + tostr(counter++);
277         string const to_base = lyx::tempName(string(), tmp);
278         lyx::unlink(to_base);
279
280         string outfile = from_file;
281
282         // The conversion commands may contain these tokens that need to be
283         // changed to infile, infile_base, outfile respectively.
284         string const token_from("$$i");
285         string const token_base("$$b");
286         string const token_to("$$o");
287
288         EdgePath::const_iterator it  = edgepath.begin();
289         EdgePath::const_iterator end = edgepath.end();
290
291         for (; it != end; ++it) {
292                 ::Converter const & conv = converters.get(*it);
293
294                 // Build the conversion command
295                 string const infile      = outfile;
296                 string const infile_base = ChangeExtension(infile, string());
297                 outfile = ChangeExtension(to_base, conv.To->extension());
298
299                 // Store these names in the shell script
300                 script << "infile="      << QuoteName(infile) << '\n'
301                        << "infile_base=" << QuoteName(infile_base) << '\n'
302                        << "outfile="     << QuoteName(outfile) << '\n';
303
304                 string command = conv.command;
305                 command = subst(command, token_from, "${infile}");
306                 command = subst(command, token_base, "${infile_base}");
307                 command = subst(command, token_to,   "${outfile}");
308                 command = LibScriptSearch(command);
309
310                 // Store in the shell script
311                 script << "\n" << command << " ||\n";
312
313                 // Test that this was successful. If not, remove
314                 // ${outfile} and exit the shell script
315                 script << "{\n"
316                        << "\t'rm' -f ${outfile}\n"
317                        << "\texit 1\n"
318                        << "}\n\n";
319
320                 // Test that the outfile exists.
321                 // ImageMagick's convert will often create ${outfile}.0,
322                 // ${outfile}.1.
323                 // If this occurs, move ${outfile}.0 to ${outfile}
324                 // and delete ${outfile}.?
325                 script << "if [ ! -f ${outfile} ]; then\n"
326                        << "\tif [ -f ${outfile}.0 ]; then\n"
327                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
328                        << "\t\t'rm' -f ${outfile}.?\n"
329                        << "\telse\n"
330                        << "\t\texit 1\n"
331                        << "\tfi\n"
332                        << "fi\n\n";
333
334                 // Delete the infile, if it isn't the original, from_file.
335                 if (infile != from_file) {
336                         script << "'rm' -f ${infile}\n\n";
337                 }
338         }
339
340         // Move the final outfile to to_file
341         script << move_file("${outfile}", QuoteName(to_file));
342         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
343
344         return true;
345 }
346
347 } // namespace anon