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