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"
22 #include "support/filetools.h"
23 #include "support/FileMonitor.h"
24 #include "support/lyxlib.h"
26 #include <boost/bind.hpp>
29 namespace support = lyx::support;
31 using support::ChangeExtension;
32 using support::FileMonitor;
33 using support::IsFileReadable;
34 using support::MakeDisplayPath;
35 using support::OnlyFilename;
36 using support::tempName;
37 using support::unlink;
38 using support::unzipFile;
39 using support::unzippedFileName;
40 using support::zippedFile;
49 class CacheItem::Impl : public boost::signals::trackable {
53 Impl(string const & file);
55 /** Start the image conversion process, checking first that it is
56 * necessary. If it is necessary, then a conversion task is started.
57 * CacheItem asumes that the conversion is asynchronous and so
58 * passes a Signal to the converting routine. When the conversion
59 * is finished, this Signal is emitted, returning the converted
60 * file to this->imageConverted.
62 * If no file conversion is needed, then convertToDisplayFormat() calls
63 * loadImage() directly.
65 * convertToDisplayFormat() will set the loading status flag as
66 * approriate through calls to setStatus().
68 void convertToDisplayFormat();
70 /** Load the image into memory. This is called either from
71 * convertToDisplayFormat() direct or from imageConverted().
75 /** Get a notification when the image conversion is done.
76 * Connected to a signal on_finish_ which is passed to
79 void imageConverted(bool);
81 /** Get a notification when the image loading is done.
82 * Connected to a signal on_finish_ which is passed to
83 * lyx::graphics::Image::loadImage.
85 void imageLoaded(bool);
87 /** Sets the status of the loading process. Also notifies
88 * listeners that the status has changed.
90 void setStatus(ImageStatus new_status);
92 /** Can be invoked directly by the user, but is also connected to the
93 * FileMonitor and so is invoked when the file is changed
94 * (if monitoring is taking place).
98 /** If we are asked to load the file for a second or further time,
99 * (because the file has changed), then we'll have to first reset
100 * many of the variables below.
104 /// The filename we refer too.
105 string const filename_;
107 FileMonitor const monitor_;
109 /// Is the file compressed?
111 /// If so, store the uncompressed file in this temporary file.
112 string unzipped_filename_;
113 /// What file are we trying to load?
114 string file_to_load_;
115 /** Should we delete the file after loading? True if the file is
116 * the result of a conversion process.
118 bool remove_loaded_file_;
120 /// The image and its loading status.
121 boost::shared_ptr<Image> image_;
125 /// This signal is emitted when the image loading status changes.
126 boost::signal<void()> statusChanged;
128 /// The connection to the signal Image::finishedLoading
129 boost::signals::connection cl_;
131 /// The connection of the signal ConvProcess::finishedConversion,
132 boost::signals::connection cc_;
135 boost::scoped_ptr<Converter> converter_;
139 CacheItem::CacheItem(string const & file)
140 : pimpl_(new Impl(file))
144 CacheItem::~CacheItem()
148 string const & CacheItem::filename() const
150 return pimpl_->filename_;
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(string 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 unlink(unzipped_filename_);
227 unzipped_filename_.erase();
229 if (remove_loaded_file_ && !file_to_load_.empty())
230 unlink(file_to_load_);
231 remove_loaded_file_ = false;
232 file_to_load_.erase();
237 status_ = WaitingToLoad;
245 if (converter_.get())
250 void CacheItem::Impl::setStatus(ImageStatus new_status)
252 if (status_ == new_status)
255 status_ = new_status;
260 void CacheItem::Impl::imageConverted(bool success)
262 string const text = success ? "succeeded" : "failed";
263 lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
265 file_to_load_ = converter_.get() ?
266 converter_->convertedFile() : string();
270 success = !file_to_load_.empty() && IsFileReadable(file_to_load_);
273 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
275 setStatus(ErrorConverting);
278 unlink(unzipped_filename_);
287 // This function gets called from the callback after the image has been
288 // converted successfully.
289 void CacheItem::Impl::loadImage()
292 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
294 image_ = Image::newImage();
297 cl_ = image_->finishedLoading.connect(
298 boost::bind(&Impl::imageLoaded, this, _1));
299 image_->load(file_to_load_);
303 void CacheItem::Impl::imageLoaded(bool success)
305 string const text = success ? "succeeded" : "failed";
306 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
308 // Clean up after loading.
310 unlink(unzipped_filename_);
312 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
313 unlink(file_to_load_);
318 setStatus(ErrorLoading);
322 // Inform the outside world.
327 } // namespace graphics
333 string const findTargetFormat(string const & from)
335 typedef lyx::graphics::Image::FormatList FormatList;
336 FormatList const formats = lyx::graphics::Image::loadableFormats();
338 // There must be a format to load from.
339 BOOST_ASSERT(!formats.empty());
341 // First ascertain if we can load directly with no conversion
342 FormatList::const_iterator it = formats.begin();
343 FormatList::const_iterator end = formats.end();
344 for (; it != end; ++it) {
349 // So, we have to convert to a loadable format. Can we?
350 it = formats.begin();
351 for (; it != end; ++it) {
352 if (lyx::graphics::Converter::isReachable(from, *it))
355 lyxerr[Debug::GRAPHICS]
356 << "Unable to convert from " << from
357 << " to " << *it << std::endl;
360 // Failed! so we have to try to convert it to PPM format
361 // with the standard converter
362 return string("ppm");
371 void CacheItem::Impl::convertToDisplayFormat()
373 setStatus(Converting);
375 // First, check that the file exists!
376 if (!IsFileReadable(filename_)) {
377 if (status_ != ErrorNoFile) {
378 setStatus(ErrorNoFile);
379 lyxerr[Debug::GRAPHICS]
380 << "\tThe file is not readable" << endl;
385 // Make a local copy in case we unzip it
387 if ((zipped_ = zippedFile(filename_))) {
388 unzipped_filename_ = tempName(string(), filename_);
389 if (unzipped_filename_.empty()) {
390 setStatus(ErrorConverting);
391 lyxerr[Debug::GRAPHICS]
392 << "\tCould not create temporary file." << endl;
395 filename = unzipFile(filename_, unzipped_filename_);
397 filename = filename_;
399 string const displayed_filename = MakeDisplayPath(filename_);
400 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
401 << "\tAttempting to convert image file: " << filename
402 << "\n\twith displayed filename: " << displayed_filename
405 string const from = formats.getFormatFromFile(filename);
407 setStatus(ErrorConverting);
408 lyxerr[Debug::GRAPHICS]
409 << "\tCould not determine file format." << endl;
412 lyxerr[Debug::GRAPHICS]
413 << "\n\tThe file contains " << from << " format data." << endl;
414 string const to = findTargetFormat(from);
417 // No conversion needed!
418 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
419 file_to_load_ = filename;
424 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
425 // Take only the filename part of the file, without path or extension.
426 string const temp = ChangeExtension(OnlyFilename(filename), string());
428 // Add some stuff to create a uniquely named temporary file.
429 // This file is deleted in loadImage after it is loaded into memory.
430 string const to_file_base = tempName(string(), temp);
431 remove_loaded_file_ = true;
433 // Remove the temp file, we only want the name...
434 // FIXME: This is unsafe!
435 unlink(to_file_base);
437 // Connect a signal to this->imageConverted and pass this signal to
438 // the graphics converter so that we can load the modified file
439 // on completion of the conversion process.
440 converter_.reset(new Converter(filename, to_file_base, from, to));
441 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
442 converter_->startConversion();
445 } // namespace graphics