]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
* src/LaTeX.C: beautification: use identical user messages
[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 /** Build the conversion script.
128  *  The script is output to the stream \p script.
129  */
130 static void build_script(string 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(string 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 << endl;
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_ = 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_ = onlyPath(to_file_base) + "lyxconvert" +
161                 convert<string>(counter++) + ".py";
162
163         std::ofstream fs(script_file_.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_) + ' ' +
181                 quoteName(onlyFilename(from_file)) + ' ' +
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
196                 ptr = ForkedCallQueue::get().add(script_command_);
197
198         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
199
200 }
201
202 void Converter::Impl::converted(pid_t /* pid */, int retval)
203 {
204         if (finished_)
205                 // We're done already!
206                 return;
207
208         finished_ = true;
209         // Clean-up behind ourselves
210         unlink(script_file_);
211
212         if (retval > 0) {
213                 unlink(to_file_);
214                 to_file_.erase();
215                 finishedConversion(false);
216         } else {
217                 finishedConversion(true);
218         }
219 }
220
221
222 static string const move_file(string const & from_file, string const & to_file)
223 {
224         if (from_file == to_file)
225                 return string();
226
227         ostringstream command;
228         command << "fromfile = " << from_file << "\n"
229                 << "tofile = "   << to_file << "\n\n"
230                 << "try:\n"
231                 << "  os.rename(fromfile, tofile)\n"
232                 << "except:\n"
233                 << "  try:\n"
234                 << "    shutil.copy(fromfile, tofile)\n"
235                 << "  except:\n"
236                 << "    sys.exit(1)\n"
237                 << "  unlinkNoThrow(fromfile)\n";
238
239         return command.str();
240 }
241
242
243 static void build_conversion_command(string const & command, ostream & script)
244 {
245         // Store in the python script
246         script << "\nif os.system(r'" << command << "') != 0:\n";
247
248         // Test that this was successful. If not, remove
249         // ${outfile} and exit the python script
250         script << "  unlinkNoThrow(outfile)\n"
251                << "  sys.exit(1)\n\n";
252
253         // Test that the outfile exists.
254         // ImageMagick's convert will often create ${outfile}.0,
255         // ${outfile}.1.
256         // If this occurs, move ${outfile}.0 to ${outfile}
257         // and delete ${outfile}.? (ignore errors)
258         script << "if not os.path.isfile(outfile):\n"
259                   "  if os.path.isfile(outfile + '.0'):\n"
260                   "    os.rename(outfile + '.0', outfile)\n"
261                   "    import glob\n"
262                   "    for file in glob.glob(outfile + '.?'):\n"
263                   "      unlinkNoThrow(file)\n"
264                   "  else:\n"
265                   "    sys.exit(1)\n\n";
266
267         // Delete the infile
268         script << "unlinkNoThrow(infile)\n\n";
269 }
270
271
272 static void build_script(string const & from_file,
273                   string const & to_file_base,
274                   string const & from_format,
275                   string const & to_format,
276                   ostream & script)
277 {
278         BOOST_ASSERT(from_format != to_format);
279         lyxerr[Debug::GRAPHICS] << "build_script ... ";
280         typedef Converters::EdgePath EdgePath;
281
282         script << "#!/usr/bin/env python\n"
283                   "import os, shutil, sys\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
291         // we do not use ChangeExtension because this is a basename
292         // which may nevertheless contain a '.'
293         string const to_file = to_file_base + '.'
294                 + formats.extension(to_format);
295
296         EdgePath const edgepath = from_format.empty() ?
297                 EdgePath() :
298                 converters.getPath(from_format, to_format);
299
300         // Create a temporary base file-name for all intermediate steps.
301         // Remember to remove the temp file because we only want the name...
302         static int counter = 0;
303         string const tmp = "gconvert" + convert<string>(counter++);
304         string const to_base = tempName(string(), tmp);
305         unlink(to_base);
306
307         // Create a copy of the file in case the original name contains
308         // problematic characters like ' or ". We can work around that problem
309         // in python, but the converters might be shell scripts and have more
310         // troubles with it.
311         string outfile = changeExtension(to_base, getExtension(from_file));
312         script << "infile = " << quoteName(from_file, quote_python) << "\n"
313                   "outfile = " << quoteName(outfile, quote_python) << "\n"
314                   "shutil.copy(infile, outfile)\n";
315
316         // Some converters (e.g. lilypond) can only output files to the
317         // current directory, so we need to change the current directory.
318         // This has the added benefit that all other files that may be
319         // generated by the converter are deleted when LyX closes and do not
320         // clutter the real working directory.
321         script << "os.chdir(" << quoteName(onlyPath(outfile)) << ")\n";
322
323         if (edgepath.empty()) {
324                 // Either from_format is unknown or we don't have a
325                 // converter path from from_format to to_format, so we use
326                 // the default converter.
327                 script << "infile = outfile\n"
328                        << "outfile = " << quoteName(to_file, quote_python)
329                        << '\n';
330
331                 ostringstream os;
332                 os << support::os::python() << ' '
333                    << libScriptSearch("$$s/scripts/convertDefault.py",
334                                       quote_python) << ' ';
335                 if (!from_format.empty())
336                         os << from_format << ':';
337                 // The extra " quotes around infile and outfile are needed
338                 // because the filename may contain spaces and it is used
339                 // as argument of os.system().
340                 os << "' + '\"' + infile + '\"' + ' "
341                    << to_format << ":' + '\"' + outfile + '\"' + '";
342                 string const command = os.str();
343
344                 lyxerr[Debug::GRAPHICS]
345                         << "\tNo converter defined! I use convertDefault.py\n\t"
346                         << command << endl;
347
348                 build_conversion_command(command, script);
349         }
350
351         // The conversion commands may contain these tokens that need to be
352         // changed to infile, infile_base, outfile respectively.
353         string const token_from("$$i");
354         string const token_base("$$b");
355         string const token_to("$$o");
356
357         EdgePath::const_iterator it  = edgepath.begin();
358         EdgePath::const_iterator end = edgepath.end();
359
360         for (; it != end; ++it) {
361                 lyx::Converter const & conv = converters.get(*it);
362
363                 // Build the conversion command
364                 string const infile      = outfile;
365                 string const infile_base = changeExtension(infile, string());
366                 outfile = changeExtension(to_base, conv.To->extension());
367
368                 // Store these names in the python script
369                 script << "infile = "      << quoteName(infile, quote_python) << "\n"
370                           "infile_base = " << quoteName(infile_base, quote_python) << "\n"
371                           "outfile = "     << quoteName(outfile, quote_python) << '\n';
372
373                 // See comment about extra " quotes above (although that
374                 // applies only for the first loop run here).
375                 string command = conv.command;
376                 command = subst(command, token_from, "' + '\"' + infile + '\"' + '");
377                 command = subst(command, token_base, "' + '\"' + infile_base + '\"' + '");
378                 command = subst(command, token_to,   "' + '\"' + outfile + '\"' + '");
379                 command = libScriptSearch(command, quote_python);
380
381                 build_conversion_command(command, script);
382         }
383
384         // Move the final outfile to to_file
385         script << move_file("outfile", quoteName(to_file, quote_python));
386         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
387 }
388
389 } // namespace graphics
390
391 } // namespace lyx