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);
44 /** Start the image conversion process, checking first that it is
45 * necessary. If it is necessary, then a conversion task is started.
46 * CacheItem asumes that the conversion is asynchronous and so
47 * passes a Signal to the converting routine. When the conversion
48 * is finished, this Signal is emitted, returning the converted
49 * file to this->imageConverted.
51 * If no file conversion is needed, then convertToDisplayFormat() calls
52 * loadImage() directly.
54 * convertToDisplayFormat() will set the loading status flag as
55 * approriate through calls to setStatus().
57 void convertToDisplayFormat();
59 /** Load the image into memory. This is called either from
60 * convertToDisplayFormat() direct or from imageConverted().
64 /** Get a notification when the image conversion is done.
65 * Connected to a signal on_finish_ which is passed to
68 void imageConverted(bool);
70 /** Get a notification when the image loading is done.
71 * Connected to a signal on_finish_ which is passed to
72 * lyx::graphics::Image::loadImage.
74 void imageLoaded(bool);
76 /** Sets the status of the loading process. Also notifies
77 * listeners that the status has changed.
79 void setStatus(ImageStatus new_status);
81 /** Can be invoked directly by the user, but is also connected to the
82 * FileMonitor and so is invoked when the file is changed
83 * (if monitoring is taking place).
87 /** If we are asked to load the file for a second or further time,
88 * (because the file has changed), then we'll have to first reset
89 * many of the variables below.
93 /// The filename we refer too.
94 FileName const filename_;
96 FileMonitor const monitor_;
98 /// Is the file compressed?
100 /// If so, store the uncompressed file in this temporary file.
101 FileName unzipped_filename_;
102 /// The target format
104 /// What file are we trying to load?
105 FileName file_to_load_;
106 /** Should we delete the file after loading? True if the file is
107 * the result of a conversion process.
109 bool remove_loaded_file_;
111 /// The image and its loading status.
112 boost::shared_ptr<Image> image_;
116 /// This signal is emitted when the image loading status changes.
117 boost::signal<void()> statusChanged;
119 /// The connection to the signal Image::finishedLoading
120 boost::signals::connection cl_;
122 /// The connection of the signal ConvProcess::finishedConversion,
123 boost::signals::connection cc_;
126 boost::scoped_ptr<Converter> converter_;
130 CacheItem::CacheItem(FileName const & file)
131 : pimpl_(new Impl(file))
135 CacheItem::~CacheItem()
141 FileName const & CacheItem::filename() const
143 return pimpl_->filename_;
147 void CacheItem::startLoading() const
149 pimpl_->startLoading();
153 void CacheItem::startMonitoring() const
155 if (!pimpl_->monitor_.monitoring())
156 pimpl_->monitor_.start();
160 bool CacheItem::monitoring() const
162 return pimpl_->monitor_.monitoring();
166 unsigned long CacheItem::checksum() const
168 return pimpl_->monitor_.checksum();
172 Image const * CacheItem::image() const
174 return pimpl_->image_.get();
178 ImageStatus CacheItem::status() const
180 return pimpl_->status_;
184 boost::signals::connection CacheItem::connect(slot_type const & slot) const
186 return pimpl_->statusChanged.connect(slot);
190 //------------------------------
191 // Implementation details follow
192 //------------------------------
195 CacheItem::Impl::Impl(FileName const & file)
197 monitor_(file, 2000),
199 remove_loaded_file_(false),
200 status_(WaitingToLoad)
202 monitor_.connect(boost::bind(&Impl::startLoading, this));
206 void CacheItem::Impl::startLoading()
208 if (status_ != WaitingToLoad)
211 convertToDisplayFormat();
215 void CacheItem::Impl::reset()
218 if (!unzipped_filename_.empty())
219 unzipped_filename_.removeFile();
220 unzipped_filename_.erase();
222 if (remove_loaded_file_ && !file_to_load_.empty())
223 file_to_load_.removeFile();
224 remove_loaded_file_ = false;
225 file_to_load_.erase();
231 status_ = WaitingToLoad;
239 if (converter_.get())
244 void CacheItem::Impl::setStatus(ImageStatus new_status)
246 if (status_ == new_status)
249 status_ = new_status;
254 void CacheItem::Impl::imageConverted(bool success)
256 string const text = success ? "succeeded" : "failed";
257 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
259 file_to_load_ = converter_.get() ?
260 FileName(converter_->convertedFile()) : FileName();
264 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
267 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
268 setStatus(ErrorConverting);
271 unzipped_filename_.removeFile();
276 // Add the converted file to the file cache
277 ConverterCache::get().add(filename_, to_, file_to_load_);
283 // This function gets called from the callback after the image has been
284 // converted successfully.
285 void CacheItem::Impl::loadImage()
288 LYXERR(Debug::GRAPHICS, "Loading image.");
290 image_.reset(Image::newImage());
293 cl_ = image_->finishedLoading.connect(
294 boost::bind(&Impl::imageLoaded, this, _1));
295 image_->load(file_to_load_);
299 void CacheItem::Impl::imageLoaded(bool success)
301 string const text = success ? "succeeded" : "failed";
302 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
304 // Clean up after loading.
306 unzipped_filename_.removeFile();
308 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
309 file_to_load_.removeFile();
314 setStatus(ErrorLoading);
318 // Inform the outside world.
323 static string const findTargetFormat(string const & from)
325 typedef vector<string> FormatList;
326 FormatList const & formats = Cache::get().loadableFormats();
328 // There must be a format to load from.
329 LASSERT(!formats.empty(), /**/);
331 // Use the standard converter if we don't know the format to load
334 return string("ppm");
336 // First ascertain if we can load directly with no conversion
337 FormatList::const_iterator it = formats.begin();
338 FormatList::const_iterator end = formats.end();
339 for (; it != end; ++it) {
344 // So, we have to convert to a loadable format. Can we?
345 it = formats.begin();
346 for (; it != end; ++it) {
347 if (lyx::graphics::Converter::isReachable(from, *it))
350 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
354 // Failed! so we have to try to convert it to PPM format
355 // with the standard converter
356 return string("ppm");
360 void CacheItem::Impl::convertToDisplayFormat()
362 setStatus(Converting);
364 // First, check that the file exists!
365 if (!filename_.isReadableFile()) {
366 if (status_ != ErrorNoFile) {
367 setStatus(ErrorNoFile);
368 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
373 // Make a local copy in case we unzip it
375 zipped_ = filename_.isZippedFile();
377 unzipped_filename_ = FileName::tempName(
378 filename_.toFilesystemEncoding());
379 if (unzipped_filename_.empty()) {
380 setStatus(ErrorConverting);
381 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
384 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
386 filename = filename_;
389 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
390 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
391 << "\tAttempting to convert image file: " << filename
392 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
394 string const from = formats.getFormatFromFile(filename);
396 setStatus(ErrorConverting);
397 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
399 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
400 to_ = findTargetFormat(from);
403 // No conversion needed!
404 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
405 file_to_load_ = filename;
410 if (ConverterCache::get().inCache(filename, to_)) {
411 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
412 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
417 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
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 // Remove the temp file, we only want the name...
425 // FIXME: This is unsafe!
426 to_file_base.removeFile();
428 // Connect a signal to this->imageConverted and pass this signal to
429 // the graphics converter so that we can load the modified file
430 // on completion of the conversion process.
431 converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
432 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
433 converter_->startConversion();
436 } // namespace graphics