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"
20 #include "support/debug.h"
23 #include "support/filetools.h"
24 #include "support/FileMonitor.h"
26 #include <boost/bind.hpp>
29 using namespace lyx::support;
35 class CacheItem::Impl : public boost::signals::trackable {
39 Impl(FileName const & file);
41 /** Start the image conversion process, checking first that it is
42 * necessary. If it is necessary, then a conversion task is started.
43 * CacheItem asumes that the conversion is asynchronous and so
44 * passes a Signal to the converting routine. When the conversion
45 * is finished, this Signal is emitted, returning the converted
46 * file to this->imageConverted.
48 * If no file conversion is needed, then convertToDisplayFormat() calls
49 * loadImage() directly.
51 * convertToDisplayFormat() will set the loading status flag as
52 * approriate through calls to setStatus().
54 void convertToDisplayFormat();
56 /** Load the image into memory. This is called either from
57 * convertToDisplayFormat() direct or from imageConverted().
61 /** Get a notification when the image conversion is done.
62 * Connected to a signal on_finish_ which is passed to
65 void imageConverted(bool);
67 /** Get a notification when the image loading is done.
68 * Connected to a signal on_finish_ which is passed to
69 * lyx::graphics::Image::loadImage.
71 void imageLoaded(bool);
73 /** Sets the status of the loading process. Also notifies
74 * listeners that the status has changed.
76 void setStatus(ImageStatus new_status);
78 /** Can be invoked directly by the user, but is also connected to the
79 * FileMonitor and so is invoked when the file is changed
80 * (if monitoring is taking place).
84 /** If we are asked to load the file for a second or further time,
85 * (because the file has changed), then we'll have to first reset
86 * many of the variables below.
90 /// The filename we refer too.
91 FileName const filename_;
93 FileMonitor const monitor_;
95 /// Is the file compressed?
97 /// If so, store the uncompressed file in this temporary file.
98 FileName unzipped_filename_;
101 /// What file are we trying to load?
102 FileName file_to_load_;
103 /** Should we delete the file after loading? True if the file is
104 * the result of a conversion process.
106 bool remove_loaded_file_;
108 /// The image and its loading status.
109 boost::shared_ptr<Image> image_;
113 /// This signal is emitted when the image loading status changes.
114 boost::signal<void()> statusChanged;
116 /// The connection to the signal Image::finishedLoading
117 boost::signals::connection cl_;
119 /// The connection of the signal ConvProcess::finishedConversion,
120 boost::signals::connection cc_;
123 boost::scoped_ptr<Converter> converter_;
127 CacheItem::CacheItem(FileName const & file)
128 : pimpl_(new Impl(file))
132 CacheItem::~CacheItem()
138 FileName const & CacheItem::filename() const
140 return pimpl_->filename_;
144 void CacheItem::startLoading() const
146 pimpl_->startLoading();
150 void CacheItem::startMonitoring() const
152 if (!pimpl_->monitor_.monitoring())
153 pimpl_->monitor_.start();
157 bool CacheItem::monitoring() const
159 return pimpl_->monitor_.monitoring();
163 unsigned long CacheItem::checksum() const
165 return pimpl_->monitor_.checksum();
169 Image const * CacheItem::image() const
171 return pimpl_->image_.get();
175 ImageStatus CacheItem::status() const
177 return pimpl_->status_;
181 boost::signals::connection CacheItem::connect(slot_type const & slot) const
183 return pimpl_->statusChanged.connect(slot);
187 //------------------------------
188 // Implementation details follow
189 //------------------------------
192 CacheItem::Impl::Impl(FileName const & file)
194 monitor_(file, 2000),
196 remove_loaded_file_(false),
197 status_(WaitingToLoad)
199 monitor_.connect(boost::bind(&Impl::startLoading, this));
203 void CacheItem::Impl::startLoading()
205 if (status_ != WaitingToLoad)
208 convertToDisplayFormat();
212 void CacheItem::Impl::reset()
215 if (!unzipped_filename_.empty())
216 unzipped_filename_.removeFile();
217 unzipped_filename_.erase();
219 if (remove_loaded_file_ && !file_to_load_.empty())
220 file_to_load_.removeFile();
221 remove_loaded_file_ = false;
222 file_to_load_.erase();
228 status_ = WaitingToLoad;
236 if (converter_.get())
241 void CacheItem::Impl::setStatus(ImageStatus new_status)
243 if (status_ == new_status)
246 status_ = new_status;
251 void CacheItem::Impl::imageConverted(bool success)
253 string const text = success ? "succeeded" : "failed";
254 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
256 file_to_load_ = converter_.get() ?
257 FileName(converter_->convertedFile()) : FileName();
261 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
264 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
265 setStatus(ErrorConverting);
268 unzipped_filename_.removeFile();
273 // Add the converted file to the file cache
274 ConverterCache::get().add(filename_, to_, file_to_load_);
280 // This function gets called from the callback after the image has been
281 // converted successfully.
282 void CacheItem::Impl::loadImage()
285 LYXERR(Debug::GRAPHICS, "Loading image.");
287 image_.reset(Image::newImage());
290 cl_ = image_->finishedLoading.connect(
291 boost::bind(&Impl::imageLoaded, this, _1));
292 image_->load(file_to_load_);
296 void CacheItem::Impl::imageLoaded(bool success)
298 string const text = success ? "succeeded" : "failed";
299 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
301 // Clean up after loading.
303 unzipped_filename_.removeFile();
305 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
306 file_to_load_.removeFile();
311 setStatus(ErrorLoading);
315 // Inform the outside world.
320 static string const findTargetFormat(string const & from)
322 typedef lyx::graphics::Image::FormatList FormatList;
323 FormatList const formats = lyx::graphics::Image::loadableFormats();
325 // There must be a format to load from.
326 BOOST_ASSERT(!formats.empty());
328 // Use the standard converter if we don't know the format to load
331 return string("ppm");
333 // First ascertain if we can load directly with no conversion
334 FormatList::const_iterator it = formats.begin();
335 FormatList::const_iterator end = formats.end();
336 for (; it != end; ++it) {
341 // So, we have to convert to a loadable format. Can we?
342 it = formats.begin();
343 for (; it != end; ++it) {
344 if (lyx::graphics::Converter::isReachable(from, *it))
347 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
351 // Failed! so we have to try to convert it to PPM format
352 // with the standard converter
353 return string("ppm");
357 void CacheItem::Impl::convertToDisplayFormat()
359 setStatus(Converting);
361 // First, check that the file exists!
362 if (!filename_.isReadableFile()) {
363 if (status_ != ErrorNoFile) {
364 setStatus(ErrorNoFile);
365 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
370 // Make a local copy in case we unzip it
372 zipped_ = filename_.isZippedFile();
374 unzipped_filename_ = FileName::tempName(
375 filename_.toFilesystemEncoding());
376 if (unzipped_filename_.empty()) {
377 setStatus(ErrorConverting);
378 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
381 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
383 filename = filename_;
386 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
387 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
388 << "\tAttempting to convert image file: " << filename
389 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
391 string const from = formats.getFormatFromFile(filename);
393 setStatus(ErrorConverting);
394 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
396 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
397 to_ = findTargetFormat(from);
400 // No conversion needed!
401 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
402 file_to_load_ = filename;
407 if (ConverterCache::get().inCache(filename, to_)) {
408 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
409 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
414 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
416 // Add some stuff to create a uniquely named temporary file.
417 // This file is deleted in loadImage after it is loaded into memory.
418 FileName const to_file_base = FileName::tempName("CacheItem");
419 remove_loaded_file_ = true;
421 // Remove the temp file, we only want the name...
422 // FIXME: This is unsafe!
423 to_file_base.removeFile();
425 // Connect a signal to this->imageConverted and pass this signal to
426 // the graphics converter so that we can load the modified file
427 // on completion of the conversion process.
428 converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
429 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
430 converter_->startConversion();
433 } // namespace graphics