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;
42 using support::quote_python;
44 using support::tempName;
45 using support::unlink;
49 using std::ostringstream;
56 class Converter::Impl : public boost::signals::trackable {
59 Impl(string const &, string const &, string const &, string const &);
62 void startConversion();
64 /** This method is connected to a signal passed to the forked call
65 * class, passing control back here when the conversion is completed.
66 * Cleans-up the temporary files, emits the finishedConversion
67 * signal and removes the Converter from the list of all processes.
69 void converted(pid_t pid, int retval);
71 /** At the end of the conversion process inform the outside world
72 * by emitting a signal.
74 typedef boost::signal<void(bool)> SignalType;
76 SignalType finishedConversion;
79 string script_command_;
91 bool Converter::isReachable(string const & from_format_name,
92 string const & to_format_name)
94 return converters.isReachable(from_format_name, to_format_name);
98 Converter::Converter(string const & from_file, string const & to_file_base,
99 string const & from_format, string const & to_format)
100 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
104 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
105 Converter::~Converter()
109 void Converter::startConversion() const
111 pimpl_->startConversion();
115 boost::signals::connection Converter::connect(slot_type const & slot) const
117 return pimpl_->finishedConversion.connect(slot);
121 string const & Converter::convertedFile() const
123 static string const empty;
124 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
127 /** Build the conversion script.
128 * The script is output to the stream \p script.
130 static void build_script(string const & from_file, string const & to_file_base,
131 string const & from_format, string const & to_format,
135 Converter::Impl::Impl(string const & from_file, string const & to_file_base,
136 string const & from_format, string const & to_format)
137 : valid_process_(false), finished_(false)
139 lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
140 << "\tfrom_file: " << from_file
141 << "\n\tto_file_base: " << to_file_base
142 << "\n\tfrom_format: " << from_format
143 << "\n\tto_format: " << to_format << endl;
145 // The converted image is to be stored in this file (we do not
146 // use ChangeExtension because this is a basename which may
147 // nevertheless contain a '.')
148 to_file_ = to_file_base + '.' + formats.extension(to_format);
150 // The conversion commands are stored in a stringstream
151 ostringstream script;
152 build_script(from_file, to_file_base, from_format, to_format, script);
153 lyxerr[Debug::GRAPHICS] << "\tConversion script:"
154 << "\n--------------------------------------\n"
156 << "\n--------------------------------------\n";
158 // Output the script to file.
159 static int counter = 0;
160 script_file_ = onlyPath(to_file_base) + "lyxconvert" +
161 convert<string>(counter++) + ".py";
163 std::ofstream fs(script_file_.c_str());
165 lyxerr << "Unable to write the conversion script to \""
166 << script_file_ << '\n'
167 << "Please check your directory permissions."
175 // The command needed to run the conversion process
176 // We create a dummy command for ease of understanding of the
177 // list of forked processes.
178 // Note: 'python ' is absolutely essential, or execvp will fail.
179 script_command_ = support::os::python() + ' ' +
180 quoteName(script_file_) + ' ' +
181 quoteName(onlyFilename(from_file)) + ' ' +
182 quoteName(to_format);
183 // All is ready to go
184 valid_process_ = true;
188 void Converter::Impl::startConversion()
190 if (!valid_process_) {
195 Forkedcall::SignalTypePtr
196 ptr = ForkedCallQueue::get().add(script_command_);
198 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
202 void Converter::Impl::converted(pid_t /* pid */, int retval)
205 // We're done already!
209 // Clean-up behind ourselves
210 unlink(script_file_);
215 finishedConversion(false);
217 finishedConversion(true);
222 static string const move_file(string const & from_file, string const & to_file)
224 if (from_file == to_file)
227 ostringstream command;
228 command << "fromfile = " << from_file << "\n"
229 << "tofile = " << to_file << "\n\n"
231 << " os.rename(fromfile, tofile)\n"
234 << " shutil.copy(fromfile, tofile)\n"
237 << " unlinkNoThrow(fromfile)\n";
239 return command.str();
243 static void build_conversion_command(string const & command, ostream & script)
245 // Store in the python script
246 script << "\nif os.system(r'" << command << "') != 0:\n";
248 // Test that this was successful. If not, remove
249 // ${outfile} and exit the python script
250 script << " unlinkNoThrow(outfile)\n"
251 << " sys.exit(1)\n\n";
253 // Test that the outfile exists.
254 // ImageMagick's convert will often create ${outfile}.0,
256 // If this occurs, move ${outfile}.0 to ${outfile}
257 // and delete ${outfile}.? (ignore errors)
258 script << "if not os.path.isfile(outfile):\n"
259 " if os.path.isfile(outfile + '.0'):\n"
260 " os.rename(outfile + '.0', outfile)\n"
262 " for file in glob.glob(outfile + '.?'):\n"
263 " unlinkNoThrow(file)\n"
268 script << "unlinkNoThrow(infile)\n\n";
272 static void build_script(string const & from_file,
273 string const & to_file_base,
274 string const & from_format,
275 string const & to_format,
278 BOOST_ASSERT(from_format != to_format);
279 lyxerr[Debug::GRAPHICS] << "build_script ... ";
280 typedef Converters::EdgePath EdgePath;
282 script << "#!/usr/bin/env python\n"
283 "import os, shutil, sys\n\n"
284 "def unlinkNoThrow(file):\n"
285 " ''' remove a file, do not throw if an error occurs '''\n"
291 // we do not use ChangeExtension because this is a basename
292 // which may nevertheless contain a '.'
293 string const to_file = to_file_base + '.'
294 + formats.extension(to_format);
296 EdgePath const edgepath = from_format.empty() ?
298 converters.getPath(from_format, to_format);
300 // Create a temporary base file-name for all intermediate steps.
301 // Remember to remove the temp file because we only want the name...
302 static int counter = 0;
303 string const tmp = "gconvert" + convert<string>(counter++);
304 string const to_base = tempName(string(), tmp);
307 // Create a copy of the file in case the original name contains
308 // problematic characters like ' or ". We can work around that problem
309 // in python, but the converters might be shell scripts and have more
311 string outfile = changeExtension(to_base, getExtension(from_file));
312 script << "infile = " << quoteName(from_file, quote_python) << "\n"
313 "outfile = " << quoteName(outfile, quote_python) << "\n"
314 "shutil.copy(infile, outfile)\n";
316 // Some converters (e.g. lilypond) can only output files to the
317 // current directory, so we need to change the current directory.
318 // This has the added benefit that all other files that may be
319 // generated by the converter are deleted when LyX closes and do not
320 // clutter the real working directory.
321 script << "os.chdir(" << quoteName(onlyPath(outfile)) << ")\n";
323 if (edgepath.empty()) {
324 // Either from_format is unknown or we don't have a
325 // converter path from from_format to to_format, so we use
326 // the default converter.
327 script << "infile = outfile\n"
328 << "outfile = " << quoteName(to_file, quote_python)
332 os << support::os::python() << ' '
333 << libScriptSearch("$$s/scripts/convertDefault.py",
334 quote_python) << ' ';
335 if (!from_format.empty())
336 os << from_format << ':';
337 // The extra " quotes around infile and outfile are needed
338 // because the filename may contain spaces and it is used
339 // as argument of os.system().
340 os << "' + '\"' + infile + '\"' + ' "
341 << to_format << ":' + '\"' + outfile + '\"' + '";
342 string const command = os.str();
344 lyxerr[Debug::GRAPHICS]
345 << "\tNo converter defined! I use convertDefault.py\n\t"
348 build_conversion_command(command, script);
351 // The conversion commands may contain these tokens that need to be
352 // changed to infile, infile_base, outfile respectively.
353 string const token_from("$$i");
354 string const token_base("$$b");
355 string const token_to("$$o");
357 EdgePath::const_iterator it = edgepath.begin();
358 EdgePath::const_iterator end = edgepath.end();
360 for (; it != end; ++it) {
361 lyx::Converter const & conv = converters.get(*it);
363 // Build the conversion command
364 string const infile = outfile;
365 string const infile_base = changeExtension(infile, string());
366 outfile = changeExtension(to_base, conv.To->extension());
368 // Store these names in the python script
369 script << "infile = " << quoteName(infile, quote_python) << "\n"
370 "infile_base = " << quoteName(infile_base, quote_python) << "\n"
371 "outfile = " << quoteName(outfile, quote_python) << '\n';
373 // See comment about extra " quotes above (although that
374 // applies only for the first loop run here).
375 string command = conv.command;
376 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
377 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
378 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
379 command = libScriptSearch(command, quote_python);
381 build_conversion_command(command, script);
384 // Move the final outfile to to_file
385 script << move_file("outfile", quoteName(to_file, quote_python));
386 lyxerr[Debug::GRAPHICS] << "ready!" << endl;
389 } // namespace graphics