2 * \file GraphicsCacheItem.cpp
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"
20 #include "support/debug.h"
23 #include "support/filetools.h"
24 #include "support/FileMonitor.h"
25 #include "support/lyxlib.h"
27 #include <boost/bind.hpp>
33 using support::FileMonitor;
34 using support::FileName;
35 using support::makeDisplayPath;
36 using support::onlyFilename;
37 using support::tempName;
38 using support::unzipFile;
43 class CacheItem::Impl : public boost::signals::trackable {
47 Impl(FileName const & file);
49 /** Start the image conversion process, checking first that it is
50 * necessary. If it is necessary, then a conversion task is started.
51 * CacheItem asumes that the conversion is asynchronous and so
52 * passes a Signal to the converting routine. When the conversion
53 * is finished, this Signal is emitted, returning the converted
54 * file to this->imageConverted.
56 * If no file conversion is needed, then convertToDisplayFormat() calls
57 * loadImage() directly.
59 * convertToDisplayFormat() will set the loading status flag as
60 * approriate through calls to setStatus().
62 void convertToDisplayFormat();
64 /** Load the image into memory. This is called either from
65 * convertToDisplayFormat() direct or from imageConverted().
69 /** Get a notification when the image conversion is done.
70 * Connected to a signal on_finish_ which is passed to
73 void imageConverted(bool);
75 /** Get a notification when the image loading is done.
76 * Connected to a signal on_finish_ which is passed to
77 * lyx::graphics::Image::loadImage.
79 void imageLoaded(bool);
81 /** Sets the status of the loading process. Also notifies
82 * listeners that the status has changed.
84 void setStatus(ImageStatus new_status);
86 /** Can be invoked directly by the user, but is also connected to the
87 * FileMonitor and so is invoked when the file is changed
88 * (if monitoring is taking place).
92 /** If we are asked to load the file for a second or further time,
93 * (because the file has changed), then we'll have to first reset
94 * many of the variables below.
98 /// The filename we refer too.
99 FileName const filename_;
101 FileMonitor const monitor_;
103 /// Is the file compressed?
105 /// If so, store the uncompressed file in this temporary file.
106 FileName unzipped_filename_;
107 /// The target format
109 /// What file are we trying to load?
110 FileName file_to_load_;
111 /** Should we delete the file after loading? True if the file is
112 * the result of a conversion process.
114 bool remove_loaded_file_;
116 /// The image and its loading status.
117 boost::shared_ptr<Image> image_;
121 /// This signal is emitted when the image loading status changes.
122 boost::signal<void()> statusChanged;
124 /// The connection to the signal Image::finishedLoading
125 boost::signals::connection cl_;
127 /// The connection of the signal ConvProcess::finishedConversion,
128 boost::signals::connection cc_;
131 boost::scoped_ptr<Converter> converter_;
135 CacheItem::CacheItem(FileName const & file)
136 : pimpl_(new Impl(file))
140 CacheItem::~CacheItem()
146 FileName 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(FileName 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 unzipped_filename_.removeFile();
225 unzipped_filename_.erase();
227 if (remove_loaded_file_ && !file_to_load_.empty())
228 file_to_load_.removeFile();
229 remove_loaded_file_ = false;
230 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 << '.');
264 file_to_load_ = converter_.get() ?
265 FileName(converter_->convertedFile()) : FileName();
269 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
272 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
273 setStatus(ErrorConverting);
276 unzipped_filename_.removeFile();
281 // Add the converted file to the file cache
282 ConverterCache::get().add(filename_, to_, file_to_load_);
288 // This function gets called from the callback after the image has been
289 // converted successfully.
290 void CacheItem::Impl::loadImage()
293 LYXERR(Debug::GRAPHICS, "Loading image.");
295 image_.reset(Image::newImage());
298 cl_ = image_->finishedLoading.connect(
299 boost::bind(&Impl::imageLoaded, this, _1));
300 image_->load(file_to_load_);
304 void CacheItem::Impl::imageLoaded(bool success)
306 string const text = success ? "succeeded" : "failed";
307 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
309 // Clean up after loading.
311 unzipped_filename_.removeFile();
313 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
314 file_to_load_.removeFile();
319 setStatus(ErrorLoading);
323 // Inform the outside world.
328 static string const findTargetFormat(string const & from)
330 typedef lyx::graphics::Image::FormatList FormatList;
331 FormatList const formats = lyx::graphics::Image::loadableFormats();
333 // There must be a format to load from.
334 BOOST_ASSERT(!formats.empty());
336 // Use the standard converter if we don't know the format to load
339 return string("ppm");
341 // First ascertain if we can load directly with no conversion
342 FormatList::const_iterator it = formats.begin();
343 FormatList::const_iterator end = formats.end();
344 for (; it != end; ++it) {
349 // So, we have to convert to a loadable format. Can we?
350 it = formats.begin();
351 for (; it != end; ++it) {
352 if (lyx::graphics::Converter::isReachable(from, *it))
355 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
359 // Failed! so we have to try to convert it to PPM format
360 // with the standard converter
361 return string("ppm");
365 void CacheItem::Impl::convertToDisplayFormat()
367 setStatus(Converting);
369 // First, check that the file exists!
370 if (!filename_.isReadableFile()) {
371 if (status_ != ErrorNoFile) {
372 setStatus(ErrorNoFile);
373 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
378 // Make a local copy in case we unzip it
380 zipped_ = filename_.isZippedFile();
382 unzipped_filename_ = tempName(FileName(), filename_.toFilesystemEncoding());
383 if (unzipped_filename_.empty()) {
384 setStatus(ErrorConverting);
385 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
388 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
390 filename = filename_;
393 docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
394 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
395 << "\tAttempting to convert image file: " << filename
396 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
398 string const from = formats.getFormatFromFile(filename);
400 setStatus(ErrorConverting);
401 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
403 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
404 to_ = findTargetFormat(from);
407 // No conversion needed!
408 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
409 file_to_load_ = filename;
414 if (ConverterCache::get().inCache(filename, to_)) {
415 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
416 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
421 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
423 // Add some stuff to create a uniquely named temporary file.
424 // This file is deleted in loadImage after it is loaded into memory.
425 FileName const to_file_base(tempName(FileName(), "CacheItem"));
426 remove_loaded_file_ = true;
428 // Remove the temp file, we only want the name...
429 // FIXME: This is unsafe!
430 to_file_base.removeFile();
432 // Connect a signal to this->imageConverted and pass this signal to
433 // the graphics converter so that we can load the modified file
434 // on completion of the conversion process.
435 converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
436 converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
437 converter_->startConversion();
440 } // namespace graphics