]> git.lyx.org Git - lyx.git/blob - src/graphics/GraphicsCacheItem.cpp
Update tex2lyx files to new format
[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         ActiveFileMonitorPtr 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 void CacheItem::checkModifiedAsync() const
183 {
184         if (!pimpl_->monitor_)
185                 return;
186         pimpl_->monitor_->checkModifiedAsync();
187 }
188
189
190 Image const * CacheItem::image() const
191 {
192         return pimpl_->image_.get();
193 }
194
195
196 ImageStatus CacheItem::status() const
197 {
198         return pimpl_->status_;
199 }
200
201
202 boost::signals2::connection CacheItem::connect(slot_type const & slot) const
203 {
204         return pimpl_->statusChanged.connect(slot);
205 }
206
207
208 //------------------------------
209 // Implementation details follow
210 //------------------------------
211
212
213 CacheItem::Impl::Impl(FileName const & file, FileName const & doc_file)
214         : filename_(file), doc_file_(doc_file),
215           zipped_(false),
216           remove_loaded_file_(false),
217           status_(WaitingToLoad)
218 {}
219
220
221 void CacheItem::Impl::startMonitor()
222 {
223         if (monitor_)
224                 return;
225         monitor_ = FileSystemWatcher::activeMonitor(filename_);
226         monitor_->connect([=](){ startLoading(); });
227 }
228
229
230 void CacheItem::Impl::startLoading()
231 {
232         if (status_ != WaitingToLoad)
233                 reset();
234
235         convertToDisplayFormat();
236 }
237
238
239 void CacheItem::Impl::reset()
240 {
241         zipped_ = false;
242         if (!unzipped_filename_.empty())
243                 unzipped_filename_.removeFile();
244         unzipped_filename_.erase();
245
246         if (remove_loaded_file_ && !file_to_load_.empty())
247                 file_to_load_.removeFile();
248         remove_loaded_file_ = false;
249         file_to_load_.erase();
250         to_.erase();
251
252         if (image_)
253                 image_.reset();
254
255         status_ = WaitingToLoad;
256
257         if (cc_.connected())
258                 cc_.disconnect();
259
260         if (converter_)
261                 converter_.reset();
262 }
263
264
265 void CacheItem::Impl::setStatus(ImageStatus new_status)
266 {
267         if (status_ == new_status)
268                 return;
269
270         status_ = new_status;
271         statusChanged();
272 }
273
274
275 void CacheItem::Impl::imageConverted(bool success)
276 {
277         string const text = success ? "succeeded" : "failed";
278         LYXERR(Debug::GRAPHICS, "Image conversion " << text << '.');
279
280         file_to_load_ = converter_ ? FileName(converter_->convertedFile())
281                                        : FileName();
282         converter_.reset();
283         cc_.disconnect();
284
285         success = !file_to_load_.empty() && file_to_load_.isReadableFile();
286
287         if (!success) {
288                 LYXERR(Debug::GRAPHICS, "Unable to find converted file!");
289                 setStatus(ErrorConverting);
290
291                 if (zipped_)
292                         unzipped_filename_.removeFile();
293
294                 return;
295         }
296
297         // Add the converted file to the file cache
298         ConverterCache::get().add(filename_, to_, file_to_load_);
299
300         setStatus(loadImage() ? Loaded : ErrorLoading);
301 }
302
303
304 // This function gets called from the callback after the image has been
305 // converted successfully.
306 bool CacheItem::Impl::loadImage()
307 {
308         LYXERR(Debug::GRAPHICS, "Loading image.");
309
310         image_.reset(newImage());
311
312         bool success = image_->load(file_to_load_);
313         string const text = success ? "succeeded" : "failed";
314         LYXERR(Debug::GRAPHICS, "Image loading " << text << '.');
315
316         // Clean up after loading.
317         if (zipped_)
318                 unzipped_filename_.removeFile();
319
320         if (remove_loaded_file_ && unzipped_filename_ != file_to_load_)
321                 file_to_load_.removeFile();
322
323         return success;
324 }
325
326
327 typedef vector<string> FormatList;
328
329 static string const findTargetFormat(FormatList const & format_list, string const & from)
330 {
331          // There must be a format to load from.
332         LASSERT(!theFormats().empty(), return string());
333
334         // Use the standard converter if we don't know the format to load
335         // from.
336         if (from.empty())
337                 return string("ppm");
338
339         // First ascertain if we can load directly with no conversion
340         FormatList::const_iterator it  = format_list.begin();
341         FormatList::const_iterator end = format_list.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 = format_list.begin();
349         for (; it != end; ++it) {
350                 if (lyx::graphics::Converter::isReachable(from, *it))
351                         return *it;
352                 else
353                         LYXERR(Debug::GRAPHICS, "Unable to convert from " << from
354                                 << " to " << *it);
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 bool CacheItem::Impl::tryDisplayFormat(FileName & filename, string & from)
364 {
365         // First, check that the file exists!
366         filename_.refresh();
367         if (!filename_.isReadableFile()) {
368                 if (status_ != ErrorNoFile) {
369                         status_ = ErrorNoFile;
370                         LYXERR(Debug::GRAPHICS, "\tThe file is not readable");
371                 }
372                 return false;
373         }
374
375         zipped_ = theFormats().isZippedFile(filename_);
376         if (zipped_) {
377                 string tempname = unzippedFileName(filename_.toFilesystemEncoding());
378                 string const ext = getExtension(tempname);
379                 tempname = changeExtension(tempname, "") + "-XXXXXX";
380                 if (!ext.empty())
381                         tempname = addExtension(tempname, ext);
382                 TempFile tempfile(tempname);
383                 tempfile.setAutoRemove(false);
384                 unzipped_filename_ = tempfile.name();
385                 if (unzipped_filename_.empty()) {
386                         status_ = ErrorConverting;
387                         LYXERR(Debug::GRAPHICS, "\tCould not create temporary file.");
388                         return false;
389                 }
390                 filename = unzipFile(filename_, unzipped_filename_.toFilesystemEncoding());
391         } else {
392                 filename = filename_;
393         }
394
395         docstring const displayed_filename = makeDisplayPath(filename_.absFileName());
396         LYXERR(Debug::GRAPHICS, "[CacheItem::Impl::convertToDisplayFormat]\n"
397                 << "\tAttempting to convert image file: " << filename
398                 << "\n\twith displayed filename: " << to_utf8(displayed_filename));
399
400         from = theFormats().getFormatFromFile(filename);
401         if (from.empty()) {
402                 status_ = ErrorConverting;
403                 LYXERR(Debug::GRAPHICS, "\tCould not determine file format.");
404         }
405         LYXERR(Debug::GRAPHICS, "\n\tThe file contains " << from << " format data.");
406         to_ = findTargetFormat(Cache::get().loadableFormats(), from);
407
408         if (from == to_) {
409                 // No conversion needed!
410                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (from == to)!");
411                 file_to_load_ = filename;
412                 status_ = loadImage() ? Loaded : ErrorLoading;
413                 return false;
414         }
415
416         if (ConverterCache::get().inCache(filename, to_)) {
417                 LYXERR(Debug::GRAPHICS, "\tNo conversion needed (file in file cache)!");
418                 file_to_load_ = ConverterCache::get().cacheName(filename, to_);
419                 status_ = loadImage() ? Loaded : ErrorLoading;
420                 return false;
421         }
422         return true;
423 }
424
425
426 void CacheItem::Impl::convertToDisplayFormat()
427 {
428         LYXERR(Debug::GRAPHICS, "\tConverting it to " << to_ << " format.");
429
430         // Make a local copy in case we unzip it
431         FileName filename;
432         string from;
433         if (!tryDisplayFormat(filename, from)) {
434                 // The image status has changed, tell it to the outside world.
435                 statusChanged();
436                 return;
437         }
438
439         // We will need a conversion, tell it to the outside world.
440         setStatus(Converting);
441
442         // Add some stuff to create a uniquely named temporary file.
443         // This file is deleted in loadImage after it is loaded into memory.
444         TempFile tempfile("CacheItem");
445         tempfile.setAutoRemove(false);
446         FileName const to_file_base = tempfile.name();
447         remove_loaded_file_ = true;
448
449         // Connect a signal to this->imageConverted and pass this signal to
450         // the graphics converter so that we can load the modified file
451         // on completion of the conversion process.
452         converter_ = make_unique<Converter>(doc_file_, filename, to_file_base.absFileName(),
453                                             from, to_);
454         converter_->connect(bind(&Impl::imageConverted, this, _1));
455         converter_->startConversion();
456 }
457
458 } // namespace graphics
459 } // namespace lyx