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