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