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"
16 #include "Converter.h"
20 #include "frontends/alert.h"
21 #include "support/lassert.h"
22 #include "support/convert.h"
23 #include "support/debug.h"
24 #include "support/FileName.h"
25 #include "support/filetools.h"
26 #include "support/ForkedCalls.h"
27 #include "support/lstrings.h"
28 #include "support/os.h"
30 #include "support/bind.h"
31 #include "support/TempFile.h"
37 using namespace lyx::support;
43 class Converter::Impl : public boost::signals2::trackable {
46 Impl(FileName const &, FileName const &, string const &, string const &, string const &);
49 void startConversion();
51 /** This method is connected to a signal passed to the forked call
52 * class, passing control back here when the conversion is completed.
53 * Cleans-up the temporary files, emits the finishedConversion
54 * signal and removes the Converter from the list of all processes.
56 void converted(pid_t pid, int retval);
58 /** At the end of the conversion process inform the outside world
59 * by emitting a signal.
61 typedef boost::signals2::signal<void(bool)> SignalType;
63 SignalType finishedConversion;
66 FileName const & doc_fname_;
68 string script_command_;
70 FileName script_file_;
80 bool Converter::isReachable(string const & from_format_name,
81 string const & to_format_name)
83 return theConverters().isReachable(from_format_name, to_format_name);
87 Converter::Converter(FileName const & doc_fname,
88 FileName const & from_file, string const & to_file_base,
89 string const & from_format, string const & to_format)
90 : pimpl_(new Impl(doc_fname, from_file, to_file_base, from_format, to_format))
94 Converter::~Converter()
100 void Converter::startConversion() const
102 pimpl_->startConversion();
106 boost::signals2::connection Converter::connect(slot_type const & slot) const
108 return pimpl_->finishedConversion.connect(slot);
112 FileName const & Converter::convertedFile() const
114 static FileName const empty;
115 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
118 /** Build the conversion script.
119 * The script is output to the stream \p script.
121 static void build_script(string const & doc_fname,
122 string const & from_file, string const & to_file_base,
123 string const & from_format, string const & to_format,
127 Converter::Impl::Impl(FileName const & doc_fname,
128 FileName const & from_file, string const & to_file_base,
129 string const & from_format, string const & to_format)
130 : doc_fname_(doc_fname), valid_process_(false), finished_(false)
132 LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
133 << "doc_fname: " << doc_fname
134 << "\n\tfrom_file: " << from_file
135 << "\n\tto_file_base: " << to_file_base
136 << "\n\tfrom_format: " << from_format
137 << "\n\tto_format: " << to_format);
139 // The converted image is to be stored in this file (we do not
140 // use ChangeExtension because this is a basename which may
141 // nevertheless contain a '.')
142 to_file_ = FileName(to_file_base + '.' + theFormats().extension(to_format));
144 // The conversion commands are stored in a stringstream
145 ostringstream script;
146 build_script(doc_fname_.absFileName(), from_file.toFilesystemEncoding(),
147 to_file_.toFilesystemEncoding(),
148 from_format, to_format, script);
149 LYXERR(Debug::GRAPHICS, "\tConversion script:"
150 "\n--------------------------------------\n"
152 << "\n--------------------------------------\n");
154 // Output the script to file.
155 TempFile tempfile(to_file_.onlyPath(), "lyxconvertXXXXXX.py");
156 tempfile.setAutoRemove(false);
157 script_file_ = tempfile.name();
159 ofstream fs(script_file_.toFilesystemEncoding().c_str());
161 lyxerr << "Unable to write the conversion script to \""
162 << script_file_ << '\n'
163 << "Please check your directory permissions."
171 // The command needed to run the conversion process
172 // We create a dummy command for ease of understanding of the
173 // list of forked processes.
174 // Note: 'python ' is absolutely essential, or execvp will fail.
175 script_command_ = os::python() + ' ' +
176 quoteName(script_file_.toFilesystemEncoding()) + ' ' +
177 quoteName(onlyFileName(from_file.toFilesystemEncoding())) + ' ' +
178 quoteName(to_format);
179 // All is ready to go
180 valid_process_ = true;
184 void Converter::Impl::startConversion()
186 if (!valid_process_) {
191 ForkedCall::SignalTypePtr ptr =
192 ForkedCallQueue::add(script_command_);
193 ptr->connect(bind(&Impl::converted, this, _1, _2));
197 void Converter::Impl::converted(pid_t /* pid */, int retval)
200 // We're done already!
204 // Clean-up behind ourselves
205 script_file_.removeFile();
208 to_file_.removeFile();
210 finishedConversion(false);
212 finishedConversion(true);
217 static string const move_file(string const & from_file, string const & to_file)
219 if (from_file == to_file)
222 ostringstream command;
223 command << "fromfile = " << from_file << "\n"
224 << "tofile = " << to_file << "\n\n"
226 << " os.rename(fromfile, tofile)\n"
229 << " shutil.copy(fromfile, tofile)\n"
232 << " unlinkNoThrow(fromfile)\n";
234 return command.str();
238 static void build_conversion_command(string const & command, ostream & script)
240 // Store in the python script
241 script << "\nif os.system(r'" << commandPrep(command) << "') != 0:\n";
243 // Test that this was successful. If not, remove
244 // ${outfile} and exit the python script
245 script << " unlinkNoThrow(outfile)\n"
246 << " sys.exit(1)\n\n";
248 // Test that the outfile exists.
249 // ImageMagick's convert will often create ${outfile}.0,
251 // If this occurs, move ${outfile}.0 to ${outfile}
252 // and delete ${outfile}.? (ignore errors)
253 script << "if not os.path.isfile(outfile):\n"
254 " if os.path.isfile(outfile + '.0'):\n"
255 " os.rename(outfile + '.0', outfile)\n"
257 " for file in glob.glob(outfile + '.?'):\n"
258 " unlinkNoThrow(file)\n"
263 script << "if infile != outfile:\n"
264 " unlinkNoThrow(infile)\n\n";
268 static string const strip_digit(string const & format)
270 // Strip trailing digits from format names e.g. "pdf6" -> "pdf"
271 return format.substr(0, format.find_last_not_of("0123456789") + 1);
275 static void build_script(string const & doc_fname,
276 string const & from_file,
277 string const & to_file,
278 string const & from_format,
279 string const & to_format,
282 LASSERT(from_format != to_format, return);
283 LYXERR(Debug::GRAPHICS, "build_script ... ");
284 typedef Graph::EdgePath EdgePath;
286 script << "#!/usr/bin/env python\n"
287 "# -*- coding: utf-8 -*-\n"
288 "import os, shutil, sys\n\n"
289 "def unlinkNoThrow(file):\n"
290 " ''' remove a file, do not throw if an error occurs '''\n"
296 EdgePath const edgepath = from_format.empty() ?
298 theConverters().getPath(from_format, to_format);
300 // Create a temporary base file-name for all intermediate steps.
301 string const from_ext = getExtension(from_file);
302 TempFile tempfile(addExtension("gconvertXXXXXX", from_ext));
303 tempfile.setAutoRemove(false);
304 string outfile = tempfile.name().toFilesystemEncoding();
305 string const to_base = from_ext.empty() ? outfile : removeExtension(outfile);
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 script << "infile = "
312 << quoteName(from_file, quote_python)
315 << quoteName(outfile, quote_python) << "\n"
316 "shutil.copy(infile, outfile)\n";
318 // Some converters (e.g. lilypond) can only output files to the
319 // current directory, so we need to change the current directory.
320 // This has the added benefit that all other files that may be
321 // generated by the converter are deleted when LyX closes and do not
322 // clutter the real working directory.
323 script << "os.chdir("
324 << quoteName(onlyPath(outfile)) << ")\n";
326 if (edgepath.empty()) {
327 // Either from_format is unknown or we don't have a
328 // converter path from from_format to to_format, so we use
329 // the default converter.
330 script << "infile = outfile\n"
332 << quoteName(to_file, quote_python) << "\n";
335 os << os::python() << ' '
336 << commandPrep("$$s/scripts/convertDefault.py") << ' ';
337 if (from_format.empty())
340 os << strip_digit(from_format) << ' ';
341 // The extra " quotes around infile and outfile are needed
342 // because the filename may contain spaces and it is used
343 // as argument of os.system().
344 os << "' + '\"' + infile + '\"' + ' "
345 << strip_digit(to_format) << " ' + '\"' + outfile + '\"' + '";
346 string const command = os.str();
348 LYXERR(Debug::GRAPHICS,
349 "\tNo converter defined! I use convertDefault.py\n\t"
352 build_conversion_command(command, script);
355 // The conversion commands may contain these tokens that need to be
356 // changed to infile, infile_base, outfile and output directory respectively.
357 string const token_from = "$$i";
358 string const token_base = "$$b";
359 string const token_to = "$$o";
360 string const token_todir = "$$d";
362 EdgePath::const_iterator it = edgepath.begin();
363 EdgePath::const_iterator end = edgepath.end();
365 for (; it != end; ++it) {
366 lyx::Converter const & conv = theConverters().get(*it);
368 // Build the conversion command
369 string const infile = outfile;
370 string const infile_base = changeExtension(infile, string());
371 outfile = conv.result_file().empty()
372 ? addExtension(to_base, conv.To()->extension())
373 : addName(subst(conv.result_dir(),
374 token_base, infile_base),
375 subst(conv.result_file(),
376 token_base, onlyFileName(infile_base)));
378 // If two formats share the same extension we may get identical names
379 if (outfile == infile && conv.result_file().empty()) {
380 TempFile tempfile(addExtension("gconvertXXXXXX", conv.To()->extension()));
381 tempfile.setAutoRemove(false);
382 outfile = tempfile.name().toFilesystemEncoding();
385 if (!theConverters().checkAuth(conv, doc_fname))
388 // Store these names in the python script
389 script << "infile = "
390 << quoteName(infile, quote_python) << "\n"
392 << quoteName(infile_base, quote_python) << "\n"
394 << quoteName(outfile, quote_python) << "\n"
395 "outdir = os.path.dirname(outfile)\n" ;
397 // See comment about extra " quotes above (although that
398 // applies only for the first loop run here).
399 string command = conv.command();
400 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
401 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
402 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
403 command = subst(command, token_todir, "' + '\"' + outdir + '\"' + '");
405 build_conversion_command(command, script);
408 // Move the final outfile to to_file
409 script << move_file("outfile", quoteName(to_file, quote_python));
410 LYXERR(Debug::GRAPHICS, "ready!");
413 } // namespace graphics