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