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