]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.C
If the graphics loader has a copy c-tor it should have copy assignment that does...
[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
256         if (!success) {
257                 lyxerr[Debug::GRAPHICS] << "Unable to find converted file!"
258                                         << endl;
259                 setStatus(ErrorConverting);
260
261                 if (zipped_)
262                         lyx::unlink(unzipped_filename_);
263
264                 return;
265         }
266
267         loadImage();
268 }
269
270
271 // This function gets called from the callback after the image has been
272 // converted successfully.
273 void CacheItem::Impl::loadImage()
274 {
275         setStatus(Loading);
276         lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
277
278         image_ = Image::newImage();
279
280         cl_.disconnect();
281         cl_ = image_->finishedLoading.connect(
282                 boost::bind(&Impl::imageLoaded, this, _1));
283         image_->load(file_to_load_);
284 }
285
286
287 void CacheItem::Impl::imageLoaded(bool success)
288 {
289         string const text = success ? "succeeded" : "failed";
290         lyxerr[Debug::GRAPHICS] << "Image loading " << text << '.' << endl;
291
292         // Clean up after loading.
293         if (zipped_)
294                 lyx::unlink(unzipped_filename_);
295
296         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
297                 lyx::unlink(file_to_load_);
298
299         cl_.disconnect();
300
301         if (!success) {
302                 setStatus(ErrorLoading);
303                 return;
304         }
305
306         // Inform the outside world.
307         setStatus(Loaded);
308 }
309
310
311 } // namespace grfx
312
313
314 namespace {
315
316 string const findTargetFormat(string const & from)
317 {
318         typedef grfx::Image::FormatList FormatList;
319         FormatList const formats = grfx::Image::loadableFormats();
320
321         // There must be a format to load from.
322         lyx::Assert(!formats.empty());
323
324         // First ascertain if we can load directly with no conversion
325         FormatList::const_iterator it  = formats.begin();
326         FormatList::const_iterator end = formats.end();
327         for (; it != end; ++it) {
328                 if (from == *it)
329                         return *it;
330         }
331
332         // So, we have to convert to a loadable format. Can we?
333         it = formats.begin();
334         for (; it != end; ++it) {
335                 if (grfx::Converter::isReachable(from, *it))
336                         return *it;
337                 else
338                         lyxerr[Debug::GRAPHICS]
339                                 << "Unable to convert from " << from
340                                 << " to " << *it << std::endl;
341         }
342
343         // Failed! so we have to try to convert it to PPM format
344         // with the standard converter
345         return string("ppm");
346 }
347
348 } // anon namespace
349
350
351 namespace grfx {
352
353 void CacheItem::Impl::convertToDisplayFormat()
354 {
355         setStatus(Converting);
356
357         // First, check that the file exists!
358         if (!IsFileReadable(filename_)) {
359                 if (status_ != ErrorNoFile) {
360                         setStatus(ErrorNoFile);
361                         lyxerr[Debug::GRAPHICS]
362                                 << "\tThe file is not readable" << endl;
363                 }
364                 return;
365         }
366
367         // Make a local copy in case we unzip it
368         string const filename = zippedFile(filename_) ?
369                 unzipFile(filename_) : filename_;
370         string const displayed_filename = MakeDisplayPath(filename_);
371         lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
372                 << "\tAttempting to convert image file: " << filename
373                 << "\n\twith displayed filename: " << displayed_filename
374                 << endl;
375
376         string from = getExtFromContents(filename);
377         lyxerr[Debug::GRAPHICS]
378                 << "\n\tThe file contains " << from << " format data." << endl;
379         string const to = findTargetFormat(from);
380
381         if (from == to) {
382                 // No conversion needed!
383                 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
384                 file_to_load_ = filename;
385                 loadImage();
386                 return;
387         }
388
389         lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
390         // Take only the filename part of the file, without path or extension.
391         string const temp = ChangeExtension(OnlyFilename(filename), string());
392
393         // Add some stuff to create a uniquely named temporary file.
394         // This file is deleted in loadImage after it is loaded into memory.
395         string const to_file_base = lyx::tempName(string(), temp);
396         remove_loaded_file_ = true;
397
398         // Remove the temp file, we only want the name...
399         lyx::unlink(to_file_base);
400
401         // Connect a signal to this->imageConverted and pass this signal to
402         // the graphics converter so that we can load the modified file
403         // on completion of the conversion process.
404         converter_.reset(new Converter(filename, to_file_base, from, to));
405         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
406         converter_->startConversion();
407 }
408
409 } // namespace grfx