]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
* Make the graphics files conform strictly to the Pimpl idiom by moving
[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 <leeming@lyx.org>
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 extern string system_lyxdir;
32
33 using std::endl;
34
35 namespace grfx {
36
37 struct Converter::Impl : public boost::signals::trackable {
38         ///
39         Impl(string const &, string const &, string const &, string const &);
40
41         ///
42         void startConversion();
43
44         /** This method is connected to a signal passed to the forked call
45          *  class, passing control back here when the conversion is completed.
46          *  Cleans-up the temporary files, emits the finishedConversion
47          *  signal and removes the Converter from the list of all processes.
48          */
49         void converted(string const & cmd, pid_t pid, int retval);
50
51         /** At the end of the conversion process inform the outside world
52          *  by emitting a signal.
53          */
54         typedef boost::signal1<void, bool> SignalType;
55         ///
56         SignalType finishedConversion;
57
58         ///
59         string script_command_;
60         ///
61         string script_file_;
62         ///
63         string to_file_;
64         ///
65         bool valid_process_;
66         ///
67         bool finished_;
68 };
69
70
71 bool Converter::isReachable(string const & from_format_name,
72                             string const & to_format_name)
73 {
74         return converters.isReachable(from_format_name, to_format_name);
75 }
76
77
78 Converter::Converter(string const & from_file,   string const & to_file_base,
79                      string const & from_format, string const & to_format)
80         : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
81 {}
82
83
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                   ostringstream & 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 conversion commands are stored in a stringstream
137         ostringstream script;
138         script << "#!/bin/sh\n";
139         bool const success = build_script(from_file, to_file_base,
140                                           from_format, to_format, script);
141
142         if (!success)
143                 return;
144
145         lyxerr[Debug::GRAPHICS] << "\tConversion script:"
146                                 << "\n--------------------------------------\n"
147                                 << script.str().c_str()
148                                 << "\n--------------------------------------\n";
149
150         // Output the script to file.
151         static int counter = 0;
152         script_file_ = OnlyPath(to_file_base) + "lyxconvert" +
153                        tostr(counter++) + ".sh";
154
155         std::ofstream fs(script_file_.c_str());
156         if (!fs.good())
157                 return;
158
159         fs << script.str().c_str();
160         fs.close();
161
162         // The converted image is to be stored in this file
163         // We do not use ChangeExtension here because this is a
164         // basename, which may nevertheless contain a dot
165         to_file_ = to_file_base + '.' + formats.extension(to_format);
166
167         // The command needed to run the conversion process
168         // We create a dummy command for ease of understanding of the
169         // list of forked processes.
170         // Note that 'sh ' is absolutely essential, or execvp will fail.
171         script_command_ = "sh " + script_file_ + " " +
172                           OnlyFilename(from_file) + " " + to_format;
173
174         // All is ready to go
175         valid_process_ = true;
176 }
177
178
179 void Converter::Impl::startConversion()
180 {
181         if (!valid_process_) {
182                 converted(string(), 0, 1);
183                 return;
184         }
185
186         // Initiate the conversion
187         Forkedcall::SignalTypePtr convert_ptr;
188         convert_ptr.reset(new Forkedcall::SignalType);
189
190         convert_ptr->connect(
191                 boost::bind(&Impl::converted, this, _1, _2, _3));
192
193         Forkedcall call;
194         int retval = call.startscript(script_command_, convert_ptr);
195         if (retval > 0) {
196                 // Unable to even start the script, so clean-up the mess!
197                 converted(string(), 0, 1);
198         }
199 }
200
201
202 void Converter::Impl::converted(string const & /* cmd */,
203                                 pid_t /* pid */, int retval)
204 {
205         if (finished_)
206                 // We're done already!
207                 return;
208
209         finished_ = true;
210         // Clean-up behind ourselves
211         lyx::unlink(script_file_);
212
213         if (retval > 0) {
214                 lyx::unlink(to_file_);
215                 to_file_.erase();
216                 finishedConversion(false);
217         } else {
218                 finishedConversion(true);
219         }
220 }
221
222 } // namespace grfx
223
224 namespace {
225
226 string const move_file(string const & from_file, string const & to_file)
227 {
228         if (from_file == to_file)
229                 return string();
230
231         ostringstream command;
232         command << "fromfile=" << from_file << "\n"
233                 << "tofile="   << to_file << "\n\n"
234                 << "'mv' -f ${fromfile} ${tofile}\n"
235                 << "if [ $? -ne 0 ]; then\n"
236                 << "\t'cp' -f ${fromfile} ${tofile}\n"
237                 << "\tif [ $? -ne 0 ]; then\n"
238                 << "\t\texit 1\n"
239                 << "\tfi\n"
240                 << "\t'rm' -f ${fromfile}\n"
241                 << "fi\n";
242
243         return command.str().c_str();
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                   ostringstream & script)
251 {
252         lyxerr[Debug::GRAPHICS] << "build_script ... ";
253         typedef Converters::EdgePath EdgePath;
254
255         string const to_file = ChangeExtension(to_file_base,
256                                                formats.extension(to_format));
257
258         if (from_format == to_format) {
259                 script << move_file(QuoteName(from_file), QuoteName(to_file));
260                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
261                 return true;
262         }
263
264         EdgePath edgepath = converters.getPath(from_format, to_format);
265
266         if (edgepath.empty()) {
267                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
268                 return false;
269         }
270
271         // Create a temporary base file-name for all intermediate steps.
272         // Remember to remove the temp file because we only want the name...
273         static int counter = 0;
274         string const tmp = "gconvert" + tostr(counter++);
275         string const to_base = lyx::tempName(string(), tmp);
276         lyx::unlink(to_base);
277
278         string outfile = from_file;
279
280         // The conversion commands may contain these tokens that need to be
281         // changed to infile, infile_base, outfile respectively.
282         string const token_from("$$i");
283         string const token_base("$$b");
284         string const token_to("$$o");
285         string const token_lib("$$s");
286
287         EdgePath::const_iterator it  = edgepath.begin();
288         EdgePath::const_iterator end = edgepath.end();
289
290         for (; it != end; ++it) {
291                 ::Converter const & conv = converters.get(*it);
292
293                 // Build the conversion command
294                 string const infile      = outfile;
295                 string const infile_base = ChangeExtension(infile, string());
296                 outfile = ChangeExtension(to_base, conv.To->extension());
297
298                 // Store these names in the shell script
299                 script << "infile="      << QuoteName(infile) << '\n'
300                        << "infile_base=" << QuoteName(infile_base) << '\n'
301                        << "outfile="     << QuoteName(outfile) << '\n';
302
303                 string command = conv.command;
304                 command = subst(command, token_from, "${infile}");
305                 command = subst(command, token_base, "${infile_base}");
306                 command = subst(command, token_to,   "${outfile}");
307                 command = subst(command, token_lib,  system_lyxdir + "scripts");
308
309                 // Store in the shell script
310                 script << "\n" << command << "\n\n";
311
312                 // Test that this was successful. If not, remove
313                 // ${outfile} and exit the shell script
314                 script << "if [ $? -ne 0 ]; then\n"
315                        << "\t'rm' -f ${outfile}\n"
316                        << "\texit 1\n"
317                        << "fi\n\n";
318
319                 // Test that the outfile exists.
320                 // ImageMagick's convert will often create ${outfile}.0,
321                 // ${outfile}.1.
322                 // If this occurs, move ${outfile}.0 to ${outfile}
323                 // and delete ${outfile}.?
324                 script << "if [ ! -f ${outfile} ]; then\n"
325                        << "\tif [ -f ${outfile}.0 ]; then\n"
326                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
327                        << "\t\t'rm' -f ${outfile}.?\n"
328                        << "\telse\n"
329                        << "\t\texit 1\n"
330                        << "\tfi\n"
331                        << "fi\n\n";
332
333                 // Delete the infile, if it isn't the original, from_file.
334                 if (infile != from_file) {
335                         script << "'rm' -f ${infile}\n\n";
336                 }
337         }
338
339         // Move the final outfile to to_file
340         script << move_file("${outfile}", QuoteName(to_file));
341         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
342
343         return true;
344 }
345
346 } // namespace anon