]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
minimal effort implementation of:
[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.
137  *  The script is output to the stream \p script.
138  */
139 void 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         build_script(from_file, to_file_base, from_format, to_format, script);
167         lyxerr[Debug::GRAPHICS] << "\tConversion script:"
168                 << "\n--------------------------------------\n"
169                 << script.str()
170                 << "\n--------------------------------------\n";
171
172         // Output the script to file.
173         static int counter = 0;
174         script_file_ = onlyPath(to_file_base) + "lyxconvert" +
175                 convert<string>(counter++) + ".py";
176
177         std::ofstream fs(script_file_.c_str());
178         if (!fs.good()) {
179                 lyxerr << "Unable to write the conversion script to \""
180                        << script_file_ << '\n'
181                        << "Please check your directory permissions."
182                        << std::endl;
183                 return;
184         }
185
186         fs << script.str();
187         fs.close();
188
189         // The command needed to run the conversion process
190         // We create a dummy command for ease of understanding of the
191         // list of forked processes.
192         // Note: 'python ' is absolutely essential, or execvp will fail.
193         script_command_ = support::os::python() + ' ' +
194                 quoteName(script_file_) + ' ' +
195                 quoteName(onlyFilename(from_file)) + ' ' +
196                 quoteName(to_format);
197         // All is ready to go
198         valid_process_ = true;
199 }
200
201
202 void Converter::Impl::startConversion()
203 {
204         if (!valid_process_) {
205                 converted(0, 1);
206                 return;
207         }
208
209         Forkedcall::SignalTypePtr
210                 ptr = ForkedCallQueue::get().add(script_command_);
211
212         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
213
214 }
215
216 void Converter::Impl::converted(pid_t /* pid */, int retval)
217 {
218         if (finished_)
219                 // We're done already!
220                 return;
221
222         finished_ = true;
223         // Clean-up behind ourselves
224         unlink(script_file_);
225
226         if (retval > 0) {
227                 unlink(to_file_);
228                 to_file_.erase();
229                 finishedConversion(false);
230         } else {
231                 finishedConversion(true);
232         }
233 }
234
235 } // namespace graphics
236 } // namespace lyx
237
238 namespace {
239
240 string const move_file(string const & from_file, string const & to_file)
241 {
242         if (from_file == to_file)
243                 return string();
244
245         ostringstream command;
246         command << "fromfile = " << from_file << "\n"
247                 << "tofile = "   << to_file << "\n\n"
248                 << "try:\n"
249                 << "  os.rename(fromfile, tofile)\n"
250                 << "except:\n"
251                 << "  try:\n"
252                 << "    shutil.copy(fromfile, tofile)\n"
253                 << "  except:\n"
254                 << "    sys.exit(1)\n"
255                 << "  unlinkNoThrow(fromfile)\n";
256
257         return command.str();
258 }
259
260
261 void build_conversion_command(string const & command, ostream & script)
262 {
263         // Store in the python script
264         script << "\nif os.system(r'" << command << "') != 0:\n";
265
266         // Test that this was successful. If not, remove
267         // ${outfile} and exit the python script
268         script << "  unlinkNoThrow(outfile)\n"
269                << "  sys.exit(1)\n\n";
270
271         // Test that the outfile exists.
272         // ImageMagick's convert will often create ${outfile}.0,
273         // ${outfile}.1.
274         // If this occurs, move ${outfile}.0 to ${outfile}
275         // and delete ${outfile}.? (ignore errors)
276         script << "if not os.path.isfile(outfile):\n"
277                   "  if os.path.isfile(outfile + '.0'):\n"
278                   "    os.rename(outfile + '.0', outfile)\n"
279                   "    import glob\n"
280                   "    for file in glob.glob(outfile + '.?'):\n"
281                   "      unlinkNoThrow(file)\n"
282                   "  else:\n"
283                   "    sys.exit(1)\n\n";
284
285         // Delete the infile
286         script << "unlinkNoThrow(infile)\n\n";
287 }
288
289
290 void build_script(string const & from_file,
291                   string const & to_file_base,
292                   string const & from_format,
293                   string const & to_format,
294                   ostream & script)
295 {
296         BOOST_ASSERT(from_format != to_format);
297         lyxerr[Debug::GRAPHICS] << "build_script ... ";
298         typedef Converters::EdgePath EdgePath;
299
300         script << "#!/usr/bin/env python\n"
301                   "import os, shutil, sys\n\n"
302                   "def unlinkNoThrow(file):\n"
303                   "  ''' remove a file, do not throw if an error occurs '''\n"
304                   "  try:\n"
305                   "    os.unlink(file)\n"
306                   "  except:\n"
307                   "    pass\n\n";
308
309         // we do not use ChangeExtension because this is a basename
310         // which may nevertheless contain a '.'
311         string const to_file = to_file_base + '.'
312                 + formats.extension(to_format);
313
314         EdgePath const edgepath = from_format.empty() ?
315                 EdgePath() :
316                 converters.getPath(from_format, to_format);
317
318         // Create a temporary base file-name for all intermediate steps.
319         // Remember to remove the temp file because we only want the name...
320         static int counter = 0;
321         string const tmp = "gconvert" + convert<string>(counter++);
322         string const to_base = tempName(string(), tmp);
323         unlink(to_base);
324
325         // Create a copy of the file in case the original name contains
326         // problematic characters like ' or ". We can work around that problem
327         // in python, but the converters might be shell scripts and have more
328         // troubles with it.
329         string outfile = changeExtension(to_base, getExtension(from_file));
330         script << "infile = '"
331                << subst(subst(from_file, "\\", "\\\\"), "'", "\\'") << "'\n"
332                   "outfile = " << quoteName(outfile) << "\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) << '\n';
341
342                 ostringstream os;
343                 os << support::os::python() << " \""
344                    << libFileSearch("scripts", "convertDefault.py") << "\" ";
345                 if (!from_format.empty())
346                         os << from_format << ':';
347                 os << "' + '\"' + infile + '\"' + ' "
348                    << to_format << ":' + '\"' + outfile + '\"' + '";
349                 string const command = os.str();
350
351                 lyxerr[Debug::GRAPHICS]
352                         << "\tNo converter defined! I use convertDefault.py\n\t"
353                         << command << endl;
354
355                 build_conversion_command(command, script);
356         }
357
358         // The conversion commands may contain these tokens that need to be
359         // changed to infile, infile_base, outfile respectively.
360         string const token_from("$$i");
361         string const token_base("$$b");
362         string const token_to("$$o");
363
364         EdgePath::const_iterator it  = edgepath.begin();
365         EdgePath::const_iterator end = edgepath.end();
366
367         for (; it != end; ++it) {
368                 ::Converter const & conv = converters.get(*it);
369
370                 // Build the conversion command
371                 string const infile      = outfile;
372                 string const infile_base = changeExtension(infile, string());
373                 outfile = changeExtension(to_base, conv.To->extension());
374
375                 // Store these names in the python script
376                 script << "infile = "      << quoteName(infile) << '\n'
377                        << "infile_base = " << quoteName(infile_base) << '\n'
378                        << "outfile = "     << quoteName(outfile) << '\n';
379
380                 string command = conv.command;
381                 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
382                 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
383                 command = subst(command, token_to,   "' + '\"' + outfile + '\"' + '");
384                 command = libScriptSearch(command);
385
386                 build_conversion_command(command, script);
387         }
388
389         // Move the final outfile to to_file
390         script << move_file("outfile", quoteName(to_file));
391         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
392 }
393
394 } // namespace anon