]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.cpp
* docstream: factorize out some code and introduce odocfstream::reset()
[lyx.git] / src / graphics / GraphicsConverter.cpp
1 /**
2  * \file GraphicsConverter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GraphicsConverter.h"
14
15 #include "Converter.h"
16 #include "Format.h"
17
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"
25
26 #include <boost/bind.hpp>
27
28 #include <sstream>
29 #include <fstream>
30
31 namespace support = lyx::support;
32
33 using support::addExtension;
34 using support::changeExtension;
35 using support::FileName;
36 using support::ForkedCall;
37 using support::getExtension;
38 using support::libScriptSearch;
39 using support::onlyPath;
40 using support::onlyFilename;
41 using support::quoteName;
42 using support::quote_python;
43 using support::subst;
44 using support::tempName;
45
46 using std::endl;
47 using std::ostream;
48 using std::ostringstream;
49 using std::string;
50
51
52 namespace lyx {
53 namespace graphics {
54
55 class Converter::Impl : public boost::signals::trackable {
56 public:
57         ///
58         Impl(FileName const &, string const &, string const &, string const &);
59
60         ///
61         void startConversion();
62
63         /** This method is connected to a signal passed to the forked call
64          *  class, passing control back here when the conversion is completed.
65          *  Cleans-up the temporary files, emits the finishedConversion
66          *  signal and removes the Converter from the list of all processes.
67          */
68         void converted(pid_t pid, int retval);
69
70         /** At the end of the conversion process inform the outside world
71          *  by emitting a signal.
72          */
73         typedef boost::signal<void(bool)> SignalType;
74         ///
75         SignalType finishedConversion;
76
77         ///
78         string script_command_;
79         ///
80         FileName script_file_;
81         ///
82         FileName to_file_;
83         ///
84         bool valid_process_;
85         ///
86         bool finished_;
87 };
88
89
90 bool Converter::isReachable(string const & from_format_name,
91                             string const & to_format_name)
92 {
93         return theConverters().isReachable(from_format_name, to_format_name);
94 }
95
96
97 Converter::Converter(FileName const & from_file, string const & to_file_base,
98                      string const & from_format, string const & to_format)
99         : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
100 {}
101
102
103 Converter::~Converter()
104 {
105         delete pimpl_;
106 }
107
108
109 void Converter::startConversion() const
110 {
111         pimpl_->startConversion();
112 }
113
114
115 boost::signals::connection Converter::connect(slot_type const & slot) const
116 {
117         return pimpl_->finishedConversion.connect(slot);
118 }
119
120
121 FileName const & Converter::convertedFile() const
122 {
123         static FileName const empty;
124         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
125 }
126
127 /** Build the conversion script.
128  *  The script is output to the stream \p script.
129  */
130 static void build_script(FileName const & from_file, string const & to_file_base,
131                   string const & from_format, string const & to_format,
132                   ostream & script);
133
134
135 Converter::Impl::Impl(FileName const & from_file, string const & to_file_base,
136                       string const & from_format, string const & to_format)
137         : valid_process_(false), finished_(false)
138 {
139         LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
140                 << "\tfrom_file:      " << from_file
141                 << "\n\tto_file_base: " << to_file_base
142                 << "\n\tfrom_format:  " << from_format
143                 << "\n\tto_format:    " << to_format);
144
145         // The converted image is to be stored in this file (we do not
146         // use ChangeExtension because this is a basename which may
147         // nevertheless contain a '.')
148         to_file_ = FileName(to_file_base + '.' +  formats.extension(to_format));
149
150         // The conversion commands are stored in a stringstream
151         ostringstream script;
152         build_script(from_file, to_file_base, from_format, to_format, script);
153         LYXERR(Debug::GRAPHICS, "\tConversion script:"
154                    "\n--------------------------------------\n"
155                 << script.str()
156                 << "\n--------------------------------------\n");
157
158         // Output the script to file.
159         static int counter = 0;
160         script_file_ = FileName(onlyPath(to_file_base) + "lyxconvert" +
161                 convert<string>(counter++) + ".py");
162
163         std::ofstream fs(script_file_.toFilesystemEncoding().c_str());
164         if (!fs.good()) {
165                 lyxerr << "Unable to write the conversion script to \""
166                        << script_file_ << '\n'
167                        << "Please check your directory permissions."
168                        << std::endl;
169                 return;
170         }
171
172         fs << script.str();
173         fs.close();
174
175         // The command needed to run the conversion process
176         // We create a dummy command for ease of understanding of the
177         // list of forked processes.
178         // Note: 'python ' is absolutely essential, or execvp will fail.
179         script_command_ = support::os::python() + ' ' +
180                 quoteName(script_file_.toFilesystemEncoding()) + ' ' +
181                 quoteName(onlyFilename(from_file.toFilesystemEncoding())) + ' ' +
182                 quoteName(to_format);
183         // All is ready to go
184         valid_process_ = true;
185 }
186
187
188 void Converter::Impl::startConversion()
189 {
190         if (!valid_process_) {
191                 converted(0, 1);
192                 return;
193         }
194
195         ForkedCall::SignalTypePtr ptr =
196                 support::ForkedCallQueue::add(script_command_);
197         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
198 }
199
200
201 void Converter::Impl::converted(pid_t /* pid */, int retval)
202 {
203         if (finished_)
204                 // We're done already!
205                 return;
206
207         finished_ = true;
208         // Clean-up behind ourselves
209         script_file_.removeFile();
210
211         if (retval > 0) {
212                 to_file_.removeFile();
213                 to_file_.erase();
214                 finishedConversion(false);
215         } else {
216                 finishedConversion(true);
217         }
218 }
219
220
221 static string const move_file(string const & from_file, string const & to_file)
222 {
223         if (from_file == to_file)
224                 return string();
225
226         ostringstream command;
227         command << "fromfile = utf8ToDefaultEncoding(" << from_file << ")\n"
228                 << "tofile = utf8ToDefaultEncoding("   << to_file << ")\n\n"
229                 << "try:\n"
230                 << "  os.rename(fromfile, tofile)\n"
231                 << "except:\n"
232                 << "  try:\n"
233                 << "    shutil.copy(fromfile, tofile)\n"
234                 << "  except:\n"
235                 << "    sys.exit(1)\n"
236                 << "  unlinkNoThrow(fromfile)\n";
237
238         return command.str();
239 }
240
241
242 static void build_conversion_command(string const & command, ostream & script)
243 {
244         // Store in the python script
245         script << "\nif os.system(r'" << command << "') != 0:\n";
246
247         // Test that this was successful. If not, remove
248         // ${outfile} and exit the python script
249         script << "  unlinkNoThrow(outfile)\n"
250                << "  sys.exit(1)\n\n";
251
252         // Test that the outfile exists.
253         // ImageMagick's convert will often create ${outfile}.0,
254         // ${outfile}.1.
255         // If this occurs, move ${outfile}.0 to ${outfile}
256         // and delete ${outfile}.? (ignore errors)
257         script << "if not os.path.isfile(outfile):\n"
258                   "  if os.path.isfile(outfile + '.0'):\n"
259                   "    os.rename(outfile + '.0', outfile)\n"
260                   "    import glob\n"
261                   "    for file in glob.glob(outfile + '.?'):\n"
262                   "      unlinkNoThrow(file)\n"
263                   "  else:\n"
264                   "    sys.exit(1)\n\n";
265
266         // Delete the infile
267         script << "unlinkNoThrow(infile)\n\n";
268 }
269
270
271 static void build_script(FileName const & from_file,
272                   string const & to_file_base,
273                   string const & from_format,
274                   string const & to_format,
275                   ostream & script)
276 {
277         BOOST_ASSERT(from_format != to_format);
278         LYXERR(Debug::GRAPHICS, "build_script ... ");
279         typedef Converters::EdgePath EdgePath;
280
281         script << "#!/usr/bin/env python\n"
282                   "# -*- coding: utf-8 -*-\n"
283                   "import os, shutil, sys, locale\n\n"
284                   "def unlinkNoThrow(file):\n"
285                   "  ''' remove a file, do not throw if an error occurs '''\n"
286                   "  try:\n"
287                   "    os.unlink(file)\n"
288                   "  except:\n"
289                   "    pass\n\n"
290                   "def utf8ToDefaultEncoding(file):\n"
291                   "  ''' if possible, convert to the default encoding '''\n"
292                   "  try:\n"
293                   "    language, output_encoding = locale.getdefaultlocale()\n"
294                   "    if output_encoding == None:\n"
295                   "      output_encoding = 'latin1'\n"
296                   "    return unicode(file, 'utf8').encode(output_encoding)\n"
297                   "  except:\n"
298                   "    return file\n\n";
299
300         // we do not use ChangeExtension because this is a basename
301         // which may nevertheless contain a '.'
302         string const to_file = to_file_base + '.'
303                 + formats.extension(to_format);
304
305         EdgePath const edgepath = from_format.empty() ?
306                 EdgePath() :
307                 theConverters().getPath(from_format, to_format);
308
309         // Create a temporary base file-name for all intermediate steps.
310         // Remember to remove the temp file because we only want the name...
311         static int counter = 0;
312         string const tmp = "gconvert" + convert<string>(counter++);
313         FileName const to_base(tempName(FileName(), tmp));
314         to_base.removeFile();
315
316         // Create a copy of the file in case the original name contains
317         // problematic characters like ' or ". We can work around that problem
318         // in python, but the converters might be shell scripts and have more
319         // troubles with it.
320         string outfile = addExtension(to_base.absFilename(), getExtension(from_file.absFilename()));
321         script << "infile = utf8ToDefaultEncoding("
322                         << quoteName(from_file.absFilename(), quote_python)
323                         << ")\n"
324                   "outfile = utf8ToDefaultEncoding("
325                         << quoteName(outfile, quote_python) << ")\n"
326                   "shutil.copy(infile, outfile)\n";
327
328         // Some converters (e.g. lilypond) can only output files to the
329         // current directory, so we need to change the current directory.
330         // This has the added benefit that all other files that may be
331         // generated by the converter are deleted when LyX closes and do not
332         // clutter the real working directory.
333         script << "os.chdir(utf8ToDefaultEncoding("
334                << quoteName(onlyPath(outfile)) << "))\n";
335
336         if (edgepath.empty()) {
337                 // Either from_format is unknown or we don't have a
338                 // converter path from from_format to to_format, so we use
339                 // the default converter.
340                 script << "infile = outfile\n"
341                        << "outfile = utf8ToDefaultEncoding("
342                        << quoteName(to_file, quote_python) << ")\n";
343
344                 ostringstream os;
345                 os << support::os::python() << ' '
346                    << libScriptSearch("$$s/scripts/convertDefault.py",
347                                       quote_python) << ' ';
348                 if (!from_format.empty())
349                         os << from_format << ':';
350                 // The extra " quotes around infile and outfile are needed
351                 // because the filename may contain spaces and it is used
352                 // as argument of os.system().
353                 os << "' + '\"' + infile + '\"' + ' "
354                    << to_format << ":' + '\"' + outfile + '\"' + '";
355                 string const command = os.str();
356
357                 LYXERR(Debug::GRAPHICS,
358                         "\tNo converter defined! I use convertDefault.py\n\t"
359                         << command);
360
361                 build_conversion_command(command, script);
362         }
363
364         // The conversion commands may contain these tokens that need to be
365         // changed to infile, infile_base, outfile respectively.
366         string const token_from = "$$i";
367         string const token_base = "$$b";
368         string const token_to   = "$$o";
369
370         EdgePath::const_iterator it  = edgepath.begin();
371         EdgePath::const_iterator end = edgepath.end();
372
373         for (; it != end; ++it) {
374                 lyx::Converter const & conv = theConverters().get(*it);
375
376                 // Build the conversion command
377                 string const infile      = outfile;
378                 string const infile_base = changeExtension(infile, string());
379                 outfile = addExtension(to_base.absFilename(), conv.To->extension());
380
381                 // Store these names in the python script
382                 script << "infile = utf8ToDefaultEncoding("
383                                 << quoteName(infile, quote_python) << ")\n"
384                           "infile_base = utf8ToDefaultEncoding("
385                                 << quoteName(infile_base, quote_python) << ")\n"
386                           "outfile = utf8ToDefaultEncoding("
387                                 << quoteName(outfile, quote_python) << ")\n";
388
389                 // See comment about extra " quotes above (although that
390                 // applies only for the first loop run here).
391                 string command = conv.command;
392                 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
393                 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
394                 command = subst(command, token_to,   "' + '\"' + outfile + '\"' + '");
395                 command = libScriptSearch(command, quote_python);
396
397                 build_conversion_command(command, script);
398         }
399
400         // Move the final outfile to to_file
401         script << move_file("outfile", quoteName(to_file, quote_python));
402         LYXERR(Debug::GRAPHICS, "ready!");
403 }
404
405 } // namespace graphics
406 } // namespace lyx