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