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