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