ImageCG.cpp 14.7 KB
Newer Older
1
/*
2
 * Copyright (C) 2004, 2005, 2006 Apple Inc. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

#include "config.h"
27
#include "BitmapImage.h"
28 29 30

#if PLATFORM(CG)

31
#include "AffineTransform.h"
32
#include "FloatConversion.h"
33
#include "FloatRect.h"
34
#include "GraphicsContextCG.h"
ggaren's avatar
ggaren committed
35
#include "ImageObserver.h"
36 37
#include "PDFDocumentImage.h"
#include "PlatformString.h"
darin's avatar
darin committed
38
#include <ApplicationServices/ApplicationServices.h>
darin@apple.com's avatar
darin@apple.com committed
39
#include <wtf/RetainPtr.h>
40

eric@webkit.org's avatar
eric@webkit.org committed
41
#if PLATFORM(MAC) || PLATFORM(CHROMIUM)
42
#include "WebCoreSystemInterface.h"
43
#endif
44

hyatt's avatar
hyatt committed
45 46 47 48
#if PLATFORM(WIN)
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif

49 50
namespace WebCore {

51
bool FrameData::clear(bool clearMetadata)
52
{
53 54 55
    if (clearMetadata)
        m_haveMetadata = false;

56
    if (m_frame) {
57
        CGImageRelease(m_frame);
58
        m_frame = 0;
59
        return true;
60
    }
61
    return false;
62 63 64 65 66 67
}

// ================================================
// Image Class
// ================================================

68 69 70 71 72
BitmapImage::BitmapImage(CGImageRef cgImage, ImageObserver* observer)
    : Image(observer)
    , m_currentFrame(0)
    , m_frames(0)
    , m_frameTimer(0)
73 74
    , m_repetitionCount(cAnimationNone)
    , m_repetitionCountStatus(Unknown)
75 76
    , m_repetitionsComplete(0)
    , m_isSolidColor(false)
77
    , m_checkedForSolidColor(false)
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    , m_animationFinished(true)
    , m_allDataReceived(true)
    , m_haveSize(true)
    , m_sizeAvailable(true)
    , m_decodedSize(0)
    , m_haveFrameCount(true)
    , m_frameCount(1)
{
    initPlatformData();
    
    CGFloat width = CGImageGetWidth(cgImage);
    CGFloat height = CGImageGetHeight(cgImage);
    m_decodedSize = width * height * 4;
    m_size = IntSize(width, height);

    m_frames.grow(1);
    m_frames[0].m_frame = cgImage;
95
    m_frames[0].m_hasAlpha = true;
96
    m_frames[0].m_haveMetadata = true;
97 98 99
    checkForSolidColor();
}

100 101
// Drawing Routines

102
void BitmapImage::checkForSolidColor()
103
{
104
    m_checkedForSolidColor = true;
105
    if (frameCount() > 1) {
106
        m_isSolidColor = false;
107 108 109 110 111 112 113 114
        return;
    }

    CGImageRef image = frameAtIndex(0);
    
    // Currently we only check for solid color in the important special case of a 1x1 image.
    if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {
        unsigned char pixel[4]; // RGBA
115
        RetainPtr<CGContextRef> bmap(AdoptCF, CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), deviceRGBColorSpaceRef(),
116 117 118 119 120 121 122 123 124 125 126
            kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big));
        if (!bmap)
            return;
        GraphicsContext(bmap.get()).setCompositeOperation(CompositeCopy);
        CGRect dst = { {0, 0}, {1, 1} };
        CGContextDrawImage(bmap.get(), dst, image);
        if (pixel[3] == 0)
            m_solidColor = Color(0, 0, 0, 0);
        else
            m_solidColor = Color(pixel[0] * 255 / pixel[3], pixel[1] * 255 / pixel[3], pixel[2] * 255 / pixel[3], pixel[3]);
        m_isSolidColor = true;
127 128 129
    }
}

130 131 132 133 134 135 136 137 138 139
static RetainPtr<CGImageRef> imageWithColorSpace(CGImageRef originalImage, ColorSpace colorSpace)
{
    CGColorSpaceRef originalColorSpace = CGImageGetColorSpace(originalImage);

    // If the image already has a (non-device) color space, we don't want to
    // override it, so return.
    if (!originalColorSpace || !CFEqual(originalColorSpace, deviceRGBColorSpaceRef()))
        return originalImage;

    switch (colorSpace) {
140
    case ColorSpaceDeviceRGB:
141
        return originalImage;
142
    case ColorSpaceSRGB:
143
        return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, sRGBColorSpaceRef()));
144 145
    case ColorSpaceLinearRGB:
        return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, linearRGBColorSpaceRef()));
146 147 148 149 150 151
    }

    ASSERT_NOT_REACHED();
    return originalImage;
}

152
CGImageRef BitmapImage::getCGImageRef()
153 154 155 156
{
    return frameAtIndex(0);
}

157 158
CGImageRef BitmapImage::getFirstCGImageRefOfSize(const IntSize& size)
{
159 160
    size_t count = frameCount();
    for (size_t i = 0; i < count; ++i) {
161 162 163 164 165 166 167 168 169
        CGImageRef cgImage = frameAtIndex(i);
        if (IntSize(CGImageGetWidth(cgImage), CGImageGetHeight(cgImage)) == size)
            return cgImage;
    }

    // Fallback to the default CGImageRef if we can't find the right size
    return getCGImageRef();
}

170
void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator compositeOp)
171
{
172 173
    startAnimation();

174
    RetainPtr<CGImageRef> image = frameAtIndex(m_currentFrame);
175 176
    if (!image) // If it's too early we won't have an image yet.
        return;
177 178
    
    if (mayFillWithSolidColor()) {
179
        fillWithSolidColor(ctxt, destRect, solidColor(), styleColorSpace, compositeOp);
180 181 182
        return;
    }

183
    float currHeight = CGImageGetHeight(image.get());
mitz@apple.com's avatar
mitz@apple.com committed
184 185 186
    if (currHeight <= srcRect.y())
        return;

alp's avatar
alp committed
187 188 189
    CGContextRef context = ctxt->platformContext();
    ctxt->save();

mitz@apple.com's avatar
mitz@apple.com committed
190 191
    bool shouldUseSubimage = false;

192 193 194
    // If the source rect is a subportion of the image, then we compute an inflated destination rect that will hold the entire image
    // and then set a clip to the portion that we want to display.
    FloatRect adjustedDestRect = destRect;
195
    FloatSize selfSize = currentFrameSize();
mitz@apple.com's avatar
mitz@apple.com committed
196 197
    if (srcRect.size() != selfSize) {
        CGInterpolationQuality interpolationQuality = CGContextGetInterpolationQuality(context);
mitz@apple.com's avatar
mitz@apple.com committed
198 199 200 201
        // When the image is scaled using high-quality interpolation, we create a temporary CGImage
        // containing only the portion we want to display. We need to do this because high-quality
        // interpolation smoothes sharp edges, causing pixels from outside the source rect to bleed
        // into the destination rect. See <rdar://problem/6112909>.
202
        shouldUseSubimage = (interpolationQuality == kCGInterpolationHigh || interpolationQuality == kCGInterpolationDefault) && (srcRect.size() != destRect.size() || !ctxt->getCTM().isIdentityOrTranslationOrFlipped());
mitz@apple.com's avatar
mitz@apple.com committed
203 204
        float xScale = srcRect.width() / destRect.width();
        float yScale = srcRect.height() / destRect.height();
mitz@apple.com's avatar
mitz@apple.com committed
205
        if (shouldUseSubimage) {
mitz@apple.com's avatar
mitz@apple.com committed
206 207 208 209 210 211 212 213 214 215 216 217 218
            FloatRect subimageRect = srcRect;
            float leftPadding = srcRect.x() - floorf(srcRect.x());
            float topPadding = srcRect.y() - floorf(srcRect.y());

            subimageRect.move(-leftPadding, -topPadding);
            adjustedDestRect.move(-leftPadding / xScale, -topPadding / yScale);

            subimageRect.setWidth(ceilf(subimageRect.width() + leftPadding));
            adjustedDestRect.setWidth(subimageRect.width() / xScale);

            subimageRect.setHeight(ceilf(subimageRect.height() + topPadding));
            adjustedDestRect.setHeight(subimageRect.height() / yScale);

219
            image.adoptCF(CGImageCreateWithImageInRect(image.get(), subimageRect));
220
            if (currHeight < srcRect.maxY()) {
221 222
                ASSERT(CGImageGetHeight(image.get()) == currHeight - CGRectIntegral(srcRect).origin.y);
                adjustedDestRect.setHeight(CGImageGetHeight(image.get()) / yScale);
mitz@apple.com's avatar
mitz@apple.com committed
223 224 225
            }
        } else {
            adjustedDestRect.setLocation(FloatPoint(destRect.x() - srcRect.x() / xScale, destRect.y() - srcRect.y() / yScale));
226
            adjustedDestRect.setSize(FloatSize(selfSize.width() / xScale, selfSize.height() / yScale));
mitz@apple.com's avatar
mitz@apple.com committed
227
        }
mitz@apple.com's avatar
mitz@apple.com committed
228 229

        CGContextClipToRect(context, destRect);
230 231 232
    }

    // If the image is only partially loaded, then shrink the destination rect that we're drawing into accordingly.
mitz@apple.com's avatar
mitz@apple.com committed
233 234
    if (!shouldUseSubimage && currHeight < selfSize.height())
        adjustedDestRect.setHeight(adjustedDestRect.height() * currHeight / selfSize.height());
235

236
    ctxt->setCompositeOperation(compositeOp);
mitz@apple.com's avatar
mitz@apple.com committed
237 238

    // Flip the coords.
239
    CGContextScaleCTM(context, 1, -1);
240
    adjustedDestRect.setY(-adjustedDestRect.maxY());
241

242 243
    // Adjust the color space.
    image = imageWithColorSpace(image.get(), styleColorSpace);
mitz@apple.com's avatar
mitz@apple.com committed
244

245 246
    // Draw the image.
    CGContextDrawImage(context, adjustedDestRect, image.get());
mitz@apple.com's avatar
mitz@apple.com committed
247

248
    ctxt->restore();
mitz@apple.com's avatar
mitz@apple.com committed
249

ggaren's avatar
ggaren committed
250 251
    if (imageObserver())
        imageObserver()->didDraw(this);
252 253
}

mitz@apple.com's avatar
mitz@apple.com committed
254
static void drawPatternCallback(void* info, CGContextRef context)
255
{
mitz's avatar
mitz committed
256 257
    CGImageRef image = (CGImageRef)info;
    CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image);
258 259
}

260
void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,
261
                        const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect)
262
{
263 264
    if (!nativeImageForCurrentFrame())
        return;
265

mitz's avatar
mitz committed
266 267 268 269 270
    ASSERT(patternTransform.isInvertible());
    if (!patternTransform.isInvertible())
        // Avoid a hang under CGContextDrawTiledImage on release builds.
        return;

271
    CGContextRef context = ctxt->platformContext();
hyatt's avatar
hyatt committed
272 273 274
    ctxt->save();
    CGContextClipToRect(context, destRect);
    ctxt->setCompositeOperation(op);
275
    CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height());
hyatt's avatar
hyatt committed
276 277 278
    CGContextScaleCTM(context, 1, -1);
    
    // Compute the scaled tile size.
279
    float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());
hyatt's avatar
hyatt committed
280 281 282
    
    // 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
    // the origin).
283 284
    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.
    float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);
285

hyatt's avatar
hyatt committed
286 287
    CGImageRef tileImage = nativeImageForCurrentFrame();
    float h = CGImageGetHeight(tileImage);
mitz's avatar
mitz committed
288

289
    RetainPtr<CGImageRef> subImage;
mitz's avatar
mitz committed
290 291 292 293 294 295
    if (tileRect.size() == size())
        subImage = tileImage;
    else {
        // Copying a sub-image out of a partially-decoded image stops the decoding of the original image. It should never happen
        // because sub-images are only used for border-image, which only renders when the image is fully decoded.
        ASSERT(h == height());
296
        subImage.adoptCF(CGImageCreateWithImageInRect(tileImage, tileRect));
mitz's avatar
mitz committed
297
    }
298 299 300

    // Adjust the color space.
    subImage = imageWithColorSpace(subImage.get(), styleColorSpace);
hyatt's avatar
hyatt committed
301
    
302 303 304
#ifndef BUILDING_ON_TIGER
    // 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
    // its buffer is the same size as the overall image.  Because a partially decoded CGImageRef with a smaller width or height than the
mitz's avatar
mitz committed
305
    // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case.
306
    // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.
307
    // FIXME: We cannot use CGContextDrawTiledImage with scaled tiles on Leopard, because it suffers from rounding errors.  Snow Leopard is ok.
308
    float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());
309
    float w = CGImageGetWidth(tileImage);
310 311 312
#ifdef BUILDING_ON_LEOPARD
    if (w == size().width() && h == size().height() && scaledTileWidth == tileRect.width() && scaledTileHeight == tileRect.height())
#else
mitz's avatar
mitz committed
313
    if (w == size().width() && h == size().height())
314
#endif
315
        CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get());
hyatt's avatar
hyatt committed
316
    else {
317 318
#endif

mitz's avatar
mitz committed
319
    // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image.
320 321 322
    // On Tiger this code runs all the time.  This code is suboptimal because the pattern does not reference the image directly, and the
    // pattern is destroyed before exiting the function.  This means any decoding the pattern does doesn't end up cached anywhere, so we
    // redecode every time we paint.
323
    static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };
hyatt's avatar
hyatt committed
324 325
    CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);
    matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));
mitz's avatar
mitz committed
326 327
    // The top of a partially-decoded image is drawn at the bottom of the tile. Map it to the top.
    matrix = CGAffineTransformTranslate(matrix, 0, size().height() - h);
328 329 330 331
    RetainPtr<CGPatternRef> pattern(AdoptCF, CGPatternCreate(subImage.get(), CGRectMake(0, 0, tileRect.width(), tileRect.height()),
                                             matrix, tileRect.width(), tileRect.height(), 
                                             kCGPatternTilingConstantSpacing, true, &patternCallbacks));
    if (!pattern) {
hyatt's avatar
hyatt committed
332
        ctxt->restore();
333
        return;
hyatt's avatar
hyatt committed
334 335
    }

336
    RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0));
hyatt's avatar
hyatt committed
337 338
    
    CGFloat alpha = 1;
339 340
    RetainPtr<CGColorRef> color(AdoptCF, CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha));
    CGContextSetFillColorSpace(context, patternSpace.get());
hyatt's avatar
hyatt committed
341 342 343 344 345

    // FIXME: Really want a public API for this.  It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).
    wkSetPatternBaseCTM(context, CGAffineTransformIdentity);
    CGContextSetPatternPhase(context, CGSizeZero);

346
    CGContextSetFillColorWithColor(context, color.get());
hyatt's avatar
hyatt committed
347
    CGContextFillRect(context, CGContextGetClipBoundingBox(context));
348

349 350 351 352
#ifndef BUILDING_ON_TIGER
    }
#endif

353 354
    ctxt->restore();

ggaren's avatar
ggaren committed
355 356
    if (imageObserver())
        imageObserver()->didDraw(this);
357 358
}

359 360 361 362

}

#endif // PLATFORM(CG)