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