]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.cpp
83bf09d289a0b88d09c716dc07705daa0b8ba33f
[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         delete pimpl_;
146 }
147
148
149 FileName const & CacheItem::filename() const
150 {
151         return pimpl_->filename_;
152 }
153
154
155 void CacheItem::startLoading() const
156 {
157         pimpl_->startLoading();
158 }
159
160
161 void CacheItem::startMonitoring() const
162 {
163         if (!pimpl_->monitor_.monitoring())
164                 pimpl_->monitor_.start();
165 }
166
167
168 bool CacheItem::monitoring() const
169 {
170         return pimpl_->monitor_.monitoring();
171 }
172
173
174 unsigned long CacheItem::checksum() const
175 {
176         return pimpl_->monitor_.checksum();
177 }
178
179
180 Image const * CacheItem::image() const
181 {
182         return pimpl_->image_.get();
183 }
184
185
186 ImageStatus CacheItem::status() const
187 {
188         return pimpl_->status_;
189 }
190
191
192 boost::signals::connection CacheItem::connect(slot_type const & slot) const
193 {
194         return pimpl_->statusChanged.connect(slot);
195 }
196
197
198 //------------------------------
199 // Implementation details follow
200 //------------------------------
201
202
203 CacheItem::Impl::Impl(FileName const & file)
204         : filename_(file),
205           monitor_(file, 2000),
206           zipped_(false),
207           remove_loaded_file_(false),
208           status_(WaitingToLoad)
209 {
210         monitor_.connect(boost::bind(&Impl::startLoading, this));
211 }
212
213
214 void CacheItem::Impl::startLoading()
215 {
216         if (status_ != WaitingToLoad)
217                 reset();
218
219         convertToDisplayFormat();
220 }
221
222
223 void CacheItem::Impl::reset()
224 {
225         zipped_ = false;
226         if (!unzipped_filename_.empty())
227                 unlink(unzipped_filename_);
228         unzipped_filename_.erase();
229
230         if (remove_loaded_file_ && !file_to_load_.empty())
231                 unlink(file_to_load_);
232         remove_loaded_file_ = false;
233         file_to_load_.erase();
234         to_.erase();
235
236         if (image_.get())
237                 image_.reset();
238
239         status_ = WaitingToLoad;
240
241         if (cl_.connected())
242                 cl_.disconnect();
243
244         if (cc_.connected())
245                 cc_.disconnect();
246
247         if (converter_.get())
248                 converter_.reset();
249 }
250
251
252 void CacheItem::Impl::setStatus(ImageStatus new_status)
253 {
254         if (status_ == new_status)
255                 return;
256
257         status_ = new_status;
258         statusChanged();
259 }
260
261
262 void CacheItem::Impl::imageConverted(bool success)
263 {
264         string const text = success ? "succeeded" : "failed";
265         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
266
267         file_to_load_ = converter_.get() ?
268                 FileName(converter_->convertedFile()) : FileName();
269         converter_.reset();
270         cc_.disconnect();
271
272         success = !file_to_load_.empty() && file_to_load_.isFileReadable();
273
274         if (!success) {
275                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
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.");
297
298         image_.reset(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 << '.');
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, "Unable to convert from " << from
359                                 << " to " << *it);
360         }
361
362         // Failed! so we have to try to convert it to PPM format
363         // with the standard converter
364         return string("ppm");
365 }
366
367
368 void CacheItem::Impl::convertToDisplayFormat()
369 {
370         setStatus(Converting);
371
372         // First, check that the file exists!
373         if (!filename_.isFileReadable()) {
374                 if (status_ != ErrorNoFile) {
375                         setStatus(ErrorNoFile);
376                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
377                 }
378                 return;
379         }
380
381         // Make a local copy in case we unzip it
382         FileName filename;
383         zipped_ = filename_.isZippedFile();
384         if (zipped_) {
385                 unzipped_filename_ = tempName(FileName(), filename_.toFilesystemEncoding());
386                 if (unzipped_filename_.empty()) {
387                         setStatus(ErrorConverting);
388                         LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
389                         return;
390                 }
391                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
392         } else {
393                 filename = filename_;
394         }
395
396         docstring const displayed_filename = makeDisplayPath(filename_.absFilename());
397         LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
398                 << "\tAttempting to convert image file: " << filename
399                 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
400
401         string const from = formats.getFormatFromFile(filename);
402         if (from.empty()) {
403                 setStatus(ErrorConverting);
404                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
405         }
406         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
407         to_ = findTargetFormat(from);
408
409         if (from == to_) {
410                 // No conversion needed!
411                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
412                 file_to_load_ = filename;
413                 loadImage();
414                 return;
415         }
416
417         if (ConverterCache::get().inCache(filename, to_)) {
418                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
419                 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
420                 loadImage();
421                 return;
422         }
423
424         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
425
426         // Add some stuff to create a uniquely named temporary file.
427         // This file is deleted in loadImage after it is loaded into memory.
428         FileName const to_file_base(tempName(FileName(), "CacheItem"));
429         remove_loaded_file_ = true;
430
431         // Remove the temp file, we only want the name...
432         // FIXME: This is unsafe!
433         unlink(to_file_base);
434
435         // Connect a signal to this->imageConverted and pass this signal to
436         // the graphics converter so that we can load the modified file
437         // on completion of the conversion process.
438         converter_.reset(new Converter(filename, to_file_base.absFilename(), from, to_));
439         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
440         converter_->startConversion();
441 }
442
443 } // namespace graphics
444 } // namespace lyx