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