2 * \file GraphicsCacheItem.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * \author Angus Leeming
10 * Full author contact details are available in file CREDITS.
15 #include "GraphicsCacheItem.h"
16 #include "GraphicsConverter.h"
17 #include "GraphicsImage.h"
19 #include "ConverterCache.h"
22 #include "support/debug.h"
23 #include "support/FileName.h"
24 #include "support/filetools.h"
25 #include "support/FileMonitor.h"
27 #include <boost/bind.hpp>
30 using namespace lyx::support;
36 class CacheItem::Impl : public boost::signals::trackable {
40 Impl(FileName const & file);
42 /** Start the image conversion process, checking first that it is
43 * necessary. If it is necessary, then a conversion task is started.
44 * CacheItem asumes that the conversion is asynchronous and so
45 * passes a Signal to the converting routine. When the conversion
46 * is finished, this Signal is emitted, returning the converted
47 * file to this->imageConverted.
49 * If no file conversion is needed, then convertToDisplayFormat() calls
50 * loadImage() directly.
52 * convertToDisplayFormat() will set the loading status flag as
53 * approriate through calls to setStatus().
55 void convertToDisplayFormat();
57 /** Load the image into memory. This is called either from
58 * convertToDisplayFormat() direct or from imageConverted().
62 /** Get a notification when the image conversion is done.
63 * Connected to a signal on_finish_ which is passed to
66 void imageConverted(bool);
68 /** Get a notification when the image loading is done.
69 * Connected to a signal on_finish_ which is passed to
70 * lyx::graphics::Image::loadImage.
72 void imageLoaded(bool);
74 /** Sets the status of the loading process. Also notifies
75 * listeners that the status has changed.
77 void setStatus(ImageStatus new_status);
79 /** Can be invoked directly by the user, but is also connected to the
80 * FileMonitor and so is invoked when the file is changed
81 * (if monitoring is taking place).
85 /** If we are asked to load the file for a second or further time,
86 * (because the file has changed), then we'll have to first reset
87 * many of the variables below.
91 /// The filename we refer too.
92 FileName const filename_;
94 FileMonitor const monitor_;
96 /// Is the file compressed?
98 /// If so, store the uncompressed file in this temporary file.
99 FileName unzipped_filename_;
100 /// The target format
102 /// What file are we trying to load?
103 FileName file_to_load_;
104 /** Should we delete the file after loading? True if the file is
105 * the result of a conversion process.
107 bool remove_loaded_file_;
109 /// The image and its loading status.
110 boost::shared_ptr<Image> image_;
114 /// This signal is emitted when the image loading status changes.
115 boost::signal<void()> statusChanged;
117 /// The connection to the signal Image::finishedLoading
118 boost::signals::connection cl_;
120 /// The connection of the signal ConvProcess::finishedConversion,
121 boost::signals::connection cc_;
124 boost::scoped_ptr<Converter> converter_;
128 CacheItem::CacheItem(FileName const & file)
129 : pimpl_(new Impl(file))
133 CacheItem::~CacheItem()
139 FileName const & CacheItem::filename() const
141 return pimpl_->filename_;
145 void CacheItem::startLoading() const
147 pimpl_->startLoading();
151 void CacheItem::startMonitoring() const
153 if (!pimpl_->monitor_.monitoring())
154 pimpl_->monitor_.start();
158 bool CacheItem::monitoring() const
160 return pimpl_->monitor_.monitoring();
164 unsigned long CacheItem::checksum() const
166 return pimpl_->monitor_.checksum();
170 Image const * CacheItem::image() const
172 return pimpl_->image_.get();
176 ImageStatus CacheItem::status() const
178 return pimpl_->status_;
182 boost::signals::connection CacheItem::connect(slot_type const & slot) const
184 return pimpl_->statusChanged.connect(slot);
188 //------------------------------
189 // Implementation details follow
190 //------------------------------
193 CacheItem::Impl::Impl(FileName const & file)
195 monitor_(file, 2000),
197 remove_loaded_file_(false),
198 status_(WaitingToLoad)
200 monitor_.connect(boost::bind(&Impl::startLoading, this));
204 void CacheItem::Impl::startLoading()
206 if (status_ != WaitingToLoad)
209 convertToDisplayFormat();
213 void CacheItem::Impl::reset()
216 if (!unzipped_filename_.empty())
217 unzipped_filename_.removeFile();
218 unzipped_filename_.erase();
220 if (remove_loaded_file_ && !file_to_load_.empty())
221 file_to_load_.removeFile();
222 remove_loaded_file_ = false;
223 file_to_load_.erase();
229 status_ = WaitingToLoad;
237 if (converter_.get())
242 void CacheItem::Impl::setStatus(ImageStatus new_status)
244 if (status_ == new_status)
247 status_ = new_status;
252 void CacheItem::Impl::imageConverted(bool success)
254 string const text = success ? "succeeded" : "failed";
255 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
257 file_to_load_ = converter_.get() ?
258 FileName(converter_->convertedFile()) : FileName();
262 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
265 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
266 setStatus(ErrorConverting);
269 unzipped_filename_.removeFile();
274 // Add the converted file to the file cache
275 ConverterCache::get().add(filename_, to_, file_to_load_);
281 // This function gets called from the callback after the image has been
282 // converted successfully.
283 void CacheItem::Impl::loadImage()
286 LYXERR(Debug::GRAPHICS, "Loading image.");
288 image_.reset(Image::newImage());
291 cl_ = image_->finishedLoading.connect(
292 boost::bind(&Impl::imageLoaded, this, _1));
293 image_->load(file_to_load_);
297 void CacheItem::Impl::imageLoaded(bool success)
299 string const text = success ? "succeeded" : "failed";
300 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
302 // Clean up after loading.
304 unzipped_filename_.removeFile();
306 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
307 file_to_load_.removeFile();
312 setStatus(ErrorLoading);
316 // Inform the outside world.
321 static string const findTargetFormat(string const & from)
323 typedef lyx::graphics::Image::FormatList FormatList;
324 FormatList const formats = lyx::graphics::Image::loadableFormats();
326 // There must be a format to load from.
327 BOOST_ASSERT(!formats.empty());
329 // Use the standard converter if we don't know the format to load
332 return string("ppm");
334 // First ascertain if we can load directly with no conversion
335 FormatList::const_iterator it = formats.begin();
336 FormatList::const_iterator end = formats.end();
337 for (; it != end; ++it) {
342 // So, we have to convert to a loadable format. Can we?
343 it = formats.begin();
344 for (; it != end; ++it) {
345 if (lyx::graphics::Converter::isReachable(from, *it))
348 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
352 // Failed! so we have to try to convert it to PPM format
353 // with the standard converter
354 return string("ppm");
358 void CacheItem::Impl::convertToDisplayFormat()
360 setStatus(Converting);
362 // First, check that the file exists!
363 if (!filename_.isReadableFile()) {
364 if (status_ != ErrorNoFile) {
365 setStatus(ErrorNoFile);
366 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
371 // Make a local copy in case we unzip it
373 zipped_ = filename_.isZippedFile();
375 unzipped_filename_ = FileName::tempName(
376 filename_.toFilesystemEncoding());
377 if (unzipped_filename_.empty()) {
378 setStatus(ErrorConverting);
379 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
382 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
384 filename = filename_;
387 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
388 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
389 << "\tAttempting to convert image file: " << filename
390 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
392 string const from = formats.getFormatFromFile(filename);
394 setStatus(ErrorConverting);
395 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
397 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
398 to_ = findTargetFormat(from);
401 // No conversion needed!
402 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
403 file_to_load_ = filename;
408 if (ConverterCache::get().inCache(filename, to_)) {
409 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
410 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
415 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
417 // Add some stuff to create a uniquely named temporary file.
418 // This file is deleted in loadImage after it is loaded into memory.
419 FileName const to_file_base = FileName::tempName("CacheItem");
420 remove_loaded_file_ = true;
422 // Remove the temp file, we only want the name...
423 // FIXME: This is unsafe!
424 to_file_base.removeFile();
426 // Connect a signal to this->imageConverted and pass this signal to
427 // the graphics converter so that we can load the modified file
428 // on completion of the conversion process.
429 converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
430 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
431 converter_->startConversion();
434 } // namespace graphics