]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.C
02c730d37af824a07c57ca159245336a98009590
[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 Voss
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 "GraphicsImage.h"
17 #include "GraphicsConverter.h"
18
19 #include "support/FileMonitor.h"
20
21 #include "debug.h"
22
23 #include "support/LAssert.h"
24 #include "support/filetools.h"
25 #include "support/lyxlib.h"
26
27 #include <boost/shared_ptr.hpp>
28 #include <boost/bind.hpp>
29 #include <boost/signals/trackable.hpp>
30
31 using namespace lyx::support;
32
33 using std::endl;
34
35 namespace grfx {
36
37 struct CacheItem::Impl : public boost::signals::trackable {
38
39         ///
40         Impl(string 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          *  grfx::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         string 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         string unzipped_filename_;
100         /// What file are we trying to load?
101         string file_to_load_;
102         /** Should we delete the file after loading? True if the file is
103          *  the result of a conversion process.
104          */
105         bool remove_loaded_file_;
106
107         /// The image and its loading status.
108         boost::shared_ptr<Image> image_;
109         ///
110         ImageStatus status_;
111
112         /// This signal is emitted when the image loading status changes.
113         boost::signal0<void> statusChanged;
114
115         /// The connection to the signal Image::finishedLoading
116         boost::signals::connection cl_;
117
118         /// The connection of the signal ConvProcess::finishedConversion,
119         boost::signals::connection cc_;
120
121         ///
122         boost::scoped_ptr<Converter> converter_;
123 };
124
125
126 CacheItem::CacheItem(string const & file)
127         : pimpl_(new Impl(file))
128 {}
129
130
131 CacheItem::~CacheItem()
132 {}
133
134
135 string const & CacheItem::filename() const
136 {
137         return pimpl_->filename_;
138 }
139
140
141 void CacheItem::startLoading() const
142 {
143         pimpl_->startLoading();
144 }
145
146
147 void CacheItem::startMonitoring() const
148 {
149         if (!pimpl_->monitor_.monitoring())
150                 pimpl_->monitor_.start();
151 }
152
153
154 bool CacheItem::monitoring() const
155 {
156         return pimpl_->monitor_.monitoring();
157 }
158
159
160 unsigned long CacheItem::checksum() const
161 {
162         return pimpl_->monitor_.checksum();
163 }
164
165
166 Image const * CacheItem::image() const
167 {
168         return pimpl_->image_.get();
169 }
170
171
172 ImageStatus CacheItem::status() const
173 {
174         return pimpl_->status_;
175 }
176
177
178 boost::signals::connection CacheItem::connect(slot_type const & slot) const
179 {
180         return pimpl_->statusChanged.connect(slot);
181 }
182
183
184 //------------------------------
185 // Implementation details follow
186 //------------------------------
187
188
189 CacheItem::Impl::Impl(string const & file)
190         : filename_(file),
191           monitor_(file, 2000),
192           zipped_(false),
193           remove_loaded_file_(false),
194           status_(WaitingToLoad)
195 {
196         monitor_.connect(boost::bind(&Impl::startLoading, this));
197 }
198
199
200 void CacheItem::Impl::startLoading()
201 {
202         if (status_ != WaitingToLoad)
203                 reset();
204
205         convertToDisplayFormat();
206 }
207
208
209 void CacheItem::Impl::reset()
210 {
211         zipped_ = false;
212         if (!unzipped_filename_.empty())
213                 unlink(unzipped_filename_);
214         unzipped_filename_.erase();
215
216         if (remove_loaded_file_ && !file_to_load_.empty())
217                 unlink(file_to_load_);
218         remove_loaded_file_ = false;
219         file_to_load_.erase();
220
221         if (image_.get())
222                 image_.reset();
223
224         status_ = WaitingToLoad;
225
226         if (cl_.connected())
227                 cl_.disconnect();
228
229         if (cc_.connected())
230                 cc_.disconnect();
231
232         if (converter_.get())
233                 converter_.reset();
234 }
235
236
237 void CacheItem::Impl::setStatus(ImageStatus new_status)
238 {
239         if (status_ == new_status)
240                 return;
241
242         status_ = new_status;
243         statusChanged();
244 }
245
246
247 void CacheItem::Impl::imageConverted(bool success)
248 {
249         string const text = success ? "succeeded" : "failed";
250         lyxerr[Debug::GRAPHICS] << "Image conversion " << text << '.' << endl;
251
252         file_to_load_ = converter_.get() ?
253                 converter_->convertedFile() : string();
254         converter_.reset();
255         cc_.disconnect();
256
257         success = !file_to_load_.empty() && IsFileReadable(file_to_load_);
258
259         if (!success) {
260                 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
261                                         << endl;
262                 setStatus(ErrorConverting);
263
264                 if (zipped_)
265                         unlink(unzipped_filename_);
266
267                 return;
268         }
269
270         loadImage();
271 }
272
273
274 // This function gets called from the callback after the image has been
275 // converted successfully.
276 void CacheItem::Impl::loadImage()
277 {
278         setStatus(Loading);
279         lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
280
281         image_ = Image::newImage();
282
283         cl_.disconnect();
284         cl_ = image_->finishedLoading.connect(
285                 boost::bind(&Impl::imageLoaded, this, _1));
286         image_->load(file_to_load_);
287 }
288
289
290 void CacheItem::Impl::imageLoaded(bool success)
291 {
292         string const text = success ? "succeeded" : "failed";
293         lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
294
295         // Clean up after loading.
296         if (zipped_)
297                 unlink(unzipped_filename_);
298
299         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
300                 unlink(file_to_load_);
301
302         cl_.disconnect();
303
304         if (!success) {
305                 setStatus(ErrorLoading);
306                 return;
307         }
308
309         // Inform the outside world.
310         setStatus(Loaded);
311 }
312
313
314 } // namespace grfx
315
316
317 namespace {
318
319 string const findTargetFormat(string const & from)
320 {
321         typedef grfx::Image::FormatList FormatList;
322         FormatList const formats = grfx::Image::loadableFormats();
323
324         // There must be a format to load from.
325         Assert(!formats.empty());
326
327         // First ascertain if we can load directly with no conversion
328         FormatList::const_iterator it  = formats.begin();
329         FormatList::const_iterator end = formats.end();
330         for (; it != end; ++it) {
331                 if (from == *it)
332                         return *it;
333         }
334
335         // So, we have to convert to a loadable format. Can we?
336         it = formats.begin();
337         for (; it != end; ++it) {
338                 if (grfx::Converter::isReachable(from, *it))
339                         return *it;
340                 else
341                         lyxerr[Debug::GRAPHICS]
342                                 << "Unable to convert from " << from
343                                 << " to " << *it << std::endl;
344         }
345
346         // Failed! so we have to try to convert it to PPM format
347         // with the standard converter
348         return string("ppm");
349 }
350
351 } // anon namespace
352
353
354 namespace grfx {
355
356 void CacheItem::Impl::convertToDisplayFormat()
357 {
358         setStatus(Converting);
359
360         // First, check that the file exists!
361         if (!IsFileReadable(filename_)) {
362                 if (status_ != ErrorNoFile) {
363                         setStatus(ErrorNoFile);
364                         lyxerr[Debug::GRAPHICS]
365                                 << "\tThe file is not readable" << endl;
366                 }
367                 return;
368         }
369
370         // Make a local copy in case we unzip it
371         string const filename = zippedFile(filename_) ?
372                 unzipFile(filename_) : filename_;
373         string const displayed_filename = MakeDisplayPath(filename_);
374         lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
375                 << "\tAttempting to convert image file: " << filename
376                 << "\n\twith displayed filename: " << displayed_filename
377                 << endl;
378
379         string from = getExtFromContents(filename);
380         lyxerr[Debug::GRAPHICS]
381                 << "\n\tThe file contains " << from << " format data." << endl;
382         string const to = findTargetFormat(from);
383
384         if (from == to) {
385                 // No conversion needed!
386                 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
387                 file_to_load_ = filename;
388                 loadImage();
389                 return;
390         }
391
392         lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
393         // Take only the filename part of the file, without path or extension.
394         string const temp = ChangeExtension(OnlyFilename(filename), string());
395
396         // Add some stuff to create a uniquely named temporary file.
397         // This file is deleted in loadImage after it is loaded into memory.
398         string const to_file_base = tempName(string(), temp);
399         remove_loaded_file_ = true;
400
401         // Remove the temp file, we only want the name...
402         unlink(to_file_base);
403
404         // Connect a signal to this->imageConverted and pass this signal to
405         // the graphics converter so that we can load the modified file
406         // on completion of the conversion process.
407         converter_.reset(new Converter(filename, to_file_base, from, to));
408         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
409         converter_->startConversion();
410 }
411
412 } // namespace grfx