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