]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
fbf5f6759e1b049366e7eb1e8ae2d906371fc9e5
[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 <a.leeming@ic.ac.uk>
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 #include "gettext.h"
20
21 #include "support/filetools.h"
22 #include "support/forkedcall.h"
23 #include "support/path.h"
24
25 #include <boost/bind.hpp>
26
27 #include <fstream>
28
29 using std::endl;
30
31
32 namespace {
33
34 string const move_file(string const & from_file, string const & to_file)
35 {
36         if (from_file == to_file)
37                 return string();
38
39         ostringstream command;
40         command << "fromfile=" << from_file << "\n"
41                 << "tofile="   << to_file << "\n\n"
42                 << "'mv' -f ${fromfile} ${tofile}\n"
43                 << "if [ $? -ne 0 ]; then\n"
44                 << "\t'cp' -f ${fromfile} ${tofile}\n"
45                 << "\tif [ $? -ne 0 ]; then\n"
46                 << "\t\texit 1\n"
47                 << "\tfi\n"
48                 << "\t'rm' -f ${fromfile}\n"
49                 << "fi\n";
50
51         return command.str().c_str();
52 }
53
54 } // namespace anon
55
56
57 namespace grfx {
58
59 GConverter & GConverter::get()
60 {
61         static GConverter singleton;
62         return singleton;
63 }
64
65
66 bool GConverter::isReachable(string const & from_format_name,
67                              string const & to_format_name) const
68 {
69         return converters.isReachable(from_format_name, to_format_name);
70 }
71
72
73 void GConverter::convert(string const & from_file, string const & to_file_base,
74                          string const & from_format, string const & to_format,
75                          SignalTypePtr on_finish)
76 {
77         lyxerr[Debug::GRAPHICS] << "[GraphicsConverter::convert]\n"
78                 << "\tfrom_file:    " << from_file
79                 << "\n\tto_file_base: " << to_file_base
80                 << "\n\tfrom_format:  " << from_format
81                 << "\n\tto_format:    " << to_format << endl;
82         // The conversion commands are stored in a stringstream
83         ostringstream script;
84         script << "#!/bin/sh\n";
85         string script_command;
86         string script_file;
87
88         bool success = build_script(from_file, to_file_base,
89                                      from_format, to_format, script);
90
91         if (success) {
92                 lyxerr[Debug::GRAPHICS] << "\tConversion script:\n"
93                         << "--------------------------------------\n"
94                         << script.str().c_str() 
95                         << "\n--------------------------------------\n";
96
97                 // Output the script to file.
98                 static int counter = 0;
99                 script_file = OnlyPath(to_file_base) + "lyxconvert" +
100                         tostr(counter++) + ".sh";
101
102                 std::ofstream fs(script_file.c_str());
103                 if (!fs.good()) {
104                         // Unable to output the conversion script to file.
105                         success = false;
106                 } else {
107
108                         fs << script.str().c_str();
109                         fs.close();
110
111                         // Create a dummy command for ease of understanding of the
112                         // list of forked processes.
113                         // Note that 'sh ' is absolutely essential, or execvp will fail.
114                         script_command =
115                                 "sh " + script_file + " " +
116                                 OnlyFilename(from_file) + " " + to_format;
117                 }
118         }
119
120         string const to_file =
121                 ChangeExtension(to_file_base, formats.extension(to_format));
122
123         if (!success) {
124                 script_file = string();
125                 script_command = 
126                         "convert -depth 8 " +
127                         from_format + ':' + from_file + ' ' +
128                         to_format + ':' + to_file;
129                 lyxerr[Debug::GRAPHICS] 
130                         << "\tNo converter defined! I use convert from ImageMagic:\n\t"
131                         << script_command << endl;
132         }       
133
134         // Launch the conversion process.
135         ConvProcessPtr shared_ptr;
136         shared_ptr.reset(new ConvProcess(script_file, script_command,
137                                          to_file, on_finish));
138         all_processes_.push_back(shared_ptr);
139 }
140
141
142 namespace {
143
144 typedef boost::shared_ptr<ConvProcess> ConvProcessPtr;
145
146 class Find_Ptr {
147 public:
148         Find_Ptr(ConvProcess * ptr) : ptr_(ptr) {}
149
150         bool operator()(ConvProcessPtr const & ptr)
151         {
152                 return ptr.get() == ptr_;
153         }
154
155 private:
156         ConvProcess * ptr_;
157 };
158
159 } // namespace anon
160
161
162 void GConverter::erase(ConvProcess * process)
163 {
164         std::list<ConvProcessPtr>::iterator begin = all_processes_.begin();
165         std::list<ConvProcessPtr>::iterator end   = all_processes_.end();
166         std::list<ConvProcessPtr>::iterator it =
167                 std::find_if(begin, end, Find_Ptr(process));
168
169         if (it == end)
170                 return;
171
172         all_processes_.erase(it);
173 }
174
175
176 bool GConverter::build_script(string const & from_file,
177                               string const & to_file_base,
178                               string const & from_format,
179                               string const & to_format,
180                               ostringstream & script) const
181 {
182         lyxerr[Debug::GRAPHICS] << "[GraphicsConverter::build_script] ... ";
183         typedef Converters::EdgePath EdgePath;
184
185         string const to_file = ChangeExtension(to_file_base,
186                                                formats.extension(to_format));
187
188         if (from_format == to_format) {
189                 script << move_file(QuoteName(from_file), QuoteName(to_file));
190                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
191                 return true;
192         }
193
194         EdgePath edgepath = converters.getPath(from_format, to_format);
195
196         if (edgepath.empty()) {
197                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
198                 return false;
199         }
200
201         // Create a temporary base file-name for all intermediate steps.
202         // Remember to remove the temp file because we only want the name...
203         static int counter = 0;
204         string const tmp = "gconvert" + tostr(counter++);
205         string const to_base = lyx::tempName(string(), tmp);
206         lyx::unlink(to_base);
207
208         string outfile = from_file;
209
210         // The conversion commands may contain these tokens that need to be
211         // changed to infile, infile_base, outfile respectively.
212         string const token_from("$$i");
213         string const token_base("$$b");
214         string const token_to("$$o");
215
216         EdgePath::const_iterator it  = edgepath.begin();
217         EdgePath::const_iterator end = edgepath.end();
218         for (; it != end; ++it) {
219                 Converter const & conv = converters.get(*it);
220
221                 // Build the conversion command
222                 string const infile      = outfile;
223                 string const infile_base = ChangeExtension(infile, string());
224                 outfile = ChangeExtension(to_base, conv.To->extension());
225
226                 // Store these names in the shell script
227                 script << "infile="      << QuoteName(infile) << '\n'
228                        << "infile_base=" << QuoteName(infile_base) << '\n'
229                        << "outfile="     << QuoteName(outfile) << '\n';
230
231                 string command = conv.command;
232                 command = subst(command, token_from, "${infile}");
233                 command = subst(command, token_base, "${infile_base}");
234                 command = subst(command, token_to,   "${outfile}");
235
236                 // Store in the shell script
237                 script << "\n" << command << "\n\n";
238
239                 // Test that this was successful. If not, remove
240                 // ${outfile} and exit the shell script
241                 script << "if [ $? -ne 0 ]; then\n"
242                        << "\t'rm' -f ${outfile}\n"
243                        << "\texit 1\n"
244                        << "fi\n\n";
245
246                 // Test that the outfile exists.
247                 // ImageMagick's convert will often create ${outfile}.0,
248                 // ${outfile}.1.
249                 // If this occurs, move ${outfile}.0 to ${outfile}
250                 // and delete ${outfile}.?
251                 script << "if [ ! -f ${outfile} ]; then\n"
252                        << "\tif [ -f ${outfile}.0 ]; then\n"
253                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
254                        << "\t\t'rm' -f ${outfile}.?\n"
255                        << "\telse\n"
256                        << "\t\texit 1\n"
257                        << "\tfi\n"
258                        << "fi\n\n";
259
260                 // Delete the infile, if it isn't the original, from_file.
261                 if (infile != from_file) {
262                         script << "'rm' -f ${infile}\n\n";
263                 }
264         }
265
266         // Move the final outfile to to_file
267         script << move_file("${outfile}", QuoteName(to_file));
268         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
269
270         return true;
271 }
272
273
274 ConvProcess::ConvProcess(string const & script_file,
275                          string const & script_command,
276                          string const & to_file, SignalTypePtr on_finish)
277         : script_file_(script_file), to_file_(to_file), on_finish_(on_finish)
278 {
279         Forkedcall::SignalTypePtr convert_ptr;
280         convert_ptr.reset(new Forkedcall::SignalType);
281
282         convert_ptr->connect(boost::bind(&ConvProcess::converted, this, _1, _2, _3));
283
284         Forkedcall call;
285         int retval = call.startscript(script_command, convert_ptr);
286         if (retval > 0) {
287                 // Unable to even start the script, so clean-up the mess!
288                 converted(string(), 0, 1);
289         }
290 }
291
292
293 void ConvProcess::converted(string const &/* cmd */,
294                             pid_t /* pid */, int retval)
295 {
296         // Clean-up behind ourselves
297         lyx::unlink(script_file_);
298
299         if (retval > 0) {
300                 lyx::unlink(to_file_);
301                 to_file_.erase();
302         }
303
304         if (on_finish_.get()) {
305                 on_finish_->operator()(to_file_);
306         }
307
308         grfx::GConverter::get().erase(this);
309 }
310
311
312 } // namespace grfx