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::libFileSearch;
37 using support::libScriptSearch;
38 using support::onlyPath;
39 using support::onlyFilename;
40 using support::quoteName;
42 using support::tempName;
43 using support::unlink;
47 using std::ostringstream;
54 class Converter::Impl : public boost::signals::trackable {
57 Impl(string const &, string const &, string const &, string const &);
60 void startConversion();
62 /** This method is connected to a signal passed to the forked call
63 * class, passing control back here when the conversion is completed.
64 * Cleans-up the temporary files, emits the finishedConversion
65 * signal and removes the Converter from the list of all processes.
67 void converted(pid_t pid, int retval);
69 /** At the end of the conversion process inform the outside world
70 * by emitting a signal.
72 typedef boost::signal<void(bool)> SignalType;
74 SignalType finishedConversion;
77 string script_command_;
89 bool Converter::isReachable(string const & from_format_name,
90 string const & to_format_name)
92 return converters.isReachable(from_format_name, to_format_name);
96 Converter::Converter(string const & from_file, string const & to_file_base,
97 string const & from_format, string const & to_format)
98 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
102 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
103 Converter::~Converter()
107 void Converter::startConversion() const
109 pimpl_->startConversion();
113 boost::signals::connection Converter::connect(slot_type const & slot) const
115 return pimpl_->finishedConversion.connect(slot);
119 string const & Converter::convertedFile() const
121 static string const empty;
122 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
125 } // namespace graphics
129 //------------------------------
130 // Implementation details follow
131 //------------------------------
135 /** Build the conversion script, returning true if able to build it.
136 * The script is output to the ostringstream 'script'.
138 bool build_script(string const & from_file, string const & to_file_base,
139 string const & from_format, string const & to_format,
148 Converter::Impl::Impl(string const & from_file, string const & to_file_base,
149 string const & from_format, string const & to_format)
150 : valid_process_(false), finished_(false)
152 lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
153 << "\tfrom_file: " << from_file
154 << "\n\tto_file_base: " << to_file_base
155 << "\n\tfrom_format: " << from_format
156 << "\n\tto_format: " << to_format << endl;
158 // The converted image is to be stored in this file (we do not
159 // use ChangeExtension because this is a basename which may
160 // nevertheless contain a '.')
161 to_file_ = to_file_base + '.' + formats.extension(to_format);
163 // The conversion commands are stored in a stringstream
164 ostringstream script;
165 script << "#!/usr/bin/env python -tt\n"
166 << "import os, sys\n\n"
167 << "def unlinkNoThrow(file):\n"
168 << " ''' remove a file, do not throw if an error occurs '''\n"
170 << " os.unlink(file)\n"
174 bool const success = build_script(from_file, to_file_base,
175 from_format, to_format, script);
179 support::os::python() + ' ' +
180 quoteName(libFileSearch("scripts", "convertDefault.py")) +
182 quoteName((from_format.empty() ? "" : from_format + ':') + from_file) +
184 quoteName(to_format + ':' + to_file_);
186 lyxerr[Debug::GRAPHICS]
187 << "\tNo converter defined! I use convertDefault.py\n\t"
188 << script_command_ << endl;
192 lyxerr[Debug::GRAPHICS] << "\tConversion script:"
193 << "\n--------------------------------------\n"
195 << "\n--------------------------------------\n";
197 // Output the script to file.
198 static int counter = 0;
199 script_file_ = onlyPath(to_file_base) + "lyxconvert" +
200 convert<string>(counter++) + ".py";
202 std::ofstream fs(script_file_.c_str());
204 lyxerr << "Unable to write the conversion script to \""
205 << script_file_ << '\n'
206 << "Please check your directory permissions."
214 // The command needed to run the conversion process
215 // We create a dummy command for ease of understanding of the
216 // list of forked processes.
217 // Note: 'sh ' is absolutely essential, or execvp will fail.
218 script_command_ = support::os::python() + ' ' +
219 quoteName(script_file_) + ' ' +
220 quoteName(onlyFilename(from_file)) + ' ' +
221 quoteName(to_format);
223 // All is ready to go
224 valid_process_ = true;
228 void Converter::Impl::startConversion()
230 if (!valid_process_) {
235 Forkedcall::SignalTypePtr
236 ptr = ForkedCallQueue::get().add(script_command_);
238 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
242 void Converter::Impl::converted(pid_t /* pid */, int retval)
245 // We're done already!
249 // Clean-up behind ourselves
250 unlink(script_file_);
255 finishedConversion(false);
257 finishedConversion(true);
261 } // namespace graphics
266 string const move_file(string const & from_file, string const & to_file)
268 if (from_file == to_file)
271 ostringstream command;
272 command << "fromfile = " << from_file << "\n"
273 << "tofile = " << to_file << "\n\n"
275 << " os.rename(fromfile, tofile)\n"
277 << " import shutil\n"
279 << " shutil.copy(fromfile, tofile)\n"
282 << " unlinkNoThrow(fromfile)\n";
284 return command.str();
289 A typical script looks like:
291 #!/usr/bin/env python -tt
294 def unlinkNoThrow(file):
295 ''' remove a file, do not throw if error occurs '''
301 infile = '/home/username/Figure3a.eps'
302 infile_base = '/home/username/Figure3a'
303 outfile = '/tmp/lyx_tmpdir12992hUwBqt/gconvert0129929eUBPm.pdf'
305 if os.system(r'epstopdf ' + '"' + infile + '"' + ' --output ' + '"' + outfile + '"' + '') != 0:
306 unlinkNoThrow(outfile)
309 if not os.path.isfile(outfile):
310 if os.path.isfile(outfile + '.0'):
311 os.rename(outfile + '.0', outfile)
313 for file in glob.glob(outfile + '.?'):
319 tofile = '/tmp/lyx_tmpdir12992hUwBqt/Figure3a129927ByaCl.ppm'
322 os.rename(fromfile, tofile)
326 shutil.copy(fromfile, tofile)
329 unlinkNoThrow(fromfile)
332 bool build_script(string const & from_file,
333 string const & to_file_base,
334 string const & from_format,
335 string const & to_format,
338 lyxerr[Debug::GRAPHICS] << "build_script ... ";
339 typedef Converters::EdgePath EdgePath;
341 if (from_format.empty())
344 // we do not use ChangeExtension because this is a basename
345 // which may nevertheless contain a '.'
346 string const to_file = to_file_base + '.'
347 + formats.extension(to_format);
349 if (from_format == to_format) {
350 script << move_file(quoteName(from_file), quoteName(to_file));
351 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
355 EdgePath edgepath = converters.getPath(from_format, to_format);
357 if (edgepath.empty()) {
358 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
362 // Create a temporary base file-name for all intermediate steps.
363 // Remember to remove the temp file because we only want the name...
364 static int counter = 0;
365 string const tmp = "gconvert" + convert<string>(counter++);
366 string const to_base = tempName(string(), tmp);
369 string outfile = from_file;
371 // The conversion commands may contain these tokens that need to be
372 // changed to infile, infile_base, outfile respectively.
373 string const token_from("$$i");
374 string const token_base("$$b");
375 string const token_to("$$o");
377 EdgePath::const_iterator it = edgepath.begin();
378 EdgePath::const_iterator end = edgepath.end();
380 for (; it != end; ++it) {
381 ::Converter const & conv = converters.get(*it);
383 // Build the conversion command
384 string const infile = outfile;
385 string const infile_base = changeExtension(infile, string());
386 outfile = changeExtension(to_base, conv.To->extension());
388 // Store these names in the shell script
389 script << "infile = " << quoteName(infile) << '\n'
390 << "infile_base = " << quoteName(infile_base) << '\n'
391 << "outfile = " << quoteName(outfile) << '\n';
393 string command = conv.command;
394 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
395 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
396 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
397 command = libScriptSearch(command);
399 // Store in the shell script
400 script << "\nif os.system(r'" << command << "') != 0:\n";
402 // Test that this was successful. If not, remove
403 // ${outfile} and exit the shell script
404 script << " unlinkNoThrow(outfile)\n"
405 << " sys.exit(1)\n\n";
407 // Test that the outfile exists.
408 // ImageMagick's convert will often create ${outfile}.0,
410 // If this occurs, move ${outfile}.0 to ${outfile}
411 // and delete ${outfile}.? (ignore errors)
412 script << "if not os.path.isfile(outfile):\n"
413 << " if os.path.isfile(outfile + '.0'):\n"
414 << " os.rename(outfile + '.0', outfile)\n"
416 << " for file in glob.glob(outfile + '.?'):\n"
417 << " unlinkNoThrow(file)\n"
419 << " sys.exit(1)\n\n";
421 // Delete the infile, if it isn't the original, from_file.
422 if (infile != from_file) {
423 script << "unlinkNoThrow(infile)\n\n";
427 // Move the final outfile to to_file
428 script << move_file("outfile", quoteName(to_file));
429 lyxerr[Debug::GRAPHICS] << "ready!" << endl;