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"
17 #include "GraphicsCache.h"
18 #include "GraphicsConverter.h"
19 #include "GraphicsImage.h"
21 #include "ConverterCache.h"
24 #include "support/debug.h"
25 #include "support/FileName.h"
26 #include "support/filetools.h"
27 #include "support/FileMonitor.h"
28 #include "support/lassert.h"
30 #include "support/bind.h"
33 using namespace lyx::support;
39 class CacheItem::Impl : public boost::signals::trackable {
43 Impl(FileName const & file);
46 * If no file conversion is needed, then tryDisplayFormat() calls
47 * loadImage() directly.
48 * \return true if a conversion is necessary and no error occurred.
50 bool tryDisplayFormat(FileName & filename, string & from);
52 /** Start the image conversion process, checking first that it is
53 * necessary. If it is necessary, then a conversion task is started.
54 * CacheItem asumes that the conversion is asynchronous and so
55 * passes a Signal to the converting routine. When the conversion
56 * is finished, this Signal is emitted, returning the converted
57 * file to this->imageConverted.
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 /** Sets the status of the loading process. Also notifies
76 * listeners that the status has changed.
78 void setStatus(ImageStatus new_status);
80 /** Can be invoked directly by the user, but is also connected to the
81 * FileMonitor and so is invoked when the file is changed
82 * (if monitoring is taking place).
86 /** If we are asked to load the file for a second or further time,
87 * (because the file has changed), then we'll have to first reset
88 * many of the variables below.
92 /// The filename we refer too.
93 FileName const filename_;
95 FileMonitor const monitor_;
97 /// Is the file compressed?
99 /// If so, store the uncompressed file in this temporary file.
100 FileName unzipped_filename_;
101 /// The target format
103 /// What file are we trying to load?
104 FileName file_to_load_;
105 /** Should we delete the file after loading? True if the file is
106 * the result of a conversion process.
108 bool remove_loaded_file_;
110 /// The image and its loading status.
111 shared_ptr<Image> image_;
115 /// This signal is emitted when the image loading status changes.
116 boost::signal<void()> statusChanged;
118 /// The connection of the signal ConvProcess::finishedConversion,
119 boost::signals::connection cc_;
122 boost::scoped_ptr<Converter> converter_;
126 CacheItem::CacheItem(FileName const & file)
127 : pimpl_(new Impl(file))
131 CacheItem::~CacheItem()
137 FileName const & CacheItem::filename() const
139 return pimpl_->filename_;
143 bool CacheItem::tryDisplayFormat() const
145 if (pimpl_->status_ != WaitingToLoad)
149 bool const conversion_needed = pimpl_->tryDisplayFormat(filename, from);
150 bool const success = status() == Loaded && !conversion_needed;
157 void CacheItem::startLoading() const
159 pimpl_->startLoading();
163 void CacheItem::startMonitoring() const
165 if (!pimpl_->monitor_.monitoring())
166 pimpl_->monitor_.start();
170 bool CacheItem::monitoring() const
172 return pimpl_->monitor_.monitoring();
176 unsigned long CacheItem::checksum() const
178 return pimpl_->monitor_.checksum();
182 Image const * CacheItem::image() const
184 return pimpl_->image_.get();
188 ImageStatus CacheItem::status() const
190 return pimpl_->status_;
194 boost::signals::connection CacheItem::connect(slot_type const & slot) const
196 return pimpl_->statusChanged.connect(slot);
200 //------------------------------
201 // Implementation details follow
202 //------------------------------
205 CacheItem::Impl::Impl(FileName const & file)
207 monitor_(file, 2000),
209 remove_loaded_file_(false),
210 status_(WaitingToLoad)
212 monitor_.connect(bind(&Impl::startLoading, this));
216 void CacheItem::Impl::startLoading()
218 if (status_ != WaitingToLoad)
221 convertToDisplayFormat();
225 void CacheItem::Impl::reset()
228 if (!unzipped_filename_.empty())
229 unzipped_filename_.removeFile();
230 unzipped_filename_.erase();
232 if (remove_loaded_file_ && !file_to_load_.empty())
233 file_to_load_.removeFile();
234 remove_loaded_file_ = false;
235 file_to_load_.erase();
241 status_ = WaitingToLoad;
246 if (converter_.get())
251 void CacheItem::Impl::setStatus(ImageStatus new_status)
253 if (status_ == new_status)
256 status_ = new_status;
261 void CacheItem::Impl::imageConverted(bool success)
263 string const text = success ? "succeeded" : "failed";
264 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
266 file_to_load_ = converter_.get() ?
267 FileName(converter_->convertedFile()) : FileName();
271 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
274 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
275 setStatus(ErrorConverting);
278 unzipped_filename_.removeFile();
283 // Add the converted file to the file cache
284 ConverterCache::get().add(filename_, to_, file_to_load_);
286 setStatus(loadImage() ? Loaded : ErrorLoading);
290 // This function gets called from the callback after the image has been
291 // converted successfully.
292 bool CacheItem::Impl::loadImage()
294 LYXERR(Debug::GRAPHICS, "Loading image.");
296 image_.reset(newImage());
298 bool success = image_->load(file_to_load_);
299 string const text = success ? "succeeded" : "failed";
300 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
302 // Clean up after loading.
304 unzipped_filename_.removeFile();
306 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
307 file_to_load_.removeFile();
313 static string const findTargetFormat(string const & from)
315 typedef vector<string> FormatList;
316 FormatList const & formats = Cache::get().loadableFormats();
318 // There must be a format to load from.
319 LASSERT(!formats.empty(), /**/);
321 // Use the standard converter if we don't know the format to load
324 return string("ppm");
326 // First ascertain if we can load directly with no conversion
327 FormatList::const_iterator it = formats.begin();
328 FormatList::const_iterator end = formats.end();
329 for (; it != end; ++it) {
334 // So, we have to convert to a loadable format. Can we?
335 it = formats.begin();
336 for (; it != end; ++it) {
337 if (lyx::graphics::Converter::isReachable(from, *it))
340 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
344 // Failed! so we have to try to convert it to PPM format
345 // with the standard converter
346 return string("ppm");
350 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
352 // First, check that the file exists!
354 if (!filename_.isReadableFile()) {
355 if (status_ != ErrorNoFile) {
356 status_ = ErrorNoFile;
357 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
362 zipped_ = formats.isZippedFile(filename_);
364 unzipped_filename_ = FileName::tempName(
365 filename_.toFilesystemEncoding());
366 if (unzipped_filename_.empty()) {
367 status_ = ErrorConverting;
368 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
371 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
373 filename = filename_;
376 docstring const displayed_filename = makeDisplayPath(filename_.absFileName());
377 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
378 << "\tAttempting to convert image file: " << filename
379 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
381 from = formats.getFormatFromFile(filename);
383 status_ = ErrorConverting;
384 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
386 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
387 to_ = findTargetFormat(from);
390 // No conversion needed!
391 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
392 file_to_load_ = filename;
393 status_ = loadImage() ? Loaded : ErrorLoading;
397 if (ConverterCache::get().inCache(filename, to_)) {
398 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
399 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
400 status_ = loadImage() ? Loaded : ErrorLoading;
407 void CacheItem::Impl::convertToDisplayFormat()
409 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
411 // Make a local copy in case we unzip it
414 if (!tryDisplayFormat(filename, from)) {
415 // The image status has changed, tell it to the outside world.
420 // We will need a conversion, tell it to the outside world.
421 setStatus(Converting);
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 = FileName::tempName("CacheItem");
426 remove_loaded_file_ = true;
428 // Connect a signal to this->imageConverted and pass this signal to
429 // the graphics converter so that we can load the modified file
430 // on completion of the conversion process.
431 converter_.reset(new Converter(filename, to_file_base.absFileName(), from, to_));
432 converter_->connect(bind(&Impl::imageConverted, this, _1));
433 converter_->startConversion();
436 } // namespace graphics