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/os.h"
25 #include <boost/bind.hpp>
31 using namespace lyx::support;
37 class Converter::Impl : public boost::signals::trackable {
40 Impl(FileName const &, string const &, string const &, string const &);
43 void startConversion();
45 /** This method is connected to a signal passed to the forked call
46 * class, passing control back here when the conversion is completed.
47 * Cleans-up the temporary files, emits the finishedConversion
48 * signal and removes the Converter from the list of all processes.
50 void converted(pid_t pid, int retval);
52 /** At the end of the conversion process inform the outside world
53 * by emitting a signal.
55 typedef boost::signal<void(bool)> SignalType;
57 SignalType finishedConversion;
60 string script_command_;
62 FileName script_file_;
72 bool Converter::isReachable(string const & from_format_name,
73 string const & to_format_name)
75 return theConverters().isReachable(from_format_name, to_format_name);
79 Converter::Converter(FileName const & from_file, string const & to_file_base,
80 string const & from_format, string const & to_format)
81 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
85 Converter::~Converter()
91 void Converter::startConversion() const
93 pimpl_->startConversion();
97 boost::signals::connection Converter::connect(slot_type const & slot) const
99 return pimpl_->finishedConversion.connect(slot);
103 FileName const & Converter::convertedFile() const
105 static FileName const empty;
106 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
109 /** Build the conversion script.
110 * The script is output to the stream \p script.
112 static void build_script(FileName const & from_file, string const & to_file_base,
113 string const & from_format, string const & to_format,
117 Converter::Impl::Impl(FileName const & from_file, string const & to_file_base,
118 string const & from_format, string const & to_format)
119 : valid_process_(false), finished_(false)
121 LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
122 << "\tfrom_file: " << from_file
123 << "\n\tto_file_base: " << to_file_base
124 << "\n\tfrom_format: " << from_format
125 << "\n\tto_format: " << to_format);
127 // The converted image is to be stored in this file (we do not
128 // use ChangeExtension because this is a basename which may
129 // nevertheless contain a '.')
130 to_file_ = FileName(to_file_base + '.' + formats.extension(to_format));
132 // The conversion commands are stored in a stringstream
133 ostringstream script;
134 build_script(from_file, to_file_base, from_format, to_format, script);
135 LYXERR(Debug::GRAPHICS, "\tConversion script:"
136 "\n--------------------------------------\n"
138 << "\n--------------------------------------\n");
140 // Output the script to file.
141 static int counter = 0;
142 script_file_ = FileName(onlyPath(to_file_base) + "lyxconvert" +
143 convert<string>(counter++) + ".py");
145 ofstream fs(script_file_.toFilesystemEncoding().c_str());
147 lyxerr << "Unable to write the conversion script to \""
148 << script_file_ << '\n'
149 << "Please check your directory permissions."
157 // The command needed to run the conversion process
158 // We create a dummy command for ease of understanding of the
159 // list of forked processes.
160 // Note: 'python ' is absolutely essential, or execvp will fail.
161 script_command_ = os::python() + ' ' +
162 quoteName(script_file_.toFilesystemEncoding()) + ' ' +
163 quoteName(onlyFilename(from_file.toFilesystemEncoding())) + ' ' +
164 quoteName(to_format);
165 // All is ready to go
166 valid_process_ = true;
170 void Converter::Impl::startConversion()
172 if (!valid_process_) {
177 ForkedCall::SignalTypePtr ptr =
178 ForkedCallQueue::add(script_command_);
179 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
183 void Converter::Impl::converted(pid_t /* pid */, int retval)
186 // We're done already!
190 // Clean-up behind ourselves
191 script_file_.removeFile();
194 to_file_.removeFile();
196 finishedConversion(false);
198 finishedConversion(true);
203 static string const move_file(string const & from_file, string const & to_file)
205 if (from_file == to_file)
208 ostringstream command;
209 command << "fromfile = utf8ToDefaultEncoding(" << from_file << ")\n"
210 << "tofile = utf8ToDefaultEncoding(" << to_file << ")\n\n"
212 << " os.rename(fromfile, tofile)\n"
215 << " shutil.copy(fromfile, tofile)\n"
218 << " unlinkNoThrow(fromfile)\n";
220 return command.str();
224 static void build_conversion_command(string const & command, ostream & script)
226 // Store in the python script
227 script << "\nif os.system(r'" << command << "') != 0:\n";
229 // Test that this was successful. If not, remove
230 // ${outfile} and exit the python script
231 script << " unlinkNoThrow(outfile)\n"
232 << " sys.exit(1)\n\n";
234 // Test that the outfile exists.
235 // ImageMagick's convert will often create ${outfile}.0,
237 // If this occurs, move ${outfile}.0 to ${outfile}
238 // and delete ${outfile}.? (ignore errors)
239 script << "if not os.path.isfile(outfile):\n"
240 " if os.path.isfile(outfile + '.0'):\n"
241 " os.rename(outfile + '.0', outfile)\n"
243 " for file in glob.glob(outfile + '.?'):\n"
244 " unlinkNoThrow(file)\n"
249 script << "unlinkNoThrow(infile)\n\n";
253 static void build_script(FileName const & from_file,
254 string const & to_file_base,
255 string const & from_format,
256 string const & to_format,
259 BOOST_ASSERT(from_format != to_format);
260 LYXERR(Debug::GRAPHICS, "build_script ... ");
261 typedef Converters::EdgePath EdgePath;
263 script << "#!/usr/bin/env python\n"
264 "# -*- coding: utf-8 -*-\n"
265 "import os, shutil, sys, locale\n\n"
266 "def unlinkNoThrow(file):\n"
267 " ''' remove a file, do not throw if an error occurs '''\n"
272 "def utf8ToDefaultEncoding(file):\n"
273 " ''' if possible, convert to the default encoding '''\n"
275 " language, output_encoding = locale.getdefaultlocale()\n"
276 " if output_encoding == None:\n"
277 " output_encoding = 'latin1'\n"
278 " return unicode(file, 'utf8').encode(output_encoding)\n"
282 // we do not use ChangeExtension because this is a basename
283 // which may nevertheless contain a '.'
284 string const to_file = to_file_base + '.'
285 + formats.extension(to_format);
287 EdgePath const edgepath = from_format.empty() ?
289 theConverters().getPath(from_format, to_format);
291 // Create a temporary base file-name for all intermediate steps.
292 // Remember to remove the temp file because we only want the name...
293 static int counter = 0;
294 string const tmp = "gconvert" + convert<string>(counter++);
295 FileName const to_base = FileName::tempName(tmp);
296 to_base.removeFile();
298 // Create a copy of the file in case the original name contains
299 // problematic characters like ' or ". We can work around that problem
300 // in python, but the converters might be shell scripts and have more
302 string outfile = addExtension(to_base.absFilename(), getExtension(from_file.absFilename()));
303 script << "infile = utf8ToDefaultEncoding("
304 << quoteName(from_file.absFilename(), quote_python)
306 "outfile = utf8ToDefaultEncoding("
307 << quoteName(outfile, quote_python) << ")\n"
308 "shutil.copy(infile, outfile)\n";
310 // Some converters (e.g. lilypond) can only output files to the
311 // current directory, so we need to change the current directory.
312 // This has the added benefit that all other files that may be
313 // generated by the converter are deleted when LyX closes and do not
314 // clutter the real working directory.
315 script << "os.chdir(utf8ToDefaultEncoding("
316 << quoteName(onlyPath(outfile)) << "))\n";
318 if (edgepath.empty()) {
319 // Either from_format is unknown or we don't have a
320 // converter path from from_format to to_format, so we use
321 // the default converter.
322 script << "infile = outfile\n"
323 << "outfile = utf8ToDefaultEncoding("
324 << quoteName(to_file, quote_python) << ")\n";
327 os << os::python() << ' '
328 << libScriptSearch("$$s/scripts/convertDefault.py",
329 quote_python) << ' ';
330 if (!from_format.empty())
331 os << from_format << ':';
332 // The extra " quotes around infile and outfile are needed
333 // because the filename may contain spaces and it is used
334 // as argument of os.system().
335 os << "' + '\"' + infile + '\"' + ' "
336 << to_format << ":' + '\"' + outfile + '\"' + '";
337 string const command = os.str();
339 LYXERR(Debug::GRAPHICS,
340 "\tNo converter defined! I use convertDefault.py\n\t"
343 build_conversion_command(command, script);
346 // The conversion commands may contain these tokens that need to be
347 // changed to infile, infile_base, outfile respectively.
348 string const token_from = "$$i";
349 string const token_base = "$$b";
350 string const token_to = "$$o";
352 EdgePath::const_iterator it = edgepath.begin();
353 EdgePath::const_iterator end = edgepath.end();
355 for (; it != end; ++it) {
356 lyx::Converter const & conv = theConverters().get(*it);
358 // Build the conversion command
359 string const infile = outfile;
360 string const infile_base = changeExtension(infile, string());
361 outfile = addExtension(to_base.absFilename(), conv.To->extension());
363 // Store these names in the python script
364 script << "infile = utf8ToDefaultEncoding("
365 << quoteName(infile, quote_python) << ")\n"
366 "infile_base = utf8ToDefaultEncoding("
367 << quoteName(infile_base, quote_python) << ")\n"
368 "outfile = utf8ToDefaultEncoding("
369 << quoteName(outfile, quote_python) << ")\n";
371 // See comment about extra " quotes above (although that
372 // applies only for the first loop run here).
373 string command = conv.command;
374 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
375 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
376 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
377 command = libScriptSearch(command, quote_python);
379 build_conversion_command(command, script);
382 // Move the final outfile to to_file
383 script << move_file("outfile", quoteName(to_file, quote_python));
384 LYXERR(Debug::GRAPHICS, "ready!");
387 } // namespace graphics