]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.C
* src/LaTeX.C: beautification: use identical user messages
[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 #include "format.h"
21
22 #include "support/filetools.h"
23 #include "support/FileMonitor.h"
24 #include "support/lyxlib.h"
25
26 #include <boost/bind.hpp>
27
28
29 namespace lyx {
30
31 using support::changeExtension;
32 using support::FileMonitor;
33 using support::isFileReadable;
34 using support::makeDisplayPath;
35 using support::onlyFilename;
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 graphics {
46
47 class CacheItem::Impl : public boost::signals::trackable {
48 public:
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::signal<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 static string const findTargetFormat(string const & from)
326 {
327         typedef lyx::graphics::Image::FormatList FormatList;
328         FormatList const formats = lyx::graphics::Image::loadableFormats();
329
330          // There must be a format to load from.
331         BOOST_ASSERT(!formats.empty());
332
333         // Use the standard converter if we don't know the format to load
334         // from.
335         if (from.empty())
336                 return string("ppm");
337
338         // First ascertain if we can load directly with no conversion
339         FormatList::const_iterator it  = formats.begin();
340         FormatList::const_iterator end = formats.end();
341         for (; it != end; ++it) {
342                 if (from == *it)
343                         return *it;
344         }
345
346         // So, we have to convert to a loadable format. Can we?
347         it = formats.begin();
348         for (; it != end; ++it) {
349                 if (lyx::graphics::Converter::isReachable(from, *it))
350                         return *it;
351                 else
352                         lyxerr[Debug::GRAPHICS]
353                                 << "Unable to convert from " << from
354                                 << " to " << *it << std::endl;
355         }
356
357         // Failed! so we have to try to convert it to PPM format
358         // with the standard converter
359         return string("ppm");
360 }
361
362
363 void CacheItem::Impl::convertToDisplayFormat()
364 {
365         setStatus(Converting);
366
367         // First, check that the file exists!
368         if (!isFileReadable(filename_)) {
369                 if (status_ != ErrorNoFile) {
370                         setStatus(ErrorNoFile);
371                         lyxerr[Debug::GRAPHICS]
372                                 << "\tThe file is not readable" << endl;
373                 }
374                 return;
375         }
376
377         // Make a local copy in case we unzip it
378         string filename;
379         zipped_ = zippedFile(filename_);
380         if (zipped_) {
381                 unzipped_filename_ = tempName(string(), filename_);
382                 if (unzipped_filename_.empty()) {
383                         setStatus(ErrorConverting);
384                         lyxerr[Debug::GRAPHICS]
385                                 << "\tCould not create temporary file." << endl;
386                         return;
387                 }
388                 filename = unzipFile(filename_, unzipped_filename_);
389         } else
390                 filename = filename_;
391
392         docstring const displayed_filename = makeDisplayPath(filename_);
393         lyxerr[Debug::GRAPHICS] << "[GrahicsCacheItem::convertToDisplayFormat]\n"
394                 << "\tAttempting to convert image file: " << filename
395                 << "\n\twith displayed filename: " << lyx::to_utf8(displayed_filename)
396                 << endl;
397
398         string const from = formats.getFormatFromFile(filename);
399         if (from.empty()) {
400                 setStatus(ErrorConverting);
401                 lyxerr[Debug::GRAPHICS]
402                         << "\tCould not determine file format." << endl;
403         }
404         lyxerr[Debug::GRAPHICS]
405                 << "\n\tThe file contains " << from << " format data." << endl;
406         string const to = findTargetFormat(from);
407
408         if (from == to) {
409                 // No conversion needed!
410                 lyxerr[Debug::GRAPHICS] << "\tNo conversion needed (from == to)!" << endl;
411                 file_to_load_ = filename;
412                 loadImage();
413                 return;
414         }
415
416         lyxerr[Debug::GRAPHICS] << "\tConverting it to " << to << " format." << endl;
417
418         // Add some stuff to create a uniquely named temporary file.
419         // This file is deleted in loadImage after it is loaded into memory.
420         string const to_file_base = tempName(string(), "CacheItem");
421         remove_loaded_file_ = true;
422
423         // Remove the temp file, we only want the name...
424         // FIXME: This is unsafe!
425         unlink(to_file_base);
426
427         // Connect a signal to this->imageConverted and pass this signal to
428         // the graphics converter so that we can load the modified file
429         // on completion of the conversion process.
430         converter_.reset(new Converter(filename, to_file_base, from, to));
431         converter_->connect(boost::bind(&Impl::imageConverted, this, _1));
432         converter_->startConversion();
433 }
434
435 } // namespace graphics
436 } // namespace lyx