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