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