]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
The std::string mammoth path.
[lyx.git] / src / graphics / GraphicsConverter.C
1 /**
2  * \file GraphicsConverter.C
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 "debug.h"
17 #include "format.h"
18
19 #include "support/filetools.h"
20 #include "support/forkedcallqueue.h"
21 #include "support/tostr.h"
22 #include "support/lstrings.h"
23 #include "support/lyxlib.h"
24
25 #include <boost/bind.hpp>
26
27 #include "support/std_sstream.h"
28 #include <fstream>
29
30 namespace support = lyx::support;
31
32 using support::ChangeExtension;
33 using support::Forkedcall;
34 using support::ForkedCallQueue;
35 using support::LibFileSearch;
36 using support::LibScriptSearch;
37 using support::OnlyPath;
38 using support::OnlyFilename;
39 using support::QuoteName;
40 using support::subst;
41 using support::tempName;
42 using support::unlink;
43
44 using std::endl;
45 using std::ostream;
46 using std::ostringstream;
47 using std::string;
48
49
50 namespace lyx {
51 namespace graphics {
52
53 struct Converter::Impl : public boost::signals::trackable {
54         ///
55         Impl(string const &, string const &, string const &, string const &);
56
57         ///
58         void startConversion();
59
60         /** This method is connected to a signal passed to the forked call
61          *  class, passing control back here when the conversion is completed.
62          *  Cleans-up the temporary files, emits the finishedConversion
63          *  signal and removes the Converter from the list of all processes.
64          */
65         void converted(pid_t pid, int retval);
66
67         /** At the end of the conversion process inform the outside world
68          *  by emitting a signal.
69          */
70         typedef boost::signal1<void, bool> SignalType;
71         ///
72         SignalType finishedConversion;
73
74         ///
75         string script_command_;
76         ///
77         string script_file_;
78         ///
79         string to_file_;
80         ///
81         bool valid_process_;
82         ///
83         bool finished_;
84 };
85
86
87 bool Converter::isReachable(string const & from_format_name,
88                             string const & to_format_name)
89 {
90         return converters.isReachable(from_format_name, to_format_name);
91 }
92
93
94 Converter::Converter(string const & from_file,   string const & to_file_base,
95                      string const & from_format, string const & to_format)
96         : pimpl_(new Impl(from_file, to_file_base, from_format, to_format))
97 {}
98
99
100 // Empty d-tor out-of-line to keep boost::scoped_ptr happy.
101 Converter::~Converter()
102 {}
103
104
105 void Converter::startConversion() const
106 {
107         pimpl_->startConversion();
108 }
109
110
111 boost::signals::connection Converter::connect(slot_type const & slot) const
112 {
113         return pimpl_->finishedConversion.connect(slot);
114 }
115
116
117 string const & Converter::convertedFile() const
118 {
119         static string const empty;
120         return pimpl_->finished_ ? pimpl_->to_file_ : empty;
121 }
122
123 } // namespace graphics
124 } // namespace lyx
125
126
127 //------------------------------
128 // Implementation details follow
129 //------------------------------
130
131 namespace {
132
133 /** Build the conversion script, returning true if able to build it.
134  *  The script is output to the ostringstream 'script'.
135  */
136 bool build_script(string const & from_file, string const & to_file_base,
137                   string const & from_format, string const & to_format,
138                   ostream & script);
139
140 } // namespace anon
141
142
143 namespace lyx {
144 namespace graphics {
145
146 Converter::Impl::Impl(string const & from_file,   string const & to_file_base,
147                       string const & from_format, string const & to_format)
148         : valid_process_(false), finished_(false)
149 {
150         lyxerr[Debug::GRAPHICS] << "Converter c-tor:\n"
151                 << "\tfrom_file:      " << from_file
152                 << "\n\tto_file_base: " << to_file_base
153                 << "\n\tfrom_format:  " << from_format
154                 << "\n\tto_format:    " << to_format << endl;
155
156         // The converted image is to be stored in this file (we do not
157         // use ChangeExtension because this is a basename which may
158         // nevertheless contain a '.')
159         to_file_ = to_file_base + '.' +  formats.extension(to_format);
160
161         // The conversion commands are stored in a stringstream
162         ostringstream script;
163         script << "#!/bin/sh\n";
164         bool const success = build_script(from_file, to_file_base,
165                                           from_format, to_format, script);
166
167         if (!success) {
168                 script_command_ =
169                         "sh " + LibFileSearch("scripts", "convertDefault.sh") +
170                         ' ' + from_format + ':' + from_file + ' ' +
171                         to_format + ':' + to_file_;
172
173                 lyxerr[Debug::GRAPHICS]
174                         << "\tNo converter defined! I use convertDefault.sh\n\t"
175                         << script_command_ << endl;
176
177         } else {
178
179                 lyxerr[Debug::GRAPHICS] << "\tConversion script:"
180                         << "\n--------------------------------------\n"
181                         << script.str()
182                         << "\n--------------------------------------\n";
183
184                 // Output the script to file.
185                 static int counter = 0;
186                 script_file_ = OnlyPath(to_file_base) + "lyxconvert" +
187                         tostr(counter++) + ".sh";
188
189                 std::ofstream fs(script_file_.c_str());
190                 if (!fs.good())
191                         return;
192
193                 fs << script.str();
194                 fs.close();
195
196                 // The command needed to run the conversion process
197                 // We create a dummy command for ease of understanding of the
198                 // list of forked processes.
199                 // Note: 'sh ' is absolutely essential, or execvp will fail.
200                 script_command_ = "sh " + script_file_ + ' ' +
201                         OnlyFilename(from_file) + ' ' + to_format;
202         }
203         // All is ready to go
204         valid_process_ = true;
205 }
206
207
208 void Converter::Impl::startConversion()
209 {
210         if (!valid_process_) {
211                 converted(0, 1);
212                 return;
213         }
214
215         Forkedcall::SignalTypePtr
216                 ptr = ForkedCallQueue::get().add(script_command_);
217
218         ptr->connect(boost::bind(&Impl::converted, this, _1, _2));
219
220 }
221
222 void Converter::Impl::converted(pid_t /* pid */, int retval)
223 {
224         if (finished_)
225                 // We're done already!
226                 return;
227
228         finished_ = true;
229         // Clean-up behind ourselves
230         unlink(script_file_);
231
232         if (retval > 0) {
233                 unlink(to_file_);
234                 to_file_.erase();
235                 finishedConversion(false);
236         } else {
237                 finishedConversion(true);
238         }
239 }
240
241 } // namespace graphics
242 } // namespace lyx
243
244 namespace {
245
246 string const move_file(string const & from_file, string const & to_file)
247 {
248         if (from_file == to_file)
249                 return string();
250
251         ostringstream command;
252         command << "fromfile=" << from_file << "\n"
253                 << "tofile="   << to_file << "\n\n"
254                 << "'mv' -f ${fromfile} ${tofile} ||\n"
255                 << "{\n"
256                 << "\t'cp' -f ${fromfile} ${tofile} ||\n"
257                 << "\t{\n"
258                 << "\t\texit 1\n"
259                 << "\t}\n"
260                 << "\t'rm' -f ${fromfile}\n"
261                 << "}\n";
262
263         return command.str();
264 }
265
266
267 bool build_script(string const & from_file,
268                   string const & to_file_base,
269                   string const & from_format,
270                   string const & to_format,
271                   ostream & script)
272 {
273         lyxerr[Debug::GRAPHICS] << "build_script ... ";
274         typedef Converters::EdgePath EdgePath;
275
276         // we do not use ChangeExtension because this is a basename
277         // which may nevertheless contain a '.'
278         string const to_file = to_file_base + '.'
279                 + formats.extension(to_format);
280
281         if (from_format == to_format) {
282                 script << move_file(QuoteName(from_file), QuoteName(to_file));
283                 lyxerr[Debug::GRAPHICS] << "ready (from == to)" << endl;
284                 return true;
285         }
286
287         EdgePath edgepath = converters.getPath(from_format, to_format);
288
289         if (edgepath.empty()) {
290                 lyxerr[Debug::GRAPHICS] << "ready (edgepath.empty())" << endl;
291                 return false;
292         }
293
294         // Create a temporary base file-name for all intermediate steps.
295         // Remember to remove the temp file because we only want the name...
296         static int counter = 0;
297         string const tmp = "gconvert" + tostr(counter++);
298         string const to_base = tempName(string(), tmp);
299         unlink(to_base);
300
301         string outfile = from_file;
302
303         // The conversion commands may contain these tokens that need to be
304         // changed to infile, infile_base, outfile respectively.
305         string const token_from("$$i");
306         string const token_base("$$b");
307         string const token_to("$$o");
308
309         EdgePath::const_iterator it  = edgepath.begin();
310         EdgePath::const_iterator end = edgepath.end();
311
312         for (; it != end; ++it) {
313                 ::Converter const & conv = converters.get(*it);
314
315                 // Build the conversion command
316                 string const infile      = outfile;
317                 string const infile_base = ChangeExtension(infile, string());
318                 outfile = ChangeExtension(to_base, conv.To->extension());
319
320                 // Store these names in the shell script
321                 script << "infile="      << QuoteName(infile) << '\n'
322                        << "infile_base=" << QuoteName(infile_base) << '\n'
323                        << "outfile="     << QuoteName(outfile) << '\n';
324
325                 string command = conv.command;
326                 command = subst(command, token_from, "${infile}");
327                 command = subst(command, token_base, "${infile_base}");
328                 command = subst(command, token_to,   "${outfile}");
329                 command = LibScriptSearch(command);
330
331                 // Store in the shell script
332                 script << "\n" << command << " ||\n";
333
334                 // Test that this was successful. If not, remove
335                 // ${outfile} and exit the shell script
336                 script << "{\n"
337                        << "\t'rm' -f ${outfile}\n"
338                        << "\texit 1\n"
339                        << "}\n\n";
340
341                 // Test that the outfile exists.
342                 // ImageMagick's convert will often create ${outfile}.0,
343                 // ${outfile}.1.
344                 // If this occurs, move ${outfile}.0 to ${outfile}
345                 // and delete ${outfile}.?
346                 script << "if [ ! -f ${outfile} ]; then\n"
347                        << "\tif [ -f ${outfile}.0 ]; then\n"
348                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
349                        << "\t\t'rm' -f ${outfile}.?\n"
350                        << "\telse\n"
351                        << "\t\texit 1\n"
352                        << "\tfi\n"
353                        << "fi\n\n";
354
355                 // Delete the infile, if it isn't the original, from_file.
356                 if (infile != from_file) {
357                         script << "'rm' -f ${infile}\n\n";
358                 }
359         }
360
361         // Move the final outfile to to_file
362         script << move_file("${outfile}", QuoteName(to_file));
363         lyxerr[Debug::GRAPHICS] << "ready!" << endl;
364
365         return true;
366 }
367
368 } // namespace anon