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