]> git.lyx.org Git - features.git/blob - src/graphics/GraphicsCacheItem.cpp
'using namespace std' instead of 'using std::xxx'
[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 #include "GraphicsConverter.h"
17 #include "GraphicsImage.h"
18
19 #include "ConverterCache.h"
20 #include "support/debug.h"
21 #include "Format.h"
22
23 #include "support/filetools.h"
24 #include "support/FileMonitor.h"
25 #include "support/lyxlib.h"
26
27 #include <boost/bind.hpp>
28
29 using namespace std;
30
31 namespace lyx {
32
33 using support::FileMonitor;
34 using support::FileName;
35 using support::makeDisplayPath;
36 using support::onlyFilename;
37 using support::tempName;
38 using support::unzipFile;
39
40
41 namespace graphics {
42
43 class CacheItem::Impl : public boost::signals::trackable {
44 public:
45
46         ///
47         Impl(FileName const & file);
48
49         /** Start the image conversion process, checking first that it is
50          *  necessary. If it is necessary, then a conversion task is started.
51          *  CacheItem asumes that the conversion is asynchronous and so
52          *  passes a Signal to the converting routine. When the conversion
53          *  is finished, this Signal is emitted, returning the converted
54          *  file to this->imageConverted.
55          *
56          *  If no file conversion is needed, then convertToDisplayFormat() calls
57          *  loadImage() directly.
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         void 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         /** Get a notification when the image loading is done.
76          *  Connected to a signal on_finish_ which is passed to
77          *  lyx::graphics::Image::loadImage.
78          */
79         void imageLoaded(bool);
80
81         /** Sets the status of the loading process. Also notifies
82          *  listeners that the status has changed.
83          */
84         void setStatus(ImageStatus new_status);
85
86         /** Can be invoked directly by the user, but is also connected to the
87          *  FileMonitor and so is invoked when the file is changed
88          *  (if monitoring is taking place).
89          */
90         void startLoading();
91
92         /** If we are asked to load the file for a second or further time,
93          *  (because the file has changed), then we'll have to first reset
94          *  many of the variables below.
95          */
96         void reset();
97
98         /// The filename we refer too.
99         FileName const filename_;
100         ///
101         FileMonitor const monitor_;
102
103         /// Is the file compressed?
104         bool zipped_;
105         /// If so, store the uncompressed file in this temporary file.
106         FileName unzipped_filename_;
107         /// The target format
108         string to_;
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.
113          */
114         bool remove_loaded_file_;
115
116         /// The image and its loading status.
117         boost::shared_ptr<Image> image_;
118         ///
119         ImageStatus status_;
120
121         /// This signal is emitted when the image loading status changes.
122         boost::signal<void()> statusChanged;
123
124         /// The connection to the signal Image::finishedLoading
125         boost::signals::connection cl_;
126
127         /// The connection of the signal ConvProcess::finishedConversion,
128         boost::signals::connection cc_;
129
130         ///
131         boost::scoped_ptr<Converter> converter_;
132 };
133
134
135 CacheItem::CacheItem(FileName const & file)
136         : pimpl_(new Impl(file))
137 {}
138
139
140 CacheItem::~CacheItem()
141 {
142         delete pimpl_;
143 }
144
145
146 FileName const & CacheItem::filename() const
147 {
148         return pimpl_->filename_;
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 (cl_.connected())
239                 cl_.disconnect();
240
241         if (cc_.connected())
242                 cc_.disconnect();
243
244         if (converter_.get())
245                 converter_.reset();
246 }
247
248
249 void CacheItem::Impl::setStatus(ImageStatus new_status)
250 {
251         if (status_ == new_status)
252                 return;
253
254         status_ = new_status;
255         statusChanged();
256 }
257
258
259 void CacheItem::Impl::imageConverted(bool success)
260 {
261         string const text = success ? "succeeded" : "failed";
262         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
263
264         file_to_load_ = converter_.get() ?
265                 FileName(converter_->convertedFile()) : FileName();
266         converter_.reset();
267         cc_.disconnect();
268
269         success = !file_to_load_.empty() && file_to_load_.isReadableFile();
270
271         if (!success) {
272                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
273                 setStatus(ErrorConverting);
274
275                 if (zipped_)
276                         unzipped_filename_.removeFile();
277
278                 return;
279         }
280
281         // Add the converted file to the file cache
282         ConverterCache::get().add(filename_, to_, file_to_load_);
283
284         loadImage();
285 }
286
287
288 // This function gets called from the callback after the image has been
289 // converted successfully.
290 void CacheItem::Impl::loadImage()
291 {
292         setStatus(Loading);
293         LYXERR(Debug::GRAPHICS, "Loading image.");
294
295         image_.reset(Image::newImage());
296
297         cl_.disconnect();
298         cl_ = image_->finishedLoading.connect(
299                 boost::bind(&Impl::imageLoaded, this, _1));
300         image_->load(file_to_load_);
301 }
302
303
304 void CacheItem::Impl::imageLoaded(bool success)
305 {
306         string const text = success ? "succeeded" : "failed";
307         LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
308
309         // Clean up after loading.
310         if (zipped_)
311                 unzipped_filename_.removeFile();
312
313         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
314                 file_to_load_.removeFile();
315
316         cl_.disconnect();
317
318         if (!success) {
319                 setStatus(ErrorLoading);
320                 return;
321         }
322
323         // Inform the outside world.
324         setStatus(Loaded);
325 }
326
327
328 static string const findTargetFormat(string const & from)
329 {
330         typedef lyx::graphics::Image::FormatList FormatList;
331         FormatList const formats = lyx::graphics::Image::loadableFormats();
332
333          // There must be a format to load from.
334         BOOST_ASSERT(!formats.empty());
335
336         // Use the standard converter if we don't know the format to load
337         // from.
338         if (from.empty())
339                 return string("ppm");
340
341         // First ascertain if we can load directly with no conversion
342         FormatList::const_iterator it  = formats.begin();
343         FormatList::const_iterator end = formats.end();
344         for (; it != end; ++it) {
345                 if (from == *it)
346                         return *it;
347         }
348
349         // So, we have to convert to a loadable format. Can we?
350         it = formats.begin();
351         for (; it != end; ++it) {
352                 if (lyx::graphics::Converter::isReachable(from, *it))
353                         return *it;
354                 else
355                         LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
356                                 << " to " << *it);
357         }
358
359         // Failed! so we have to try to convert it to PPM format
360         // with the standard converter
361         return string("ppm");
362 }
363
364
365 void CacheItem::Impl::convertToDisplayFormat()
366 {
367         setStatus(Converting);
368
369         // First, check that the file exists!
370         if (!filename_.isReadableFile()) {
371                 if (status_ != ErrorNoFile) {
372                         setStatus(ErrorNoFile);
373                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
374                 }
375                 return;
376         }
377
378         // Make a local copy in case we unzip it
379         FileName filename;
380         zipped_ = filename_.isZippedFile();
381         if (zipped_) {
382                 unzipped_filename_ = tempName(FileName(), filename_.toFilesystemEncoding());
383                 if (unzipped_filename_.empty()) {
384                         setStatus(ErrorConverting);
385                         LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
386                         return;
387                 }
388                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
389         } else {
390                 filename = filename_;
391         }
392
393         docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
394         LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
395                 << "\tAttempting to convert image file: " << filename
396                 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
397
398         string const from = formats.getFormatFromFile(filename);
399         if (from.empty()) {
400                 setStatus(ErrorConverting);
401                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
402         }
403         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
404         to_ = findTargetFormat(from);
405
406         if (from == to_) {
407                 // No conversion needed!
408                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
409                 file_to_load_ = filename;
410                 loadImage();
411                 return;
412         }
413
414         if (ConverterCache::get().inCache(filename, to_)) {
415                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
416                 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
417                 loadImage();
418                 return;
419         }
420
421         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
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(tempName(FileName(), "CacheItem"));
426         remove_loaded_file_ = true;
427
428         // Remove the temp file, we only want the name...
429         // FIXME: This is unsafe!
430         to_file_base.removeFile();
431
432         // Connect a signal to this->imageConverted and pass this signal to
433         // the graphics converter so that we can load the modified file
434         // on completion of the conversion process.
435         converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
436         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
437         converter_->startConversion();
438 }
439
440 } // namespace graphics
441 } // namespace lyx