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 // Use the standard converter if we don't know the format to load
340 if (!formats.empty())
341 return string("ppm");
343 // First ascertain if we can load directly with no conversion
344 FormatList::const_iterator it = formats.begin();
345 FormatList::const_iterator end = formats.end();
346 for (; it != end; ++it) {
351 // So, we have to convert to a loadable format. Can we?
352 it = formats.begin();
353 for (; it != end; ++it) {
354 if (lyx::graphics::Converter::isReachable(from, *it))
357 lyxerr[Debug::GRAPHICS]
358 << "Unable to convert from " << from
359 << " to " << *it << std::endl;
362 // Failed! so we have to try to convert it to PPM format
363 // with the standard converter
364 return string("ppm");
373 void CacheItem::Impl::convertToDisplayFormat()
375 setStatus(Converting);
377 // First, check that the file exists!
378 if (!IsFileReadable(filename_)) {
379 if (status_ != ErrorNoFile) {
380 setStatus(ErrorNoFile);
381 lyxerr[Debug::GRAPHICS]
382 << "\tThe file is not readable" << endl;
387 // Make a local copy in case we unzip it
389 zipped_ = zippedFile(filename_);
391 unzipped_filename_ = tempName(string(), filename_);
392 if (unzipped_filename_.empty()) {
393 setStatus(ErrorConverting);
394 lyxerr[Debug::GRAPHICS]
395 << "\tCould not create temporary file." << endl;
398 filename = unzipFile(filename_, unzipped_filename_);
400 filename = filename_;
402 string const displayed_filename = MakeDisplayPath(filename_);
403 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
404 << "\tAttempting to convert image file: " << filename
405 << "\n\twith displayed filename: " << displayed_filename
408 string const from = formats.getFormatFromFile(filename);
410 setStatus(ErrorConverting);
411 lyxerr[Debug::GRAPHICS]
412 << "\tCould not determine file format." << endl;
414 lyxerr[Debug::GRAPHICS]
415 << "\n\tThe file contains " << from << " format data." << endl;
416 string const to = findTargetFormat(from);
419 // No conversion needed!
420 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
421 file_to_load_ = filename;
426 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
427 // Take only the filename part of the file, without path or extension.
428 string const temp = ChangeExtension(OnlyFilename(filename), string());
430 // Add some stuff to create a uniquely named temporary file.
431 // This file is deleted in loadImage after it is loaded into memory.
432 string const to_file_base = tempName(string(), temp);
433 remove_loaded_file_ = true;
435 // Remove the temp file, we only want the name...
436 // FIXME: This is unsafe!
437 unlink(to_file_base);
439 // Connect a signal to this->imageConverted and pass this signal to
440 // the graphics converter so that we can load the modified file
441 // on completion of the conversion process.
442 converter_.reset(new Converter(filename, to_file_base, from, to));
443 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
444 converter_->startConversion();
447 } // namespace graphics