2 * Copyright (C) 2004, 2005, 2006 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
27 #include "BitmapImage.h"
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>
42 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
43 #include "WebCoreSystemInterface.h"
47 #include <WebKitSystemInterface/WebKitSystemInterface.h>
52 bool FrameData::clear(bool clearMetadata)
55 m_haveMetadata = false;
58 CGImageRelease(m_frame);
65 // ================================================
67 // ================================================
69 BitmapImage::BitmapImage(CGImageRef cgImage, ImageObserver* observer)
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)
82 , m_sizeAvailable(true)
84 , m_haveFrameCount(true)
89 CGFloat width = CGImageGetWidth(cgImage);
90 CGFloat height = CGImageGetHeight(cgImage);
91 m_decodedSize = width * height * 4;
92 m_size = IntSize(width, height);
95 m_frames[0].m_frame = cgImage;
96 m_frames[0].m_hasAlpha = true;
97 m_frames[0].m_haveMetadata = true;
103 void BitmapImage::checkForSolidColor()
105 m_checkedForSolidColor = true;
106 if (frameCount() > 1) {
107 m_isSolidColor = false;
111 CGImageRef image = frameAtIndex(0);
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));
120 GraphicsContext(bmap.get()).setCompositeOperation(CompositeCopy);
121 CGRect dst = { {0, 0}, {1, 1} };
122 CGContextDrawImage(bmap.get(), dst, image);
124 m_solidColor = Color(0, 0, 0, 0);
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;
131 RetainPtr<CGImageRef> Image::imageWithColorSpace(CGImageRef originalImage, ColorSpace colorSpace)
133 CGColorSpaceRef originalColorSpace = CGImageGetColorSpace(originalImage);
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;
140 switch (colorSpace) {
141 case ColorSpaceDeviceRGB:
142 return originalImage;
144 return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, sRGBColorSpaceRef()));
145 case ColorSpaceLinearRGB:
146 return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, linearRGBColorSpaceRef()));
149 ASSERT_NOT_REACHED();
150 return originalImage;
153 CGImageRef BitmapImage::getCGImageRef()
155 return frameAtIndex(0);
158 CGImageRef BitmapImage::getFirstCGImageRefOfSize(const IntSize& size)
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)
167 // Fallback to the default CGImageRef if we can't find the right size
168 return getCGImageRef();
171 RetainPtr<CFArrayRef> BitmapImage::getCGImageArray()
173 size_t count = frameCount();
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);
182 return RetainPtr<CFArrayRef>(AdoptCF, array);
185 void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator compositeOp)
189 RetainPtr<CGImageRef> image = frameAtIndex(m_currentFrame);
190 if (!image) // If it's too early we won't have an image yet.
193 if (mayFillWithSolidColor()) {
194 fillWithSolidColor(ctxt, destRect, solidColor(), styleColorSpace, compositeOp);
198 FloatSize selfSize = currentFrameSize();
200 ctxt->drawNativeImage(image.get(), selfSize, styleColorSpace, destRect, srcRect, compositeOp);
203 imageObserver()->didDraw(this);
206 static void drawPatternCallback(void* info, CGContextRef context)
208 CGImageRef image = (CGImageRef)info;
209 CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image);
212 void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
213 const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
215 if (!nativeImageForCurrentFrame())
218 ASSERT(patternTransform.isInvertible());
219 if (!patternTransform.isInvertible())
220 // Avoid a hang under CGContextDrawTiledImage on release builds.
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);
230 // Compute the scaled tile size.
231 float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
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
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);
238 CGImageRef tileImage = nativeImageForCurrentFrame();
239 float h = CGImageGetHeight(tileImage);
241 RetainPtr<CGImageRef> subImage;
242 if (tileRect.size() == size())
243 subImage = tileImage;
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));
251 // Adjust the color space.
252 subImage = Image::imageWithColorSpace(subImage.get(), styleColorSpace);
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())
263 if (w == size().width() && h == size().height())
265 CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get());
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));
280 RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0));
283 RetainPtr<CGColorRef> color(AdoptCF, CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha));
284 CGContextSetFillColorSpace(context, patternSpace.get());
286 // FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
287 wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
288 CGContextSetPatternPhase(context, CGSizeZero);
290 CGContextSetFillColorWithColor(context, color.get());
291 CGContextFillRect(context, CGContextGetClipBoundingBox(context));
295 stateSaver.restore();
298 imageObserver()->didDraw(this);