]> git.lyx.org Git - features.git/blob - src/graphics/GraphicsCacheItem.cpp
move GuiImage::loadableFormats() to support/imagetools.{h,cpp} and simplify this...
[features.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
29 #include <boost/bind.hpp>
30
31 using namespace std;
32 using namespace lyx::support;
33
34 namespace lyx {
35
36 namespace graphics {
37
38 class CacheItem::Impl : public boost::signals::trackable {
39 public:
40
41         ///
42         Impl(FileName const & file);
43
44         /** Start the image conversion process, checking first that it is
45          *  necessary. If it is necessary, then a conversion task is started.
46          *  CacheItem asumes that the conversion is asynchronous and so
47          *  passes a Signal to the converting routine. When the conversion
48          *  is finished, this Signal is emitted, returning the converted
49          *  file to this->imageConverted.
50          *
51          *  If no file conversion is needed, then convertToDisplayFormat() calls
52          *  loadImage() directly.
53          *
54          *  convertToDisplayFormat() will set the loading status flag as
55          *  approriate through calls to setStatus().
56          */
57         void convertToDisplayFormat();
58
59         /** Load the image into memory. This is called either from
60          *  convertToDisplayFormat() direct or from imageConverted().
61          */
62         void loadImage();
63
64         /** Get a notification when the image conversion is done.
65          *  Connected to a signal on_finish_ which is passed to
66          *  Converter::convert.
67          */
68         void imageConverted(bool);
69
70         /** Get a notification when the image loading is done.
71          *  Connected to a signal on_finish_ which is passed to
72          *  lyx::graphics::Image::loadImage.
73          */
74         void imageLoaded(bool);
75
76         /** Sets the status of the loading process. Also notifies
77          *  listeners that the status has changed.
78          */
79         void setStatus(ImageStatus new_status);
80
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).
84          */
85         void startLoading();
86
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.
90          */
91         void reset();
92
93         /// The filename we refer too.
94         FileName const filename_;
95         ///
96         FileMonitor const monitor_;
97
98         /// Is the file compressed?
99         bool zipped_;
100         /// If so, store the uncompressed file in this temporary file.
101         FileName unzipped_filename_;
102         /// The target format
103         string to_;
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.
108          */
109         bool remove_loaded_file_;
110
111         /// The image and its loading status.
112         boost::shared_ptr<Image> image_;
113         ///
114         ImageStatus status_;
115
116         /// This signal is emitted when the image loading status changes.
117         boost::signal<void()> statusChanged;
118
119         /// The connection to the signal Image::finishedLoading
120         boost::signals::connection cl_;
121
122         /// The connection of the signal ConvProcess::finishedConversion,
123         boost::signals::connection cc_;
124
125         ///
126         boost::scoped_ptr<Converter> converter_;
127 };
128
129
130 CacheItem::CacheItem(FileName const & file)
131         : pimpl_(new Impl(file))
132 {}
133
134
135 CacheItem::~CacheItem()
136 {
137         delete pimpl_;
138 }
139
140
141 FileName const & CacheItem::filename() const
142 {
143         return pimpl_->filename_;
144 }
145
146
147 void CacheItem::startLoading() const
148 {
149         pimpl_->startLoading();
150 }
151
152
153 void CacheItem::startMonitoring() const
154 {
155         if (!pimpl_->monitor_.monitoring())
156                 pimpl_->monitor_.start();
157 }
158
159
160 bool CacheItem::monitoring() const
161 {
162         return pimpl_->monitor_.monitoring();
163 }
164
165
166 unsigned long CacheItem::checksum() const
167 {
168         return pimpl_->monitor_.checksum();
169 }
170
171
172 Image const * CacheItem::image() const
173 {
174         return pimpl_->image_.get();
175 }
176
177
178 ImageStatus CacheItem::status() const
179 {
180         return pimpl_->status_;
181 }
182
183
184 boost::signals::connection CacheItem::connect(slot_type const & slot) const
185 {
186         return pimpl_->statusChanged.connect(slot);
187 }
188
189
190 //------------------------------
191 // Implementation details follow
192 //------------------------------
193
194
195 CacheItem::Impl::Impl(FileName const & file)
196         : filename_(file),
197           monitor_(file, 2000),
198           zipped_(false),
199           remove_loaded_file_(false),
200           status_(WaitingToLoad)
201 {
202         monitor_.connect(boost::bind(&Impl::startLoading, this));
203 }
204
205
206 void CacheItem::Impl::startLoading()
207 {
208         if (status_ != WaitingToLoad)
209                 reset();
210
211         convertToDisplayFormat();
212 }
213
214
215 void CacheItem::Impl::reset()
216 {
217         zipped_ = false;
218         if (!unzipped_filename_.empty())
219                 unzipped_filename_.removeFile();
220         unzipped_filename_.erase();
221
222         if (remove_loaded_file_ && !file_to_load_.empty())
223                 file_to_load_.removeFile();
224         remove_loaded_file_ = false;
225         file_to_load_.erase();
226         to_.erase();
227
228         if (image_.get())
229                 image_.reset();
230
231         status_ = WaitingToLoad;
232
233         if (cl_.connected())
234                 cl_.disconnect();
235
236         if (cc_.connected())
237                 cc_.disconnect();
238
239         if (converter_.get())
240                 converter_.reset();
241 }
242
243
244 void CacheItem::Impl::setStatus(ImageStatus new_status)
245 {
246         if (status_ == new_status)
247                 return;
248
249         status_ = new_status;
250         statusChanged();
251 }
252
253
254 void CacheItem::Impl::imageConverted(bool success)
255 {
256         string const text = success ? "succeeded" : "failed";
257         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
258
259         file_to_load_ = converter_.get() ?
260                 FileName(converter_->convertedFile()) : FileName();
261         converter_.reset();
262         cc_.disconnect();
263
264         success = !file_to_load_.empty() && file_to_load_.isReadableFile();
265
266         if (!success) {
267                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
268                 setStatus(ErrorConverting);
269
270                 if (zipped_)
271                         unzipped_filename_.removeFile();
272
273                 return;
274         }
275
276         // Add the converted file to the file cache
277         ConverterCache::get().add(filename_, to_, file_to_load_);
278
279         loadImage();
280 }
281
282
283 // This function gets called from the callback after the image has been
284 // converted successfully.
285 void CacheItem::Impl::loadImage()
286 {
287         setStatus(Loading);
288         LYXERR(Debug::GRAPHICS, "Loading image.");
289
290         image_.reset(Image::newImage());
291
292         cl_.disconnect();
293         cl_ = image_->finishedLoading.connect(
294                 boost::bind(&Impl::imageLoaded, this, _1));
295         image_->load(file_to_load_);
296 }
297
298
299 void CacheItem::Impl::imageLoaded(bool success)
300 {
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         cl_.disconnect();
312
313         if (!success) {
314                 setStatus(ErrorLoading);
315                 return;
316         }
317
318         // Inform the outside world.
319         setStatus(Loaded);
320 }
321
322
323 static string const findTargetFormat(string const & from)
324 {
325         typedef vector<string> FormatList;
326         FormatList const & formats = Cache::get().loadableFormats();
327
328          // There must be a format to load from.
329         LASSERT(!formats.empty(), /**/);
330
331         // Use the standard converter if we don't know the format to load
332         // from.
333         if (from.empty())
334                 return string("ppm");
335
336         // First ascertain if we can load directly with no conversion
337         FormatList::const_iterator it  = formats.begin();
338         FormatList::const_iterator end = formats.end();
339         for (; it != end; ++it) {
340                 if (from == *it)
341                         return *it;
342         }
343
344         // So, we have to convert to a loadable format. Can we?
345         it = formats.begin();
346         for (; it != end; ++it) {
347                 if (lyx::graphics::Converter::isReachable(from, *it))
348                         return *it;
349                 else
350                         LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
351                                 << " to " << *it);
352         }
353
354         // Failed! so we have to try to convert it to PPM format
355         // with the standard converter
356         return string("ppm");
357 }
358
359
360 void CacheItem::Impl::convertToDisplayFormat()
361 {
362         setStatus(Converting);
363
364         // First, check that the file exists!
365         if (!filename_.isReadableFile()) {
366                 if (status_ != ErrorNoFile) {
367                         setStatus(ErrorNoFile);
368                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
369                 }
370                 return;
371         }
372
373         // Make a local copy in case we unzip it
374         FileName filename;
375         zipped_ = filename_.isZippedFile();
376         if (zipped_) {
377                 unzipped_filename_ = FileName::tempName(
378                         filename_.toFilesystemEncoding());
379                 if (unzipped_filename_.empty()) {
380                         setStatus(ErrorConverting);
381                         LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
382                         return;
383                 }
384                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
385         } else {
386                 filename = filename_;
387         }
388
389         docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
390         LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
391                 << "\tAttempting to convert image file: " << filename
392                 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
393
394         string const from = formats.getFormatFromFile(filename);
395         if (from.empty()) {
396                 setStatus(ErrorConverting);
397                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
398         }
399         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
400         to_ = findTargetFormat(from);
401
402         if (from == to_) {
403                 // No conversion needed!
404                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
405                 file_to_load_ = filename;
406                 loadImage();
407                 return;
408         }
409
410         if (ConverterCache::get().inCache(filename, to_)) {
411                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
412                 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
413                 loadImage();
414                 return;
415         }
416
417         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
418
419         // Add some stuff to create a uniquely named temporary file.
420         // This file is deleted in loadImage after it is loaded into memory.
421         FileName const to_file_base = FileName::tempName("CacheItem");
422         remove_loaded_file_ = true;
423
424         // Remove the temp file, we only want the name...
425         // FIXME: This is unsafe!
426         to_file_base.removeFile();
427
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(boost::bind(&Impl::imageConverted, this, _1));
433         converter_->startConversion();
434 }
435
436 } // namespace graphics
437 } // namespace lyx