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