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