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