2 * \file GraphicsConverter.cpp
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"
18 #include "support/convert.h"
19 #include "support/debug.h"
20 #include "support/filetools.h"
21 #include "support/ForkedCalls.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::addExtension;
34 using support::changeExtension;
35 using support::FileName;
36 using support::ForkedCall;
37 using support::getExtension;
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;
48 using std::ostringstream;
55 class Converter::Impl : public boost::signals::trackable {
58 Impl(FileName 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_;
80 FileName script_file_;
90 bool Converter::isReachable(string const & from_format_name,
91 string const & to_format_name)
93 return theConverters().isReachable(from_format_name, to_format_name);
97 Converter::Converter(FileName 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 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 FileName const & Converter::convertedFile() const
123 static FileName 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(FileName const & from_file, string const & to_file_base,
131 string const & from_format, string const & to_format,
135 Converter::Impl::Impl(FileName 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);
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_ = FileName(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_ = FileName(onlyPath(to_file_base) + "lyxconvert" +
161 convert<string>(counter++) + ".py");
163 std::ofstream fs(script_file_.toFilesystemEncoding().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_.toFilesystemEncoding()) + ' ' +
181 quoteName(onlyFilename(from_file.toFilesystemEncoding())) + ' ' +
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 ptr =
196 support::ForkedCallQueue::add(script_command_);
197 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
201 void Converter::Impl::converted(pid_t /* pid */, int retval)
204 // We're done already!
208 // Clean-up behind ourselves
209 script_file_.removeFile();
212 to_file_.removeFile();
214 finishedConversion(false);
216 finishedConversion(true);
221 static string const move_file(string const & from_file, string const & to_file)
223 if (from_file == to_file)
226 ostringstream command;
227 command << "fromfile = utf8ToDefaultEncoding(" << from_file << ")\n"
228 << "tofile = utf8ToDefaultEncoding(" << to_file << ")\n\n"
230 << " os.rename(fromfile, tofile)\n"
233 << " shutil.copy(fromfile, tofile)\n"
236 << " unlinkNoThrow(fromfile)\n";
238 return command.str();
242 static void build_conversion_command(string const & command, ostream & script)
244 // Store in the python script
245 script << "\nif os.system(r'" << command << "') != 0:\n";
247 // Test that this was successful. If not, remove
248 // ${outfile} and exit the python script
249 script << " unlinkNoThrow(outfile)\n"
250 << " sys.exit(1)\n\n";
252 // Test that the outfile exists.
253 // ImageMagick's convert will often create ${outfile}.0,
255 // If this occurs, move ${outfile}.0 to ${outfile}
256 // and delete ${outfile}.? (ignore errors)
257 script << "if not os.path.isfile(outfile):\n"
258 " if os.path.isfile(outfile + '.0'):\n"
259 " os.rename(outfile + '.0', outfile)\n"
261 " for file in glob.glob(outfile + '.?'):\n"
262 " unlinkNoThrow(file)\n"
267 script << "unlinkNoThrow(infile)\n\n";
271 static void build_script(FileName const & from_file,
272 string const & to_file_base,
273 string const & from_format,
274 string const & to_format,
277 BOOST_ASSERT(from_format != to_format);
278 LYXERR(Debug::GRAPHICS, "build_script ... ");
279 typedef Converters::EdgePath EdgePath;
281 script << "#!/usr/bin/env python\n"
282 "# -*- coding: utf-8 -*-\n"
283 "import os, shutil, sys, locale\n\n"
284 "def unlinkNoThrow(file):\n"
285 " ''' remove a file, do not throw if an error occurs '''\n"
290 "def utf8ToDefaultEncoding(file):\n"
291 " ''' if possible, convert to the default encoding '''\n"
293 " language, output_encoding = locale.getdefaultlocale()\n"
294 " if output_encoding == None:\n"
295 " output_encoding = 'latin1'\n"
296 " return unicode(file, 'utf8').encode(output_encoding)\n"
300 // we do not use ChangeExtension because this is a basename
301 // which may nevertheless contain a '.'
302 string const to_file = to_file_base + '.'
303 + formats.extension(to_format);
305 EdgePath const edgepath = from_format.empty() ?
307 theConverters().getPath(from_format, to_format);
309 // Create a temporary base file-name for all intermediate steps.
310 // Remember to remove the temp file because we only want the name...
311 static int counter = 0;
312 string const tmp = "gconvert" + convert<string>(counter++);
313 FileName const to_base(tempName(FileName(), tmp));
314 to_base.removeFile();
316 // Create a copy of the file in case the original name contains
317 // problematic characters like ' or ". We can work around that problem
318 // in python, but the converters might be shell scripts and have more
320 string outfile = addExtension(to_base.absFilename(), getExtension(from_file.absFilename()));
321 script << "infile = utf8ToDefaultEncoding("
322 << quoteName(from_file.absFilename(), quote_python)
324 "outfile = utf8ToDefaultEncoding("
325 << quoteName(outfile, quote_python) << ")\n"
326 "shutil.copy(infile, outfile)\n";
328 // Some converters (e.g. lilypond) can only output files to the
329 // current directory, so we need to change the current directory.
330 // This has the added benefit that all other files that may be
331 // generated by the converter are deleted when LyX closes and do not
332 // clutter the real working directory.
333 script << "os.chdir(utf8ToDefaultEncoding("
334 << quoteName(onlyPath(outfile)) << "))\n";
336 if (edgepath.empty()) {
337 // Either from_format is unknown or we don't have a
338 // converter path from from_format to to_format, so we use
339 // the default converter.
340 script << "infile = outfile\n"
341 << "outfile = utf8ToDefaultEncoding("
342 << quoteName(to_file, quote_python) << ")\n";
345 os << support::os::python() << ' '
346 << libScriptSearch("$$s/scripts/convertDefault.py",
347 quote_python) << ' ';
348 if (!from_format.empty())
349 os << from_format << ':';
350 // The extra " quotes around infile and outfile are needed
351 // because the filename may contain spaces and it is used
352 // as argument of os.system().
353 os << "' + '\"' + infile + '\"' + ' "
354 << to_format << ":' + '\"' + outfile + '\"' + '";
355 string const command = os.str();
357 LYXERR(Debug::GRAPHICS,
358 "\tNo converter defined! I use convertDefault.py\n\t"
361 build_conversion_command(command, script);
364 // The conversion commands may contain these tokens that need to be
365 // changed to infile, infile_base, outfile respectively.
366 string const token_from = "$$i";
367 string const token_base = "$$b";
368 string const token_to = "$$o";
370 EdgePath::const_iterator it = edgepath.begin();
371 EdgePath::const_iterator end = edgepath.end();
373 for (; it != end; ++it) {
374 lyx::Converter const & conv = theConverters().get(*it);
376 // Build the conversion command
377 string const infile = outfile;
378 string const infile_base = changeExtension(infile, string());
379 outfile = addExtension(to_base.absFilename(), conv.To->extension());
381 // Store these names in the python script
382 script << "infile = utf8ToDefaultEncoding("
383 << quoteName(infile, quote_python) << ")\n"
384 "infile_base = utf8ToDefaultEncoding("
385 << quoteName(infile_base, quote_python) << ")\n"
386 "outfile = utf8ToDefaultEncoding("
387 << quoteName(outfile, quote_python) << ")\n";
389 // See comment about extra " quotes above (although that
390 // applies only for the first loop run here).
391 string command = conv.command;
392 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
393 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
394 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
395 command = libScriptSearch(command, quote_python);
397 build_conversion_command(command, script);
400 // Move the final outfile to to_file
401 script << move_file("outfile", quoteName(to_file, quote_python));
402 LYXERR(Debug::GRAPHICS, "ready!");
405 } // namespace graphics