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/FileName.h"
21 #include "support/filetools.h"
22 #include "support/ForkedCalls.h"
23 #include "support/lstrings.h"
24 #include "support/os.h"
26 #include <boost/bind.hpp>
32 using namespace lyx::support;
38 class Converter::Impl : public boost::signals::trackable {
41 Impl(FileName const &, string const &, string const &, string const &);
44 void startConversion();
46 /** This method is connected to a signal passed to the forked call
47 * class, passing control back here when the conversion is completed.
48 * Cleans-up the temporary files, emits the finishedConversion
49 * signal and removes the Converter from the list of all processes.
51 void converted(pid_t pid, int retval);
53 /** At the end of the conversion process inform the outside world
54 * by emitting a signal.
56 typedef boost::signal<void(bool)> SignalType;
58 SignalType finishedConversion;
61 string script_command_;
63 FileName script_file_;
73 bool Converter::isReachable(string const & from_format_name,
74 string const & to_format_name)
76 return theConverters().isReachable(from_format_name, to_format_name);
80 Converter::Converter(FileName const & from_file, string const & to_file_base,
81 string const & from_format, string const & to_format)
82 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
86 Converter::~Converter()
92 void Converter::startConversion() const
94 pimpl_->startConversion();
98 boost::signals::connection Converter::connect(slot_type const & slot) const
100 return pimpl_->finishedConversion.connect(slot);
104 FileName const & Converter::convertedFile() const
106 static FileName const empty;
107 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
110 /** Build the conversion script.
111 * The script is output to the stream \p script.
113 static void build_script(FileName const & from_file, string const & to_file_base,
114 string const & from_format, string const & to_format,
118 Converter::Impl::Impl(FileName const & from_file, string const & to_file_base,
119 string const & from_format, string const & to_format)
120 : valid_process_(false), finished_(false)
122 LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
123 << "\tfrom_file: " << from_file
124 << "\n\tto_file_base: " << to_file_base
125 << "\n\tfrom_format: " << from_format
126 << "\n\tto_format: " << to_format);
128 // The converted image is to be stored in this file (we do not
129 // use ChangeExtension because this is a basename which may
130 // nevertheless contain a '.')
131 to_file_ = FileName(to_file_base + '.' + formats.extension(to_format));
133 // The conversion commands are stored in a stringstream
134 ostringstream script;
135 build_script(from_file, to_file_base, from_format, to_format, script);
136 LYXERR(Debug::GRAPHICS, "\tConversion script:"
137 "\n--------------------------------------\n"
139 << "\n--------------------------------------\n");
141 // Output the script to file.
142 static int counter = 0;
143 script_file_ = FileName(onlyPath(to_file_base) + "lyxconvert" +
144 convert<string>(counter++) + ".py");
146 ofstream fs(script_file_.toFilesystemEncoding().c_str());
148 lyxerr << "Unable to write the conversion script to \""
149 << script_file_ << '\n'
150 << "Please check your directory permissions."
158 // The command needed to run the conversion process
159 // We create a dummy command for ease of understanding of the
160 // list of forked processes.
161 // Note: 'python ' is absolutely essential, or execvp will fail.
162 script_command_ = os::python() + ' ' +
163 quoteName(script_file_.toFilesystemEncoding()) + ' ' +
164 quoteName(onlyFilename(from_file.toFilesystemEncoding())) + ' ' +
165 quoteName(to_format);
166 // All is ready to go
167 valid_process_ = true;
171 void Converter::Impl::startConversion()
173 if (!valid_process_) {
178 ForkedCall::SignalTypePtr ptr =
179 ForkedCallQueue::add(script_command_);
180 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
184 void Converter::Impl::converted(pid_t /* pid */, int retval)
187 // We're done already!
191 // Clean-up behind ourselves
192 script_file_.removeFile();
195 to_file_.removeFile();
197 finishedConversion(false);
199 finishedConversion(true);
204 static string const move_file(string const & from_file, string const & to_file)
206 if (from_file == to_file)
209 ostringstream command;
210 command << "fromfile = utf8ToDefaultEncoding(" << from_file << ")\n"
211 << "tofile = utf8ToDefaultEncoding(" << to_file << ")\n\n"
213 << " os.rename(fromfile, tofile)\n"
216 << " shutil.copy(fromfile, tofile)\n"
219 << " unlinkNoThrow(fromfile)\n";
221 return command.str();
225 static void build_conversion_command(string const & command, ostream & script)
227 // Store in the python script
228 script << "\nif os.system(r'" << command << "') != 0:\n";
230 // Test that this was successful. If not, remove
231 // ${outfile} and exit the python script
232 script << " unlinkNoThrow(outfile)\n"
233 << " sys.exit(1)\n\n";
235 // Test that the outfile exists.
236 // ImageMagick's convert will often create ${outfile}.0,
238 // If this occurs, move ${outfile}.0 to ${outfile}
239 // and delete ${outfile}.? (ignore errors)
240 script << "if not os.path.isfile(outfile):\n"
241 " if os.path.isfile(outfile + '.0'):\n"
242 " os.rename(outfile + '.0', outfile)\n"
244 " for file in glob.glob(outfile + '.?'):\n"
245 " unlinkNoThrow(file)\n"
250 script << "unlinkNoThrow(infile)\n\n";
254 static void build_script(FileName const & from_file,
255 string const & to_file_base,
256 string const & from_format,
257 string const & to_format,
260 BOOST_ASSERT(from_format != to_format);
261 LYXERR(Debug::GRAPHICS, "build_script ... ");
262 typedef Converters::EdgePath EdgePath;
264 script << "#!/usr/bin/env python\n"
265 "# -*- coding: utf-8 -*-\n"
266 "import os, shutil, sys, locale\n\n"
267 "def unlinkNoThrow(file):\n"
268 " ''' remove a file, do not throw if an error occurs '''\n"
273 "def utf8ToDefaultEncoding(file):\n"
274 " ''' if possible, convert to the default encoding '''\n"
276 " language, output_encoding = locale.getdefaultlocale()\n"
277 " if output_encoding == None:\n"
278 " output_encoding = 'latin1'\n"
279 " return unicode(file, 'utf8').encode(output_encoding)\n"
283 // we do not use ChangeExtension because this is a basename
284 // which may nevertheless contain a '.'
285 string const to_file = to_file_base + '.'
286 + formats.extension(to_format);
288 EdgePath const edgepath = from_format.empty() ?
290 theConverters().getPath(from_format, to_format);
292 // Create a temporary base file-name for all intermediate steps.
293 // Remember to remove the temp file because we only want the name...
294 static int counter = 0;
295 string const tmp = "gconvert" + convert<string>(counter++);
296 FileName const to_base = FileName::tempName(tmp);
297 to_base.removeFile();
299 // Create a copy of the file in case the original name contains
300 // problematic characters like ' or ". We can work around that problem
301 // in python, but the converters might be shell scripts and have more
303 string outfile = addExtension(to_base.absFilename(), getExtension(from_file.absFilename()));
304 script << "infile = utf8ToDefaultEncoding("
305 << quoteName(from_file.absFilename(), quote_python)
307 "outfile = utf8ToDefaultEncoding("
308 << quoteName(outfile, quote_python) << ")\n"
309 "shutil.copy(infile, outfile)\n";
311 // Some converters (e.g. lilypond) can only output files to the
312 // current directory, so we need to change the current directory.
313 // This has the added benefit that all other files that may be
314 // generated by the converter are deleted when LyX closes and do not
315 // clutter the real working directory.
316 script << "os.chdir(utf8ToDefaultEncoding("
317 << quoteName(onlyPath(outfile)) << "))\n";
319 if (edgepath.empty()) {
320 // Either from_format is unknown or we don't have a
321 // converter path from from_format to to_format, so we use
322 // the default converter.
323 script << "infile = outfile\n"
324 << "outfile = utf8ToDefaultEncoding("
325 << quoteName(to_file, quote_python) << ")\n";
328 os << os::python() << ' '
329 << libScriptSearch("$$s/scripts/convertDefault.py",
330 quote_python) << ' ';
331 if (!from_format.empty())
332 os << from_format << ':';
333 // The extra " quotes around infile and outfile are needed
334 // because the filename may contain spaces and it is used
335 // as argument of os.system().
336 os << "' + '\"' + infile + '\"' + ' "
337 << to_format << ":' + '\"' + outfile + '\"' + '";
338 string const command = os.str();
340 LYXERR(Debug::GRAPHICS,
341 "\tNo converter defined! I use convertDefault.py\n\t"
344 build_conversion_command(command, script);
347 // The conversion commands may contain these tokens that need to be
348 // changed to infile, infile_base, outfile respectively.
349 string const token_from = "$$i";
350 string const token_base = "$$b";
351 string const token_to = "$$o";
353 EdgePath::const_iterator it = edgepath.begin();
354 EdgePath::const_iterator end = edgepath.end();
356 for (; it != end; ++it) {
357 lyx::Converter const & conv = theConverters().get(*it);
359 // Build the conversion command
360 string const infile = outfile;
361 string const infile_base = changeExtension(infile, string());
362 outfile = addExtension(to_base.absFilename(), conv.To->extension());
364 // Store these names in the python script
365 script << "infile = utf8ToDefaultEncoding("
366 << quoteName(infile, quote_python) << ")\n"
367 "infile_base = utf8ToDefaultEncoding("
368 << quoteName(infile_base, quote_python) << ")\n"
369 "outfile = utf8ToDefaultEncoding("
370 << quoteName(outfile, quote_python) << ")\n";
372 // See comment about extra " quotes above (although that
373 // applies only for the first loop run here).
374 string command = conv.command;
375 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
376 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
377 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
378 command = libScriptSearch(command, quote_python);
380 build_conversion_command(command, script);
383 // Move the final outfile to to_file
384 script << move_file("outfile", quoteName(to_file, quote_python));
385 LYXERR(Debug::GRAPHICS, "ready!");
388 } // namespace graphics