• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2004, 2005, 2006 Apple Computer, 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 PLATFORM(CG)
30 
31 #include "TransformationMatrix.h"
32 #include "FloatConversion.h"
33 #include "FloatRect.h"
34 #include "GraphicsContext.h"
35 #include "ImageObserver.h"
36 #include "PDFDocumentImage.h"
37 #include "PlatformString.h"
38 #include <ApplicationServices/ApplicationServices.h>
39 
40 #if PLATFORM(MAC) || PLATFORM(CHROMIUM)
41 #include "WebCoreSystemInterface.h"
42 #endif
43 
44 #if PLATFORM(WIN)
45 #include <WebKitSystemInterface/WebKitSystemInterface.h>
46 #endif
47 
48 namespace WebCore {
49 
clear(bool clearMetadata)50 bool FrameData::clear(bool clearMetadata)
51 {
52     if (clearMetadata)
53         m_haveMetadata = false;
54 
55     if (m_frame) {
56         CGImageRelease(m_frame);
57         m_frame = 0;
58         return true;
59     }
60     return false;
61 }
62 
63 // ================================================
64 // Image Class
65 // ================================================
66 
BitmapImage(CGImageRef cgImage,ImageObserver * observer)67 BitmapImage::BitmapImage(CGImageRef cgImage, ImageObserver* observer)
68     : Image(observer)
69     , m_currentFrame(0)
70     , m_frames(0)
71     , m_frameTimer(0)
72     , m_repetitionCount(cAnimationNone)
73     , m_repetitionCountStatus(Unknown)
74     , m_repetitionsComplete(0)
75     , m_isSolidColor(false)
76     , m_checkedForSolidColor(false)
77     , m_animationFinished(true)
78     , m_allDataReceived(true)
79     , m_haveSize(true)
80     , m_sizeAvailable(true)
81     , m_decodedSize(0)
82     , m_haveFrameCount(true)
83     , m_frameCount(1)
84 {
85     initPlatformData();
86 
87     CGFloat width = CGImageGetWidth(cgImage);
88     CGFloat height = CGImageGetHeight(cgImage);
89     m_decodedSize = width * height * 4;
90     m_size = IntSize(width, height);
91 
92     m_frames.grow(1);
93     m_frames[0].m_frame = cgImage;
94     m_frames[0].m_hasAlpha = true;
95     m_frames[0].m_haveMetadata = true;
96     checkForSolidColor();
97 }
98 
99 // Drawing Routines
100 
checkForSolidColor()101 void BitmapImage::checkForSolidColor()
102 {
103     m_checkedForSolidColor = true;
104     if (frameCount() > 1)
105         m_isSolidColor = false;
106     else {
107         CGImageRef image = frameAtIndex(0);
108 
109         // Currently we only check for solid color in the important special case of a 1x1 image.
110         if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
111             unsigned char pixel[4]; // RGBA
112             CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
113             CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space,
114                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
115             if (bmap) {
116                 GraphicsContext(bmap).setCompositeOperation(CompositeCopy);
117                 CGRect dst = { {0, 0}, {1, 1} };
118                 CGContextDrawImage(bmap, dst, image);
119                 if (pixel[3] == 0)
120                     m_solidColor = Color(0, 0, 0, 0);
121                 else
122                     m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);
123                 m_isSolidColor = true;
124                 CFRelease(bmap);
125             }
126             CFRelease(space);
127         }
128     }
129 }
130 
getCGImageRef()131 CGImageRef BitmapImage::getCGImageRef()
132 {
133     return frameAtIndex(0);
134 }
135 
draw(GraphicsContext * ctxt,const FloatRect & destRect,const FloatRect & srcRect,CompositeOperator compositeOp)136 void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOp)
137 {
138     startAnimation();
139 
140     CGImageRef image = frameAtIndex(m_currentFrame);
141     if (!image) // If it's too early we won't have an image yet.
142         return;
143 
144     if (mayFillWithSolidColor()) {
145         fillWithSolidColor(ctxt, destRect, solidColor(), compositeOp);
146         return;
147     }
148 
149     float currHeight = CGImageGetHeight(image);
150     if (currHeight <= srcRect.y())
151         return;
152 
153     CGContextRef context = ctxt->platformContext();
154     ctxt->save();
155 
156     bool shouldUseSubimage = false;
157 
158     // If the source rect is a subportion of the image, then we compute an inflated destination rect that will hold the entire image
159     // and then set a clip to the portion that we want to display.
160     FloatRect adjustedDestRect = destRect;
161     FloatSize selfSize = currentFrameSize();
162     if (srcRect.size() != selfSize) {
163         CGInterpolationQuality interpolationQuality = CGContextGetInterpolationQuality(context);
164         // When the image is scaled using high-quality interpolation, we create a temporary CGImage
165         // containing only the portion we want to display. We need to do this because high-quality
166         // interpolation smoothes sharp edges, causing pixels from outside the source rect to bleed
167         // into the destination rect. See <rdar://problem/6112909>.
168         shouldUseSubimage = (interpolationQuality == kCGInterpolationHigh || interpolationQuality == kCGInterpolationDefault) && srcRect.size() != destRect.size();
169         float xScale = srcRect.width() / destRect.width();
170         float yScale = srcRect.height() / destRect.height();
171         if (shouldUseSubimage) {
172             FloatRect subimageRect = srcRect;
173             float leftPadding = srcRect.x() - floorf(srcRect.x());
174             float topPadding = srcRect.y() - floorf(srcRect.y());
175 
176             subimageRect.move(-leftPadding, -topPadding);
177             adjustedDestRect.move(-leftPadding / xScale, -topPadding / yScale);
178 
179             subimageRect.setWidth(ceilf(subimageRect.width() + leftPadding));
180             adjustedDestRect.setWidth(subimageRect.width() / xScale);
181 
182             subimageRect.setHeight(ceilf(subimageRect.height() + topPadding));
183             adjustedDestRect.setHeight(subimageRect.height() / yScale);
184 
185             image = CGImageCreateWithImageInRect(image, subimageRect);
186             if (currHeight < srcRect.bottom()) {
187                 ASSERT(CGImageGetHeight(image) == currHeight - CGRectIntegral(srcRect).origin.y);
188                 adjustedDestRect.setHeight(CGImageGetHeight(image) / yScale);
189             }
190         } else {
191             adjustedDestRect.setLocation(FloatPoint(destRect.x() - srcRect.x() / xScale, destRect.y() - srcRect.y() / yScale));
192             adjustedDestRect.setSize(FloatSize(selfSize.width() / xScale, selfSize.height() / yScale));
193         }
194 
195         CGContextClipToRect(context, destRect);
196     }
197 
198     // If the image is only partially loaded, then shrink the destination rect that we're drawing into accordingly.
199     if (!shouldUseSubimage && currHeight < selfSize.height())
200         adjustedDestRect.setHeight(adjustedDestRect.height() * currHeight / selfSize.height());
201 
202     ctxt->setCompositeOperation(compositeOp);
203 
204     // Flip the coords.
205     CGContextScaleCTM(context, 1, -1);
206     adjustedDestRect.setY(-adjustedDestRect.bottom());
207 
208     // Draw the image.
209     CGContextDrawImage(context, adjustedDestRect, image);
210 
211     if (shouldUseSubimage)
212         CGImageRelease(image);
213 
214     ctxt->restore();
215 
216     if (imageObserver())
217         imageObserver()->didDraw(this);
218 }
219 
drawPatternCallback(void * info,CGContextRef context)220 static void drawPatternCallback(void* info, CGContextRef context)
221 {
222     CGImageRef image = (CGImageRef)info;
223     CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image);
224 }
225 
drawPattern(GraphicsContext * ctxt,const FloatRect & tileRect,const TransformationMatrix & patternTransform,const FloatPoint & phase,CompositeOperator op,const FloatRect & destRect)226 void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const TransformationMatrix& patternTransform,
227                         const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
228 {
229     if (!nativeImageForCurrentFrame())
230         return;
231 
232     ASSERT(patternTransform.isInvertible());
233     if (!patternTransform.isInvertible())
234         // Avoid a hang under CGContextDrawTiledImage on release builds.
235         return;
236 
237     CGContextRef context = ctxt->platformContext();
238     ctxt->save();
239     CGContextClipToRect(context, destRect);
240     ctxt->setCompositeOperation(op);
241     CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height());
242     CGContextScaleCTM(context, 1, -1);
243 
244     // Compute the scaled tile size.
245     float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
246 
247     // 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
248     // the origin).
249     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.
250     float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);
251 
252     CGImageRef tileImage = nativeImageForCurrentFrame();
253     float h = CGImageGetHeight(tileImage);
254 
255     CGImageRef subImage;
256     if (tileRect.size() == size())
257         subImage = tileImage;
258     else {
259         // Copying a sub-image out of a partially-decoded image stops the decoding of the original image. It should never happen
260         // because sub-images are only used for border-image, which only renders when the image is fully decoded.
261         ASSERT(h == height());
262         subImage = CGImageCreateWithImageInRect(tileImage, tileRect);
263     }
264 
265 #ifndef BUILDING_ON_TIGER
266     // 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
267     // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
268     // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.
269     // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.
270     // FIXME: We cannot use CGContextDrawTiledImage with scaled tiles on Leopard, because it suffers from rounding errors.  Snow Leopard is ok.
271     float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
272     float w = CGImageGetWidth(tileImage);
273 #ifdef BUILDING_ON_LEOPARD
274     if (w == size().width() && h == size().height() && scaledTileWidth == tileRect.width() && scaledTileHeight == tileRect.height())
275 #else
276     if (w == size().width() && h == size().height())
277 #endif
278         CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage);
279     else {
280 #endif
281 
282     // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image.
283     // On Tiger this code runs all the time.  This code is suboptimal because the pattern does not reference the image directly, and the
284     // pattern is destroyed before exiting the function.  This means any decoding the pattern does doesn't end up cached anywhere, so we
285     // redecode every time we paint.
286     static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
287     CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
288     matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));
289     // The top of a partially-decoded image is drawn at the bottom of the tile. Map it to the top.
290     matrix = CGAffineTransformTranslate(matrix, 0, size().height() - h);
291     CGPatternRef pattern = CGPatternCreate(subImage, CGRectMake(0, 0, tileRect.width(), tileRect.height()),
292                                            matrix, tileRect.width(), tileRect.height(),
293                                            kCGPatternTilingConstantSpacing, true, &patternCallbacks);
294     if (pattern == NULL) {
295         if (subImage != tileImage)
296             CGImageRelease(subImage);
297         ctxt->restore();
298         return;
299     }
300 
301     CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);
302 
303     CGFloat alpha = 1;
304     CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha);
305     CGContextSetFillColorSpace(context, patternSpace);
306     CGColorSpaceRelease(patternSpace);
307     CGPatternRelease(pattern);
308 
309     // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
310     wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
311     CGContextSetPatternPhase(context, CGSizeZero);
312 
313     CGContextSetFillColorWithColor(context, color);
314     CGContextFillRect(context, CGContextGetClipBoundingBox(context));
315 
316     CGColorRelease(color);
317 
318 #ifndef BUILDING_ON_TIGER
319     }
320 #endif
321 
322     if (subImage != tileImage)
323         CGImageRelease(subImage);
324     ctxt->restore();
325 
326     if (imageObserver())
327         imageObserver()->didDraw(this);
328 }
329 
330 
331 }
332 
333 #endif // PLATFORM(CG)
334