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