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/lassert.h"
19 #include "support/convert.h"
20 #include "support/debug.h"
21 #include "support/FileName.h"
22 #include "support/filetools.h"
23 #include "support/ForkedCalls.h"
24 #include "support/lstrings.h"
26 #include "support/TempFile.h"
32 using namespace lyx::support;
38 class Converter::Impl {
41 Impl(FileName const & doc_fname,
42 FileName const & from_file, string const & to_file_base,
43 string const & from_format, string const & to_format);
46 void startConversion();
48 /** This method is connected to a signal passed to the forked call
49 * class, passing control back here when the conversion is completed.
50 * Cleans-up the temporary files, emits the finishedConversion
51 * signal and removes the Converter from the list of all processes.
53 void converted(pid_t pid, int retval);
55 /** At the end of the conversion process inform the outside world
56 * by emitting a signal.
58 typedef signals2::signal<void(bool)> sig;
60 sig finishedConversion;
63 FileName const doc_fname_;
65 string script_command_;
67 FileName script_file_;
79 bool Converter::isReachable(string const & from_format_name,
80 string const & to_format_name)
82 return theConverters().isReachable(from_format_name, to_format_name);
86 Converter::Converter(FileName const & doc_fname,
87 FileName const & from_file, string const & to_file_base,
88 string const & from_format, string const & to_format)
89 : pimpl_(new Impl(doc_fname, from_file, to_file_base, from_format, to_format))
93 Converter::~Converter()
99 void Converter::startConversion() const
101 pimpl_->startConversion();
105 signals2::connection Converter::connect(slot_type const & slot) const
107 return pimpl_->finishedConversion.connect(slot);
111 FileName const & Converter::convertedFile() const
113 static FileName const empty;
114 return pimpl_->finished_ ? pimpl_->to_file_ : empty;
117 /** Build the conversion script.
118 * The script is output to the stream \p script.
120 static void build_script(string const & doc_fname,
121 string const & from_file, string const & to_file_base,
122 string const & from_format, string const & to_format,
126 Converter::Impl::Impl(FileName const & doc_fname,
127 FileName const & from_file, string const & to_file_base,
128 string const & from_format, string const & to_format)
129 : doc_fname_(doc_fname), valid_process_(false), finished_(false)
131 LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
132 << "doc_fname: " << doc_fname
133 << "\n\tfrom_file: " << from_file
134 << "\n\tto_file_base: " << to_file_base
135 << "\n\tfrom_format: " << from_format
136 << "\n\tto_format: " << to_format);
138 // The converted image is to be stored in this file (we do not
139 // use ChangeExtension because this is a basename which may
140 // nevertheless contain a '.')
141 to_file_ = FileName(to_file_base + '.' + theFormats().extension(to_format));
143 // The conversion commands are stored in a stringstream
144 ostringstream script;
145 build_script(doc_fname_.absFileName(), from_file.toFilesystemEncoding(),
146 to_file_.toFilesystemEncoding(),
147 from_format, to_format, script);
148 LYXERR(Debug::GRAPHICS, "\tConversion script:"
149 "\n--------------------------------------\n"
151 << "\n--------------------------------------\n");
153 // Output the script to file.
154 TempFile tempfile(to_file_.onlyPath(), "lyxconvertXXXXXX.py");
155 tempfile.setAutoRemove(false);
156 script_file_ = tempfile.name();
158 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_ = 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::sigPtr ptr = ForkedCallQueue::add(script_command_);
191 ptr->connect(ForkedCall::slot([this](pid_t pid, int retval){
192 converted(pid, retval);
193 }).track_foreign(tracker_.p()));
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 << "# -*- coding: utf-8 -*-\n"
287 "import os, shutil, sys\n\n"
288 "def unlinkNoThrow(file):\n"
289 " ''' remove a file, do not throw if an error occurs '''\n"
295 EdgePath const edgepath = from_format.empty() ?
297 theConverters().getPath(from_format, to_format);
299 // Create a temporary base file-name for all intermediate steps.
300 string const from_ext = getExtension(from_file);
301 TempFile tempfile(addExtension("gconvertXXXXXX", from_ext));
302 tempfile.setAutoRemove(false);
303 string outfile = tempfile.name().toFilesystemEncoding();
304 string const to_base = from_ext.empty() ? outfile : removeExtension(outfile);
306 // Create a copy of the file in case the original name contains
307 // problematic characters like ' or ". We can work around that problem
308 // in python, but the converters might be shell scripts and have more
310 script << "infile = "
311 << quoteName(from_file, quote_python)
314 << quoteName(outfile, quote_python) << "\n"
315 "shutil.copy(infile, outfile)\n";
317 // Some converters (e.g. lilypond) can only output files to the
318 // current directory, so we need to change the current directory.
319 // This has the added benefit that all other files that may be
320 // generated by the converter are deleted when LyX closes and do not
321 // clutter the real working directory.
322 script << "os.chdir("
323 << quoteName(onlyPath(outfile)) << ")\n";
325 if (edgepath.empty()) {
326 // Either from_format is unknown or we don't have a
327 // converter path from from_format to to_format, so we use
328 // the default converter.
329 script << "infile = outfile\n"
331 << quoteName(to_file, quote_python) << "\n";
334 os << os::python() << ' '
335 << commandPrep("$$s/scripts/convertDefault.py") << ' ';
336 if (from_format.empty())
339 os << strip_digit(from_format) << ' ';
340 // The extra " quotes around infile and outfile are needed
341 // because the filename may contain spaces and it is used
342 // as argument of os.system().
343 os << "' + '\"' + infile + '\"' + ' "
344 << strip_digit(to_format) << " ' + '\"' + outfile + '\"' + '";
345 string const command = os.str();
347 LYXERR(Debug::GRAPHICS,
348 "\tNo converter defined! I use convertDefault.py\n\t"
351 build_conversion_command(command, script);
354 // The conversion commands may contain these tokens that need to be
355 // changed to infile, infile_base, outfile and output directory respectively.
356 string const token_from = "$$i";
357 string const token_base = "$$b";
358 string const token_to = "$$o";
359 string const token_todir = "$$d";
361 EdgePath::const_iterator it = edgepath.begin();
362 EdgePath::const_iterator end = edgepath.end();
364 for (; it != end; ++it) {
365 lyx::Converter const & conv = theConverters().get(*it);
367 // Build the conversion command
368 string const infile = outfile;
369 string const infile_base = changeExtension(infile, string());
370 outfile = conv.result_file().empty()
371 ? addExtension(to_base, conv.To()->extension())
372 : addName(subst(conv.result_dir(),
373 token_base, infile_base),
374 subst(conv.result_file(),
375 token_base, onlyFileName(infile_base)));
377 // If two formats share the same extension we may get identical names
378 if (outfile == infile && conv.result_file().empty()) {
379 TempFile tmpfile(addExtension("gconvertXXXXXX", conv.To()->extension()));
380 tmpfile.setAutoRemove(false);
381 outfile = tmpfile.name().toFilesystemEncoding();
384 if (!theConverters().checkAuth(conv, doc_fname))
387 // Store these names in the python script
388 script << "infile = "
389 << quoteName(infile, quote_python) << "\n"
391 << quoteName(infile_base, quote_python) << "\n"
393 << quoteName(outfile, quote_python) << "\n"
394 "outdir = os.path.dirname(outfile)\n" ;
396 // See comment about extra " quotes above (although that
397 // applies only for the first loop run here).
398 string command = conv.command();
399 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
400 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
401 command = subst(command, token_to, "' + '\"' + outfile + '\"' + '");
402 command = subst(command, token_todir, "' + '\"' + outdir + '\"' + '");
404 build_conversion_command(command, script);
407 // Move the final outfile to to_file
408 script << move_file("outfile", quoteName(to_file, quote_python));
409 LYXERR(Debug::GRAPHICS, "ready!");
412 } // namespace graphics