initial import
[vuplus_webkit] / Source / WebCore / platform / graphics / cg / ImageCG.cpp
1 /*
2  * Copyright (C) 2004, 2005, 2006 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "BitmapImage.h"
28
29 #if USE(CG)
30
31 #include "AffineTransform.h"
32 #include "FloatConversion.h"
33 #include "FloatRect.h"
34 #include "GraphicsContextCG.h"
35 #include "ImageObserver.h"
36 #include "PDFDocumentImage.h"
37 #include "PlatformString.h"
38 #include <ApplicationServices/ApplicationServices.h>
39 #include <CoreFoundation/CFArray.h>
40 #include <wtf/RetainPtr.h>
41
42 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
43 #include "WebCoreSystemInterface.h"
44 #endif
45
46 #if PLATFORM(WIN)
47 #include <WebKitSystemInterface/WebKitSystemInterface.h>
48 #endif
49
50 namespace WebCore {
51
52 bool FrameData::clear(bool clearMetadata)
53 {
54     if (clearMetadata)
55         m_haveMetadata = false;
56
57     if (m_frame) {
58         CGImageRelease(m_frame);
59         m_frame = 0;
60         return true;
61     }
62     return false;
63 }
64
65 // ================================================
66 // Image Class
67 // ================================================
68
69 BitmapImage::BitmapImage(CGImageRef cgImage, ImageObserver* observer)
70     : Image(observer)
71     , m_currentFrame(0)
72     , m_frames(0)
73     , m_frameTimer(0)
74     , m_repetitionCount(cAnimationNone)
75     , m_repetitionCountStatus(Unknown)
76     , m_repetitionsComplete(0)
77     , m_isSolidColor(false)
78     , m_checkedForSolidColor(false)
79     , m_animationFinished(true)
80     , m_allDataReceived(true)
81     , m_haveSize(true)
82     , m_sizeAvailable(true)
83     , m_decodedSize(0)
84     , m_haveFrameCount(true)
85     , m_frameCount(1)
86 {
87     initPlatformData();
88     
89     CGFloat width = CGImageGetWidth(cgImage);
90     CGFloat height = CGImageGetHeight(cgImage);
91     m_decodedSize = width * height * 4;
92     m_size = IntSize(width, height);
93
94     m_frames.grow(1);
95     m_frames[0].m_frame = cgImage;
96     m_frames[0].m_hasAlpha = true;
97     m_frames[0].m_haveMetadata = true;
98     checkForSolidColor();
99 }
100
101 // Drawing Routines
102
103 void BitmapImage::checkForSolidColor()
104 {
105     m_checkedForSolidColor = true;
106     if (frameCount() > 1) {
107         m_isSolidColor = false;
108         return;
109     }
110
111     CGImageRef image = frameAtIndex(0);
112     
113     // Currently we only check for solid color in the important special case of a 1x1 image.
114     if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
115         unsigned char pixel[4]; // RGBA
116         RetainPtr<CGContextRef> bmap(AdoptCF, CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), deviceRGBColorSpaceRef(),
117             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big));
118         if (!bmap)
119             return;
120         GraphicsContext(bmap.get()).setCompositeOperation(CompositeCopy);
121         CGRect dst = { {0, 0}, {1, 1} };
122         CGContextDrawImage(bmap.get(), dst, image);
123         if (pixel[3] == 0)
124             m_solidColor = Color(0, 0, 0, 0);
125         else
126             m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);
127         m_isSolidColor = true;
128     }
129 }
130
131 RetainPtr<CGImageRef> Image::imageWithColorSpace(CGImageRef originalImage, ColorSpace colorSpace)
132 {
133     CGColorSpaceRef originalColorSpace = CGImageGetColorSpace(originalImage);
134
135     // If the image already has a (non-device) color space, we don't want to
136     // override it, so return.
137     if (!originalColorSpace || !CFEqual(originalColorSpace, deviceRGBColorSpaceRef()))
138         return originalImage;
139
140     switch (colorSpace) {
141     case ColorSpaceDeviceRGB:
142         return originalImage;
143     case ColorSpaceSRGB:
144         return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, sRGBColorSpaceRef()));
145     case ColorSpaceLinearRGB:
146         return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, linearRGBColorSpaceRef()));
147     }
148
149     ASSERT_NOT_REACHED();
150     return originalImage;
151 }
152
153 CGImageRef BitmapImage::getCGImageRef()
154 {
155     return frameAtIndex(0);
156 }
157
158 CGImageRef BitmapImage::getFirstCGImageRefOfSize(const IntSize& size)
159 {
160     size_t count = frameCount();
161     for (size_t i = 0; i < count; ++i) {
162         CGImageRef cgImage = frameAtIndex(i);
163         if (cgImage && IntSize(CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)) == size)
164             return cgImage;
165     }
166
167     // Fallback to the default CGImageRef if we can't find the right size
168     return getCGImageRef();
169 }
170
171 RetainPtr<CFArrayRef> BitmapImage::getCGImageArray()
172 {
173     size_t count = frameCount();
174     if (!count)
175         return 0;
176     
177     CFMutableArrayRef array = CFArrayCreateMutable(NULL, count, &kCFTypeArrayCallBacks);
178     for (size_t i = 0; i < count; ++i) {
179         if (CGImageRef currFrame = frameAtIndex(i))
180             CFArrayAppendValue(array, currFrame);
181     }
182     return RetainPtr<CFArrayRef>(AdoptCF, array);
183 }
184
185 void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator compositeOp)
186 {
187     startAnimation();
188
189     RetainPtr<CGImageRef> image = frameAtIndex(m_currentFrame);
190     if (!image) // If it's too early we won't have an image yet.
191         return;
192     
193     if (mayFillWithSolidColor()) {
194         fillWithSolidColor(ctxt, destRect, solidColor(), styleColorSpace, compositeOp);
195         return;
196     }
197
198     FloatSize selfSize = currentFrameSize();
199
200     ctxt->drawNativeImage(image.get(), selfSize, styleColorSpace, destRect, srcRect, compositeOp);
201
202     if (imageObserver())
203         imageObserver()->didDraw(this);
204 }
205
206 static void drawPatternCallback(void* info, CGContextRef context)
207 {
208     CGImageRef image = (CGImageRef)info;
209     CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image);
210 }
211
212 void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
213                         const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
214 {
215     if (!nativeImageForCurrentFrame())
216         return;
217
218     ASSERT(patternTransform.isInvertible());
219     if (!patternTransform.isInvertible())
220         // Avoid a hang under CGContextDrawTiledImage on release builds.
221         return;
222
223     CGContextRef context = ctxt->platformContext();
224     GraphicsContextStateSaver stateSaver(*ctxt);
225     CGContextClipToRect(context, destRect);
226     ctxt->setCompositeOperation(op);
227     CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height());
228     CGContextScaleCTM(context, 1, -1);
229     
230     // Compute the scaled tile size.
231     float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
232     
233     // We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being
234     // the origin).
235     float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); // We translated the context so that destRect.x() is the origin, so subtract it out.
236     float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);
237
238     CGImageRef tileImage = nativeImageForCurrentFrame();
239     float h = CGImageGetHeight(tileImage);
240
241     RetainPtr<CGImageRef> subImage;
242     if (tileRect.size() == size())
243         subImage = tileImage;
244     else {
245         // Copying a sub-image out of a partially-decoded image stops the decoding of the original image. It should never happen
246         // because sub-images are only used for border-image, which only renders when the image is fully decoded.
247         ASSERT(h == height());
248         subImage.adoptCF(CGImageCreateWithImageInRect(tileImage, tileRect));
249     }
250
251     // Adjust the color space.
252     subImage = Image::imageWithColorSpace(subImage.get(), styleColorSpace);
253     
254     // Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that
255     // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
256     // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.
257     // FIXME: We cannot use CGContextDrawTiledImage with scaled tiles on Leopard, because it suffers from rounding errors.  Snow Leopard is ok.
258     float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
259     float w = CGImageGetWidth(tileImage);
260 #ifdef BUILDING_ON_LEOPARD
261     if (w == size().width() && h == size().height() && scaledTileWidth == tileRect.width() && scaledTileHeight == tileRect.height())
262 #else
263     if (w == size().width() && h == size().height())
264 #endif
265         CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get());
266     else {
267
268     // On Leopard and newer, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image.
269     static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
270     CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
271     matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));
272     // The top of a partially-decoded image is drawn at the bottom of the tile. Map it to the top.
273     matrix = CGAffineTransformTranslate(matrix, 0, size().height() - h);
274     RetainPtr<CGPatternRef> pattern(AdoptCF, CGPatternCreate(subImage.get(), CGRectMake(0, 0, tileRect.width(), tileRect.height()),
275                                              matrix, tileRect.width(), tileRect.height(), 
276                                              kCGPatternTilingConstantSpacing, true, &patternCallbacks));
277     if (!pattern)
278         return;
279
280     RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0));
281     
282     CGFloat alpha = 1;
283     RetainPtr<CGColorRef> color(AdoptCF, CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha));
284     CGContextSetFillColorSpace(context, patternSpace.get());
285
286     // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
287     wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
288     CGContextSetPatternPhase(context, CGSizeZero);
289
290     CGContextSetFillColorWithColor(context, color.get());
291     CGContextFillRect(context, CGContextGetClipBoundingBox(context));
292
293     }
294
295     stateSaver.restore();
296
297     if (imageObserver())
298         imageObserver()->didDraw(this);
299 }
300
301
302 }
303
304 #endif // USE(CG)