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