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