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