]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.cpp
Better naming for enums
[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
26 #include "support/TempFile.h"
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 {
39 public:
40         ///
41         Impl(FileName const & doc_fname,
42              FileName const & from_file, string const & to_file_base,
43              string const & from_format, string const & to_format);
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 signals2::signal<void(bool)> sig;
59         ///
60         sig finishedConversion;
61
62         ///
63         FileName const doc_fname_;
64         ///
65         string script_command_;
66         ///
67         FileName script_file_;
68         ///
69         FileName to_file_;
70         ///
71         bool valid_process_;
72         ///
73         bool finished_;
74         ///
75         Trackable tracker_;
76 };
77
78
79 bool Converter::isReachable(string const & from_format_name,
80                             string const & to_format_name)
81 {
82         return theConverters().isReachable(from_format_name, to_format_name);
83 }
84
85
86 Converter::Converter(FileName const & doc_fname,
87                      FileName const & from_file, string const & to_file_base,
88                      string const & from_format, string const & to_format)
89         : pimpl_(new Impl(doc_fname, from_file, to_file_base, from_format, to_format))
90 {}
91
92
93 Converter::~Converter()
94 {
95         delete pimpl_;
96 }
97
98
99 void Converter::startConversion() const
100 {
101         pimpl_->startConversion();
102 }
103
104
105 signals2::connection Converter::connect(slot_type const & slot) const
106 {
107         return pimpl_->finishedConversion.connect(slot);
108 }
109
110
111 FileName const & Converter::convertedFile() const
112 {
113         static FileName const empty;
114         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
115 }
116
117 /** Build the conversion script.
118  *  The script is output to the stream \p script.
119  */
120 static void build_script(string const & doc_fname,
121                   string const & from_file, string const & to_file_base,
122                   string const & from_format, string const & to_format,
123                   ostream & script);
124
125
126 Converter::Impl::Impl(FileName const & doc_fname,
127                       FileName const & from_file, string const & to_file_base,
128                       string const & from_format, string const & to_format)
129         : doc_fname_(doc_fname), valid_process_(false), finished_(false)
130 {
131         LYXERR(Debug::GRAPHICS, "Converter c-tor:\n"
132                 << "doc_fname:        " << doc_fname
133                 << "\n\tfrom_file:    " << from_file
134                 << "\n\tto_file_base: " << to_file_base
135                 << "\n\tfrom_format:  " << from_format
136                 << "\n\tto_format:    " << to_format);
137
138         // The converted image is to be stored in this file (we do not
139         // use ChangeExtension because this is a basename which may
140         // nevertheless contain a '.')
141         to_file_ = FileName(to_file_base + '.' +  theFormats().extension(to_format));
142
143         // The conversion commands are stored in a stringstream
144         ostringstream script;
145         build_script(doc_fname_.absFileName(), from_file.toFilesystemEncoding(),
146                      to_file_.toFilesystemEncoding(),
147                      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         TempFile tempfile(to_file_.onlyPath(), "lyxconvertXXXXXX.py");
155         tempfile.setAutoRemove(false);
156         script_file_ = tempfile.name();
157
158         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                        << 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_ = 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::sigPtr ptr = ForkedCallQueue::add(script_command_);
191         ptr->connect(ForkedCall::slot([this](pid_t pid, int retval){
192                                 converted(pid, retval);
193                         }).track_foreign(tracker_.p()));
194 }
195
196
197 void Converter::Impl::converted(pid_t /* pid */, int retval)
198 {
199         if (finished_)
200                 // We're done already!
201                 return;
202
203         finished_ = true;
204         // Clean-up behind ourselves
205         script_file_.removeFile();
206
207         if (retval > 0) {
208                 to_file_.removeFile();
209                 to_file_.erase();
210                 finishedConversion(false);
211         } else {
212                 finishedConversion(true);
213         }
214 }
215
216
217 static string const move_file(string const & from_file, string const & to_file)
218 {
219         if (from_file == to_file)
220                 return string();
221
222         ostringstream command;
223         command << "fromfile = " << from_file << "\n"
224                 << "tofile = "   << to_file << "\n\n"
225                 << "try:\n"
226                 << "  os.rename(fromfile, tofile)\n"
227                 << "except:\n"
228                 << "  try:\n"
229                 << "    shutil.copy(fromfile, tofile)\n"
230                 << "  except:\n"
231                 << "    sys.exit(1)\n"
232                 << "  unlinkNoThrow(fromfile)\n";
233
234         return command.str();
235 }
236
237
238 static void build_conversion_command(string const & command, ostream & script)
239 {
240         // Store in the python script
241         script << "\nif os.system(r'" << commandPrep(command) << "') != 0:\n";
242
243         // Test that this was successful. If not, remove
244         // ${outfile} and exit the python script
245         script << "  unlinkNoThrow(outfile)\n"
246                << "  sys.exit(1)\n\n";
247
248         // Test that the outfile exists.
249         // ImageMagick's convert will often create ${outfile}.0,
250         // ${outfile}.1.
251         // If this occurs, move ${outfile}.0 to ${outfile}
252         // and delete ${outfile}.? (ignore errors)
253         script << "if not os.path.isfile(outfile):\n"
254                   "  if os.path.isfile(outfile + '.0'):\n"
255                   "    os.rename(outfile + '.0', outfile)\n"
256                   "    import glob\n"
257                   "    for file in glob.glob(outfile + '.?'):\n"
258                   "      unlinkNoThrow(file)\n"
259                   "  else:\n"
260                   "    sys.exit(1)\n\n";
261
262         // Delete the infile
263         script << "if infile != outfile:\n"
264                   "  unlinkNoThrow(infile)\n\n";
265 }
266
267
268 static string const strip_digit(string const & format)
269 {
270         // Strip trailing digits from format names e.g. "pdf6" -> "pdf"
271         return format.substr(0, format.find_last_not_of("0123456789") + 1);
272 }
273
274
275 static void build_script(string const & doc_fname,
276                   string const & from_file,
277                   string const & to_file,
278                   string const & from_format,
279                   string const & to_format,
280                   ostream & script)
281 {
282         LASSERT(from_format != to_format, return);
283         LYXERR(Debug::GRAPHICS, "build_script ... ");
284         typedef Graph::EdgePath EdgePath;
285
286         script << "# -*- coding: utf-8 -*-\n"
287                   "import os, shutil, sys\n\n"
288                   "def unlinkNoThrow(file):\n"
289                   "  ''' remove a file, do not throw if an error occurs '''\n"
290                   "  try:\n"
291                   "    os.unlink(file)\n"
292                   "  except:\n"
293                   "    pass\n\n";
294
295         EdgePath const edgepath = from_format.empty() ?
296                 EdgePath() :
297                 theConverters().getPath(from_format, to_format);
298
299         // Create a temporary base file-name for all intermediate steps.
300         string const from_ext = getExtension(from_file);
301         TempFile tempfile(addExtension("gconvertXXXXXX", from_ext));
302         tempfile.setAutoRemove(false);
303         string outfile = tempfile.name().toFilesystemEncoding();
304         string const to_base = from_ext.empty() ? outfile : removeExtension(outfile);
305
306         // Create a copy of the file in case the original name contains
307         // problematic characters like ' or ". We can work around that problem
308         // in python, but the converters might be shell scripts and have more
309         // troubles with it.
310         script << "infile = "
311                         << quoteName(from_file, quote_python)
312                         << "\n"
313                   "outfile = "
314                         << quoteName(outfile, quote_python) << "\n"
315                   "shutil.copy(infile, outfile)\n";
316
317         // Some converters (e.g. lilypond) can only output files to the
318         // current directory, so we need to change the current directory.
319         // This has the added benefit that all other files that may be
320         // generated by the converter are deleted when LyX closes and do not
321         // clutter the real working directory.
322         script << "os.chdir("
323                << quoteName(onlyPath(outfile)) << ")\n";
324
325         if (edgepath.empty()) {
326                 // Either from_format is unknown or we don't have a
327                 // converter path from from_format to to_format, so we use
328                 // the default converter.
329                 script << "infile = outfile\n"
330                        << "outfile = "
331                        << quoteName(to_file, quote_python) << "\n";
332
333                 ostringstream os;
334                 os << os::python() << ' '
335                    << commandPrep("$$s/scripts/convertDefault.py") << ' ';
336                 if (from_format.empty())
337                         os << "unknown ";
338                 else
339                         os << strip_digit(from_format) << ' ';
340                 // The extra " quotes around infile and outfile are needed
341                 // because the filename may contain spaces and it is used
342                 // as argument of os.system().
343                 os << "' + '\"' + infile + '\"' + ' "
344                    << strip_digit(to_format) << " ' + '\"' + outfile + '\"' + '";
345                 string const command = os.str();
346
347                 LYXERR(Debug::GRAPHICS,
348                         "\tNo converter defined! I use convertDefault.py\n\t"
349                         << command);
350
351                 build_conversion_command(command, script);
352         }
353
354         // The conversion commands may contain these tokens that need to be
355         // changed to infile, infile_base, outfile and output directory respectively.
356         string const token_from  = "$$i";
357         string const token_base  = "$$b";
358         string const token_to    = "$$o";
359         string const token_todir = "$$d";
360
361         EdgePath::const_iterator it  = edgepath.begin();
362         EdgePath::const_iterator end = edgepath.end();
363
364         for (; it != end; ++it) {
365                 lyx::Converter const & conv = theConverters().get(*it);
366
367                 // Build the conversion command
368                 string const infile      = outfile;
369                 string const infile_base = changeExtension(infile, string());
370                 outfile = conv.result_file().empty()
371                         ? addExtension(to_base, conv.To()->extension())
372                         : addName(subst(conv.result_dir(),
373                                         token_base, infile_base),
374                                   subst(conv.result_file(),
375                                         token_base, onlyFileName(infile_base)));
376
377                 // If two formats share the same extension we may get identical names
378                 if (outfile == infile && conv.result_file().empty()) {
379                         TempFile tmpfile(addExtension("gconvertXXXXXX", conv.To()->extension()));
380                         tmpfile.setAutoRemove(false);
381                         outfile = tmpfile.name().toFilesystemEncoding();
382                 }
383
384                 if (!theConverters().checkAuth(conv, doc_fname))
385                         return;
386
387                 // Store these names in the python script
388                 script << "infile = "
389                                 << quoteName(infile, quote_python) << "\n"
390                           "infile_base = "
391                                 << quoteName(infile_base, quote_python) << "\n"
392                           "outfile = "
393                                 << quoteName(outfile, quote_python) << "\n"
394                           "outdir  = os.path.dirname(outfile)\n" ;
395
396                 // See comment about extra " quotes above (although that
397                 // applies only for the first loop run here).
398                 string command = conv.command();
399                 command = subst(command, token_from,  "' + '\"' + infile + '\"' + '");
400                 command = subst(command, token_base,  "' + '\"' + infile_base + '\"' + '");
401                 command = subst(command, token_to,    "' + '\"' + outfile + '\"' + '");
402                 command = subst(command, token_todir, "' + '\"' + outdir + '\"' + '");
403
404                 build_conversion_command(command, script);
405         }
406
407         // Move the final outfile to to_file
408         script << move_file("outfile", quoteName(to_file, quote_python));
409         LYXERR(Debug::GRAPHICS, "ready!");
410 }
411
412 } // namespace graphics
413 } // namespace lyx