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