]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.cpp
Correct comment
[lyx.git] / src / graphics / GraphicsCacheItem.cpp
1 /**
2  * \file GraphicsCacheItem.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Baruch Even
7  * \author Herbert Voß
8  * \author Angus Leeming
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "GraphicsCacheItem.h"
16
17 #include "GraphicsCache.h"
18 #include "GraphicsConverter.h"
19 #include "GraphicsImage.h"
20
21 #include "ConverterCache.h"
22 #include "Format.h"
23
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"
30
31 #include "support/bind.h"
32 #include "support/TempFile.h"
33
34 using namespace std;
35 using namespace lyx::support;
36
37 namespace lyx {
38
39 namespace graphics {
40
41 class CacheItem::Impl : public boost::signals2::trackable {
42 public:
43
44         ///
45         Impl(FileName const & file);
46
47         /**
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. 
51          */
52         bool tryDisplayFormat(FileName & filename, string & from);
53
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.
60          *
61          *  convertToDisplayFormat() will set the loading status flag as
62          *  approriate through calls to setStatus().
63          */
64         void convertToDisplayFormat();
65
66         /** Load the image into memory. This is called either from
67          *  convertToDisplayFormat() direct or from imageConverted().
68          */
69         bool loadImage();
70
71         /** Get a notification when the image conversion is done.
72          *  Connected to a signal on_finish_ which is passed to
73          *  Converter::convert.
74          */
75         void imageConverted(bool);
76
77         /** Sets the status of the loading process. Also notifies
78          *  listeners that the status has changed.
79          */
80         void setStatus(ImageStatus new_status);
81
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).
85          */
86         void startLoading();
87
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.
91          */
92         void reset();
93
94         /// The filename we refer too.
95         FileName const filename_;
96         ///
97         FileMonitor const monitor_;
98
99         /// Is the file compressed?
100         bool zipped_;
101         /// If so, store the uncompressed file in this temporary file.
102         FileName unzipped_filename_;
103         /// The target format
104         string to_;
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.
109          */
110         bool remove_loaded_file_;
111
112         /// The image and its loading status.
113         std::shared_ptr<Image> image_;
114         ///
115         ImageStatus status_;
116
117         /// This signal is emitted when the image loading status changes.
118         boost::signals2::signal<void()> statusChanged;
119
120         /// The connection of the signal ConvProcess::finishedConversion,
121         boost::signals2::connection cc_;
122
123         ///
124         unique_ptr<Converter> converter_;
125 };
126
127
128 CacheItem::CacheItem(FileName const & file)
129         : pimpl_(new Impl(file))
130 {}
131
132
133 CacheItem::~CacheItem()
134 {
135         delete pimpl_;
136 }
137
138
139 FileName const & CacheItem::filename() const
140 {
141         return pimpl_->filename_;
142 }
143
144
145 bool CacheItem::tryDisplayFormat() const
146 {
147         if (pimpl_->status_ != WaitingToLoad)
148                 pimpl_->reset();
149         FileName filename;
150         string from;
151         bool const conversion_needed = pimpl_->tryDisplayFormat(filename, from);
152         bool const success = status() == Loaded && !conversion_needed;
153         if (!success)
154                 pimpl_->reset();
155         return success;
156 }
157
158
159 void CacheItem::startLoading() const
160 {
161         pimpl_->startLoading();
162 }
163
164
165 void CacheItem::startMonitoring() const
166 {
167         if (!pimpl_->monitor_.monitoring())
168                 pimpl_->monitor_.start();
169 }
170
171
172 bool CacheItem::monitoring() const
173 {
174         return pimpl_->monitor_.monitoring();
175 }
176
177
178 unsigned long CacheItem::checksum() const
179 {
180         return pimpl_->monitor_.checksum();
181 }
182
183
184 Image const * CacheItem::image() const
185 {
186         return pimpl_->image_.get();
187 }
188
189
190 ImageStatus CacheItem::status() const
191 {
192         return pimpl_->status_;
193 }
194
195
196 boost::signals2::connection CacheItem::connect(slot_type const & slot) const
197 {
198         return pimpl_->statusChanged.connect(slot);
199 }
200
201
202 //------------------------------
203 // Implementation details follow
204 //------------------------------
205
206
207 CacheItem::Impl::Impl(FileName const & file)
208         : filename_(file),
209           monitor_(file, 2000),
210           zipped_(false),
211           remove_loaded_file_(false),
212           status_(WaitingToLoad)
213 {
214         monitor_.connect(bind(&Impl::startLoading, this));
215 }
216
217
218 void CacheItem::Impl::startLoading()
219 {
220         if (status_ != WaitingToLoad)
221                 reset();
222
223         convertToDisplayFormat();
224 }
225
226
227 void CacheItem::Impl::reset()
228 {
229         zipped_ = false;
230         if (!unzipped_filename_.empty())
231                 unzipped_filename_.removeFile();
232         unzipped_filename_.erase();
233
234         if (remove_loaded_file_ && !file_to_load_.empty())
235                 file_to_load_.removeFile();
236         remove_loaded_file_ = false;
237         file_to_load_.erase();
238         to_.erase();
239
240         if (image_)
241                 image_.reset();
242
243         status_ = WaitingToLoad;
244
245         if (cc_.connected())
246                 cc_.disconnect();
247
248         if (converter_)
249                 converter_.reset();
250 }
251
252
253 void CacheItem::Impl::setStatus(ImageStatus new_status)
254 {
255         if (status_ == new_status)
256                 return;
257
258         status_ = new_status;
259         statusChanged();
260 }
261
262
263 void CacheItem::Impl::imageConverted(bool success)
264 {
265         string const text = success ? "succeeded" : "failed";
266         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
267
268         file_to_load_ = converter_ ? FileName(converter_->convertedFile())
269                                        : FileName();
270         converter_.reset();
271         cc_.disconnect();
272
273         success = !file_to_load_.empty() && file_to_load_.isReadableFile();
274
275         if (!success) {
276                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
277                 setStatus(ErrorConverting);
278
279                 if (zipped_)
280                         unzipped_filename_.removeFile();
281
282                 return;
283         }
284
285         // Add the converted file to the file cache
286         ConverterCache::get().add(filename_, to_, file_to_load_);
287
288         setStatus(loadImage() ? Loaded : ErrorLoading);
289 }
290
291
292 // This function gets called from the callback after the image has been
293 // converted successfully.
294 bool CacheItem::Impl::loadImage()
295 {
296         LYXERR(Debug::GRAPHICS, "Loading image.");
297
298         image_.reset(newImage());
299
300         bool success = image_->load(file_to_load_);
301         string const text = success ? "succeeded" : "failed";
302         LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
303
304         // Clean up after loading.
305         if (zipped_)
306                 unzipped_filename_.removeFile();
307
308         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
309                 file_to_load_.removeFile();
310
311         return success;
312 }
313
314
315 static string const findTargetFormat(string const & from)
316 {
317         typedef vector<string> FormatList;
318         FormatList const & formats = Cache::get().loadableFormats();
319
320          // There must be a format to load from.
321         LASSERT(!formats.empty(), return string());
322
323         // Use the standard converter if we don't know the format to load
324         // from.
325         if (from.empty())
326                 return string("ppm");
327
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) {
332                 if (from == *it)
333                         return *it;
334         }
335
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))
340                         return *it;
341                 else
342                         LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
343                                 << " to " << *it);
344         }
345
346         // Failed! so we have to try to convert it to PPM format
347         // with the standard converter
348         return string("ppm");
349 }
350
351
352 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
353 {
354         // First, check that the file exists!
355         filename_.refresh();
356         if (!filename_.isReadableFile()) {
357                 if (status_ != ErrorNoFile) {
358                         status_ = ErrorNoFile;
359                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
360                 }
361                 return false;
362         }
363
364         zipped_ = formats.isZippedFile(filename_);
365         if (zipped_) {
366                 string tempname = unzippedFileName(filename_.toFilesystemEncoding());
367                 string const ext = getExtension(tempname);
368                 tempname = changeExtension(tempname, "") + "-XXXXXX";
369                 if (!ext.empty())
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.");
377                         return false;
378                 }
379                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
380         } else {
381                 filename = filename_;
382         }
383
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));
388
389         from = formats.getFormatFromFile(filename);
390         if (from.empty()) {
391                 status_ = ErrorConverting;
392                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
393         }
394         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
395         to_ = findTargetFormat(from);
396
397         if (from == to_) {
398                 // No conversion needed!
399                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
400                 file_to_load_ = filename;
401                 status_ = loadImage() ? Loaded : ErrorLoading;
402                 return false;
403         }
404
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;
409                 return false;
410         }
411         return true;
412 }
413
414
415 void CacheItem::Impl::convertToDisplayFormat()
416 {
417         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
418
419         // Make a local copy in case we unzip it
420         FileName filename;
421         string from;
422         if (!tryDisplayFormat(filename, from)) {
423                 // The image status has changed, tell it to the outside world.
424                 statusChanged();
425                 return;
426         }
427
428         // We will need a conversion, tell it to the outside world.
429         setStatus(Converting);
430
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;
437
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(),
442                                             from, to_);
443         converter_->connect(bind(&Impl::imageConverted, this, _1));
444         converter_->startConversion();
445 }
446
447 } // namespace graphics
448 } // namespace lyx