2 * \file GraphicsConverter.C
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS.
13 #include "GraphicsConverter.h"
15 #include "converter.h"
19 #include "support/filetools.h"
20 #include "support/forkedcallqueue.h"
21 #include "support/convert.h"
22 #include "support/lstrings.h"
23 #include "support/lyxlib.h"
24 #include "support/os.h"
26 #include <boost/bind.hpp>
31 namespace support = lyx::support;
33 using support::changeExtension;
34 using support::Forkedcall;
35 using support::ForkedCallQueue;
36 using support::getExtension;
37 using support::libFileSearch;
38 using support::libScriptSearch;
39 using support::onlyPath;
40 using support::onlyFilename;
41 using support::quoteName;
43 using support::tempName;
44 using support::unlink;
48 using std::ostringstream;
55 class Converter::Impl : public boost::signals::trackable {
58 Impl(string const &, string const &, string const &, string const &);
61 void startConversion();
63 /** This method is connected to a signal passed to the forked call
64 * class, passing control back here when the conversion is completed.
65 * Cleans-up the temporary files, emits the finishedConversion
66 * signal and removes the Converter from the list of all processes.
68 void converted(pid_t pid, int retval);
70 /** At the end of the conversion process inform the outside world
71 * by emitting a signal.
73 typedef boost::signal<void(bool)> SignalType;
75 SignalType finishedConversion;
78 string script_command_;
90 bool Converter::isReachable(string const & from_format_name,
91 string const & to_format_name)
93 return converters.isReachable(from_format_name, to_format_name);
97 Converter::Converter(string const & from_file, string const & to_file_base,
98 string const & from_format, string const & to_format)
99 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
103 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
104 Converter::~Converter()
108 void Converter::startConversion() const
110 pimpl_->startConversion();
114 boost::signals::connection Converter::connect(slot_type const & slot) const
116 return pimpl_->finishedConversion.connect(slot);
120 string const & Converter::convertedFile() const
122 static string const empty;
123 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
126 } // namespace graphics
130 //------------------------------
131 // Implementation details follow
132 //------------------------------
136 /** Build the conversion script, returning true if able to build it.
137 * The script is output to the ostringstream 'script'.
139 bool build_script(string const & from_file, string const & to_file_base,
140 string const & from_format, string const & to_format,
149 Converter::Impl::Impl(string const & from_file, string const & to_file_base,
150 string const & from_format, string const & to_format)
151 : valid_process_(false), finished_(false)
153 lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
154 << "\tfrom_file: " << from_file
155 << "\n\tto_file_base: " << to_file_base
156 << "\n\tfrom_format: " << from_format
157 << "\n\tto_format: " << to_format << endl;
159 // The converted image is to be stored in this file (we do not
160 // use ChangeExtension because this is a basename which may
161 // nevertheless contain a '.')
162 to_file_ = to_file_base + '.' + formats.extension(to_format);
164 // The conversion commands are stored in a stringstream
165 ostringstream script;
166 bool const success = build_script(from_file, to_file_base,
167 from_format, to_format, script);
171 support::os::python() + ' ' +
172 quoteName(libFileSearch("scripts", "convertDefault.py")) +
174 quoteName((from_format.empty() ? "" : from_format + ':') + from_file) +
176 quoteName(to_format + ':' + to_file_);
178 lyxerr[Debug::GRAPHICS]
179 << "\tNo converter defined! I use convertDefault.py\n\t"
180 << script_command_ << endl;
184 lyxerr[Debug::GRAPHICS] << "\tConversion script:"
185 << "\n--------------------------------------\n"
187 << "\n--------------------------------------\n";
189 // Output the script to file.
190 static int counter = 0;
191 script_file_ = onlyPath(to_file_base) + "lyxconvert" +
192 convert<string>(counter++) + ".py";
194 std::ofstream fs(script_file_.c_str());
196 lyxerr << "Unable to write the conversion script to \""
197 << script_file_ << '\n'
198 << "Please check your directory permissions."
206 // The command needed to run the conversion process
207 // We create a dummy command for ease of understanding of the
208 // list of forked processes.
209 // Note: 'sh ' is absolutely essential, or execvp will fail.
210 script_command_ = support::os::python() + ' ' +
211 quoteName(script_file_) + ' ' +
212 quoteName(onlyFilename(from_file)) + ' ' +
213 quoteName(to_format);
215 // All is ready to go
216 valid_process_ = true;
220 void Converter::Impl::startConversion()
222 if (!valid_process_) {
227 Forkedcall::SignalTypePtr
228 ptr = ForkedCallQueue::get().add(script_command_);
230 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
234 void Converter::Impl::converted(pid_t /* pid */, int retval)
237 // We're done already!
241 // Clean-up behind ourselves
242 unlink(script_file_);
247 finishedConversion(false);
249 finishedConversion(true);
253 } // namespace graphics
258 string const move_file(string const & from_file, string const & to_file)
260 if (from_file == to_file)
263 ostringstream command;
264 command << "fromfile = " << from_file << "\n"
265 << "tofile = " << to_file << "\n\n"
267 << " os.rename(fromfile, tofile)\n"
270 << " shutil.copy(fromfile, tofile)\n"
273 << " unlinkNoThrow(fromfile)\n";
275 return command.str();
279 bool build_script(string const & from_file,
280 string const & to_file_base,
281 string const & from_format,
282 string const & to_format,
285 BOOST_ASSERT(from_format != to_format);
286 lyxerr[Debug::GRAPHICS] << "build_script ... ";
287 typedef Converters::EdgePath EdgePath;
289 if (from_format.empty())
292 script << "#!/usr/bin/env python -tt\n"
293 "import os, shutil, sys\n\n"
294 "def unlinkNoThrow(file):\n"
295 " ''' remove a file, do not throw if an error occurs '''\n"
301 // we do not use ChangeExtension because this is a basename
302 // which may nevertheless contain a '.'
303 string const to_file = to_file_base + '.'
304 + formats.extension(to_format);
306 EdgePath edgepath = converters.getPath(from_format, to_format);
308 if (edgepath.empty()) {
309 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
313 // Create a temporary base file-name for all intermediate steps.
314 // Remember to remove the temp file because we only want the name...
315 static int counter = 0;
316 string const tmp = "gconvert" + convert<string>(counter++);
317 string const to_base = tempName(string(), tmp);
320 // Create a copy of the file in case the original name contains
321 // problematic characters like ' or ". We can work around that problem
322 // in python, but the converters might be shell scripts and have more
324 string outfile = changeExtension(to_base, getExtension(from_file));
325 script << "infile = '"
326 << subst(subst(from_file, "\\", "\\\\"), "'", "\\'") << "'\n"
327 "outfile = " << quoteName(outfile) << "\n"
328 "shutil.copy(infile, outfile)\n";
330 // The conversion commands may contain these tokens that need to be
331 // changed to infile, infile_base, outfile respectively.
332 string const token_from("$$i");
333 string const token_base("$$b");
334 string const token_to("$$o");
336 EdgePath::const_iterator it = edgepath.begin();
337 EdgePath::const_iterator end = edgepath.end();
339 for (; it != end; ++it) {
340 ::Converter const & conv = converters.get(*it);
342 // Build the conversion command
343 string const infile = outfile;
344 string const infile_base = changeExtension(infile, string());
345 outfile = changeExtension(to_base, conv.To->extension());
347 // Store these names in the shell script
348 script << "infile = " << quoteName(infile) << '\n'
349 << "infile_base = " << quoteName(infile_base) << '\n'
350 << "outfile = " << quoteName(outfile) << '\n';
352 string command = conv.command;
353 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
354 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
355 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
356 command = libScriptSearch(command);
358 // Store in the shell script
359 script << "\nif os.system(r'" << command << "') != 0:\n";
361 // Test that this was successful. If not, remove
362 // ${outfile} and exit the shell script
363 script << " unlinkNoThrow(outfile)\n"
364 << " sys.exit(1)\n\n";
366 // Test that the outfile exists.
367 // ImageMagick's convert will often create ${outfile}.0,
369 // If this occurs, move ${outfile}.0 to ${outfile}
370 // and delete ${outfile}.? (ignore errors)
371 script << "if not os.path.isfile(outfile):\n"
372 " if os.path.isfile(outfile + '.0'):\n"
373 " os.rename(outfile + '.0', outfile)\n"
375 " for file in glob.glob(outfile + '.?'):\n"
376 " unlinkNoThrow(file)\n"
381 script << "unlinkNoThrow(infile)\n\n";
384 // Move the final outfile to to_file
385 script << move_file("outfile", quoteName(to_file));
386 lyxerr[Debug::GRAPHICS] << "ready!" << endl;