]> git.lyx.org Git - features.git/blob - src/graphics/GraphicsConverter.C
7f32d30ffcc7b243e10393a4770d7ff3a76fc4af
[features.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(string const & cmd, 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(string(), 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, _3));
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(string(), 0, 1);
210         }
211 }
212
213
214 void Converter::Impl::converted(string const & /* cmd */,
215                                 pid_t /* pid */, int retval)
216 {
217         if (finished_)
218                 // We're done already!
219                 return;
220
221         finished_ = true;
222         // Clean-up behind ourselves
223         lyx::unlink(script_file_);
224
225         if (retval > 0) {
226                 lyx::unlink(to_file_);
227                 to_file_.erase();
228                 finishedConversion(false);
229         } else {
230                 finishedConversion(true);
231         }
232 }
233
234 } // namespace grfx
235
236 namespace {
237
238 string const move_file(string const & from_file, string const & to_file)
239 {
240         if (from_file == to_file)
241                 return string();
242
243         ostringstream command;
244         command << "fromfile=" << from_file << "\n"
245                 << "tofile="   << to_file << "\n\n"
246                 << "'mv' -f ${fromfile} ${tofile}\n"
247                 << "if [ $? -ne 0 ]; then\n"
248                 << "\t'cp' -f ${fromfile} ${tofile}\n"
249                 << "\tif [ $? -ne 0 ]; then\n"
250                 << "\t\texit 1\n"
251                 << "\tfi\n"
252                 << "\t'rm' -f ${fromfile}\n"
253                 << "fi\n";
254
255         return command.str().c_str();
256 }
257
258
259 bool build_script(string const & from_file,
260                   string const & to_file_base,
261                   string const & from_format,
262                   string const & to_format,
263                   ostream & script)
264 {
265         lyxerr[Debug::GRAPHICS] << "build_script ... ";
266         typedef Converters::EdgePath EdgePath;
267
268         // we do not use ChangeExtension because this is a basename
269         // which may nevertheless contain a '.'
270         string const to_file = to_file_base + '.'
271                 + formats.extension(to_format);
272
273         if (from_format == to_format) {
274                 script << move_file(QuoteName(from_file), QuoteName(to_file));
275                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
276                 return true;
277         }
278
279         EdgePath edgepath = converters.getPath(from_format, to_format);
280
281         if (edgepath.empty()) {
282                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
283                 return false;
284         }
285
286         // Create a temporary base file-name for all intermediate steps.
287         // Remember to remove the temp file because we only want the name...
288         static int counter = 0;
289         string const tmp = "gconvert" + tostr(counter++);
290         string const to_base = lyx::tempName(string(), tmp);
291         lyx::unlink(to_base);
292
293         string outfile = from_file;
294
295         // The conversion commands may contain these tokens that need to be
296         // changed to infile, infile_base, outfile respectively.
297         string const token_from("$$i");
298         string const token_base("$$b");
299         string const token_to("$$o");
300
301         EdgePath::const_iterator it  = edgepath.begin();
302         EdgePath::const_iterator end = edgepath.end();
303
304         for (; it != end; ++it) {
305                 ::Converter const & conv = converters.get(*it);
306
307                 // Build the conversion command
308                 string const infile      = outfile;
309                 string const infile_base = ChangeExtension(infile, string());
310                 outfile = ChangeExtension(to_base, conv.To->extension());
311
312                 // Store these names in the shell script
313                 script << "infile="      << QuoteName(infile) << '\n'
314                        << "infile_base=" << QuoteName(infile_base) << '\n'
315                        << "outfile="     << QuoteName(outfile) << '\n';
316
317                 string command = conv.command;
318                 command = subst(command, token_from, "${infile}");
319                 command = subst(command, token_base, "${infile_base}");
320                 command = subst(command, token_to,   "${outfile}");
321                 command = LibScriptSearch(command);
322
323                 // Store in the shell script
324                 script << "\n" << command << "\n\n";
325
326                 // Test that this was successful. If not, remove
327                 // ${outfile} and exit the shell script
328                 script << "if [ $? -ne 0 ]; then\n"
329                        << "\t'rm' -f ${outfile}\n"
330                        << "\texit 1\n"
331                        << "fi\n\n";
332
333                 // Test that the outfile exists.
334                 // ImageMagick's convert will often create ${outfile}.0,
335                 // ${outfile}.1.
336                 // If this occurs, move ${outfile}.0 to ${outfile}
337                 // and delete ${outfile}.?
338                 script << "if [ ! -f ${outfile} ]; then\n"
339                        << "\tif [ -f ${outfile}.0 ]; then\n"
340                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
341                        << "\t\t'rm' -f ${outfile}.?\n"
342                        << "\telse\n"
343                        << "\t\texit 1\n"
344                        << "\tfi\n"
345                        << "fi\n\n";
346
347                 // Delete the infile, if it isn't the original, from_file.
348                 if (infile != from_file) {
349                         script << "'rm' -f ${infile}\n\n";
350                 }
351         }
352
353         // Move the final outfile to to_file
354         script << move_file("${outfile}", QuoteName(to_file));
355         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
356
357         return true;
358 }
359
360 } // namespace anon