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