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>
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::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 /// 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::signal<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 static string const findTargetFormat(string const & from)
327 typedef lyx::graphics::Image::FormatList FormatList;
328 FormatList const formats = lyx::graphics::Image::loadableFormats();
330 // There must be a format to load from.
331 BOOST_ASSERT(!formats.empty());
333 // Use the standard converter if we don't know the format to load
336 return string("ppm");
338 // First ascertain if we can load directly with no conversion
339 FormatList::const_iterator it = formats.begin();
340 FormatList::const_iterator end = formats.end();
341 for (; it != end; ++it) {
346 // So, we have to convert to a loadable format. Can we?
347 it = formats.begin();
348 for (; it != end; ++it) {
349 if (lyx::graphics::Converter::isReachable(from, *it))
352 lyxerr[Debug::GRAPHICS]
353 << "Unable to convert from " << from
354 << " to " << *it << std::endl;
357 // Failed! so we have to try to convert it to PPM format
358 // with the standard converter
359 return string("ppm");
363 void CacheItem::Impl::convertToDisplayFormat()
365 setStatus(Converting);
367 // First, check that the file exists!
368 if (!isFileReadable(filename_)) {
369 if (status_ != ErrorNoFile) {
370 setStatus(ErrorNoFile);
371 lyxerr[Debug::GRAPHICS]
372 << "\tThe file is not readable" << endl;
377 // Make a local copy in case we unzip it
379 zipped_ = zippedFile(filename_);
381 unzipped_filename_ = tempName(string(), filename_);
382 if (unzipped_filename_.empty()) {
383 setStatus(ErrorConverting);
384 lyxerr[Debug::GRAPHICS]
385 << "\tCould not create temporary file." << endl;
388 filename = unzipFile(filename_, unzipped_filename_);
390 filename = filename_;
392 docstring const displayed_filename = makeDisplayPath(filename_);
393 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
394 << "\tAttempting to convert image file: " << filename
395 << "\n\twith displayed filename: " << lyx::to_utf8(displayed_filename)
398 string const from = formats.getFormatFromFile(filename);
400 setStatus(ErrorConverting);
401 lyxerr[Debug::GRAPHICS]
402 << "\tCould not determine file format." << endl;
404 lyxerr[Debug::GRAPHICS]
405 << "\n\tThe file contains " << from << " format data." << endl;
406 string const to = findTargetFormat(from);
409 // No conversion needed!
410 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
411 file_to_load_ = filename;
416 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
418 // Add some stuff to create a uniquely named temporary file.
419 // This file is deleted in loadImage after it is loaded into memory.
420 string const to_file_base = tempName(string(), "CacheItem");
421 remove_loaded_file_ = true;
423 // Remove the temp file, we only want the name...
424 // FIXME: This is unsafe!
425 unlink(to_file_base);
427 // Connect a signal to this->imageConverted and pass this signal to
428 // the graphics converter so that we can load the modified file
429 // on completion of the conversion process.
430 converter_.reset(new Converter(filename, to_file_base, from, to));
431 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
432 converter_->startConversion();
435 } // namespace graphics