]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsConverter.C
fix typo that put too many include paths for most people
[lyx.git] / src / graphics / GraphicsConverter.C
1 /*
2  * \file GraphicsConverter.C
3  * Copyright 2002 the LyX Team
4  * Read the file COPYING
5  *
6  * \author Angus Leeming <a.leeming@ic.ac.uk>
7  */
8
9 #include <config.h>
10
11 #ifdef __GNUG__
12 #pragma implementation
13 #endif
14
15 #include "GraphicsConverter.h"
16
17 #include "converter.h"
18 #include "debug.h"
19 #include "gettext.h"
20
21 #include "frontends/Alert.h"
22
23 #include "support/filetools.h"
24 #include "support/forkedcall.h"
25 #include "support/path.h"
26
27 #include <fstream>
28
29 namespace {
30
31 string const move_file(string const & from_file, string const & to_file)
32 {
33         if (from_file == to_file)
34                 return string();
35
36         ostringstream command;
37         command << "fromfile=" << from_file << "\n"
38                 << "tofile="   << to_file << "\n\n"
39                 << "'mv' -f ${fromfile} ${tofile}\n"
40                 << "if [ $? -ne 0 ]; then\n"
41                 << "\t'cp' -f ${fromfile} ${tofile}\n"
42                 << "\tif [ $? -ne 0 ]; then\n"
43                 << "\t\texit 1\n"
44                 << "\tfi\n"
45                 << "\t'rm' -f ${fromfile}\n"
46                 << "fi\n";
47
48         return command.str().c_str();
49 }
50
51 } // namespace anon
52
53
54 namespace grfx {
55
56 GConverter & GConverter::get()
57 {
58         static GConverter singleton;
59         return singleton;
60 }
61
62
63 bool GConverter::isReachable(string const & from_format_name,
64                              string const & to_format_name) const
65 {
66         return converters.isReachable(from_format_name, to_format_name);
67 }
68
69
70 void GConverter::convert(string const & from_file, string const & to_file_base,
71                          string const & from_format, string const & to_format,
72                          SignalTypePtr on_finish)
73 {
74         // The conversion commands are stored in a stringstream
75         ostringstream script;
76         script << "#!/bin/sh\n";
77
78         bool const success = build_script(from_file, to_file_base,
79                                           from_format, to_format, script);
80
81         if (!success) {
82                 lyxerr[Debug::GRAPHICS]
83                         << "Unable to build the conversion script" << std::endl;
84                 on_finish->emit(string());
85                 return;
86         }
87
88         lyxerr[Debug::GRAPHICS] << "Conversion script:\n\n"
89                                 << script.str().c_str() << "\n" << std::endl;
90
91         // Output the script to file.
92         static int counter = 0;
93         string const script_file = OnlyPath(to_file_base) + "lyxconvert" +
94                 tostr(counter++) + ".sh";
95
96         std::ofstream fs(script_file.c_str());
97         if (!fs.good()) {
98                 // Unable to output the conversion script to file.
99                 on_finish->emit(string());
100                 return;
101         }
102
103         fs << script.str().c_str();
104         fs.close();
105
106         // Create a dummy command for ease of understanding of the
107         // list of forked processes.
108         // Note that 'sh ' is absolutely essential, or execvp will fail.
109         string const script_command =
110                 "sh " + script_file + " " +
111                 OnlyFilename(from_file) + " " + to_format;
112
113         string const to_file =
114                 ChangeExtension(to_file_base, formats.extension(to_format));
115
116         // Launch the conversion process.
117         ConvProcessPtr shared_ptr;
118         shared_ptr.reset(new ConvProcess(script_file, script_command,
119                                          to_file, on_finish));
120         all_processes_.push_back(shared_ptr);
121 }
122
123
124 namespace {
125
126 typedef boost::shared_ptr<ConvProcess> ConvProcessPtr;
127
128 class Find_Ptr {
129 public:
130         Find_Ptr(ConvProcess * ptr) : ptr_(ptr) {}
131
132         bool operator()(ConvProcessPtr const & ptr)
133         {
134                 return ptr.get() == ptr_;
135         }
136
137 private:
138         ConvProcess * ptr_;
139 };
140
141 } // namespace anon
142
143
144 void GConverter::erase(ConvProcess * process)
145 {
146         std::list<ConvProcessPtr>::iterator begin = all_processes_.begin();
147         std::list<ConvProcessPtr>::iterator end   = all_processes_.end();
148         std::list<ConvProcessPtr>::iterator it =
149                 std::find_if(begin, end, Find_Ptr(process));
150
151         if (it == end)
152                 return;
153
154         all_processes_.erase(it);
155 }
156
157
158 bool GConverter::build_script(string const & from_file,
159                               string const & to_file_base,
160                               string const & from_format,
161                               string const & to_format,
162                               ostringstream & script) const
163 {
164         typedef Converters::EdgePath EdgePath;
165
166         string const to_file = ChangeExtension(to_file_base,
167                                                formats.extension(to_format));
168
169         if (from_format == to_format) {
170                 script << move_file(QuoteName(from_file), QuoteName(to_file));
171                 return true;
172         }
173
174         EdgePath edgepath = converters.getPath(from_format, to_format);
175
176         if (edgepath.empty()) {
177                 Alert::alert(_("Cannot convert file"),
178                            _("No information for converting from ")
179                            + formats.prettyName(from_format) + _(" to ")
180                            + formats.prettyName(to_format));
181                 return false;
182         }
183
184         // Create a temporary base file-name for all intermediate steps.
185         // Remember to remove the temp file because we only want the name...
186         static int counter = 0;
187         string const tmp = "gconvert" + tostr(counter++);
188         string const to_base = lyx::tempName(string(), tmp);
189         lyx::unlink(to_base);
190
191         string outfile = from_file;
192
193         // The conversion commands may contain these tokens that need to be
194         // changed to infile, infile_base, outfile respectively.
195         string const token_from("$$i");
196         string const token_base("$$b");
197         string const token_to("$$o");
198
199         EdgePath::const_iterator it  = edgepath.begin();
200         EdgePath::const_iterator end = edgepath.end();
201         for (; it != end; ++it) {
202                 Converter const & conv = converters.get(*it);
203
204                 // Build the conversion command
205                 string const infile      = outfile;
206                 string const infile_base = ChangeExtension(infile, string());
207                 outfile = ChangeExtension(to_base, conv.To->extension());
208
209                 // Store these names in the shell script
210                 script << "infile="      << QuoteName(infile) << '\n'
211                        << "infile_base=" << QuoteName(infile_base) << '\n'
212                        << "outfile="     << QuoteName(outfile) << '\n';
213
214                 string command = conv.command;
215                 command = subst(command, token_from, "${infile}");
216                 command = subst(command, token_base, "${infile_base}");
217                 command = subst(command, token_to,   "${outfile}");
218
219                 // Store in the shell script
220                 script << "\n" << command << "\n\n";
221
222                 // Test that this was successful. If not, remove
223                 // ${outfile} and exit the shell script
224                 script << "if [ $? -ne 0 ]; then\n"
225                        << "\t'rm' -f ${outfile}\n"
226                        << "\texit 1\n"
227                        << "fi\n\n";
228
229                 // Test that the outfile exists.
230                 // ImageMagick's convert will often create ${outfile}.0,
231                 // ${outfile}.1.
232                 // If this occurs, move ${outfile}.0 to ${outfile}
233                 // and delete ${outfile}.?
234                 script << "if [ ! -f ${outfile} ]; then\n"
235                        << "\tif [ -f ${outfile}.0 ]; then\n"
236                        << "\t\t'mv' -f ${outfile}.0 ${outfile}\n"
237                        << "\t\t'rm' -f ${outfile}.?\n"
238                        << "\telse\n"
239                        << "\t\texit 1\n"
240                        << "\tfi\n"
241                        << "fi\n\n";
242
243                 // Delete the infile, if it isn't the original, from_file.
244                 if (infile != from_file) {
245                         script << "'rm' -f ${infile}\n\n";
246                 }
247         }
248
249         // Move the final outfile to to_file
250         script << move_file("${outfile}", QuoteName(to_file));
251
252         return true;
253 }
254
255
256 ConvProcess::ConvProcess(string const & script_file,
257                          string const & script_command,
258                          string const & to_file, SignalTypePtr on_finish)
259         : script_file_(script_file), to_file_(to_file), on_finish_(on_finish)
260 {
261         Forkedcall::SignalTypePtr convert_ptr;
262         convert_ptr.reset(new Forkedcall::SignalType);
263
264         convert_ptr->connect(SigC::slot(this, &ConvProcess::converted));
265
266         Forkedcall call;
267         int retval = call.startscript(script_command, convert_ptr);
268         if (retval > 0) {
269                 // Unable to even start the script, so clean-up the mess!
270                 converted(string(), 0, 1);
271         }
272 }
273
274
275 void ConvProcess::converted(string const &/* cmd */,
276                             pid_t /* pid */, int retval)
277 {
278         // Clean-up behind ourselves
279         lyx::unlink(script_file_);
280
281         if (retval > 0) {
282                 lyx::unlink(to_file_);
283                 to_file_.erase();
284         }
285
286         if (on_finish_.get()) {
287                 on_finish_->emit(to_file_);
288         }
289
290         grfx::GConverter::get().erase(this);
291 }
292
293
294 } // namespace grfx