]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.C
Really dull and boring header shit
[lyx.git] / src / graphics / GraphicsCacheItem.C
1 /**
2  * \file GraphicsCacheItem.C
3  * Read the file COPYING
4  *
5  * \author Baruch Even 
6  * \author Herbert Voss 
7  * \author Angus Leeming 
8  *
9  * Full author contact details are available in file CREDITS
10  */
11
12 #include <config.h>
13
14 #ifdef __GNUG__
15 #pragma implementation
16 #endif
17
18 #include "GraphicsCacheItem.h"
19 #include "GraphicsImage.h"
20 #include "GraphicsConverter.h"
21
22 #include "support/FileMonitor.h"
23
24 #include "debug.h"
25
26 #include "support/LAssert.h"
27 #include "support/filetools.h"
28
29 #include <boost/shared_ptr.hpp>
30 #include <boost/bind.hpp>
31 #include <boost/signals/trackable.hpp>
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                 lyx::unlink(unzipped_filename_);
214         unzipped_filename_.erase();
215
216         if (remove_loaded_file_ && !file_to_load_.empty())
217                 lyx::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         lyxerr[Debug::GRAPHICS] << "Unable to find converted file!" << endl;
259
260         if (!success) {
261                 setStatus(ErrorConverting);
262
263                 if (zipped_)
264                         lyx::unlink(unzipped_filename_);
265
266                 return;
267         }
268
269         loadImage();
270 }
271
272
273 // This function gets called from the callback after the image has been
274 // converted successfully.
275 void CacheItem::Impl::loadImage()
276 {
277         setStatus(Loading);
278         lyxerr[Debug::GRAPHICS] << "Loading image." << endl;
279
280         image_ = Image::newImage();
281
282         cl_.disconnect();
283         cl_ = image_->finishedLoading.connect(
284                 boost::bind(&Impl::imageLoaded, this, _1));
285         image_->load(file_to_load_);
286 }
287
288
289 void CacheItem::Impl::imageLoaded(bool success)
290 {
291         string const text = success ? "succeeded" : "failed";
292         lyxerr[Debug::GRAPHICS] << "Image loading " << text << "." << endl;
293
294         // Clean up after loading.
295         if (zipped_)
296                 lyx::unlink(unzipped_filename_);
297
298         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
299                 lyx::unlink(file_to_load_);
300
301         cl_.disconnect();
302
303         if (!success) {
304                 setStatus(ErrorLoading);
305                 return;
306         }
307
308         // Inform the outside world.
309         setStatus(Loaded);
310 }
311
312
313 } // namespace grfx
314
315
316 namespace {
317
318 string const findTargetFormat(string const & from)
319 {
320         typedef grfx::Image::FormatList FormatList;
321         FormatList const formats = grfx::Image::loadableFormats();
322
323         // There must be a format to load from.
324         lyx::Assert(!formats.empty());
325
326         // First ascertain if we can load directly with no conversion
327         FormatList::const_iterator it1 = formats.begin();
328         FormatList::const_iterator end = formats.end();
329         for (; it1 != end; ++it1) {
330                 if (from == *it1)
331                         return *it1;
332         }
333
334         // So, we have to convert to a loadable format. Can we?
335         FormatList::const_iterator it2 = formats.begin();
336         for (; it2 != end; ++it2) {
337                 if (grfx::Converter::isReachable(from, *it2))
338                         return *it2;
339         }
340
341         // Failed! so we have to try to convert it to XPM format
342         // with the standard converter
343         return string("xpm");
344 }
345
346 } // anon namespace
347
348
349 namespace grfx {
350
351 void CacheItem::Impl::convertToDisplayFormat()
352 {
353         setStatus(Converting);
354
355         // First, check that the file exists!
356         if (!IsFileReadable(filename_)) {
357                 if (status_ != ErrorNoFile) {
358                         setStatus(ErrorNoFile);
359                         lyxerr[Debug::GRAPHICS]
360                                 << "\tThe file is not readable" << endl;
361                 }
362                 return;
363         }
364
365         // Make a local copy in case we unzip it
366         string const filename = zippedFile(filename_) ?
367                 unzipFile(filename_) : filename_;
368         string const displayed_filename = MakeDisplayPath(filename_);
369         lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
370                 << "\tAttempting to convert image file: " << filename
371                 << "\n\twith displayed filename: " << displayed_filename
372                 << endl;
373
374         string from = getExtFromContents(filename);
375         lyxerr[Debug::GRAPHICS]
376                 << "\n\tThe file contains " << from << " format data." << endl;
377         string const to = findTargetFormat(from);
378
379         if (from == to) {
380                 // No conversion needed!
381                 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
382                 file_to_load_ = filename;
383                 loadImage();
384                 return;
385         }
386
387         lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
388         // Take only the filename part of the file, without path or extension.
389         string const temp = ChangeExtension(OnlyFilename(filename), string());
390
391         // Add some stuff to create a uniquely named temporary file.
392         // This file is deleted in loadImage after it is loaded into memory.
393         string const to_file_base = lyx::tempName(string(), temp);
394         remove_loaded_file_ = true;
395
396         // Remove the temp file, we only want the name...
397         lyx::unlink(to_file_base);
398
399         // Connect a signal to this->imageConverted and pass this signal to
400         // the graphics converter so that we can load the modified file
401         // on completion of the conversion process.
402         converter_.reset(new Converter(filename, to_file_base, from, to));
403         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
404         converter_->startConversion();
405 }
406
407 } // namespace grfx