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"
19 #include "ConverterCache.h"
23 #include "support/filetools.h"
24 #include "support/FileMonitor.h"
25 #include "support/lyxlib.h"
27 #include <boost/bind.hpp>
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::zippedFile;
47 class 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 /// The target format
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();
238 status_ = WaitingToLoad;
246 if (converter_.get())
251 void CacheItem::Impl::setStatus(ImageStatus new_status)
253 if (status_ == new_status)
256 status_ = new_status;
261 void CacheItem::Impl::imageConverted(bool success)
263 string const text = success ? "succeeded" : "failed";
264 lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
266 file_to_load_ = converter_.get() ?
267 converter_->convertedFile() : string();
271 success = !file_to_load_.empty() && isFileReadable(file_to_load_);
274 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
276 setStatus(ErrorConverting);
279 unlink(unzipped_filename_);
284 // Add the converted file to the file cache
285 ConverterCache::get().add(filename_, to_, file_to_load_);
291 // This function gets called from the callback after the image has been
292 // converted successfully.
293 void CacheItem::Impl::loadImage()
296 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
298 image_ = Image::newImage();
301 cl_ = image_->finishedLoading.connect(
302 boost::bind(&Impl::imageLoaded, this, _1));
303 image_->load(file_to_load_);
307 void CacheItem::Impl::imageLoaded(bool success)
309 string const text = success ? "succeeded" : "failed";
310 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
312 // Clean up after loading.
314 unlink(unzipped_filename_);
316 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
317 unlink(file_to_load_);
322 setStatus(ErrorLoading);
326 // Inform the outside world.
331 static 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 // Use the standard converter if we don't know the format to load
342 return string("ppm");
344 // First ascertain if we can load directly with no conversion
345 FormatList::const_iterator it = formats.begin();
346 FormatList::const_iterator end = formats.end();
347 for (; it != end; ++it) {
352 // So, we have to convert to a loadable format. Can we?
353 it = formats.begin();
354 for (; it != end; ++it) {
355 if (lyx::graphics::Converter::isReachable(from, *it))
358 lyxerr[Debug::GRAPHICS]
359 << "Unable to convert from " << from
360 << " to " << *it << std::endl;
363 // Failed! so we have to try to convert it to PPM format
364 // with the standard converter
365 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
385 zipped_ = zippedFile(filename_);
387 unzipped_filename_ = tempName(string(), filename_);
388 if (unzipped_filename_.empty()) {
389 setStatus(ErrorConverting);
390 lyxerr[Debug::GRAPHICS]
391 << "\tCould not create temporary file." << endl;
394 filename = unzipFile(filename_, unzipped_filename_);
396 filename = filename_;
398 docstring const displayed_filename = makeDisplayPath(filename_);
399 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
400 << "\tAttempting to convert image file: " << filename
401 << "\n\twith displayed filename: " << lyx::to_utf8(displayed_filename)
404 string const from = formats.getFormatFromFile(filename);
406 setStatus(ErrorConverting);
407 lyxerr[Debug::GRAPHICS]
408 << "\tCould not determine file format." << endl;
410 lyxerr[Debug::GRAPHICS]
411 << "\n\tThe file contains " << from << " format data." << endl;
412 to_ = findTargetFormat(from);
415 // No conversion needed!
416 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
417 file_to_load_ = filename;
422 if (ConverterCache::get().inCache(filename, to_)) {
423 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (file in file cache)!"
425 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
430 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to_ << " format." << endl;
432 // Add some stuff to create a uniquely named temporary file.
433 // This file is deleted in loadImage after it is loaded into memory.
434 string const to_file_base = tempName(string(), "CacheItem");
435 remove_loaded_file_ = true;
437 // Remove the temp file, we only want the name...
438 // FIXME: This is unsafe!
439 unlink(to_file_base);
441 // Connect a signal to this->imageConverted and pass this signal to
442 // the graphics converter so that we can load the modified file
443 // on completion of the conversion process.
444 converter_.reset(new Converter(filename, to_file_base, from, to_));
445 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
446 converter_->startConversion();
449 } // namespace graphics