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/filename.h"
24 #include "support/filetools.h"
25 #include "support/FileMonitor.h"
26 #include "support/lyxlib.h"
28 #include <boost/bind.hpp>
33 using support::FileMonitor;
34 using support::FileName;
35 using support::isFileReadable;
36 using support::makeDisplayPath;
37 using support::onlyFilename;
38 using support::tempName;
39 using support::unlink;
40 using support::unzipFile;
41 using support::zippedFile;
49 class CacheItem::Impl : public boost::signals::trackable {
53 Impl(FileName 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 FileName const filename_;
107 FileMonitor const monitor_;
109 /// Is the file compressed?
111 /// If so, store the uncompressed file in this temporary file.
112 FileName unzipped_filename_;
113 /// The target format
115 /// What file are we trying to load?
116 FileName file_to_load_;
117 /** Should we delete the file after loading? True if the file is
118 * the result of a conversion process.
120 bool remove_loaded_file_;
122 /// The image and its loading status.
123 boost::shared_ptr<Image> image_;
127 /// This signal is emitted when the image loading status changes.
128 boost::signal<void()> statusChanged;
130 /// The connection to the signal Image::finishedLoading
131 boost::signals::connection cl_;
133 /// The connection of the signal ConvProcess::finishedConversion,
134 boost::signals::connection cc_;
137 boost::scoped_ptr<Converter> converter_;
141 CacheItem::CacheItem(FileName const & file)
142 : pimpl_(new Impl(file))
146 CacheItem::~CacheItem()
150 FileName const & CacheItem::filename() const
152 return pimpl_->filename_;
156 void CacheItem::startLoading() const
158 pimpl_->startLoading();
162 void CacheItem::startMonitoring() const
164 if (!pimpl_->monitor_.monitoring())
165 pimpl_->monitor_.start();
169 bool CacheItem::monitoring() const
171 return pimpl_->monitor_.monitoring();
175 unsigned long CacheItem::checksum() const
177 return pimpl_->monitor_.checksum();
181 Image const * CacheItem::image() const
183 return pimpl_->image_.get();
187 ImageStatus CacheItem::status() const
189 return pimpl_->status_;
193 boost::signals::connection CacheItem::connect(slot_type const & slot) const
195 return pimpl_->statusChanged.connect(slot);
199 //------------------------------
200 // Implementation details follow
201 //------------------------------
204 CacheItem::Impl::Impl(FileName const & file)
206 monitor_(file, 2000),
208 remove_loaded_file_(false),
209 status_(WaitingToLoad)
211 monitor_.connect(boost::bind(&Impl::startLoading, this));
215 void CacheItem::Impl::startLoading()
217 if (status_ != WaitingToLoad)
220 convertToDisplayFormat();
224 void CacheItem::Impl::reset()
227 if (!unzipped_filename_.empty())
228 unlink(unzipped_filename_);
229 unzipped_filename_.erase();
231 if (remove_loaded_file_ && !file_to_load_.empty())
232 unlink(file_to_load_);
233 remove_loaded_file_ = false;
234 file_to_load_.erase();
240 status_ = WaitingToLoad;
248 if (converter_.get())
253 void CacheItem::Impl::setStatus(ImageStatus new_status)
255 if (status_ == new_status)
258 status_ = new_status;
263 void CacheItem::Impl::imageConverted(bool success)
265 string const text = success ? "succeeded" : "failed";
266 lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
268 file_to_load_ = converter_.get() ?
269 FileName(converter_->convertedFile()) : FileName();
273 success = !file_to_load_.empty() && isFileReadable(file_to_load_);
276 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
278 setStatus(ErrorConverting);
281 unlink(unzipped_filename_);
286 // Add the converted file to the file cache
287 ConverterCache::get().add(filename_, to_, file_to_load_);
293 // This function gets called from the callback after the image has been
294 // converted successfully.
295 void CacheItem::Impl::loadImage()
298 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
300 image_ = Image::newImage();
303 cl_ = image_->finishedLoading.connect(
304 boost::bind(&Impl::imageLoaded, this, _1));
305 image_->load(file_to_load_);
309 void CacheItem::Impl::imageLoaded(bool success)
311 string const text = success ? "succeeded" : "failed";
312 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
314 // Clean up after loading.
316 unlink(unzipped_filename_);
318 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
319 unlink(file_to_load_);
324 setStatus(ErrorLoading);
328 // Inform the outside world.
333 static 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 // Use the standard converter if we don't know the format to load
344 return string("ppm");
346 // First ascertain if we can load directly with no conversion
347 FormatList::const_iterator it = formats.begin();
348 FormatList::const_iterator end = formats.end();
349 for (; it != end; ++it) {
354 // So, we have to convert to a loadable format. Can we?
355 it = formats.begin();
356 for (; it != end; ++it) {
357 if (lyx::graphics::Converter::isReachable(from, *it))
360 lyxerr[Debug::GRAPHICS]
361 << "Unable to convert from " << from
362 << " to " << *it << std::endl;
365 // Failed! so we have to try to convert it to PPM format
366 // with the standard converter
367 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 zipped_ = zippedFile(filename_);
389 unzipped_filename_ = FileName(tempName(string(), filename_.toFilesystemEncoding()));
390 if (unzipped_filename_.empty()) {
391 setStatus(ErrorConverting);
392 lyxerr[Debug::GRAPHICS]
393 << "\tCould not create temporary file." << endl;
396 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
398 filename = filename_;
400 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
401 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
402 << "\tAttempting to convert image file: " << filename
403 << "\n\twith displayed filename: " << lyx::to_utf8(displayed_filename)
406 string const from = formats.getFormatFromFile(filename);
408 setStatus(ErrorConverting);
409 lyxerr[Debug::GRAPHICS]
410 << "\tCould not determine file format." << endl;
412 lyxerr[Debug::GRAPHICS]
413 << "\n\tThe file contains " << from << " format data." << endl;
414 to_ = findTargetFormat(from);
417 // No conversion needed!
418 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
419 file_to_load_ = filename;
424 if (ConverterCache::get().inCache(filename, to_)) {
425 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (file in file cache)!"
427 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
432 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to_ << " format." << endl;
434 // Add some stuff to create a uniquely named temporary file.
435 // This file is deleted in loadImage after it is loaded into memory.
436 string const to_file_base = tempName(string(), "CacheItem");
437 remove_loaded_file_ = true;
439 // Remove the temp file, we only want the name...
440 // FIXME: This is unsafe!
441 unlink(FileName(to_file_base));
443 // Connect a signal to this->imageConverted and pass this signal to
444 // the graphics converter so that we can load the modified file
445 // on completion of the conversion process.
446 converter_.reset(new Converter(filename, to_file_base, from, to_));
447 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
448 converter_->startConversion();
451 } // namespace graphics