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>
28 namespace support = lyx::support;
30 using support::ChangeExtension;
31 using support::FileMonitor;
32 using support::IsFileReadable;
33 using support::MakeDisplayPath;
34 using support::OnlyFilename;
35 using support::getExtFromContents;
36 using support::tempName;
37 using support::unlink;
38 using support::unzipFile;
39 using support::zippedFile;
48 struct CacheItem::Impl : public boost::signals::trackable {
51 Impl(string const & file);
53 /** Start the image conversion process, checking first that it is
54 * necessary. If it is necessary, then a conversion task is started.
55 * CacheItem asumes that the conversion is asynchronous and so
56 * passes a Signal to the converting routine. When the conversion
57 * is finished, this Signal is emitted, returning the converted
58 * file to this->imageConverted.
60 * If no file conversion is needed, then convertToDisplayFormat() calls
61 * loadImage() directly.
63 * convertToDisplayFormat() will set the loading status flag as
64 * approriate through calls to setStatus().
66 void convertToDisplayFormat();
68 /** Load the image into memory. This is called either from
69 * convertToDisplayFormat() direct or from imageConverted().
73 /** Get a notification when the image conversion is done.
74 * Connected to a signal on_finish_ which is passed to
77 void imageConverted(bool);
79 /** Get a notification when the image loading is done.
80 * Connected to a signal on_finish_ which is passed to
81 * lyx::graphics::Image::loadImage.
83 void imageLoaded(bool);
85 /** Sets the status of the loading process. Also notifies
86 * listeners that the status has changed.
88 void setStatus(ImageStatus new_status);
90 /** Can be invoked directly by the user, but is also connected to the
91 * FileMonitor and so is invoked when the file is changed
92 * (if monitoring is taking place).
96 /** If we are asked to load the file for a second or further time,
97 * (because the file has changed), then we'll have to first reset
98 * many of the variables below.
102 /// The filename we refer too.
103 string const filename_;
105 FileMonitor const monitor_;
107 /// Is the file compressed?
109 /// If so, store the uncompressed file in this temporary file.
110 string unzipped_filename_;
111 /// What file are we trying to load?
112 string file_to_load_;
113 /** Should we delete the file after loading? True if the file is
114 * the result of a conversion process.
116 bool remove_loaded_file_;
118 /// The image and its loading status.
119 boost::shared_ptr<Image> image_;
123 /// This signal is emitted when the image loading status changes.
124 boost::signal0<void> statusChanged;
126 /// The connection to the signal Image::finishedLoading
127 boost::signals::connection cl_;
129 /// The connection of the signal ConvProcess::finishedConversion,
130 boost::signals::connection cc_;
133 boost::scoped_ptr<Converter> converter_;
137 CacheItem::CacheItem(string const & file)
138 : pimpl_(new Impl(file))
142 CacheItem::~CacheItem()
146 string const & CacheItem::filename() const
148 return pimpl_->filename_;
152 void CacheItem::startLoading() const
154 pimpl_->startLoading();
158 void CacheItem::startMonitoring() const
160 if (!pimpl_->monitor_.monitoring())
161 pimpl_->monitor_.start();
165 bool CacheItem::monitoring() const
167 return pimpl_->monitor_.monitoring();
171 unsigned long CacheItem::checksum() const
173 return pimpl_->monitor_.checksum();
177 Image const * CacheItem::image() const
179 return pimpl_->image_.get();
183 ImageStatus CacheItem::status() const
185 return pimpl_->status_;
189 boost::signals::connection CacheItem::connect(slot_type const & slot) const
191 return pimpl_->statusChanged.connect(slot);
195 //------------------------------
196 // Implementation details follow
197 //------------------------------
200 CacheItem::Impl::Impl(string const & file)
202 monitor_(file, 2000),
204 remove_loaded_file_(false),
205 status_(WaitingToLoad)
207 monitor_.connect(boost::bind(&Impl::startLoading, this));
211 void CacheItem::Impl::startLoading()
213 if (status_ != WaitingToLoad)
216 convertToDisplayFormat();
220 void CacheItem::Impl::reset()
223 if (!unzipped_filename_.empty())
224 unlink(unzipped_filename_);
225 unzipped_filename_.erase();
227 if (remove_loaded_file_ && !file_to_load_.empty())
228 unlink(file_to_load_);
229 remove_loaded_file_ = false;
230 file_to_load_.erase();
235 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 << '.' << endl;
263 file_to_load_ = converter_.get() ?
264 converter_->convertedFile() : string();
268 success = !file_to_load_.empty() && IsFileReadable(file_to_load_);
271 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
273 setStatus(ErrorConverting);
276 unlink(unzipped_filename_);
285 // This function gets called from the callback after the image has been
286 // converted successfully.
287 void CacheItem::Impl::loadImage()
290 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
292 image_ = Image::newImage();
295 cl_ = image_->finishedLoading.connect(
296 boost::bind(&Impl::imageLoaded, this, _1));
297 image_->load(file_to_load_);
301 void CacheItem::Impl::imageLoaded(bool success)
303 string const text = success ? "succeeded" : "failed";
304 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
306 // Clean up after loading.
308 unlink(unzipped_filename_);
310 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
311 unlink(file_to_load_);
316 setStatus(ErrorLoading);
320 // Inform the outside world.
325 } // namespace graphics
331 string const findTargetFormat(string const & from)
333 typedef lyx::graphics::Image::FormatList FormatList;
334 FormatList const formats = lyx::graphics::Image::loadableFormats();
336 // There must be a format to load from.
337 BOOST_ASSERT(!formats.empty());
339 // First ascertain if we can load directly with no conversion
340 FormatList::const_iterator it = formats.begin();
341 FormatList::const_iterator end = formats.end();
342 for (; it != end; ++it) {
347 // So, we have to convert to a loadable format. Can we?
348 it = formats.begin();
349 for (; it != end; ++it) {
350 if (lyx::graphics::Converter::isReachable(from, *it))
353 lyxerr[Debug::GRAPHICS]
354 << "Unable to convert from " << from
355 << " to " << *it << std::endl;
358 // Failed! so we have to try to convert it to PPM format
359 // with the standard converter
360 return string("ppm");
369 void CacheItem::Impl::convertToDisplayFormat()
371 setStatus(Converting);
373 // First, check that the file exists!
374 if (!IsFileReadable(filename_)) {
375 if (status_ != ErrorNoFile) {
376 setStatus(ErrorNoFile);
377 lyxerr[Debug::GRAPHICS]
378 << "\tThe file is not readable" << endl;
383 // Make a local copy in case we unzip it
384 string const filename = zippedFile(filename_) ?
385 unzipFile(filename_) : filename_;
386 string const displayed_filename = MakeDisplayPath(filename_);
387 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
388 << "\tAttempting to convert image file: " << filename
389 << "\n\twith displayed filename: " << displayed_filename
392 string from = getExtFromContents(filename);
393 lyxerr[Debug::GRAPHICS]
394 << "\n\tThe file contains " << from << " format data." << endl;
395 string const to = findTargetFormat(from);
398 // No conversion needed!
399 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
400 file_to_load_ = filename;
405 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
406 // Take only the filename part of the file, without path or extension.
407 string const temp = ChangeExtension(OnlyFilename(filename), string());
409 // Add some stuff to create a uniquely named temporary file.
410 // This file is deleted in loadImage after it is loaded into memory.
411 string const to_file_base = tempName(string(), temp);
412 remove_loaded_file_ = true;
414 // Remove the temp file, we only want the name...
415 unlink(to_file_base);
417 // Connect a signal to this->imageConverted and pass this signal to
418 // the graphics converter so that we can load the modified file
419 // on completion of the conversion process.
420 converter_.reset(new Converter(filename, to_file_base, from, to));
421 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
422 converter_->startConversion();
425 } // namespace graphics