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