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