• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // This complicated-looking declaration tells the FrameData Vector that it should copy without
57 // invoking our constructor or destructor. This allows us to have a vector even for a struct
58 // that's not copyable.
59 namespace WTF {
60     template<> class 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 : Noncopyable {
FrameDataFrameData72     FrameData()
73         : m_frame(0)
74         , m_haveMetadata(false)
75         , m_isComplete(false)
76         , m_duration(0)
77         , m_hasAlpha(true)
78     {
79     }
80 
~FrameDataFrameData81     ~FrameData()
82     {
83         clear(true);
84     }
85 
86     // Clear the cached image data on the frame, and (optionally) the metadata.
87     // Returns whether there was cached image data to clear.
88     bool clear(bool clearMetadata);
89 
90     NativeImagePtr m_frame;
91     bool m_haveMetadata;
92     bool m_isComplete;
93     float m_duration;
94     bool m_hasAlpha;
95 };
96 
97 // =================================================
98 // BitmapImage Class
99 // =================================================
100 
101 class BitmapImage : public Image {
102     friend class GeneratedImage;
103     friend class GraphicsContext;
104 public:
105     static PassRefPtr<BitmapImage> create(NativeImagePtr nativeImage, ImageObserver* observer = 0)
106     {
107         return adoptRef(new BitmapImage(nativeImage, observer));
108     }
109     static PassRefPtr<BitmapImage> create(ImageObserver* observer = 0)
110     {
111         return adoptRef(new BitmapImage(observer));
112     }
113     ~BitmapImage();
114 
isBitmapImage()115     virtual bool isBitmapImage() const { return true; }
116 
hasSingleSecurityOrigin()117     virtual bool hasSingleSecurityOrigin() const { return true; }
118 
119     virtual IntSize size() const;
120     IntSize currentFrameSize() const;
121 
122     virtual bool dataChanged(bool allDataReceived);
123     virtual String filenameExtension() const;
124 
125     // It may look unusual that there is no start animation call as public API.  This is because
126     // we start and stop animating lazily.  Animation begins whenever someone draws the image.  It will
127     // automatically pause once all observers no longer want to render the image anywhere.
128     virtual void stopAnimation();
129     virtual void resetAnimation();
130 
decodedSize()131     virtual unsigned decodedSize() const { return m_decodedSize; }
132 
133 #if PLATFORM(MAC)
134     // Accessors for native image formats.
135     virtual NSImage* getNSImage();
136     virtual CFDataRef getTIFFRepresentation();
137 #endif
138 
139 #if PLATFORM(CG)
140     virtual CGImageRef getCGImageRef();
141 #endif
142 
143 #if PLATFORM(WIN) || (PLATFORM(QT) && OS(WINDOWS))
144     static PassRefPtr<BitmapImage> create(HBITMAP);
145 #endif
146 #if PLATFORM(WIN)
147     virtual bool getHBITMAP(HBITMAP);
148     virtual bool getHBITMAPOfSize(HBITMAP, LPSIZE);
149 #endif
150 
151 #if PLATFORM(ANDROID)
152     virtual void setURL(const String& str);
153 #endif
154 
155 #if PLATFORM(GTK)
156     virtual GdkPixbuf* getGdkPixbuf();
157 #endif
158 
nativeImageForCurrentFrame()159     virtual NativeImagePtr nativeImageForCurrentFrame() { return frameAtIndex(currentFrame()); }
160 
161 protected:
162     enum RepetitionCountStatus {
163       Unknown,    // We haven't checked the source's repetition count.
164       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).
165       Certain,    // The repetition count is known to be correct.
166     };
167 
168     BitmapImage(NativeImagePtr, ImageObserver* = 0);
169     BitmapImage(ImageObserver* = 0);
170 
171 #if PLATFORM(WIN)
172     virtual void drawFrameMatchingSourceSize(GraphicsContext*, const FloatRect& dstRect, const IntSize& srcSize, ColorSpace styleColorSpace, CompositeOperator);
173 #endif
174     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator);
175 
176 #if (OS(WINCE) && !PLATFORM(QT))
177     virtual void drawPattern(GraphicsContext*, const FloatRect& srcRect, const TransformationMatrix& patternTransform,
178                              const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator, const FloatRect& destRect);
179 #endif
180 
181 #if PLATFORM(HAIKU)
182     virtual BBitmap* getBBitmap() const;
183 #endif
184 
currentFrame()185     size_t currentFrame() const { return m_currentFrame; }
186     size_t frameCount();
187     NativeImagePtr frameAtIndex(size_t);
188     bool frameIsCompleteAtIndex(size_t);
189     float frameDurationAtIndex(size_t);
190     bool frameHasAlphaAtIndex(size_t);
191 
192     // Decodes and caches a frame. Never accessed except internally.
193     void cacheFrame(size_t index);
194 
195     // Called to invalidate cached data.  When |destroyAll| is true, we wipe out
196     // the entire frame buffer cache and tell the image source to destroy
197     // everything; this is used when e.g. we want to free some room in the image
198     // cache.  If |destroyAll| is false, we only delete frames up to the current
199     // one; this is used while animating large images to keep memory footprint
200     // low without redecoding the whole image on every frame.
201     virtual void destroyDecodedData(bool destroyAll = true);
202 
203     // If the image is large enough, calls destroyDecodedData() and passes
204     // |destroyAll| along.
205     void destroyDecodedDataIfNecessary(bool destroyAll);
206 
207     // Generally called by destroyDecodedData(), destroys whole-image metadata
208     // and notifies observers that the memory footprint has (hopefully)
209     // decreased by |framesCleared| times the size (in bytes) of a frame.
210     void destroyMetadataAndNotify(int framesCleared);
211 
212     // Whether or not size is available yet.
213     bool isSizeAvailable();
214 
215     // Animation.
216     int repetitionCount(bool imageKnownToBeComplete);  // |imageKnownToBeComplete| should be set if the caller knows the entire image has been decoded.
217     bool shouldAnimate();
218     virtual void startAnimation(bool catchUpIfNecessary = true);
219     void advanceAnimation(Timer<BitmapImage>*);
220 
221     // Function that does the real work of advancing the animation.  When
222     // skippingFrames is true, we're in the middle of a loop trying to skip over
223     // a bunch of animation frames, so we should not do things like decode each
224     // one or notify our observers.
225     // Returns whether the animation was advanced.
226     bool internalAdvanceAnimation(bool skippingFrames);
227 
228     // Handle platform-specific data
229     void initPlatformData();
230     void invalidatePlatformData();
231 
232     // Checks to see if the image is a 1x1 solid color.  We optimize these images and just do a fill rect instead.
233     // This check should happen regardless whether m_checkedForSolidColor is already set, as the frame may have
234     // changed.
235     void checkForSolidColor();
236 
mayFillWithSolidColor()237     virtual bool mayFillWithSolidColor()
238     {
239         if (!m_checkedForSolidColor && frameCount() > 0) {
240             checkForSolidColor();
241             // WINCE PORT: checkForSolidColor() doesn't set m_checkedForSolidColor until
242             // it gets enough information to make final decision.
243 #if !OS(WINCE)
244             ASSERT(m_checkedForSolidColor);
245 #endif
246         }
247         return m_isSolidColor && m_currentFrame == 0;
248     }
solidColor()249     virtual Color solidColor() const { return m_solidColor; }
250 
251     ImageSource m_source;
252     mutable IntSize m_size; // The size to use for the overall image (will just be the size of the first image).
253 
254     size_t m_currentFrame; // The index of the current frame of animation.
255     Vector<FrameData> m_frames; // An array of the cached frames of the animation. We have to ref frames to pin them in the cache.
256 
257     Timer<BitmapImage>* m_frameTimer;
258     int m_repetitionCount; // How many total animation loops we should do.  This will be cAnimationNone if this image type is incapable of animation.
259     RepetitionCountStatus m_repetitionCountStatus;
260     int m_repetitionsComplete;  // How many repetitions we've finished.
261     double m_desiredFrameStartTime;  // The system time at which we hope to see the next call to startAnimation().
262 
263 #if PLATFORM(MAC)
264     mutable RetainPtr<NSImage> m_nsImage; // A cached NSImage of frame 0. Only built lazily if someone actually queries for one.
265     mutable RetainPtr<CFDataRef> m_tiffRep; // Cached TIFF rep for frame 0.  Only built lazily if someone queries for one.
266 #endif
267 
268     Color m_solidColor;  // If we're a 1x1 solid color, this is the color to use to fill.
269     bool m_isSolidColor;  // Whether or not we are a 1x1 solid image.
270     bool m_checkedForSolidColor; // Whether we've checked the frame for solid color.
271 
272     bool m_animationFinished;  // Whether or not we've completed the entire animation.
273 
274     bool m_allDataReceived;  // Whether or not we've received all our data.
275 
276     mutable bool m_haveSize; // Whether or not our |m_size| member variable has the final overall image size yet.
277     bool m_sizeAvailable; // Whether or not we can obtain the size of the first image frame yet from ImageIO.
278     mutable bool m_hasUniformFrameSize;
279 
280     unsigned m_decodedSize; // The current size of all decoded frames.
281 
282     mutable bool m_haveFrameCount;
283     size_t m_frameCount;
284 };
285 
286 }
287 
288 #endif
289