1 /*
2  * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
3  * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
4  * Copyright (C) 2008-2009 Torch Mobile, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #ifndef BitmapImage_h
29 #define BitmapImage_h
30 
31 #include "Image.h"
32 #include "Color.h"
33 #include "IntSize.h"
34 
35 #if PLATFORM(MAC)
36 #include <wtf/RetainPtr.h>
37 #ifdef __OBJC__
38 @class NSImage;
39 #else
40 class NSImage;
41 #endif
42 #endif
43 
44 #if PLATFORM(WIN)
45 typedef struct HBITMAP__ *HBITMAP;
46 #endif
47 
48 #if PLATFORM(HAIKU)
49 class BBitmap;
50 #endif
51 
52 namespace WebCore {
53     struct FrameData;
54 }
55 
56 namespace WTF {
57     // FIXME: This declaration gives FrameData a default constructor that zeroes
58     // all its data members, even though FrameData's default constructor defined
59     // below does not zero all its data members. One of these must be wrong!
60     template<> struct VectorTraits<WebCore::FrameData> : public SimpleClassVectorTraits { };
61 }
62 
63 namespace WebCore {
64 
65 template <typename T> class Timer;
66 
67 // ================================================
68 // FrameData Class
69 // ================================================
70 
71 struct FrameData {
72     WTF_MAKE_NONCOPYABLE(FrameData);
73 public:
74     FrameData()
75         : m_frame(0)
76         , m_haveMetadata(false)
77         , m_isComplete(false)
78         , m_duration(0)
79         , m_hasAlpha(true)
80     {
81     }
82 
83     ~FrameData()
84     {
85         clear(true);
86     }
87 
88     // Clear the cached image data on the frame, and (optionally) the metadata.
89     // Returns whether there was cached image data to clear.
90     bool clear(bool clearMetadata);
91 
92     NativeImagePtr m_frame;
93     bool m_haveMetadata;
94     bool m_isComplete;
95     float m_duration;
96     bool m_hasAlpha;
97 };
98 
99 // =================================================
100 // BitmapImage Class
101 // =================================================
102 
103 class BitmapImage : public Image {
104     friend class GeneratedImage;
105     friend class GraphicsContext;
106 public:
107     static PassRefPtr<BitmapImage> create(NativeImagePtr nativeImage, ImageObserver* observer = 0)
108     {
109         return adoptRef(new BitmapImage(nativeImage, observer));
110     }
111     static PassRefPtr<BitmapImage> create(ImageObserver* observer = 0)
112     {
113         return adoptRef(new BitmapImage(observer));
114     }
115     ~BitmapImage();
116 
117     virtual bool isBitmapImage() const { return true; }
118 
119     virtual bool hasSingleSecurityOrigin() const { return true; }
120 
121     virtual IntSize size() const;
122     IntSize currentFrameSize() const;
123     virtual bool getHotSpot(IntPoint&) const;
124 
125     virtual bool dataChanged(bool allDataReceived);
126     virtual String filenameExtension() const;
127 
128     // It may look unusual that there is no start animation call as public API.  This is because
129     // we start and stop animating lazily.  Animation begins whenever someone draws the image.  It will
130     // automatically pause once all observers no longer want to render the image anywhere.
131     virtual void stopAnimation();
132     virtual void resetAnimation();
133 
134     virtual unsigned decodedSize() const { return m_decodedSize; }
135 
136 #if PLATFORM(MAC)
137     // Accessors for native image formats.
138     virtual NSImage* getNSImage();
139     virtual CFDataRef getTIFFRepresentation();
140 #endif
141 
142 #if USE(CG)
143     virtual CGImageRef getCGImageRef();
144     virtual CGImageRef getFirstCGImageRefOfSize(const IntSize&);
145     virtual RetainPtr<CFArrayRef> getCGImageArray();
146 #endif
147 
148 #if PLATFORM(WIN) || (PLATFORM(QT) && OS(WINDOWS))
149     static PassRefPtr<BitmapImage> create(HBITMAP);
150 #endif
151 #if PLATFORM(WIN)
152     virtual bool getHBITMAP(HBITMAP);
153     virtual bool getHBITMAPOfSize(HBITMAP, LPSIZE);
154 #endif
155 
156 #if PLATFORM(GTK)
157     virtual GdkPixbuf* getGdkPixbuf();
158 #endif
159 
160     virtual NativeImagePtr nativeImageForCurrentFrame() { return frameAtIndex(currentFrame()); }
161     bool frameHasAlphaAtIndex(size_t);
162 
163 #if !ASSERT_DISABLED
164     bool notSolidColor()
165     {
166         return size().width() != 1 || size().height() != 1 || frameCount() > 1;
167     }
168 #endif
169 
170 protected:
171     enum RepetitionCountStatus {
172       Unknown,    // We haven't checked the source's repetition count.
173       Uncertain,  // We have a repetition count, but it might be wrong (some GIFs have a count after the image data, and will report "loop once" until all data has been decoded).
174       Certain     // The repetition count is known to be correct.
175     };
176 
177     BitmapImage(NativeImagePtr, ImageObserver* = 0);
178     BitmapImage(ImageObserver* = 0);
179 
180 #if PLATFORM(WIN)
181     virtual void drawFrameMatchingSourceSize(GraphicsContext*, const FloatRect& dstRect, const IntSize& srcSize, ColorSpace styleColorSpace, CompositeOperator);
182 #endif
183     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator);
184 
185 #if (OS(WINCE) && !PLATFORM(QT))
186     virtual void drawPattern(GraphicsContext*, const FloatRect& srcRect, const AffineTransform& patternTransform,
187                              const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator, const FloatRect& destRect);
188 #endif
189 
190 #if PLATFORM(HAIKU)
191     virtual BBitmap* getBBitmap() const;
192 #endif
193 
194     size_t currentFrame() const { return m_currentFrame; }
195     size_t frameCount();
196     NativeImagePtr frameAtIndex(size_t);
197     bool frameIsCompleteAtIndex(size_t);
198     float frameDurationAtIndex(size_t);
199 
200     // Decodes and caches a frame. Never accessed except internally.
201     void cacheFrame(size_t index);
202 
203     // Called to invalidate cached data.  When |destroyAll| is true, we wipe out
204     // the entire frame buffer cache and tell the image source to destroy
205     // everything; this is used when e.g. we want to free some room in the image
206     // cache.  If |destroyAll| is false, we only delete frames up to the current
207     // one; this is used while animating large images to keep memory footprint
208     // low without redecoding the whole image on every frame.
209     virtual void destroyDecodedData(bool destroyAll = true);
210 
211     // If the image is large enough, calls destroyDecodedData() and passes
212     // |destroyAll| along.
213     void destroyDecodedDataIfNecessary(bool destroyAll);
214 
215     // Generally called by destroyDecodedData(), destroys whole-image metadata
216     // and notifies observers that the memory footprint has (hopefully)
217     // decreased by |framesCleared| times the size (in bytes) of a frame.
218     void destroyMetadataAndNotify(int framesCleared);
219 
220     // Whether or not size is available yet.
221     bool isSizeAvailable();
222 
223     // Called after asking the source for any information that may require
224     // decoding part of the image (e.g., the image size).  We need to report
225     // the partially decoded data to our observer so it has an accurate
226     // account of the BitmapImage's memory usage.
227     void didDecodeProperties() const;
228 
229     // Animation.
230     int repetitionCount(bool imageKnownToBeComplete);  // |imageKnownToBeComplete| should be set if the caller knows the entire image has been decoded.
231     bool shouldAnimate();
232     virtual void startAnimation(bool catchUpIfNecessary = true);
233     void advanceAnimation(Timer<BitmapImage>*);
234 
235     // Function that does the real work of advancing the animation.  When
236     // skippingFrames is true, we're in the middle of a loop trying to skip over
237     // a bunch of animation frames, so we should not do things like decode each
238     // one or notify our observers.
239     // Returns whether the animation was advanced.
240     bool internalAdvanceAnimation(bool skippingFrames);
241 
242     // Handle platform-specific data
243     void initPlatformData();
244     void invalidatePlatformData();
245 
246     // Checks to see if the image is a 1x1 solid color.  We optimize these images and just do a fill rect instead.
247     // This check should happen regardless whether m_checkedForSolidColor is already set, as the frame may have
248     // changed.
249     void checkForSolidColor();
250 
251     virtual bool mayFillWithSolidColor()
252     {
253         if (!m_checkedForSolidColor && frameCount() > 0) {
254             checkForSolidColor();
255             // WINCE PORT: checkForSolidColor() doesn't set m_checkedForSolidColor until
256             // it gets enough information to make final decision.
257 #if !OS(WINCE)
258             ASSERT(m_checkedForSolidColor);
259 #endif
260         }
261         return m_isSolidColor && m_currentFrame == 0;
262     }
263     virtual Color solidColor() const { return m_solidColor; }
264 
265     ImageSource m_source;
266     mutable IntSize m_size; // The size to use for the overall image (will just be the size of the first image).
267 
268     size_t m_currentFrame; // The index of the current frame of animation.
269     Vector<FrameData> m_frames; // An array of the cached frames of the animation. We have to ref frames to pin them in the cache.
270 
271     Timer<BitmapImage>* m_frameTimer;
272     int m_repetitionCount; // How many total animation loops we should do.  This will be cAnimationNone if this image type is incapable of animation.
273     RepetitionCountStatus m_repetitionCountStatus;
274     int m_repetitionsComplete;  // How many repetitions we've finished.
275     double m_desiredFrameStartTime;  // The system time at which we hope to see the next call to startAnimation().
276 
277 #if PLATFORM(MAC)
278     mutable RetainPtr<NSImage> m_nsImage; // A cached NSImage of frame 0. Only built lazily if someone actually queries for one.
279     mutable RetainPtr<CFDataRef> m_tiffRep; // Cached TIFF rep for frame 0.  Only built lazily if someone queries for one.
280 #endif
281 
282     Color m_solidColor;  // If we're a 1x1 solid color, this is the color to use to fill.
283     bool m_isSolidColor;  // Whether or not we are a 1x1 solid image.
284     bool m_checkedForSolidColor; // Whether we've checked the frame for solid color.
285 
286     bool m_animationFinished;  // Whether or not we've completed the entire animation.
287 
288     bool m_allDataReceived;  // Whether or not we've received all our data.
289 
290     mutable bool m_haveSize; // Whether or not our |m_size| member variable has the final overall image size yet.
291     bool m_sizeAvailable; // Whether or not we can obtain the size of the first image frame yet from ImageIO.
292     mutable bool m_hasUniformFrameSize;
293 
294     unsigned m_decodedSize; // The current size of all decoded frames.
295     mutable unsigned m_decodedPropertiesSize; // The size of data decoded by the source to determine image properties (e.g. size, frame count, etc).
296 
297     mutable bool m_haveFrameCount;
298     size_t m_frameCount;
299 };
300 
301 }
302 
303 #endif
304