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::zippedFile;
48 class CacheItem::Impl : public boost::signals::trackable {
52 Impl(string const & file);
54 /** Start the image conversion process, checking first that it is
55 * necessary. If it is necessary, then a conversion task is started.
56 * CacheItem asumes that the conversion is asynchronous and so
57 * passes a Signal to the converting routine. When the conversion
58 * is finished, this Signal is emitted, returning the converted
59 * file to this->imageConverted.
61 * If no file conversion is needed, then convertToDisplayFormat() calls
62 * loadImage() directly.
64 * convertToDisplayFormat() will set the loading status flag as
65 * approriate through calls to setStatus().
67 void convertToDisplayFormat();
69 /** Load the image into memory. This is called either from
70 * convertToDisplayFormat() direct or from imageConverted().
74 /** Get a notification when the image conversion is done.
75 * Connected to a signal on_finish_ which is passed to
78 void imageConverted(bool);
80 /** Get a notification when the image loading is done.
81 * Connected to a signal on_finish_ which is passed to
82 * lyx::graphics::Image::loadImage.
84 void imageLoaded(bool);
86 /** Sets the status of the loading process. Also notifies
87 * listeners that the status has changed.
89 void setStatus(ImageStatus new_status);
91 /** Can be invoked directly by the user, but is also connected to the
92 * FileMonitor and so is invoked when the file is changed
93 * (if monitoring is taking place).
97 /** If we are asked to load the file for a second or further time,
98 * (because the file has changed), then we'll have to first reset
99 * many of the variables below.
103 /// The filename we refer too.
104 string const filename_;
106 FileMonitor const monitor_;
108 /// Is the file compressed?
110 /// If so, store the uncompressed file in this temporary file.
111 string unzipped_filename_;
112 /// What file are we trying to load?
113 string file_to_load_;
114 /** Should we delete the file after loading? True if the file is
115 * the result of a conversion process.
117 bool remove_loaded_file_;
119 /// The image and its loading status.
120 boost::shared_ptr<Image> image_;
124 /// This signal is emitted when the image loading status changes.
125 boost::signal<void()> statusChanged;
127 /// The connection to the signal Image::finishedLoading
128 boost::signals::connection cl_;
130 /// The connection of the signal ConvProcess::finishedConversion,
131 boost::signals::connection cc_;
134 boost::scoped_ptr<Converter> converter_;
138 CacheItem::CacheItem(string const & file)
139 : pimpl_(new Impl(file))
143 CacheItem::~CacheItem()
147 string const & CacheItem::filename() const
149 return pimpl_->filename_;
153 void CacheItem::startLoading() const
155 pimpl_->startLoading();
159 void CacheItem::startMonitoring() const
161 if (!pimpl_->monitor_.monitoring())
162 pimpl_->monitor_.start();
166 bool CacheItem::monitoring() const
168 return pimpl_->monitor_.monitoring();
172 unsigned long CacheItem::checksum() const
174 return pimpl_->monitor_.checksum();
178 Image const * CacheItem::image() const
180 return pimpl_->image_.get();
184 ImageStatus CacheItem::status() const
186 return pimpl_->status_;
190 boost::signals::connection CacheItem::connect(slot_type const & slot) const
192 return pimpl_->statusChanged.connect(slot);
196 //------------------------------
197 // Implementation details follow
198 //------------------------------
201 CacheItem::Impl::Impl(string const & file)
203 monitor_(file, 2000),
205 remove_loaded_file_(false),
206 status_(WaitingToLoad)
208 monitor_.connect(boost::bind(&Impl::startLoading, this));
212 void CacheItem::Impl::startLoading()
214 if (status_ != WaitingToLoad)
217 convertToDisplayFormat();
221 void CacheItem::Impl::reset()
224 if (!unzipped_filename_.empty())
225 unlink(unzipped_filename_);
226 unzipped_filename_.erase();
228 if (remove_loaded_file_ && !file_to_load_.empty())
229 unlink(file_to_load_);
230 remove_loaded_file_ = false;
231 file_to_load_.erase();
236 status_ = WaitingToLoad;
244 if (converter_.get())
249 void CacheItem::Impl::setStatus(ImageStatus new_status)
251 if (status_ == new_status)
254 status_ = new_status;
259 void CacheItem::Impl::imageConverted(bool success)
261 string const text = success ? "succeeded" : "failed";
262 lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
264 file_to_load_ = converter_.get() ?
265 converter_->convertedFile() : string();
269 success = !file_to_load_.empty() && isFileReadable(file_to_load_);
272 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
274 setStatus(ErrorConverting);
277 unlink(unzipped_filename_);
286 // This function gets called from the callback after the image has been
287 // converted successfully.
288 void CacheItem::Impl::loadImage()
291 lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
293 image_ = Image::newImage();
296 cl_ = image_->finishedLoading.connect(
297 boost::bind(&Impl::imageLoaded, this, _1));
298 image_->load(file_to_load_);
302 void CacheItem::Impl::imageLoaded(bool success)
304 string const text = success ? "succeeded" : "failed";
305 lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
307 // Clean up after loading.
309 unlink(unzipped_filename_);
311 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
312 unlink(file_to_load_);
317 setStatus(ErrorLoading);
321 // Inform the outside world.
326 } // namespace graphics
332 string const findTargetFormat(string const & from)
334 typedef lyx::graphics::Image::FormatList FormatList;
335 FormatList const formats = lyx::graphics::Image::loadableFormats();
337 // There must be a format to load from.
338 BOOST_ASSERT(!formats.empty());
340 // Use the standard converter if we don't know the format to load
343 return string("ppm");
345 // First ascertain if we can load directly with no conversion
346 FormatList::const_iterator it = formats.begin();
347 FormatList::const_iterator end = formats.end();
348 for (; it != end; ++it) {
353 // So, we have to convert to a loadable format. Can we?
354 it = formats.begin();
355 for (; it != end; ++it) {
356 if (lyx::graphics::Converter::isReachable(from, *it))
359 lyxerr[Debug::GRAPHICS]
360 << "Unable to convert from " << from
361 << " to " << *it << std::endl;
364 // Failed! so we have to try to convert it to PPM format
365 // with the standard converter
366 return string("ppm");
375 void CacheItem::Impl::convertToDisplayFormat()
377 setStatus(Converting);
379 // First, check that the file exists!
380 if (!isFileReadable(filename_)) {
381 if (status_ != ErrorNoFile) {
382 setStatus(ErrorNoFile);
383 lyxerr[Debug::GRAPHICS]
384 << "\tThe file is not readable" << endl;
389 // Make a local copy in case we unzip it
391 zipped_ = zippedFile(filename_);
393 unzipped_filename_ = tempName(string(), filename_);
394 if (unzipped_filename_.empty()) {
395 setStatus(ErrorConverting);
396 lyxerr[Debug::GRAPHICS]
397 << "\tCould not create temporary file." << endl;
400 filename = unzipFile(filename_, unzipped_filename_);
402 filename = filename_;
404 docstring const displayed_filename = makeDisplayPath(filename_);
405 lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
406 << "\tAttempting to convert image file: " << filename
407 << "\n\twith displayed filename: " << lyx::to_utf8(displayed_filename)
410 string const from = formats.getFormatFromFile(filename);
412 setStatus(ErrorConverting);
413 lyxerr[Debug::GRAPHICS]
414 << "\tCould not determine file format." << endl;
416 lyxerr[Debug::GRAPHICS]
417 << "\n\tThe file contains " << from << " format data." << endl;
418 string const to = findTargetFormat(from);
421 // No conversion needed!
422 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
423 file_to_load_ = filename;
428 lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
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(), "CacheItem");
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