]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.C
the string -> char patch
[lyx.git] / src / graphics / GraphicsCacheItem.C
1 /**
2  * \file GraphicsCacheItem.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voss
8  * \author Angus Leeming
9  *
10  * Full author contact details are available in file CREDITS
11  */
12
13 #include <config.h>
14
15 #ifdef __GNUG__
16 #pragma implementation
17 #endif
18
19 #include "GraphicsCacheItem.h"
20 #include "GraphicsImage.h"
21 #include "GraphicsConverter.h"
22
23 #include "support/FileMonitor.h"
24
25 #include "debug.h"
26
27 #include "support/LAssert.h"
28 #include "support/filetools.h"
29
30 #include <boost/shared_ptr.hpp>
31 #include <boost/bind.hpp>
32 #include <boost/signals/trackable.hpp>
33
34 using std::endl;
35
36 namespace grfx {
37
38 struct CacheItem::Impl : public boost::signals::trackable {
39
40         ///
41         Impl(string const & file);
42
43         /** Start the image conversion process, checking first that it is
44          *  necessary. If it is necessary, then a conversion task is started.
45          *  CacheItem asumes that the conversion is asynchronous and so
46          *  passes a Signal to the converting routine. When the conversion
47          *  is finished, this Signal is emitted, returning the converted
48          *  file to this->imageConverted.
49          *
50          *  If no file conversion is needed, then convertToDisplayFormat() calls
51          *  loadImage() directly.
52          *
53          *  convertToDisplayFormat() will set the loading status flag as
54          *  approriate through calls to setStatus().
55          */
56         void convertToDisplayFormat();
57
58         /** Load the image into memory. This is called either from
59          *  convertToDisplayFormat() direct or from imageConverted().
60          */
61         void loadImage();
62
63         /** Get a notification when the image conversion is done.
64          *  Connected to a signal on_finish_ which is passed to
65          *  Converter::convert.
66          */
67         void imageConverted(bool);
68
69         /** Get a notification when the image loading is done.
70          *  Connected to a signal on_finish_ which is passed to
71          *  grfx::Image::loadImage.
72          */
73         void imageLoaded(bool);
74
75         /** Sets the status of the loading process. Also notifies
76          *  listeners that the status has changed.
77          */
78         void setStatus(ImageStatus new_status);
79
80         /** Can be invoked directly by the user, but is also connected to the
81          *  FileMonitor and so is invoked when the file is changed
82          *  (if monitoring is taking place).
83          */
84         void startLoading();
85
86         /** If we are asked to load the file for a second or further time,
87          *  (because the file has changed), then we'll have to first reset
88          *  many of the variables below.
89          */
90         void reset();
91
92         /// The filename we refer too.
93         string const filename_;
94         ///
95         FileMonitor const monitor_;
96
97         /// Is the file compressed?
98         bool zipped_;
99         /// If so, store the uncompressed file in this temporary file.
100         string unzipped_filename_;
101         /// What file are we trying to load?
102         string file_to_load_;
103         /** Should we delete the file after loading? True if the file is
104          *  the result of a conversion process.
105          */
106         bool remove_loaded_file_;
107
108         /// The image and its loading status.
109         boost::shared_ptr<Image> image_;
110         ///
111         ImageStatus status_;
112
113         /// This signal is emitted when the image loading status changes.
114         boost::signal0<void> statusChanged;
115
116         /// The connection to the signal Image::finishedLoading
117         boost::signals::connection cl_;
118
119         /// The connection of the signal ConvProcess::finishedConversion,
120         boost::signals::connection cc_;
121
122         ///
123         boost::scoped_ptr<Converter> converter_;
124 };
125
126
127 CacheItem::CacheItem(string const & file)
128         : pimpl_(new Impl(file))
129 {}
130
131
132 CacheItem::~CacheItem()
133 {}
134
135
136 string const & CacheItem::filename() const
137 {
138         return pimpl_->filename_;
139 }
140
141
142 void CacheItem::startLoading() const
143 {
144         pimpl_->startLoading();
145 }
146
147
148 void CacheItem::startMonitoring() const
149 {
150         if (!pimpl_->monitor_.monitoring())
151                 pimpl_->monitor_.start();
152 }
153
154
155 bool CacheItem::monitoring() const
156 {
157         return pimpl_->monitor_.monitoring();
158 }
159
160
161 unsigned long CacheItem::checksum() const
162 {
163         return pimpl_->monitor_.checksum();
164 }
165
166
167 Image const * CacheItem::image() const
168 {
169         return pimpl_->image_.get();
170 }
171
172
173 ImageStatus CacheItem::status() const
174 {
175         return pimpl_->status_;
176 }
177
178
179 boost::signals::connection CacheItem::connect(slot_type const & slot) const
180 {
181         return pimpl_->statusChanged.connect(slot);
182 }
183
184
185 //------------------------------
186 // Implementation details follow
187 //------------------------------
188
189
190 CacheItem::Impl::Impl(string const & file)
191         : filename_(file),
192           monitor_(file, 2000),
193           zipped_(false),
194           remove_loaded_file_(false),
195           status_(WaitingToLoad)
196 {
197         monitor_.connect(boost::bind(&Impl::startLoading, this));
198 }
199
200
201 void CacheItem::Impl::startLoading()
202 {
203         if (status_ != WaitingToLoad)
204                 reset();
205
206         convertToDisplayFormat();
207 }
208
209
210 void CacheItem::Impl::reset()
211 {
212         zipped_ = false;
213         if (!unzipped_filename_.empty())
214                 lyx::unlink(unzipped_filename_);
215         unzipped_filename_.erase();
216
217         if (remove_loaded_file_ && !file_to_load_.empty())
218                 lyx::unlink(file_to_load_);
219         remove_loaded_file_ = false;
220         file_to_load_.erase();
221
222         if (image_.get())
223                 image_.reset();
224
225         status_ = WaitingToLoad;
226
227         if (cl_.connected())
228                 cl_.disconnect();
229
230         if (cc_.connected())
231                 cc_.disconnect();
232
233         if (converter_.get())
234                 converter_.reset();
235 }
236
237
238 void CacheItem::Impl::setStatus(ImageStatus new_status)
239 {
240         if (status_ == new_status)
241                 return;
242
243         status_ = new_status;
244         statusChanged();
245 }
246
247
248 void CacheItem::Impl::imageConverted(bool success)
249 {
250         string const text = success ? "succeeded" : "failed";
251         lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
252
253         file_to_load_ = converter_.get() ?
254                 converter_->convertedFile() : string();
255         converter_.reset();
256         cc_.disconnect();
257
258         success = !file_to_load_.empty() && IsFileReadable(file_to_load_);
259         lyxerr[Debug::GRAPHICS] << "Unable to find converted file!" << endl;
260
261         if (!success) {
262                 setStatus(ErrorConverting);
263
264                 if (zipped_)
265                         lyx::unlink(unzipped_filename_);
266
267                 return;
268         }
269
270         loadImage();
271 }
272
273
274 // This function gets called from the callback after the image has been
275 // converted successfully.
276 void CacheItem::Impl::loadImage()
277 {
278         setStatus(Loading);
279         lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
280
281         image_ = Image::newImage();
282
283         cl_.disconnect();
284         cl_ = image_->finishedLoading.connect(
285                 boost::bind(&Impl::imageLoaded, this, _1));
286         image_->load(file_to_load_);
287 }
288
289
290 void CacheItem::Impl::imageLoaded(bool success)
291 {
292         string const text = success ? "succeeded" : "failed";
293         lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
294
295         // Clean up after loading.
296         if (zipped_)
297                 lyx::unlink(unzipped_filename_);
298
299         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
300                 lyx::unlink(file_to_load_);
301
302         cl_.disconnect();
303
304         if (!success) {
305                 setStatus(ErrorLoading);
306                 return;
307         }
308
309         // Inform the outside world.
310         setStatus(Loaded);
311 }
312
313
314 } // namespace grfx
315
316
317 namespace {
318
319 string const findTargetFormat(string const & from)
320 {
321         typedef grfx::Image::FormatList FormatList;
322         FormatList const formats = grfx::Image::loadableFormats();
323
324         // There must be a format to load from.
325         lyx::Assert(!formats.empty());
326
327         // First ascertain if we can load directly with no conversion
328         FormatList::const_iterator it  = formats.begin();
329         FormatList::const_iterator end = formats.end();
330         for (; it != end; ++it) {
331                 if (from == *it)
332                         return *it;
333         }
334
335         // So, we have to convert to a loadable format. Can we?
336         it = formats.begin();
337         for (; it != end; ++it) {
338                 if (grfx::Converter::isReachable(from, *it))
339                         return *it;
340                 else
341                         lyxerr[Debug::GRAPHICS]
342                                 << "Unable to convert from " << from
343                                 << " to " << *it << std::endl;
344         }
345
346         // Failed! so we have to try to convert it to XPM format
347         // with the standard converter
348         return string("xpm");
349 }
350
351 } // anon namespace
352
353
354 namespace grfx {
355
356 void CacheItem::Impl::convertToDisplayFormat()
357 {
358         setStatus(Converting);
359
360         // First, check that the file exists!
361         if (!IsFileReadable(filename_)) {
362                 if (status_ != ErrorNoFile) {
363                         setStatus(ErrorNoFile);
364                         lyxerr[Debug::GRAPHICS]
365                                 << "\tThe file is not readable" << endl;
366                 }
367                 return;
368         }
369
370         // Make a local copy in case we unzip it
371         string const filename = zippedFile(filename_) ?
372                 unzipFile(filename_) : filename_;
373         string const displayed_filename = MakeDisplayPath(filename_);
374         lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
375                 << "\tAttempting to convert image file: " << filename
376                 << "\n\twith displayed filename: " << displayed_filename
377                 << endl;
378
379         string from = getExtFromContents(filename);
380         lyxerr[Debug::GRAPHICS]
381                 << "\n\tThe file contains " << from << " format data." << endl;
382         string const to = findTargetFormat(from);
383
384         if (from == to) {
385                 // No conversion needed!
386                 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
387                 file_to_load_ = filename;
388                 loadImage();
389                 return;
390         }
391
392         lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
393         // Take only the filename part of the file, without path or extension.
394         string const temp = ChangeExtension(OnlyFilename(filename), string());
395
396         // Add some stuff to create a uniquely named temporary file.
397         // This file is deleted in loadImage after it is loaded into memory.
398         string const to_file_base = lyx::tempName(string(), temp);
399         remove_loaded_file_ = true;
400
401         // Remove the temp file, we only want the name...
402         lyx::unlink(to_file_base);
403
404         // Connect a signal to this->imageConverted and pass this signal to
405         // the graphics converter so that we can load the modified file
406         // on completion of the conversion process.
407         converter_.reset(new Converter(filename, to_file_base, from, to));
408         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
409         converter_->startConversion();
410 }
411
412 } // namespace grfx