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"
18 #include "GraphicsCache.h"
19 #include "GraphicsConverter.h"
20 #include "GraphicsImage.h"
22 #include "ConverterCache.h"
25 #include "support/debug.h"
26 #include "support/FileName.h"
27 #include "support/filetools.h"
28 #include "support/FileMonitor.h"
29 #include "support/lassert.h"
30 #include "support/unique_ptr.h"
32 #include "support/TempFile.h"
35 using namespace lyx::support;
41 class CacheItem::Impl {
45 Impl(FileName const & file, FileName const & doc_file);
50 * If no file conversion is needed, then tryDisplayFormat() calls
51 * loadImage() directly.
52 * \return true if a conversion is necessary and no error occurred.
54 bool tryDisplayFormat(FileName & filename, string & from);
56 /** Start the image conversion process, checking first that it is
57 * necessary. If it is necessary, then a conversion task is started.
58 * CacheItem asumes that the conversion is asynchronous and so
59 * passes a Signal to the converting routine. When the conversion
60 * is finished, this Signal is emitted, returning the converted
61 * file to this->imageConverted.
63 * convertToDisplayFormat() will set the loading status flag as
64 * approriate through calls to setStatus().
66 void convertToDisplayFormat();
68 /** Load the image into memory. This is called either from
69 * convertToDisplayFormat() direct or from imageConverted().
73 /** Get a notification when the image conversion is done.
74 * Connected to a signal on_finish_ which is passed to
77 void imageConverted(bool);
79 /** Sets the status of the loading process. Also notifies
80 * listeners that the status has changed.
82 void setStatus(ImageStatus new_status);
84 /** Can be invoked directly by the user, but is also connected to the
85 * FileMonitor and so is invoked when the file is changed
86 * (if monitoring is taking place).
90 /** If we are asked to load the file for a second or further time,
91 * (because the file has changed), then we'll have to first reset
92 * many of the variables below.
96 /// The filename we refer too.
97 FileName const filename_;
98 /// The document filename this graphic item belongs to
99 FileName const doc_file_;
101 ActiveFileMonitorPtr 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 std::shared_ptr<Image> image_;
121 /// This signal is emitted when the image loading status changes.
122 signals2::signal<void()> statusChanged;
125 unique_ptr<Converter> converter_;
129 CacheItem::CacheItem(FileName const & file, FileName const & doc_file)
130 : pimpl_(new Impl(file,doc_file))
134 CacheItem::~CacheItem()
140 FileName const & CacheItem::filename() const
142 return pimpl_->filename_;
146 bool CacheItem::tryDisplayFormat() const
148 if (pimpl_->status_ != WaitingToLoad)
152 bool const conversion_needed = pimpl_->tryDisplayFormat(filename, from);
153 bool const success = status() == Loaded && !conversion_needed;
160 void CacheItem::startLoading() const
162 pimpl_->startLoading();
166 void CacheItem::startMonitoring() const
168 pimpl_->startMonitor();
172 bool CacheItem::monitoring() const
174 return (bool)pimpl_->monitor_;
178 void CacheItem::checkModifiedAsync() const
180 if (!pimpl_->monitor_)
182 pimpl_->monitor_->checkModifiedAsync();
186 Image const * CacheItem::image() const
188 return pimpl_->image_.get();
192 ImageStatus CacheItem::status() const
194 return pimpl_->status_;
198 signals2::connection CacheItem::connect(slot_type const & slot) const
200 return pimpl_->statusChanged.connect(slot);
204 //------------------------------
205 // Implementation details follow
206 //------------------------------
209 CacheItem::Impl::Impl(FileName const & file, FileName const & doc_file)
210 : filename_(file), doc_file_(doc_file),
212 remove_loaded_file_(false),
213 status_(WaitingToLoad)
217 void CacheItem::Impl::startMonitor()
221 monitor_ = FileSystemWatcher::activeMonitor(filename_);
222 // Disconnected at the same time as this is destroyed.
223 monitor_->connect([=](bool /* exists */){ startLoading(); });
227 void CacheItem::Impl::startLoading()
229 if (status_ != WaitingToLoad)
232 convertToDisplayFormat();
236 void CacheItem::Impl::reset()
239 if (!unzipped_filename_.empty())
240 unzipped_filename_.removeFile();
241 unzipped_filename_.erase();
243 if (remove_loaded_file_ && !file_to_load_.empty())
244 file_to_load_.removeFile();
245 remove_loaded_file_ = false;
246 file_to_load_.erase();
252 status_ = WaitingToLoad;
259 void CacheItem::Impl::setStatus(ImageStatus new_status)
261 if (status_ == new_status)
264 status_ = new_status;
269 void CacheItem::Impl::imageConverted(bool success)
271 string const text = success ? "succeeded" : "failed";
272 LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
274 file_to_load_ = converter_ ? FileName(converter_->convertedFile())
278 success = !file_to_load_.empty() && file_to_load_.isReadableFile();
281 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
282 setStatus(ErrorConverting);
285 unzipped_filename_.removeFile();
290 // Add the converted file to the file cache
291 ConverterCache::get().add(filename_, to_, file_to_load_);
293 setStatus(loadImage() ? Loaded : ErrorLoading);
297 // This function gets called from the callback after the image has been
298 // converted successfully.
299 bool CacheItem::Impl::loadImage()
301 LYXERR(Debug::GRAPHICS, "Loading image.");
303 image_.reset(newImage());
305 bool success = image_->load(file_to_load_);
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();
320 typedef vector<string> FormatList;
322 static string const findTargetFormat(FormatList const & format_list, string const & from)
324 // There must be a format to load from.
325 LASSERT(!theFormats().empty(), return string());
327 // Use the standard converter if we don't know the format to load
330 return string("ppm");
332 // First ascertain if we can load directly with no conversion
333 FormatList::const_iterator it = format_list.begin();
334 FormatList::const_iterator end = format_list.end();
335 for (; it != end; ++it) {
340 // So, we have to convert to a loadable format. Can we?
341 it = format_list.begin();
342 for (; it != end; ++it) {
343 if (lyx::graphics::Converter::isReachable(from, *it))
346 LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
350 // Failed! so we have to try to convert it to PPM format
351 // with the standard converter
352 return string("ppm");
356 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
358 // First, check that the file exists!
360 if (!filename_.isReadableFile()) {
361 if (status_ != ErrorNoFile) {
362 status_ = ErrorNoFile;
363 LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
368 zipped_ = theFormats().isZippedFile(filename_);
370 string tempname = unzippedFileName(filename_.toFilesystemEncoding());
371 string const ext = getExtension(tempname);
372 tempname = changeExtension(tempname, "") + "-XXXXXX";
374 tempname = addExtension(tempname, ext);
375 TempFile tempfile(tempname);
376 tempfile.setAutoRemove(false);
377 unzipped_filename_ = tempfile.name();
378 if (unzipped_filename_.empty()) {
379 status_ = ErrorConverting;
380 LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
383 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
385 filename = filename_;
388 docstring const displayed_filename = makeDisplayPath(filename_.absFileName());
389 LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
390 << "\tAttempting to convert image file: " << filename
391 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
393 from = theFormats().getFormatFromFile(filename);
395 status_ = ErrorConverting;
396 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
398 LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
399 to_ = findTargetFormat(Cache::get().loadableFormats(), from);
402 // No conversion needed!
403 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
404 file_to_load_ = filename;
405 status_ = loadImage() ? Loaded : ErrorLoading;
409 if (ConverterCache::get().inCache(filename, to_)) {
410 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
411 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
412 status_ = loadImage() ? Loaded : ErrorLoading;
419 void CacheItem::Impl::convertToDisplayFormat()
421 LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
423 // Make a local copy in case we unzip it
426 if (!tryDisplayFormat(filename, from)) {
427 // The image status has changed, tell it to the outside world.
432 // We will need a conversion, tell it to the outside world.
433 setStatus(Converting);
435 // Add some stuff to create a uniquely named temporary file.
436 // This file is deleted in loadImage after it is loaded into memory.
437 TempFile tempfile("CacheItem");
438 tempfile.setAutoRemove(false);
439 FileName const to_file_base = tempfile.name();
440 remove_loaded_file_ = true;
442 // Connect a signal to this->imageConverted and pass this signal to
443 // the graphics converter so that we can load the modified file
444 // on completion of the conversion process.
445 converter_ = make_unique<Converter>(doc_file_, filename,
446 to_file_base.absFileName(),
448 // Connection is closed at the same time as *this is destroyed.
449 converter_->connect([this](bool success){
450 imageConverted(success);
452 converter_->startConversion();
455 } // namespace graphics