]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.cpp
3359682ce875e5b79c8cbc16eb391251289a46d7
[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
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         /**
45          *  If no file conversion is needed, then tryDisplayFormat() calls
46          *  loadImage() directly.
47          * \return true if a conversion is necessary.
48          */
49         bool tryDisplayFormat(FileName & filename, string & from);
50
51         /** Start the image conversion process, checking first that it is
52          *  necessary. If it is necessary, then a conversion task is started.
53          *  CacheItem asumes that the conversion is asynchronous and so
54          *  passes a Signal to the converting routine. When the conversion
55          *  is finished, this Signal is emitted, returning the converted
56          *  file to this->imageConverted.
57          *
58          *  convertToDisplayFormat() will set the loading status flag as
59          *  approriate through calls to setStatus().
60          */
61         void convertToDisplayFormat();
62
63         /** Load the image into memory. This is called either from
64          *  convertToDisplayFormat() direct or from imageConverted().
65          */
66         void loadImage();
67
68         /** Get a notification when the image conversion is done.
69          *  Connected to a signal on_finish_ which is passed to
70          *  Converter::convert.
71          */
72         void imageConverted(bool);
73
74         /** Sets the status of the loading process. Also notifies
75          *  listeners that the status has changed.
76          */
77         void setStatus(ImageStatus new_status);
78
79         /** Can be invoked directly by the user, but is also connected to the
80          *  FileMonitor and so is invoked when the file is changed
81          *  (if monitoring is taking place).
82          */
83         void startLoading();
84
85         /** If we are asked to load the file for a second or further time,
86          *  (because the file has changed), then we'll have to first reset
87          *  many of the variables below.
88          */
89         void reset();
90
91         /// The filename we refer too.
92         FileName const filename_;
93         ///
94         FileMonitor const monitor_;
95
96         /// Is the file compressed?
97         bool zipped_;
98         /// If so, store the uncompressed file in this temporary file.
99         FileName unzipped_filename_;
100         /// The target format
101         string to_;
102         /// What file are we trying to load?
103         FileName file_to_load_;
104         /** Should we delete the file after loading? True if the file is
105          *  the result of a conversion process.
106          */
107         bool remove_loaded_file_;
108
109         /// The image and its loading status.
110         boost::shared_ptr<Image> image_;
111         ///
112         ImageStatus status_;
113
114         /// This signal is emitted when the image loading status changes.
115         boost::signal<void()> statusChanged;
116
117         /// The connection of the signal ConvProcess::finishedConversion,
118         boost::signals::connection cc_;
119
120         ///
121         boost::scoped_ptr<Converter> converter_;
122 };
123
124
125 CacheItem::CacheItem(FileName const & file)
126         : pimpl_(new Impl(file))
127 {}
128
129
130 CacheItem::~CacheItem()
131 {
132         delete pimpl_;
133 }
134
135
136 FileName const & CacheItem::filename() const
137 {
138         return pimpl_->filename_;
139 }
140
141
142 bool CacheItem::tryDisplayFormat() const
143 {
144         if (pimpl_->status_ != WaitingToLoad)
145                 pimpl_->reset();
146         FileName filename;
147         string from;
148         return pimpl_->tryDisplayFormat(filename, from);
149 }
150
151
152 void CacheItem::startLoading() const
153 {
154         pimpl_->startLoading();
155 }
156
157
158 void CacheItem::startMonitoring() const
159 {
160         if (!pimpl_->monitor_.monitoring())
161                 pimpl_->monitor_.start();
162 }
163
164
165 bool CacheItem::monitoring() const
166 {
167         return pimpl_->monitor_.monitoring();
168 }
169
170
171 unsigned long CacheItem::checksum() const
172 {
173         return pimpl_->monitor_.checksum();
174 }
175
176
177 Image const * CacheItem::image() const
178 {
179         return pimpl_->image_.get();
180 }
181
182
183 ImageStatus CacheItem::status() const
184 {
185         return pimpl_->status_;
186 }
187
188
189 boost::signals::connection CacheItem::connect(slot_type const & slot) const
190 {
191         return pimpl_->statusChanged.connect(slot);
192 }
193
194
195 //------------------------------
196 // Implementation details follow
197 //------------------------------
198
199
200 CacheItem::Impl::Impl(FileName const & file)
201         : filename_(file),
202           monitor_(file, 2000),
203           zipped_(false),
204           remove_loaded_file_(false),
205           status_(WaitingToLoad)
206 {
207         monitor_.connect(boost::bind(&Impl::startLoading, this));
208 }
209
210
211 void CacheItem::Impl::startLoading()
212 {
213         if (status_ != WaitingToLoad)
214                 reset();
215
216         convertToDisplayFormat();
217 }
218
219
220 void CacheItem::Impl::reset()
221 {
222         zipped_ = false;
223         if (!unzipped_filename_.empty())
224                 unzipped_filename_.removeFile();
225         unzipped_filename_.erase();
226
227         if (remove_loaded_file_ && !file_to_load_.empty())
228                 file_to_load_.removeFile();
229         remove_loaded_file_ = false;
230         file_to_load_.erase();
231         to_.erase();
232
233         if (image_.get())
234                 image_.reset();
235
236         status_ = WaitingToLoad;
237
238         if (cc_.connected())
239                 cc_.disconnect();
240
241         if (converter_.get())
242                 converter_.reset();
243 }
244
245
246 void CacheItem::Impl::setStatus(ImageStatus new_status)
247 {
248         if (status_ == new_status)
249                 return;
250
251         status_ = new_status;
252         statusChanged();
253 }
254
255
256 void CacheItem::Impl::imageConverted(bool success)
257 {
258         string const text = success ? "succeeded" : "failed";
259         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
260
261         file_to_load_ = converter_.get() ?
262                 FileName(converter_->convertedFile()) : FileName();
263         converter_.reset();
264         cc_.disconnect();
265
266         success = !file_to_load_.empty() && file_to_load_.isReadableFile();
267
268         if (!success) {
269                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
270                 setStatus(ErrorConverting);
271
272                 if (zipped_)
273                         unzipped_filename_.removeFile();
274
275                 return;
276         }
277
278         // Add the converted file to the file cache
279         ConverterCache::get().add(filename_, to_, file_to_load_);
280
281         loadImage();
282 }
283
284
285 // This function gets called from the callback after the image has been
286 // converted successfully.
287 void CacheItem::Impl::loadImage()
288 {
289         setStatus(Loading);
290         LYXERR(Debug::GRAPHICS, "Loading image.");
291
292         image_.reset(Image::newImage());
293
294         bool success = image_->load(file_to_load_);
295         string const text = success ? "succeeded" : "failed";
296         LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
297
298         // Clean up after loading.
299         if (zipped_)
300                 unzipped_filename_.removeFile();
301
302         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
303                 file_to_load_.removeFile();
304
305         if (!success) {
306                 setStatus(ErrorLoading);
307                 return;
308         }
309
310         // Inform the outside world.
311         setStatus(Loaded);
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(), /**/);
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         setStatus(Converting);
355
356         // First, check that the file exists!
357         if (!filename_.isReadableFile()) {
358                 if (status_ != ErrorNoFile) {
359                         setStatus(ErrorNoFile);
360                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
361                 }
362                 return true;
363         }
364
365         zipped_ = filename_.isZippedFile();
366         if (zipped_) {
367                 unzipped_filename_ = FileName::tempName(
368                         filename_.toFilesystemEncoding());
369                 if (unzipped_filename_.empty()) {
370                         setStatus(ErrorConverting);
371                         LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
372                         return true;
373                 }
374                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
375         } else {
376                 filename = filename_;
377         }
378
379         docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
380         LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
381                 << "\tAttempting to convert image file: " << filename
382                 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
383
384         from = formats.getFormatFromFile(filename);
385         if (from.empty()) {
386                 setStatus(ErrorConverting);
387                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
388         }
389         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
390         to_ = findTargetFormat(from);
391
392         if (from == to_) {
393                 // No conversion needed!
394                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
395                 file_to_load_ = filename;
396                 loadImage();
397                 return true;
398         }
399
400         if (ConverterCache::get().inCache(filename, to_)) {
401                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
402                 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
403                 loadImage();
404                 return true;
405         }
406         return false;
407 }
408
409
410 void CacheItem::Impl::convertToDisplayFormat()
411 {
412         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
413
414         // Make a local copy in case we unzip it
415         FileName filename;
416         string from;
417         if (tryDisplayFormat(filename, from))
418                 return;
419
420         // Add some stuff to create a uniquely named temporary file.
421         // This file is deleted in loadImage after it is loaded into memory.
422         FileName const to_file_base = FileName::tempName("CacheItem");
423         remove_loaded_file_ = true;
424
425         // Remove the temp file, we only want the name...
426         // FIXME: This is unsafe!
427         to_file_base.removeFile();
428
429         // Connect a signal to this->imageConverted and pass this signal to
430         // the graphics converter so that we can load the modified file
431         // on completion of the conversion process.
432         converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
433         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
434         converter_->startConversion();
435 }
436
437 } // namespace graphics
438 } // namespace lyx