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"
29 #include "support/unique_ptr.h"
31 #include "support/bind.h"
32 #include "support/TempFile.h"
35 using namespace lyx::support;
41 class CacheItem::Impl : public boost::signals2::trackable {
45 Impl(FileName const & file);
48 * If no file conversion is needed, then tryDisplayFormat() calls
49 * loadImage() directly.
50 * \return true if a conversion is necessary and no error occurred.
52 bool tryDisplayFormat(FileName & filename, string & from);
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 * convertToDisplayFormat() will set the loading status flag as
62 * approriate through calls to setStatus().
64 void convertToDisplayFormat();
66 /** Load the image into memory. This is called either from
67 * convertToDisplayFormat() direct or from imageConverted().
71 /** Get a notification when the image conversion is done.
72 * Connected to a signal on_finish_ which is passed to
75 void imageConverted(bool);
77 /** Sets the status of the loading process. Also notifies
78 * listeners that the status has changed.
80 void setStatus(ImageStatus new_status);
82 /** Can be invoked directly by the user, but is also connected to the
83 * FileMonitor and so is invoked when the file is changed
84 * (if monitoring is taking place).
88 /** If we are asked to load the file for a second or further time,
89 * (because the file has changed), then we'll have to first reset
90 * many of the variables below.
94 /// The filename we refer too.
95 FileName const filename_;
97 FileMonitor const monitor_;
99 /// Is the file compressed?
101 /// If so, store the uncompressed file in this temporary file.
102 FileName unzipped_filename_;
103 /// The target format
105 /// What file are we trying to load?
106 FileName file_to_load_;
107 /** Should we delete the file after loading? True if the file is
108 * the result of a conversion process.
110 bool remove_loaded_file_;
112 /// The image and its loading status.
113 std::shared_ptr<Image> image_;
117 /// This signal is emitted when the image loading status changes.
118 boost::signals2::signal<void()> statusChanged;
120 /// The connection of the signal ConvProcess::finishedConversion,
121 boost::signals2::connection cc_;
124 unique_ptr<Converter> converter_;
128 CacheItem::CacheItem(FileName const & file)
129 : pimpl_(new Impl(file))
133 CacheItem::~CacheItem()
139 FileName const & CacheItem::filename() const
141 return pimpl_->filename_;
145 bool CacheItem::tryDisplayFormat() const
147 if (pimpl_->status_ != WaitingToLoad)
151 bool const conversion_needed = pimpl_->tryDisplayFormat(filename, from);
152 bool const success = status() == Loaded && !conversion_needed;
159 void CacheItem::startLoading() const
161 pimpl_->startLoading();
165 void CacheItem::startMonitoring() const
167 if (!pimpl_->monitor_.monitoring())
168 pimpl_->monitor_.start();
172 bool CacheItem::monitoring() const
174 return pimpl_->monitor_.monitoring();
178 unsigned long CacheItem::checksum() const
180 return pimpl_->monitor_.checksum();
184 Image const * CacheItem::image() const
186 return pimpl_->image_.get();
190 ImageStatus CacheItem::status() const
192 return pimpl_->status_;
196 boost::signals2::connection CacheItem::connect(slot_type const & slot) const
198 return pimpl_->statusChanged.connect(slot);
202 //------------------------------
203 // Implementation details follow
204 //------------------------------
207 CacheItem::Impl::Impl(FileName const & file)
209 monitor_(file, 2000),
211 remove_loaded_file_(false),
212 status_(WaitingToLoad)
214 monitor_.connect(bind(&Impl::startLoading, this));
218 void CacheItem::Impl::startLoading()
220 if (status_ != WaitingToLoad)
223 convertToDisplayFormat();
227 void CacheItem::Impl::reset()
230 if (!unzipped_filename_.empty())
231 unzipped_filename_.removeFile();
232 unzipped_filename_.erase();
234 if (remove_loaded_file_ && !file_to_load_.empty())
235 file_to_load_.removeFile();
236 remove_loaded_file_ = false;
237 file_to_load_.erase();
243 status_ = WaitingToLoad;
253 void CacheItem::Impl::setStatus(ImageStatus new_status)
255 if (status_ == new_status)
258 status_ = new_status;
263 void CacheItem::Impl::imageConverted(bool success)
265 string const text = success ? "succeeded" : "failed";
266 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
268 file_to_load_ = converter_ ? FileName(converter_->convertedFile())
273 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
276 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
277 setStatus(ErrorConverting);
280 unzipped_filename_.removeFile();
285 // Add the converted file to the file cache
286 ConverterCache::get().add(filename_, to_, file_to_load_);
288 setStatus(loadImage() ? Loaded : ErrorLoading);
292 // This function gets called from the callback after the image has been
293 // converted successfully.
294 bool CacheItem::Impl::loadImage()
296 LYXERR(Debug::GRAPHICS, "Loading image.");
298 image_.reset(newImage());
300 bool success = image_->load(file_to_load_);
301 string const text = success ? "succeeded" : "failed";
302 LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
304 // Clean up after loading.
306 unzipped_filename_.removeFile();
308 if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
309 file_to_load_.removeFile();
315 static string const findTargetFormat(string const & from)
317 typedef vector<string> FormatList;
318 FormatList const & formats = Cache::get().loadableFormats();
320 // There must be a format to load from.
321 LASSERT(!formats.empty(), return string());
323 // Use the standard converter if we don't know the format to load
326 return string("ppm");
328 // First ascertain if we can load directly with no conversion
329 FormatList::const_iterator it = formats.begin();
330 FormatList::const_iterator end = formats.end();
331 for (; it != end; ++it) {
336 // So, we have to convert to a loadable format. Can we?
337 it = formats.begin();
338 for (; it != end; ++it) {
339 if (lyx::graphics::Converter::isReachable(from, *it))
342 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
346 // Failed! so we have to try to convert it to PPM format
347 // with the standard converter
348 return string("ppm");
352 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
354 // First, check that the file exists!
356 if (!filename_.isReadableFile()) {
357 if (status_ != ErrorNoFile) {
358 status_ = ErrorNoFile;
359 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
364 zipped_ = formats.isZippedFile(filename_);
366 string tempname = unzippedFileName(filename_.toFilesystemEncoding());
367 string const ext = getExtension(tempname);
368 tempname = changeExtension(tempname, "") + "-XXXXXX";
370 tempname = addExtension(tempname, ext);
371 TempFile tempfile(tempname);
372 tempfile.setAutoRemove(false);
373 unzipped_filename_ = tempfile.name();
374 if (unzipped_filename_.empty()) {
375 status_ = ErrorConverting;
376 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
379 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
381 filename = filename_;
384 docstring const displayed_filename = makeDisplayPath(filename_.absFileName());
385 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
386 << "\tAttempting to convert image file: " << filename
387 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
389 from = formats.getFormatFromFile(filename);
391 status_ = ErrorConverting;
392 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
394 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
395 to_ = findTargetFormat(from);
398 // No conversion needed!
399 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
400 file_to_load_ = filename;
401 status_ = loadImage() ? Loaded : ErrorLoading;
405 if (ConverterCache::get().inCache(filename, to_)) {
406 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
407 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
408 status_ = loadImage() ? Loaded : ErrorLoading;
415 void CacheItem::Impl::convertToDisplayFormat()
417 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
419 // Make a local copy in case we unzip it
422 if (!tryDisplayFormat(filename, from)) {
423 // The image status has changed, tell it to the outside world.
428 // We will need a conversion, tell it to the outside world.
429 setStatus(Converting);
431 // Add some stuff to create a uniquely named temporary file.
432 // This file is deleted in loadImage after it is loaded into memory.
433 TempFile tempfile("CacheItem");
434 tempfile.setAutoRemove(false);
435 FileName const to_file_base = tempfile.name();
436 remove_loaded_file_ = true;
438 // Connect a signal to this->imageConverted and pass this signal to
439 // the graphics converter so that we can load the modified file
440 // on completion of the conversion process.
441 converter_ = make_unique<Converter>(filename, to_file_base.absFileName(),
443 converter_->connect(bind(&Impl::imageConverted, this, _1));
444 converter_->startConversion();
447 } // namespace graphics