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