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