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