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"
31 #include "support/TempFile.h"
34 using namespace lyx::support;
40 class CacheItem::Impl : public boost::signals::trackable {
44 Impl(FileName const & file);
47 * If no file conversion is needed, then tryDisplayFormat() calls
48 * loadImage() directly.
49 * \return true if a conversion is necessary and no error occurred.
51 bool tryDisplayFormat(FileName & filename, string & from);
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 * convertToDisplayFormat() will set the loading status flag as
61 * approriate through calls to setStatus().
63 void convertToDisplayFormat();
65 /** Load the image into memory. This is called either from
66 * convertToDisplayFormat() direct or from imageConverted().
70 /** Get a notification when the image conversion is done.
71 * Connected to a signal on_finish_ which is passed to
74 void imageConverted(bool);
76 /** Sets the status of the loading process. Also notifies
77 * listeners that the status has changed.
79 void setStatus(ImageStatus new_status);
81 /** Can be invoked directly by the user, but is also connected to the
82 * FileMonitor and so is invoked when the file is changed
83 * (if monitoring is taking place).
87 /** If we are asked to load the file for a second or further time,
88 * (because the file has changed), then we'll have to first reset
89 * many of the variables below.
93 /// The filename we refer too.
94 FileName const filename_;
96 FileMonitor const monitor_;
98 /// Is the file compressed?
100 /// If so, store the uncompressed file in this temporary file.
101 FileName unzipped_filename_;
102 /// The target format
104 /// What file are we trying to load?
105 FileName file_to_load_;
106 /** Should we delete the file after loading? True if the file is
107 * the result of a conversion process.
109 bool remove_loaded_file_;
111 /// The image and its loading status.
112 shared_ptr<Image> image_;
116 /// This signal is emitted when the image loading status changes.
117 boost::signal<void()> statusChanged;
119 /// The connection of the signal ConvProcess::finishedConversion,
120 boost::signals::connection cc_;
123 boost::scoped_ptr<Converter> converter_;
127 CacheItem::CacheItem(FileName const & file)
128 : pimpl_(new Impl(file))
132 CacheItem::~CacheItem()
138 FileName const & CacheItem::filename() const
140 return pimpl_->filename_;
144 bool CacheItem::tryDisplayFormat() const
146 if (pimpl_->status_ != WaitingToLoad)
150 bool const conversion_needed = pimpl_->tryDisplayFormat(filename, from);
151 bool const success = status() == Loaded && !conversion_needed;
158 void CacheItem::startLoading() const
160 pimpl_->startLoading();
164 void CacheItem::startMonitoring() const
166 if (!pimpl_->monitor_.monitoring())
167 pimpl_->monitor_.start();
171 bool CacheItem::monitoring() const
173 return pimpl_->monitor_.monitoring();
177 unsigned long CacheItem::checksum() const
179 return pimpl_->monitor_.checksum();
183 Image const * CacheItem::image() const
185 return pimpl_->image_.get();
189 ImageStatus CacheItem::status() const
191 return pimpl_->status_;
195 boost::signals::connection CacheItem::connect(slot_type const & slot) const
197 return pimpl_->statusChanged.connect(slot);
201 //------------------------------
202 // Implementation details follow
203 //------------------------------
206 CacheItem::Impl::Impl(FileName const & file)
208 monitor_(file, 2000),
210 remove_loaded_file_(false),
211 status_(WaitingToLoad)
213 monitor_.connect(bind(&Impl::startLoading, this));
217 void CacheItem::Impl::startLoading()
219 if (status_ != WaitingToLoad)
222 convertToDisplayFormat();
226 void CacheItem::Impl::reset()
229 if (!unzipped_filename_.empty())
230 unzipped_filename_.removeFile();
231 unzipped_filename_.erase();
233 if (remove_loaded_file_ && !file_to_load_.empty())
234 file_to_load_.removeFile();
235 remove_loaded_file_ = false;
236 file_to_load_.erase();
242 status_ = WaitingToLoad;
247 if (converter_.get())
252 void CacheItem::Impl::setStatus(ImageStatus new_status)
254 if (status_ == new_status)
257 status_ = new_status;
262 void CacheItem::Impl::imageConverted(bool success)
264 string const text = success ? "succeeded" : "failed";
265 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
267 file_to_load_ = converter_.get() ?
268 FileName(converter_->convertedFile()) : FileName();
272 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
275 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
276 setStatus(ErrorConverting);
279 unzipped_filename_.removeFile();
284 // Add the converted file to the file cache
285 ConverterCache::get().add(filename_, to_, file_to_load_);
287 setStatus(loadImage() ? Loaded : ErrorLoading);
291 // This function gets called from the callback after the image has been
292 // converted successfully.
293 bool CacheItem::Impl::loadImage()
295 LYXERR(Debug::GRAPHICS, "Loading image.");
297 image_.reset(newImage());
299 bool success = image_->load(file_to_load_);
300 string const text = success ? "succeeded" : "failed";
301 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
303 // Clean up after loading.
305 unzipped_filename_.removeFile();
307 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
308 file_to_load_.removeFile();
314 static string const findTargetFormat(string const & from)
316 typedef vector<string> FormatList;
317 FormatList const & formats = Cache::get().loadableFormats();
319 // There must be a format to load from.
320 LASSERT(!formats.empty(), return string());
322 // Use the standard converter if we don't know the format to load
325 return string("ppm");
327 // First ascertain if we can load directly with no conversion
328 FormatList::const_iterator it = formats.begin();
329 FormatList::const_iterator end = formats.end();
330 for (; it != end; ++it) {
335 // So, we have to convert to a loadable format. Can we?
336 it = formats.begin();
337 for (; it != end; ++it) {
338 if (lyx::graphics::Converter::isReachable(from, *it))
341 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
345 // Failed! so we have to try to convert it to PPM format
346 // with the standard converter
347 return string("ppm");
351 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
353 // First, check that the file exists!
355 if (!filename_.isReadableFile()) {
356 if (status_ != ErrorNoFile) {
357 status_ = ErrorNoFile;
358 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
363 zipped_ = formats.isZippedFile(filename_);
365 TempFile tempfile(filename_.toFilesystemEncoding());
366 tempfile.setAutoRemove(false);
367 unzipped_filename_ = tempfile.name();
368 if (unzipped_filename_.empty()) {
369 status_ = ErrorConverting;
370 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
373 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
375 filename = filename_;
378 docstring const displayed_filename = makeDisplayPath(filename_.absFileName());
379 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
380 << "\tAttempting to convert image file: " << filename
381 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
383 from = formats.getFormatFromFile(filename);
385 status_ = ErrorConverting;
386 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
388 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
389 to_ = findTargetFormat(from);
392 // No conversion needed!
393 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
394 file_to_load_ = filename;
395 status_ = loadImage() ? Loaded : ErrorLoading;
399 if (ConverterCache::get().inCache(filename, to_)) {
400 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
401 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
402 status_ = loadImage() ? Loaded : ErrorLoading;
409 void CacheItem::Impl::convertToDisplayFormat()
411 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
413 // Make a local copy in case we unzip it
416 if (!tryDisplayFormat(filename, from)) {
417 // The image status has changed, tell it to the outside world.
422 // We will need a conversion, tell it to the outside world.
423 setStatus(Converting);
425 // Add some stuff to create a uniquely named temporary file.
426 // This file is deleted in loadImage after it is loaded into memory.
427 TempFile tempfile("CacheItem");
428 tempfile.setAutoRemove(false);
429 FileName const to_file_base = tempfile.name();
430 remove_loaded_file_ = true;
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(bind(&Impl::imageConverted, this, _1));
437 converter_->startConversion();
440 } // namespace graphics