2 * \file GraphicsCacheItem.C
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"
21 #include "support/filetools.h"
22 #include "support/FileMonitor.h"
23 #include "support/lyxlib.h"
25 #include <boost/bind.hpp>
27 namespace support = lyx::support;
29 using support::ChangeExtension;
30 using support::FileMonitor;
31 using support::IsFileReadable;
32 using support::MakeDisplayPath;
33 using support::OnlyFilename;
34 using support::getExtFromContents;
35 using support::tempName;
36 using support::unlink;
37 using support::unzipFile;
38 using support::zippedFile;
45 struct CacheItem::Impl : public boost::signals::trackable {
48 Impl(string const & file);
50 /** Start the image conversion process, checking first that it is
51 * necessary. If it is necessary, then a conversion task is started.
52 * CacheItem asumes that the conversion is asynchronous and so
53 * passes a Signal to the converting routine. When the conversion
54 * is finished, this Signal is emitted, returning the converted
55 * file to this->imageConverted.
57 * If no file conversion is needed, then convertToDisplayFormat() calls
58 * loadImage() directly.
60 * convertToDisplayFormat() will set the loading status flag as
61 * approriate through calls to setStatus().
63 void convertToDisplayFormat();
65 /** Load the image into memory. This is called either from
66 * convertToDisplayFormat() direct or from imageConverted().
70 /** Get a notification when the image conversion is done.
71 * Connected to a signal on_finish_ which is passed to
74 void imageConverted(bool);
76 /** Get a notification when the image loading is done.
77 * Connected to a signal on_finish_ which is passed to
78 * lyx::graphics::Image::loadImage.
80 void imageLoaded(bool);
82 /** Sets the status of the loading process. Also notifies
83 * listeners that the status has changed.
85 void setStatus(ImageStatus new_status);
87 /** Can be invoked directly by the user, but is also connected to the
88 * FileMonitor and so is invoked when the file is changed
89 * (if monitoring is taking place).
93 /** If we are asked to load the file for a second or further time,
94 * (because the file has changed), then we'll have to first reset
95 * many of the variables below.
99 /// The filename we refer too.
100 string const filename_;
102 FileMonitor const monitor_;
104 /// Is the file compressed?
106 /// If so, store the uncompressed file in this temporary file.
107 string unzipped_filename_;
108 /// What file are we trying to load?
109 string file_to_load_;
110 /** Should we delete the file after loading? True if the file is
111 * the result of a conversion process.
113 bool remove_loaded_file_;
115 /// The image and its loading status.
116 boost::shared_ptr<Image> image_;
120 /// This signal is emitted when the image loading status changes.
121 boost::signal0<void> statusChanged;
123 /// The connection to the signal Image::finishedLoading
124 boost::signals::connection cl_;
126 /// The connection of the signal ConvProcess::finishedConversion,
127 boost::signals::connection cc_;
130 boost::scoped_ptr<Converter> converter_;
134 CacheItem::CacheItem(string const & file)
135 : pimpl_(new Impl(file))
139 CacheItem::~CacheItem()
143 string const & CacheItem::filename() const
145 return pimpl_->filename_;
149 void CacheItem::startLoading() const
151 pimpl_->startLoading();
155 void CacheItem::startMonitoring() const
157 if (!pimpl_->monitor_.monitoring())
158 pimpl_->monitor_.start();
162 bool CacheItem::monitoring() const
164 return pimpl_->monitor_.monitoring();
168 unsigned long CacheItem::checksum() const
170 return pimpl_->monitor_.checksum();
174 Image const * CacheItem::image() const
176 return pimpl_->image_.get();
180 ImageStatus CacheItem::status() const
182 return pimpl_->status_;
186 boost::signals::connection CacheItem::connect(slot_type const & slot) const
188 return pimpl_->statusChanged.connect(slot);
192 //------------------------------
193 // Implementation details follow
194 //------------------------------
197 CacheItem::Impl::Impl(string const & file)
199 monitor_(file, 2000),
201 remove_loaded_file_(false),
202 status_(WaitingToLoad)
204 monitor_.connect(boost::bind(&Impl::startLoading, this));
208 void CacheItem::Impl::startLoading()
210 if (status_ != WaitingToLoad)
213 convertToDisplayFormat();
217 void CacheItem::Impl::reset()
220 if (!unzipped_filename_.empty())
221 unlink(unzipped_filename_);
222 unzipped_filename_.erase();
224 if (remove_loaded_file_ && !file_to_load_.empty())
225 unlink(file_to_load_);
226 remove_loaded_file_ = false;
227 file_to_load_.erase();
232 status_ = WaitingToLoad;
240 if (converter_.get())
245 void CacheItem::Impl::setStatus(ImageStatus new_status)
247 if (status_ == new_status)
250 status_ = new_status;
255 void CacheItem::Impl::imageConverted(bool success)
257 string const text = success ? "succeeded" : "failed";
258 lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
260 file_to_load_ = converter_.get() ?
261 converter_->convertedFile() : string();
265 success = !file_to_load_.empty() && IsFileReadable(file_to_load_);
268 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
270 setStatus(ErrorConverting);
273 unlink(unzipped_filename_);
282 // This function gets called from the callback after the image has been
283 // converted successfully.
284 void CacheItem::Impl::loadImage()
287 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
289 image_ = Image::newImage();
292 cl_ = image_->finishedLoading.connect(
293 boost::bind(&Impl::imageLoaded, this, _1));
294 image_->load(file_to_load_);
298 void CacheItem::Impl::imageLoaded(bool success)
300 string const text = success ? "succeeded" : "failed";
301 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
303 // Clean up after loading.
305 unlink(unzipped_filename_);
307 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
308 unlink(file_to_load_);
313 setStatus(ErrorLoading);
317 // Inform the outside world.
322 } // namespace graphics
328 string const findTargetFormat(string const & from)
330 typedef lyx::graphics::Image::FormatList FormatList;
331 FormatList const formats = lyx::graphics::Image::loadableFormats();
333 // There must be a format to load from.
334 BOOST_ASSERT(!formats.empty());
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]
351 << "Unable to convert from " << from
352 << " to " << *it << std::endl;
355 // Failed! so we have to try to convert it to PPM format
356 // with the standard converter
357 return string("ppm");
366 void CacheItem::Impl::convertToDisplayFormat()
368 setStatus(Converting);
370 // First, check that the file exists!
371 if (!IsFileReadable(filename_)) {
372 if (status_ != ErrorNoFile) {
373 setStatus(ErrorNoFile);
374 lyxerr[Debug::GRAPHICS]
375 << "\tThe file is not readable" << endl;
380 // Make a local copy in case we unzip it
381 string const filename = zippedFile(filename_) ?
382 unzipFile(filename_) : filename_;
383 string const displayed_filename = MakeDisplayPath(filename_);
384 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
385 << "\tAttempting to convert image file: " << filename
386 << "\n\twith displayed filename: " << displayed_filename
389 string from = getExtFromContents(filename);
390 lyxerr[Debug::GRAPHICS]
391 << "\n\tThe file contains " << from << " format data." << endl;
392 string const to = findTargetFormat(from);
395 // No conversion needed!
396 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
397 file_to_load_ = filename;
402 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
403 // Take only the filename part of the file, without path or extension.
404 string const temp = ChangeExtension(OnlyFilename(filename), string());
406 // Add some stuff to create a uniquely named temporary file.
407 // This file is deleted in loadImage after it is loaded into memory.
408 string const to_file_base = tempName(string(), temp);
409 remove_loaded_file_ = true;
411 // Remove the temp file, we only want the name...
412 unlink(to_file_base);
414 // Connect a signal to this->imageConverted and pass this signal to
415 // the graphics converter so that we can load the modified file
416 // on completion of the conversion process.
417 converter_.reset(new Converter(filename, to_file_base, from, to));
418 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
419 converter_->startConversion();
422 } // namespace graphics