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