]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
Fix bug 2637
[lyx.git] / src / graphics / GraphicsConverter.C
1 /**
2  * \file GraphicsConverter.C
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 "debug.h"
17 #include "format.h"
18
19 #include "support/filetools.h"
20 #include "support/forkedcallqueue.h"
21 #include "support/convert.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::changeExtension;
34 using support::Forkedcall;
35 using support::ForkedCallQueue;
36 using support::getExtension;
37 using support::libFileSearch;
38 using support::libScriptSearch;
39 using support::onlyPath;
40 using support::onlyFilename;
41 using support::quoteName;
42 using support::subst;
43 using support::tempName;
44 using support::unlink;
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(string 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         string script_file_;
81         ///
82         string 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 converters.isReachable(from_format_name, to_format_name);
94 }
95
96
97 Converter::Converter(string 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 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
104 Converter::~Converter()
105 {}
106
107
108 void Converter::startConversion() const
109 {
110         pimpl_->startConversion();
111 }
112
113
114 boost::signals::connection Converter::connect(slot_type const & slot) const
115 {
116         return pimpl_->finishedConversion.connect(slot);
117 }
118
119
120 string const & Converter::convertedFile() const
121 {
122         static string const empty;
123         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
124 }
125
126 } // namespace graphics
127 } // namespace lyx
128
129
130 //------------------------------
131 // Implementation details follow
132 //------------------------------
133
134 namespace {
135
136 /** Build the conversion script, returning true if able to build it.
137  *  The script is output to the ostringstream 'script'.
138  */
139 bool build_script(string const & from_file, string const & to_file_base,
140                   string const & from_format, string const & to_format,
141                   ostream & script);
142
143 } // namespace anon
144
145
146 namespace lyx {
147 namespace graphics {
148
149 Converter::Impl::Impl(string const & from_file,   string const & to_file_base,
150                       string const & from_format, string const & to_format)
151         : valid_process_(false), finished_(false)
152 {
153         lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
154                 << "\tfrom_file:      " << from_file
155                 << "\n\tto_file_base: " << to_file_base
156                 << "\n\tfrom_format:  " << from_format
157                 << "\n\tto_format:    " << to_format << endl;
158
159         // The converted image is to be stored in this file (we do not
160         // use ChangeExtension because this is a basename which may
161         // nevertheless contain a '.')
162         to_file_ = to_file_base + '.' +  formats.extension(to_format);
163
164         // The conversion commands are stored in a stringstream
165         ostringstream script;
166         bool const success = build_script(from_file, to_file_base,
167                                           from_format, to_format, script);
168
169         if (!success) {
170                 script_command_ =
171                         support::os::python() + ' ' +
172                         quoteName(libFileSearch("scripts", "convertDefault.py")) +
173                         ' ' +
174                         quoteName((from_format.empty() ? "" : from_format + ':') + from_file) +
175                         ' ' +
176                         quoteName(to_format + ':' + to_file_);
177
178                 lyxerr[Debug::GRAPHICS]
179                         << "\tNo converter defined! I use convertDefault.py\n\t"
180                         << script_command_ << endl;
181
182         } else {
183
184                 lyxerr[Debug::GRAPHICS] << "\tConversion script:"
185                         << "\n--------------------------------------\n"
186                         << script.str()
187                         << "\n--------------------------------------\n";
188
189                 // Output the script to file.
190                 static int counter = 0;
191                 script_file_ = onlyPath(to_file_base) + "lyxconvert" +
192                         convert<string>(counter++) + ".py";
193
194                 std::ofstream fs(script_file_.c_str());
195                 if (!fs.good()) {
196                         lyxerr << "Unable to write the conversion script to \""
197                                << script_file_ << '\n'
198                                << "Please check your directory permissions."
199                                << std::endl;
200                         return;
201                 }
202
203                 fs << script.str();
204                 fs.close();
205
206                 // The command needed to run the conversion process
207                 // We create a dummy command for ease of understanding of the
208                 // list of forked processes.
209                 // Note: 'sh ' is absolutely essential, or execvp will fail.
210                 script_command_ = support::os::python() + ' ' +
211                         quoteName(script_file_) + ' ' +
212                         quoteName(onlyFilename(from_file)) + ' ' +
213                         quoteName(to_format);
214         }
215         // All is ready to go
216         valid_process_ = true;
217 }
218
219
220 void Converter::Impl::startConversion()
221 {
222         if (!valid_process_) {
223                 converted(0, 1);
224                 return;
225         }
226
227         Forkedcall::SignalTypePtr
228                 ptr = ForkedCallQueue::get().add(script_command_);
229
230         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
231
232 }
233
234 void Converter::Impl::converted(pid_t /* pid */, int retval)
235 {
236         if (finished_)
237                 // We're done already!
238                 return;
239
240         finished_ = true;
241         // Clean-up behind ourselves
242         unlink(script_file_);
243
244         if (retval > 0) {
245                 unlink(to_file_);
246                 to_file_.erase();
247                 finishedConversion(false);
248         } else {
249                 finishedConversion(true);
250         }
251 }
252
253 } // namespace graphics
254 } // namespace lyx
255
256 namespace {
257
258 string const move_file(string const & from_file, string const & to_file)
259 {
260         if (from_file == to_file)
261                 return string();
262
263         ostringstream command;
264         command << "fromfile = " << from_file << "\n"
265                 << "tofile = "   << to_file << "\n\n"
266                 << "try:\n"
267                 << "  os.rename(fromfile, tofile)\n"
268                 << "except:\n"
269                 << "  try:\n"
270                 << "    shutil.copy(fromfile, tofile)\n"
271                 << "  except:\n"
272                 << "    sys.exit(1)\n"
273                 << "  unlinkNoThrow(fromfile)\n";
274
275         return command.str();
276 }
277
278
279 bool build_script(string const & from_file,
280                   string const & to_file_base,
281                   string const & from_format,
282                   string const & to_format,
283                   ostream & script)
284 {
285         BOOST_ASSERT(from_format != to_format);
286         lyxerr[Debug::GRAPHICS] << "build_script ... ";
287         typedef Converters::EdgePath EdgePath;
288
289         if (from_format.empty())
290                 return false;
291
292         script << "#!/usr/bin/env python -tt\n"
293                   "import os, shutil, sys\n\n"
294                   "def unlinkNoThrow(file):\n"
295                   "  ''' remove a file, do not throw if an error occurs '''\n"
296                   "  try:\n"
297                   "    os.unlink(file)\n"
298                   "  except:\n"
299                   "    pass\n\n";
300
301         // we do not use ChangeExtension because this is a basename
302         // which may nevertheless contain a '.'
303         string const to_file = to_file_base + '.'
304                 + formats.extension(to_format);
305
306         EdgePath edgepath = converters.getPath(from_format, to_format);
307
308         if (edgepath.empty()) {
309                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
310                 return false;
311         }
312
313         // Create a temporary base file-name for all intermediate steps.
314         // Remember to remove the temp file because we only want the name...
315         static int counter = 0;
316         string const tmp = "gconvert" + convert<string>(counter++);
317         string const to_base = tempName(string(), tmp);
318         unlink(to_base);
319
320         // Create a copy of the file in case the original name contains
321         // problematic characters like ' or ". We can work around that problem
322         // in python, but the converters might be shell scripts and have more
323         // troubles with it.
324         string outfile = changeExtension(to_base, getExtension(from_file));
325         script << "infile = '"
326                << subst(subst(from_file, "\\", "\\\\"), "'", "\\'") << "'\n"
327                   "outfile = " << quoteName(outfile) << "\n"
328                   "shutil.copy(infile, outfile)\n";
329
330         // The conversion commands may contain these tokens that need to be
331         // changed to infile, infile_base, outfile respectively.
332         string const token_from("$$i");
333         string const token_base("$$b");
334         string const token_to("$$o");
335
336         EdgePath::const_iterator it  = edgepath.begin();
337         EdgePath::const_iterator end = edgepath.end();
338
339         for (; it != end; ++it) {
340                 ::Converter const & conv = converters.get(*it);
341
342                 // Build the conversion command
343                 string const infile      = outfile;
344                 string const infile_base = changeExtension(infile, string());
345                 outfile = changeExtension(to_base, conv.To->extension());
346
347                 // Store these names in the shell script
348                 script << "infile = "      << quoteName(infile) << '\n'
349                        << "infile_base = " << quoteName(infile_base) << '\n'
350                        << "outfile = "     << quoteName(outfile) << '\n';
351
352                 string command = conv.command;
353                 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
354                 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
355                 command = subst(command, token_to,   "' + '\"' + outfile + '\"' + '");
356                 command = libScriptSearch(command);
357
358                 // Store in the shell script
359                 script << "\nif os.system(r'" << command << "') != 0:\n";
360
361                 // Test that this was successful. If not, remove
362                 // ${outfile} and exit the shell script
363                 script << "  unlinkNoThrow(outfile)\n"
364                        << "  sys.exit(1)\n\n";
365
366                 // Test that the outfile exists.
367                 // ImageMagick's convert will often create ${outfile}.0,
368                 // ${outfile}.1.
369                 // If this occurs, move ${outfile}.0 to ${outfile}
370                 // and delete ${outfile}.? (ignore errors)
371                 script << "if not os.path.isfile(outfile):\n"
372                           "  if os.path.isfile(outfile + '.0'):\n"
373                           "    os.rename(outfile + '.0', outfile)\n"
374                           "    import glob\n"
375                           "    for file in glob.glob(outfile + '.?'):\n"
376                           "      unlinkNoThrow(file)\n"
377                           "  else:\n"
378                           "    sys.exit(1)\n\n";
379
380                 // Delete the infile
381                 script << "unlinkNoThrow(infile)\n\n";
382         }
383
384         // Move the final outfile to to_file
385         script << move_file("outfile", quoteName(to_file));
386         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
387
388         return true;
389 }
390
391 } // namespace anon