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"
17 #include "GraphicsCache.h"
18 #include "GraphicsConverter.h"
19 #include "GraphicsImage.h"
21 #include "ConverterCache.h"
24 #include "support/debug.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/FileMonitor.h"
29 #include <boost/bind.hpp>
32 using namespace lyx::support;
38 class CacheItem::Impl : public boost::signals::trackable {
42 Impl(FileName const & file);
45 * If no file conversion is needed, then tryDisplayFormat() calls
46 * loadImage() directly.
47 * \return true if a conversion is necessary and no error occurred.
49 bool tryDisplayFormat(FileName & filename, string & from);
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.
58 * convertToDisplayFormat() will set the loading status flag as
59 * approriate through calls to setStatus().
61 void convertToDisplayFormat();
63 /** Load the image into memory. This is called either from
64 * convertToDisplayFormat() direct or from imageConverted().
68 /** Get a notification when the image conversion is done.
69 * Connected to a signal on_finish_ which is passed to
72 void imageConverted(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 of the signal ConvProcess::finishedConversion,
118 boost::signals::connection cc_;
121 boost::scoped_ptr<Converter> converter_;
125 CacheItem::CacheItem(FileName const & file)
126 : pimpl_(new Impl(file))
130 CacheItem::~CacheItem()
136 FileName const & CacheItem::filename() const
138 return pimpl_->filename_;
142 bool CacheItem::tryDisplayFormat() const
144 if (pimpl_->status_ != WaitingToLoad)
146 bool const conversion_needed = pimpl_->tryDisplayFormat(FileName(), string());
147 bool const success = status() == Loaded && !conversion_needed;
154 void CacheItem::startLoading() const
156 pimpl_->startLoading();
160 void CacheItem::startMonitoring() const
162 if (!pimpl_->monitor_.monitoring())
163 pimpl_->monitor_.start();
167 bool CacheItem::monitoring() const
169 return pimpl_->monitor_.monitoring();
173 unsigned long CacheItem::checksum() const
175 return pimpl_->monitor_.checksum();
179 Image const * CacheItem::image() const
181 return pimpl_->image_.get();
185 ImageStatus CacheItem::status() const
187 return pimpl_->status_;
191 boost::signals::connection CacheItem::connect(slot_type const & slot) const
193 return pimpl_->statusChanged.connect(slot);
197 //------------------------------
198 // Implementation details follow
199 //------------------------------
202 CacheItem::Impl::Impl(FileName const & file)
204 monitor_(file, 2000),
206 remove_loaded_file_(false),
207 status_(WaitingToLoad)
209 monitor_.connect(boost::bind(&Impl::startLoading, this));
213 void CacheItem::Impl::startLoading()
215 if (status_ != WaitingToLoad)
218 convertToDisplayFormat();
222 void CacheItem::Impl::reset()
225 if (!unzipped_filename_.empty())
226 unzipped_filename_.removeFile();
227 unzipped_filename_.erase();
229 if (remove_loaded_file_ && !file_to_load_.empty())
230 file_to_load_.removeFile();
231 remove_loaded_file_ = false;
232 file_to_load_.erase();
238 status_ = WaitingToLoad;
243 if (converter_.get())
248 void CacheItem::Impl::setStatus(ImageStatus new_status)
250 if (status_ == new_status)
253 status_ = new_status;
258 void CacheItem::Impl::imageConverted(bool success)
260 string const text = success ? "succeeded" : "failed";
261 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
263 file_to_load_ = converter_.get() ?
264 FileName(converter_->convertedFile()) : FileName();
268 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
271 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
272 setStatus(ErrorConverting);
275 unzipped_filename_.removeFile();
280 // Add the converted file to the file cache
281 ConverterCache::get().add(filename_, to_, file_to_load_);
283 setStatus(loadImage() ? Loaded : ErrorLoading);
287 // This function gets called from the callback after the image has been
288 // converted successfully.
289 bool CacheItem::Impl::loadImage()
291 LYXERR(Debug::GRAPHICS, "Loading image.");
293 image_.reset(newImage());
295 bool success = image_->load(file_to_load_);
296 string const text = success ? "succeeded" : "failed";
297 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
299 // Clean up after loading.
301 unzipped_filename_.removeFile();
303 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
304 file_to_load_.removeFile();
310 static string const findTargetFormat(string const & from)
312 typedef vector<string> FormatList;
313 FormatList const & formats = Cache::get().loadableFormats();
315 // There must be a format to load from.
316 LASSERT(!formats.empty(), /**/);
318 // Use the standard converter if we don't know the format to load
321 return string("ppm");
323 // First ascertain if we can load directly with no conversion
324 FormatList::const_iterator it = formats.begin();
325 FormatList::const_iterator end = formats.end();
326 for (; it != end; ++it) {
331 // So, we have to convert to a loadable format. Can we?
332 it = formats.begin();
333 for (; it != end; ++it) {
334 if (lyx::graphics::Converter::isReachable(from, *it))
337 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
341 // Failed! so we have to try to convert it to PPM format
342 // with the standard converter
343 return string("ppm");
347 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
349 // First, check that the file exists!
350 if (!filename_.isReadableFile()) {
351 if (status_ != ErrorNoFile) {
352 status_ = ErrorNoFile;
353 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
358 zipped_ = filename_.isZippedFile();
360 unzipped_filename_ = FileName::tempName(
361 filename_.toFilesystemEncoding());
362 if (unzipped_filename_.empty()) {
363 status_ = ErrorConverting;
364 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
367 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
369 filename = filename_;
372 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
373 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
374 << "\tAttempting to convert image file: " << filename
375 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
377 from = formats.getFormatFromFile(filename);
379 status_ = ErrorConverting;
380 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
382 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
383 to_ = findTargetFormat(from);
386 // No conversion needed!
387 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
388 file_to_load_ = filename;
389 status_ = loadImage() ? Loaded : ErrorLoading;
393 if (ConverterCache::get().inCache(filename, to_)) {
394 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
395 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
396 status_ = loadImage() ? Loaded : ErrorLoading;
403 void CacheItem::Impl::convertToDisplayFormat()
405 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
407 // Make a local copy in case we unzip it
410 if (!tryDisplayFormat(filename, from)) {
411 // The image status has changed, tell it to the outside world.
416 // We will need a conversion, tell it to the outside world.
417 setStatus(Converting);
419 // Add some stuff to create a uniquely named temporary file.
420 // This file is deleted in loadImage after it is loaded into memory.
421 FileName const to_file_base = FileName::tempName("CacheItem");
422 remove_loaded_file_ = true;
424 // Connect a signal to this->imageConverted and pass this signal to
425 // the graphics converter so that we can load the modified file
426 // on completion of the conversion process.
427 converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
428 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
429 converter_->startConversion();
432 } // namespace graphics