1/*
2 * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
3 * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "config.h"
28#include "platform/graphics/Image.h"
29
30#include "platform/Length.h"
31#include "platform/MIMETypeRegistry.h"
32#include "platform/SharedBuffer.h"
33#include "platform/TraceEvent.h"
34#include "platform/geometry/FloatPoint.h"
35#include "platform/geometry/FloatRect.h"
36#include "platform/geometry/FloatSize.h"
37#include "platform/graphics/BitmapImage.h"
38#include "platform/graphics/GraphicsContext.h"
39#include "platform/graphics/GraphicsContextStateSaver.h"
40#include "public/platform/Platform.h"
41#include "public/platform/WebData.h"
42#include "wtf/MainThread.h"
43#include "wtf/StdLibExtras.h"
44
45#include <math.h>
46
47namespace blink {
48
49Image::Image(ImageObserver* observer)
50    : m_imageObserver(observer)
51{
52}
53
54Image::~Image()
55{
56}
57
58Image* Image::nullImage()
59{
60    ASSERT(isMainThread());
61    DEFINE_STATIC_REF(Image, nullImage, (BitmapImage::create()));
62    return nullImage;
63}
64
65PassRefPtr<Image> Image::loadPlatformResource(const char *name)
66{
67    const WebData& resource = Platform::current()->loadResource(name);
68    if (resource.isEmpty())
69        return Image::nullImage();
70
71    RefPtr<Image> image = BitmapImage::create();
72    image->setData(resource, true);
73    return image.release();
74}
75
76bool Image::supportsType(const String& type)
77{
78    return MIMETypeRegistry::isSupportedImageResourceMIMEType(type);
79}
80
81bool Image::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
82{
83    m_encodedImageData = data;
84    if (!m_encodedImageData.get())
85        return true;
86
87    int length = m_encodedImageData->size();
88    if (!length)
89        return true;
90
91    return dataChanged(allDataReceived);
92}
93
94void Image::fillWithSolidColor(GraphicsContext* ctxt, const FloatRect& dstRect, const Color& color, CompositeOperator op)
95{
96    if (!color.alpha())
97        return;
98
99    CompositeOperator previousOperator = ctxt->compositeOperation();
100    ctxt->setCompositeOperation(!color.hasAlpha() && op == CompositeSourceOver ? CompositeCopy : op);
101    ctxt->fillRect(dstRect, color);
102    ctxt->setCompositeOperation(previousOperator);
103}
104
105FloatRect Image::adjustForNegativeSize(const FloatRect& rect)
106{
107    FloatRect norm = rect;
108    if (norm.width() < 0) {
109        norm.setX(norm.x() + norm.width());
110        norm.setWidth(-norm.width());
111    }
112    if (norm.height() < 0) {
113        norm.setY(norm.y() + norm.height());
114        norm.setHeight(-norm.height());
115    }
116    return norm;
117}
118
119void Image::draw(GraphicsContext* ctx, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator op, WebBlendMode blendMode, RespectImageOrientationEnum)
120{
121    draw(ctx, dstRect, srcRect, op, blendMode);
122}
123
124void Image::drawTiled(GraphicsContext* ctxt, const FloatRect& destRect, const FloatPoint& srcPoint, const FloatSize& scaledTileSize, CompositeOperator op, WebBlendMode blendMode, const IntSize& repeatSpacing)
125{
126    if (mayFillWithSolidColor()) {
127        fillWithSolidColor(ctxt, destRect, solidColor(), op);
128        return;
129    }
130
131    // See <https://webkit.org/b/59043>.
132    ASSERT(!isBitmapImage() || notSolidColor());
133
134    FloatSize intrinsicTileSize = size();
135    if (hasRelativeWidth())
136        intrinsicTileSize.setWidth(scaledTileSize.width());
137    if (hasRelativeHeight())
138        intrinsicTileSize.setHeight(scaledTileSize.height());
139
140    FloatSize scale(scaledTileSize.width() / intrinsicTileSize.width(),
141                    scaledTileSize.height() / intrinsicTileSize.height());
142
143    FloatSize actualTileSize(scaledTileSize.width() + repeatSpacing.width(), scaledTileSize.height() + repeatSpacing.height());
144    FloatRect oneTileRect;
145    oneTileRect.setX(destRect.x() + fmodf(fmodf(-srcPoint.x(), actualTileSize.width()) - actualTileSize.width(), actualTileSize.width()));
146    oneTileRect.setY(destRect.y() + fmodf(fmodf(-srcPoint.y(), actualTileSize.height()) - actualTileSize.height(), actualTileSize.height()));
147    oneTileRect.setSize(scaledTileSize);
148
149    // Check and see if a single draw of the image can cover the entire area we are supposed to tile.
150    if (oneTileRect.contains(destRect)) {
151        FloatRect visibleSrcRect;
152        visibleSrcRect.setX((destRect.x() - oneTileRect.x()) / scale.width());
153        visibleSrcRect.setY((destRect.y() - oneTileRect.y()) / scale.height());
154        visibleSrcRect.setWidth(destRect.width() / scale.width());
155        visibleSrcRect.setHeight(destRect.height() / scale.height());
156        draw(ctxt, destRect, visibleSrcRect, op, blendMode);
157        return;
158    }
159
160    FloatRect tileRect(FloatPoint(), intrinsicTileSize);
161    drawPattern(ctxt, tileRect, scale, oneTileRect.location(), op, destRect, blendMode, repeatSpacing);
162
163    startAnimation();
164}
165
166// FIXME: Merge with the other drawTiled eventually, since we need a combination of both for some things.
167void Image::drawTiled(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect,
168    const FloatSize& providedTileScaleFactor, TileRule hRule, TileRule vRule, CompositeOperator op)
169{
170    if (mayFillWithSolidColor()) {
171        fillWithSolidColor(ctxt, dstRect, solidColor(), op);
172        return;
173    }
174
175    // FIXME: We do not support 'space' yet. For now just map it to 'repeat'.
176    if (hRule == SpaceTile)
177        hRule = RepeatTile;
178    if (vRule == SpaceTile)
179        vRule = RepeatTile;
180
181    // FIXME: if this code is used for background-repeat: round (in addition to
182    // border-image-repeat), then add logic to deal with the background-size: auto
183    // special case. The aspect ratio should be maintained in this case.
184    FloatSize tileScaleFactor = providedTileScaleFactor;
185    bool useLowInterpolationQuality = false;
186    if (hRule == RoundTile) {
187        float hRepetitions = std::max(1.0f, roundf(dstRect.width() / (tileScaleFactor.width() * srcRect.width())));
188        tileScaleFactor.setWidth(dstRect.width() / (srcRect.width() * hRepetitions));
189    }
190    if (vRule == RoundTile) {
191        float vRepetitions = std::max(1.0f, roundf(dstRect.height() / (tileScaleFactor.height() * srcRect.height())));
192        tileScaleFactor.setHeight(dstRect.height() / (srcRect.height() * vRepetitions));
193    }
194    if (hRule == RoundTile || vRule == RoundTile) {
195        // High interpolation quality rounds the scaled tile to an integer size (see Image::drawPattern).
196        // To avoid causing a visual problem, linear interpolation must be used instead.
197        // FIXME: Allow using high-quality interpolation in this case, too.
198        useLowInterpolationQuality = true;
199    }
200
201    // We want to construct the phase such that the pattern is centered (when stretch is not
202    // set for a particular rule).
203    float hPhase = tileScaleFactor.width() * srcRect.x();
204    float vPhase = tileScaleFactor.height() * srcRect.y();
205    float scaledTileWidth = tileScaleFactor.width() * srcRect.width();
206    float scaledTileHeight = tileScaleFactor.height() * srcRect.height();
207    if (hRule == Image::RepeatTile)
208        hPhase -= (dstRect.width() - scaledTileWidth) / 2;
209    if (vRule == Image::RepeatTile)
210        vPhase -= (dstRect.height() - scaledTileHeight) / 2;
211    FloatPoint patternPhase(dstRect.x() - hPhase, dstRect.y() - vPhase);
212
213    if (useLowInterpolationQuality) {
214        InterpolationQuality previousInterpolationQuality = ctxt->imageInterpolationQuality();
215        ctxt->setImageInterpolationQuality(InterpolationLow);
216        drawPattern(ctxt, srcRect, tileScaleFactor, patternPhase, op, dstRect);
217        ctxt->setImageInterpolationQuality(previousInterpolationQuality);
218    } else {
219        drawPattern(ctxt, srcRect, tileScaleFactor, patternPhase, op, dstRect);
220    }
221
222    startAnimation();
223}
224
225void Image::drawPattern(GraphicsContext* context, const FloatRect& floatSrcRect, const FloatSize& scale,
226    const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& destRect, WebBlendMode blendMode, const IntSize& repeatSpacing)
227{
228    TRACE_EVENT0("skia", "Image::drawPattern");
229    if (RefPtr<NativeImageSkia> bitmap = nativeImageForCurrentFrame())
230        bitmap->drawPattern(context, adjustForNegativeSize(floatSrcRect), scale, phase, compositeOp, destRect, blendMode, repeatSpacing);
231}
232
233void Image::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
234{
235    intrinsicRatio = size();
236    intrinsicWidth = Length(intrinsicRatio.width(), Fixed);
237    intrinsicHeight = Length(intrinsicRatio.height(), Fixed);
238}
239
240PassRefPtr<Image> Image::imageForDefaultFrame()
241{
242    RefPtr<Image> image(this);
243
244    return image.release();
245}
246
247} // namespace blink
248