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