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