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>
35 using support::addExtension;
36 using support::changeExtension;
37 using support::FileName;
38 using support::ForkedCall;
39 using support::getExtension;
40 using support::libScriptSearch;
41 using support::onlyPath;
42 using support::onlyFilename;
43 using support::quoteName;
44 using support::quote_python;
46 using support::tempName;
50 class Converter::Impl : public boost::signals::trackable {
53 Impl(FileName const &, string const &, string const &, string const &);
56 void startConversion();
58 /** This method is connected to a signal passed to the forked call
59 * class, passing control back here when the conversion is completed.
60 * Cleans-up the temporary files, emits the finishedConversion
61 * signal and removes the Converter from the list of all processes.
63 void converted(pid_t pid, int retval);
65 /** At the end of the conversion process inform the outside world
66 * by emitting a signal.
68 typedef boost::signal<void(bool)> SignalType;
70 SignalType finishedConversion;
73 string script_command_;
75 FileName script_file_;
85 bool Converter::isReachable(string const & from_format_name,
86 string const & to_format_name)
88 return theConverters().isReachable(from_format_name, to_format_name);
92 Converter::Converter(FileName const & from_file, string const & to_file_base,
93 string const & from_format, string const & to_format)
94 : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
98 Converter::~Converter()
104 void Converter::startConversion() const
106 pimpl_->startConversion();
110 boost::signals::connection Converter::connect(slot_type const & slot) const
112 return pimpl_->finishedConversion.connect(slot);
116 FileName const & Converter::convertedFile() const
118 static FileName const empty;
119 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
122 /** Build the conversion script.
123 * The script is output to the stream \p script.
125 static void build_script(FileName const & from_file, string const & to_file_base,
126 string const & from_format, string const & to_format,
130 Converter::Impl::Impl(FileName const & from_file, string const & to_file_base,
131 string const & from_format, string const & to_format)
132 : valid_process_(false), finished_(false)
134 LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
135 << "\tfrom_file: " << from_file
136 << "\n\tto_file_base: " << to_file_base
137 << "\n\tfrom_format: " << from_format
138 << "\n\tto_format: " << to_format);
140 // The converted image is to be stored in this file (we do not
141 // use ChangeExtension because this is a basename which may
142 // nevertheless contain a '.')
143 to_file_ = FileName(to_file_base + '.' + formats.extension(to_format));
145 // The conversion commands are stored in a stringstream
146 ostringstream script;
147 build_script(from_file, to_file_base, from_format, to_format, script);
148 LYXERR(Debug::GRAPHICS, "\tConversion script:"
149 "\n--------------------------------------\n"
151 << "\n--------------------------------------\n");
153 // Output the script to file.
154 static int counter = 0;
155 script_file_ = FileName(onlyPath(to_file_base) + "lyxconvert" +
156 convert<string>(counter++) + ".py");
158 std::ofstream fs(script_file_.toFilesystemEncoding().c_str());
160 lyxerr << "Unable to write the conversion script to \""
161 << script_file_ << '\n'
162 << "Please check your directory permissions."
170 // The command needed to run the conversion process
171 // We create a dummy command for ease of understanding of the
172 // list of forked processes.
173 // Note: 'python ' is absolutely essential, or execvp will fail.
174 script_command_ = support::os::python() + ' ' +
175 quoteName(script_file_.toFilesystemEncoding()) + ' ' +
176 quoteName(onlyFilename(from_file.toFilesystemEncoding())) + ' ' +
177 quoteName(to_format);
178 // All is ready to go
179 valid_process_ = true;
183 void Converter::Impl::startConversion()
185 if (!valid_process_) {
190 ForkedCall::SignalTypePtr ptr =
191 support::ForkedCallQueue::add(script_command_);
192 ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
196 void Converter::Impl::converted(pid_t /* pid */, int retval)
199 // We're done already!
203 // Clean-up behind ourselves
204 script_file_.removeFile();
207 to_file_.removeFile();
209 finishedConversion(false);
211 finishedConversion(true);
216 static string const move_file(string const & from_file, string const & to_file)
218 if (from_file == to_file)
221 ostringstream command;
222 command << "fromfile = utf8ToDefaultEncoding(" << from_file << ")\n"
223 << "tofile = utf8ToDefaultEncoding(" << to_file << ")\n\n"
225 << " os.rename(fromfile, tofile)\n"
228 << " shutil.copy(fromfile, tofile)\n"
231 << " unlinkNoThrow(fromfile)\n";
233 return command.str();
237 static void build_conversion_command(string const & command, ostream & script)
239 // Store in the python script
240 script << "\nif os.system(r'" << command << "') != 0:\n";
242 // Test that this was successful. If not, remove
243 // ${outfile} and exit the python script
244 script << " unlinkNoThrow(outfile)\n"
245 << " sys.exit(1)\n\n";
247 // Test that the outfile exists.
248 // ImageMagick's convert will often create ${outfile}.0,
250 // If this occurs, move ${outfile}.0 to ${outfile}
251 // and delete ${outfile}.? (ignore errors)
252 script << "if not os.path.isfile(outfile):\n"
253 " if os.path.isfile(outfile + '.0'):\n"
254 " os.rename(outfile + '.0', outfile)\n"
256 " for file in glob.glob(outfile + '.?'):\n"
257 " unlinkNoThrow(file)\n"
262 script << "unlinkNoThrow(infile)\n\n";
266 static void build_script(FileName const & from_file,
267 string const & to_file_base,
268 string const & from_format,
269 string const & to_format,
272 BOOST_ASSERT(from_format != to_format);
273 LYXERR(Debug::GRAPHICS, "build_script ... ");
274 typedef Converters::EdgePath EdgePath;
276 script << "#!/usr/bin/env python\n"
277 "# -*- coding: utf-8 -*-\n"
278 "import os, shutil, sys, locale\n\n"
279 "def unlinkNoThrow(file):\n"
280 " ''' remove a file, do not throw if an error occurs '''\n"
285 "def utf8ToDefaultEncoding(file):\n"
286 " ''' if possible, convert to the default encoding '''\n"
288 " language, output_encoding = locale.getdefaultlocale()\n"
289 " if output_encoding == None:\n"
290 " output_encoding = 'latin1'\n"
291 " return unicode(file, 'utf8').encode(output_encoding)\n"
295 // we do not use ChangeExtension because this is a basename
296 // which may nevertheless contain a '.'
297 string const to_file = to_file_base + '.'
298 + formats.extension(to_format);
300 EdgePath const edgepath = from_format.empty() ?
302 theConverters().getPath(from_format, to_format);
304 // Create a temporary base file-name for all intermediate steps.
305 // Remember to remove the temp file because we only want the name...
306 static int counter = 0;
307 string const tmp = "gconvert" + convert<string>(counter++);
308 FileName const to_base(tempName(FileName(), tmp));
309 to_base.removeFile();
311 // Create a copy of the file in case the original name contains
312 // problematic characters like ' or ". We can work around that problem
313 // in python, but the converters might be shell scripts and have more
315 string outfile = addExtension(to_base.absFilename(), getExtension(from_file.absFilename()));
316 script << "infile = utf8ToDefaultEncoding("
317 << quoteName(from_file.absFilename(), quote_python)
319 "outfile = utf8ToDefaultEncoding("
320 << quoteName(outfile, quote_python) << ")\n"
321 "shutil.copy(infile, outfile)\n";
323 // Some converters (e.g. lilypond) can only output files to the
324 // current directory, so we need to change the current directory.
325 // This has the added benefit that all other files that may be
326 // generated by the converter are deleted when LyX closes and do not
327 // clutter the real working directory.
328 script << "os.chdir(utf8ToDefaultEncoding("
329 << quoteName(onlyPath(outfile)) << "))\n";
331 if (edgepath.empty()) {
332 // Either from_format is unknown or we don't have a
333 // converter path from from_format to to_format, so we use
334 // the default converter.
335 script << "infile = outfile\n"
336 << "outfile = utf8ToDefaultEncoding("
337 << quoteName(to_file, quote_python) << ")\n";
340 os << support::os::python() << ' '
341 << libScriptSearch("$$s/scripts/convertDefault.py",
342 quote_python) << ' ';
343 if (!from_format.empty())
344 os << from_format << ':';
345 // The extra " quotes around infile and outfile are needed
346 // because the filename may contain spaces and it is used
347 // as argument of os.system().
348 os << "' + '\"' + infile + '\"' + ' "
349 << to_format << ":' + '\"' + outfile + '\"' + '";
350 string const command = os.str();
352 LYXERR(Debug::GRAPHICS,
353 "\tNo converter defined! I use convertDefault.py\n\t"
356 build_conversion_command(command, script);
359 // The conversion commands may contain these tokens that need to be
360 // changed to infile, infile_base, outfile respectively.
361 string const token_from = "$$i";
362 string const token_base = "$$b";
363 string const token_to = "$$o";
365 EdgePath::const_iterator it = edgepath.begin();
366 EdgePath::const_iterator end = edgepath.end();
368 for (; it != end; ++it) {
369 lyx::Converter const & conv = theConverters().get(*it);
371 // Build the conversion command
372 string const infile = outfile;
373 string const infile_base = changeExtension(infile, string());
374 outfile = addExtension(to_base.absFilename(), conv.To->extension());
376 // Store these names in the python script
377 script << "infile = utf8ToDefaultEncoding("
378 << quoteName(infile, quote_python) << ")\n"
379 "infile_base = utf8ToDefaultEncoding("
380 << quoteName(infile_base, quote_python) << ")\n"
381 "outfile = utf8ToDefaultEncoding("
382 << quoteName(outfile, quote_python) << ")\n";
384 // See comment about extra " quotes above (although that
385 // applies only for the first loop run here).
386 string command = conv.command;
387 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
388 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
389 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
390 command = libScriptSearch(command, quote_python);
392 build_conversion_command(command, script);
395 // Move the final outfile to to_file
396 script << move_file("outfile", quoteName(to_file, quote_python));
397 LYXERR(Debug::GRAPHICS, "ready!");
400 } // namespace graphics