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