diff options
| author | Steve Block <steveblock@google.com> | 2011-05-06 11:45:16 +0100 |
|---|---|---|
| committer | Steve Block <steveblock@google.com> | 2011-05-12 13:44:10 +0100 |
| commit | cad810f21b803229eb11403f9209855525a25d57 (patch) | |
| tree | 29a6fd0279be608e0fe9ffe9841f722f0f4e4269 /Source/WebCore/platform/graphics/cg | |
| parent | 121b0cf4517156d0ac5111caf9830c51b69bae8f (diff) | |
| download | external_webkit-cad810f21b803229eb11403f9209855525a25d57.zip external_webkit-cad810f21b803229eb11403f9209855525a25d57.tar.gz external_webkit-cad810f21b803229eb11403f9209855525a25d57.tar.bz2 | |
Merge WebKit at r75315: Initial merge by git.
Change-Id: I570314b346ce101c935ed22a626b48c2af266b84
Diffstat (limited to 'Source/WebCore/platform/graphics/cg')
25 files changed, 4510 insertions, 0 deletions
diff --git a/Source/WebCore/platform/graphics/cg/ColorCG.cpp b/Source/WebCore/platform/graphics/cg/ColorCG.cpp new file mode 100644 index 0000000..c9b05da --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ColorCG.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2010 Apple Inc. All rights reserved. + * + * 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" +#include "Color.h" + +#if PLATFORM(CG) + +#include "GraphicsContextCG.h" +#include <wtf/Assertions.h> +#include <wtf/RetainPtr.h> +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +Color::Color(CGColorRef color) +{ + if (!color) { + m_color = 0; + m_valid = false; + return; + } + + size_t numComponents = CGColorGetNumberOfComponents(color); + const CGFloat* components = CGColorGetComponents(color); + + float r = 0; + float g = 0; + float b = 0; + float a = 0; + + switch (numComponents) { + case 2: + r = g = b = components[0]; + a = components[1]; + break; + case 4: + r = components[0]; + g = components[1]; + b = components[2]; + a = components[3]; + break; + default: + ASSERT_NOT_REACHED(); + } + + m_color = makeRGBA(r * 255, g * 255, b * 255, a * 255); + m_valid = true; +} + +static inline CGColorSpaceRef cachedCGColorSpace(ColorSpace colorSpace) +{ + switch (colorSpace) { + case ColorSpaceDeviceRGB: + return deviceRGBColorSpaceRef(); + case ColorSpaceSRGB: + return sRGBColorSpaceRef(); + case ColorSpaceLinearRGB: + return linearRGBColorSpaceRef(); + } + ASSERT_NOT_REACHED(); + return deviceRGBColorSpaceRef(); +} + +static CGColorRef leakCGColor(const Color& color, ColorSpace colorSpace) +{ + CGFloat components[4]; + color.getRGBA(components[0], components[1], components[2], components[3]); + return CGColorCreate(cachedCGColorSpace(colorSpace), components); +} + +template<ColorSpace colorSpace> static CGColorRef cachedCGColor(const Color& color) +{ + switch (color.rgb()) { + case Color::transparent: { + static CGColorRef transparentCGColor = leakCGColor(color, colorSpace); + return transparentCGColor; + } + case Color::black: { + static CGColorRef blackCGColor = leakCGColor(color, colorSpace); + return blackCGColor; + } + case Color::white: { + static CGColorRef whiteCGColor = leakCGColor(color, colorSpace); + return whiteCGColor; + } + } + + ASSERT(color.rgb()); + + const size_t cacheSize = 32; + static RGBA32 cachedRGBAValues[cacheSize]; + static RetainPtr<CGColorRef>* cachedCGColors = new RetainPtr<CGColorRef>[cacheSize]; + + for (size_t i = 0; i < cacheSize; ++i) { + if (cachedRGBAValues[i] == color.rgb()) + return cachedCGColors[i].get(); + } + + CGColorRef newCGColor = leakCGColor(color, colorSpace); + + static size_t cursor; + cachedRGBAValues[cursor] = color.rgb(); + cachedCGColors[cursor].adoptCF(newCGColor); + if (++cursor == cacheSize) + cursor = 0; + + return newCGColor; +} + +CGColorRef cachedCGColor(const Color& color, ColorSpace colorSpace) +{ + switch (colorSpace) { + case ColorSpaceDeviceRGB: + return cachedCGColor<ColorSpaceDeviceRGB>(color); + case ColorSpaceSRGB: + return cachedCGColor<ColorSpaceSRGB>(color); + case ColorSpaceLinearRGB: + return cachedCGColor<ColorSpaceLinearRGB>(color); + } + ASSERT_NOT_REACHED(); + return cachedCGColor(color, ColorSpaceDeviceRGB); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/FloatPointCG.cpp b/Source/WebCore/platform/graphics/cg/FloatPointCG.cpp new file mode 100644 index 0000000..f9c3353 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/FloatPointCG.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2005 Nokia. All rights reserved. + * + * 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" +#include "FloatPoint.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +FloatPoint::FloatPoint(const CGPoint& p) : m_x(p.x), m_y(p.y) +{ +} + +FloatPoint::operator CGPoint() const +{ + return CGPointMake(m_x, m_y); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/FloatRectCG.cpp b/Source/WebCore/platform/graphics/cg/FloatRectCG.cpp new file mode 100644 index 0000000..a1ce367 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/FloatRectCG.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2005 Nokia. All rights reserved. + * + * 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" +#include "FloatRect.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +FloatRect::FloatRect(const CGRect& r) : m_location(r.origin), m_size(r.size) +{ +} + +FloatRect::operator CGRect() const +{ + return CGRectMake(x(), y(), width(), height()); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/FloatSizeCG.cpp b/Source/WebCore/platform/graphics/cg/FloatSizeCG.cpp new file mode 100644 index 0000000..383af21 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/FloatSizeCG.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2005 Nokia. All rights reserved. + * + * 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" +#include "FloatSize.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +FloatSize::FloatSize(const CGSize& s) : m_width(s.width), m_height(s.height) +{ +} + +FloatSize::operator CGSize() const +{ + return CGSizeMake(m_width, m_height); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/FontPlatformData.h b/Source/WebCore/platform/graphics/cg/FontPlatformData.h new file mode 100644 index 0000000..e21b444 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/FontPlatformData.h @@ -0,0 +1,105 @@ +/* + * This file is part of the internal font implementation. It should not be included by anyone other than + * FontMac.cpp, FontWin.cpp and Font.cpp. + * + * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#ifndef FontPlatformData_h +#define FontPlatformData_h + +#include "FontOrientation.h" +#include "RefCountedGDIHandle.h" +#include "StringImpl.h" +#include <wtf/Forward.h> +#include <wtf/PassRefPtr.h> +#include <wtf/RefCounted.h> +#include <wtf/RetainPtr.h> + +typedef struct HFONT__* HFONT; +typedef struct CGFont* CGFontRef; + +namespace WebCore { + +class FontDescription; + +class FontPlatformData { +public: + FontPlatformData() + : m_size(0) + , m_syntheticBold(false) + , m_syntheticOblique(false) + , m_useGDI(false) + { + } + + FontPlatformData(HFONT, float size, bool bold, bool oblique, bool useGDI); + FontPlatformData(float size, bool bold, bool oblique); + + FontPlatformData(HFONT, CGFontRef, float size, bool bold, bool oblique, bool useGDI); + ~FontPlatformData(); + + FontPlatformData(WTF::HashTableDeletedValueType) : m_font(WTF::HashTableDeletedValue) { } + bool isHashTableDeletedValue() const { return m_font.isHashTableDeletedValue(); } + + HFONT hfont() const { return m_font->handle(); } + CGFontRef cgFont() const { return m_cgFont.get(); } + + float size() const { return m_size; } + void setSize(float size) { m_size = size; } + bool syntheticBold() const { return m_syntheticBold; } + bool syntheticOblique() const { return m_syntheticOblique; } + bool useGDI() const { return m_useGDI; } + + FontOrientation orientation() const { return Horizontal; } // FIXME: Implement. + + unsigned hash() const + { + return m_font->hash(); + } + + bool operator==(const FontPlatformData& other) const + { + return m_font == other.m_font + && m_cgFont == other.m_cgFont + && m_size == other.m_size + && m_syntheticBold == other.m_syntheticBold + && m_syntheticOblique == other.m_syntheticOblique + && m_useGDI == other.m_useGDI; + } + +#ifndef NDEBUG + String description() const; +#endif + +private: + void platformDataInit(HFONT, float size, HDC, WCHAR* faceName); + + RefPtr<RefCountedGDIHandle<HFONT> > m_font; + RetainPtr<CGFontRef> m_cgFont; + + float m_size; + bool m_syntheticBold; + bool m_syntheticOblique; + bool m_useGDI; +}; + +} // namespace WebCore + +#endif diff --git a/Source/WebCore/platform/graphics/cg/GradientCG.cpp b/Source/WebCore/platform/graphics/cg/GradientCG.cpp new file mode 100644 index 0000000..974dd6b --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/GradientCG.cpp @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2006, 2007, 2008 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2007 Alp Toker <alp@atoker.com> + * + * 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" +#include "Gradient.h" + +#include "GraphicsContextCG.h" +#include <ApplicationServices/ApplicationServices.h> +#include <wtf/RetainPtr.h> + +namespace WebCore { + +void Gradient::platformDestroy() +{ +#if USE_CG_SHADING + CGShadingRelease(m_gradient); +#else + CGGradientRelease(m_gradient); +#endif + m_gradient = 0; +} + +#if USE_CG_SHADING +static void gradientCallback(void* info, const CGFloat* in, CGFloat* out) +{ + float r, g, b, a; + static_cast<const Gradient*>(info)->getColor(*in, &r, &g, &b, &a); + out[0] = r; + out[1] = g; + out[2] = b; + out[3] = a; +} + +CGShadingRef Gradient::platformGradient() +{ + if (m_gradient) + return m_gradient; + + const CGFloat intervalRanges[2] = { 0, 1 }; + const CGFloat colorComponentRanges[4 * 2] = { 0, 1, 0, 1, 0, 1, 0, 1 }; + const CGFunctionCallbacks gradientCallbacks = { 0, gradientCallback, 0 }; + RetainPtr<CGFunctionRef> colorFunction(AdoptCF, CGFunctionCreate(this, 1, intervalRanges, 4, colorComponentRanges, &gradientCallbacks)); + + CGColorSpaceRef colorSpace = deviceRGBColorSpaceRef(); + + if (m_radial) + m_gradient = CGShadingCreateRadial(colorSpace, m_p0, m_r0, m_p1, m_r1, colorFunction.get(), true, true); + else + m_gradient = CGShadingCreateAxial(colorSpace, m_p0, m_p1, colorFunction.get(), true, true); + + return m_gradient; +} +#else +CGGradientRef Gradient::platformGradient() +{ + if (m_gradient) + return m_gradient; + + sortStopsIfNecessary(); + + const int cReservedStops = 3; + Vector<CGFloat, 4 * cReservedStops> colorComponents; + colorComponents.reserveCapacity(m_stops.size() * 4); // RGBA components per stop + + Vector<CGFloat, cReservedStops> locations; + locations.reserveCapacity(m_stops.size()); + + for (size_t i = 0; i < m_stops.size(); ++i) { + colorComponents.uncheckedAppend(m_stops[i].red); + colorComponents.uncheckedAppend(m_stops[i].green); + colorComponents.uncheckedAppend(m_stops[i].blue); + colorComponents.uncheckedAppend(m_stops[i].alpha); + + locations.uncheckedAppend(m_stops[i].stop); + } + + m_gradient = CGGradientCreateWithColorComponents(deviceRGBColorSpaceRef(), colorComponents.data(), locations.data(), m_stops.size()); + + return m_gradient; +} +#endif + +void Gradient::fill(GraphicsContext* context, const FloatRect& rect) +{ + context->clip(rect); + paint(context); +} + +void Gradient::paint(GraphicsContext* context) +{ + CGContextRef ctx = context->platformContext(); + paint(ctx); +} + +void Gradient::paint(CGContextRef context) +{ +#if USE_CG_SHADING + CGContextDrawShading(context, platformGradient()); +#else + CGGradientDrawingOptions extendOptions = kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation; + if (m_radial) { + bool needScaling = aspectRatio() != 1; + if (needScaling) { + CGContextSaveGState(context); + // Scale from the center of the gradient. We only ever scale non-deprecated gradients, + // for which m_p0 == m_p1. + ASSERT(m_p0 == m_p1); + CGContextTranslateCTM(context, m_p0.x(), m_p0.y()); + CGContextScaleCTM(context, 1, 1 / aspectRatio()); + CGContextTranslateCTM(context, -m_p0.x(), -m_p0.y()); + } + + CGContextDrawRadialGradient(context, platformGradient(), m_p0, m_r0, m_p1, m_r1, extendOptions); + + if (needScaling) + CGContextRestoreGState(context); + } else + CGContextDrawLinearGradient(context, platformGradient(), m_p0, m_p1, extendOptions); +#endif +} + +} //namespace diff --git a/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp b/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp new file mode 100644 index 0000000..c19bd72 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (C) 2010 Apple Inc. All rights reserved. + * Copyright (C) 2010 Google Inc. All rights reserved. + * + * 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" + +#if ENABLE(3D_CANVAS) + +#include "GraphicsContext3D.h" +#include "GraphicsContextCG.h" + +#include "Image.h" + +#include <CoreGraphics/CGBitmapContext.h> +#include <CoreGraphics/CGContext.h> +#include <CoreGraphics/CGDataProvider.h> +#include <CoreGraphics/CGImage.h> + +#include <wtf/RetainPtr.h> + +namespace WebCore { + +enum SourceDataFormatBase { + SourceFormatBaseR = 0, + SourceFormatBaseA, + SourceFormatBaseRA, + SourceFormatBaseAR, + SourceFormatBaseRGB, + SourceFormatBaseRGBA, + SourceFormatBaseARGB, + SourceFormatBaseNumFormats +}; + +enum AlphaFormat { + AlphaFormatNone = 0, + AlphaFormatFirst, + AlphaFormatLast, + AlphaFormatNumFormats +}; + +// This returns SourceFormatNumFormats if the combination of input parameters is unsupported. +static GraphicsContext3D::SourceDataFormat getSourceDataFormat(unsigned int componentsPerPixel, AlphaFormat alphaFormat, bool is16BitFormat, bool bigEndian) +{ + const static SourceDataFormatBase formatTableBase[4][AlphaFormatNumFormats] = { // componentsPerPixel x AlphaFormat + // AlphaFormatNone AlphaFormatFirst AlphaFormatLast + { SourceFormatBaseR, SourceFormatBaseA, SourceFormatBaseA }, // 1 componentsPerPixel + { SourceFormatBaseNumFormats, SourceFormatBaseAR, SourceFormatBaseRA }, // 2 componentsPerPixel + { SourceFormatBaseRGB, SourceFormatBaseNumFormats, SourceFormatBaseNumFormats }, // 3 componentsPerPixel + { SourceFormatBaseNumFormats, SourceFormatBaseARGB, SourceFormatBaseRGBA } // 4 componentsPerPixel + }; + const static GraphicsContext3D::SourceDataFormat formatTable[SourceFormatBaseNumFormats][4] = { // SourceDataFormatBase x bitsPerComponent x endian + // 8bits, little endian 8bits, big endian 16bits, little endian 16bits, big endian + { GraphicsContext3D::SourceFormatR8, GraphicsContext3D::SourceFormatR8, GraphicsContext3D::SourceFormatR16Little, GraphicsContext3D::SourceFormatR16Big }, + { GraphicsContext3D::SourceFormatA8, GraphicsContext3D::SourceFormatA8, GraphicsContext3D::SourceFormatA16Little, GraphicsContext3D::SourceFormatA16Big }, + { GraphicsContext3D::SourceFormatAR8, GraphicsContext3D::SourceFormatRA8, GraphicsContext3D::SourceFormatRA16Little, GraphicsContext3D::SourceFormatRA16Big }, + { GraphicsContext3D::SourceFormatRA8, GraphicsContext3D::SourceFormatAR8, GraphicsContext3D::SourceFormatAR16Little, GraphicsContext3D::SourceFormatAR16Big }, + { GraphicsContext3D::SourceFormatBGR8, GraphicsContext3D::SourceFormatRGB8, GraphicsContext3D::SourceFormatRGB16Little, GraphicsContext3D::SourceFormatRGB16Big }, + { GraphicsContext3D::SourceFormatABGR8, GraphicsContext3D::SourceFormatRGBA8, GraphicsContext3D::SourceFormatRGBA16Little, GraphicsContext3D::SourceFormatRGBA16Big }, + { GraphicsContext3D::SourceFormatBGRA8, GraphicsContext3D::SourceFormatARGB8, GraphicsContext3D::SourceFormatARGB16Little, GraphicsContext3D::SourceFormatARGB16Big } + }; + + ASSERT(componentsPerPixel <= 4 && componentsPerPixel > 0); + SourceDataFormatBase formatBase = formatTableBase[componentsPerPixel - 1][alphaFormat]; + if (formatBase == SourceFormatBaseNumFormats) + return GraphicsContext3D::SourceFormatNumFormats; + return formatTable[formatBase][(is16BitFormat ? 2 : 0) + (bigEndian ? 1 : 0)]; +} + +bool GraphicsContext3D::getImageData(Image* image, + GC3Denum format, + GC3Denum type, + bool premultiplyAlpha, + bool ignoreGammaAndColorProfile, + Vector<uint8_t>& outputVector) +{ + if (!image) + return false; + CGImageRef cgImage; + RetainPtr<CGImageRef> decodedImage; + if (image->data()) { + ImageSource decoder(ImageSource::AlphaNotPremultiplied, + ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); + decoder.setData(image->data(), true); + if (!decoder.frameCount()) + return false; + decodedImage = decoder.createFrameAtIndex(0); + cgImage = decodedImage.get(); + } else + cgImage = image->nativeImageForCurrentFrame(); + if (!cgImage) + return false; + + size_t width = CGImageGetWidth(cgImage); + size_t height = CGImageGetHeight(cgImage); + if (!width || !height) + return false; + size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); + size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); + if (bitsPerComponent != 8 && bitsPerComponent != 16) + return false; + if (bitsPerPixel % bitsPerComponent) + return false; + size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; + + CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); + bool bigEndianSource = false; + // These could technically be combined into one large switch + // statement, but we prefer not to so that we fail fast if we + // encounter an unexpected image configuration. + if (bitsPerComponent == 16) { + switch (bitInfo & kCGBitmapByteOrderMask) { + case kCGBitmapByteOrder16Big: + bigEndianSource = true; + break; + case kCGBitmapByteOrder16Little: + bigEndianSource = false; + break; + case kCGBitmapByteOrderDefault: + // This is a bug in earlier version of cg where the default endian + // is little whereas the decoded 16-bit png image data is actually + // Big. Later version (10.6.4) no longer returns ByteOrderDefault. + bigEndianSource = true; + break; + default: + return false; + } + } else { + switch (bitInfo & kCGBitmapByteOrderMask) { + case kCGBitmapByteOrder32Big: + bigEndianSource = true; + break; + case kCGBitmapByteOrder32Little: + bigEndianSource = false; + break; + case kCGBitmapByteOrderDefault: + // It appears that the default byte order is actually big + // endian even on little endian architectures. + bigEndianSource = true; + break; + default: + return false; + } + } + + AlphaOp neededAlphaOp = AlphaDoNothing; + AlphaFormat alphaFormat = AlphaFormatNone; + switch (CGImageGetAlphaInfo(cgImage)) { + case kCGImageAlphaPremultipliedFirst: + // This path is only accessible for MacOS earlier than 10.6.4. + // This is a special case for texImage2D with HTMLCanvasElement input, + // in which case image->data() should be null. + ASSERT(!image->data()); + if (!premultiplyAlpha) + neededAlphaOp = AlphaDoUnmultiply; + alphaFormat = AlphaFormatFirst; + break; + case kCGImageAlphaFirst: + // This path is only accessible for MacOS earlier than 10.6.4. + if (premultiplyAlpha) + neededAlphaOp = AlphaDoPremultiply; + alphaFormat = AlphaFormatFirst; + break; + case kCGImageAlphaNoneSkipFirst: + // This path is only accessible for MacOS earlier than 10.6.4. + alphaFormat = AlphaFormatFirst; + break; + case kCGImageAlphaPremultipliedLast: + // This is a special case for texImage2D with HTMLCanvasElement input, + // in which case image->data() should be null. + ASSERT(!image->data()); + if (!premultiplyAlpha) + neededAlphaOp = AlphaDoUnmultiply; + alphaFormat = AlphaFormatLast; + break; + case kCGImageAlphaLast: + if (premultiplyAlpha) + neededAlphaOp = AlphaDoPremultiply; + alphaFormat = AlphaFormatLast; + break; + case kCGImageAlphaNoneSkipLast: + alphaFormat = AlphaFormatLast; + break; + case kCGImageAlphaNone: + alphaFormat = AlphaFormatNone; + break; + default: + return false; + } + SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); + if (srcDataFormat == SourceFormatNumFormats) + return false; + + RetainPtr<CFDataRef> pixelData; + pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); + if (!pixelData) + return false; + const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); + outputVector.resize(width * height * 4); + unsigned int srcUnpackAlignment = 0; + size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); + unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; + if (padding) { + srcUnpackAlignment = padding + 1; + while (bytesPerRow % srcUnpackAlignment) + ++srcUnpackAlignment; + } + bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, + format, type, neededAlphaOp, outputVector.data()); + return rt; +} + +void GraphicsContext3D::paintToCanvas(const unsigned char* imagePixels, int imageWidth, int imageHeight, int canvasWidth, int canvasHeight, CGContextRef context) +{ + if (!imagePixels || imageWidth <= 0 || imageHeight <= 0 || canvasWidth <= 0 || canvasHeight <= 0 || !context) + return; + int rowBytes = imageWidth * 4; + RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithData(0, imagePixels, rowBytes * imageHeight, 0)); + RetainPtr<CGImageRef> cgImage(AdoptCF, CGImageCreate(imageWidth, imageHeight, 8, 32, rowBytes, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, + dataProvider.get(), 0, false, kCGRenderingIntentDefault)); + // CSS styling may cause the canvas's content to be resized on + // the page. Go back to the Canvas to figure out the correct + // width and height to draw. + CGRect rect = CGRectMake(0, 0, canvasWidth, canvasHeight); + // We want to completely overwrite the previous frame's + // rendering results. + CGContextSaveGState(context); + CGContextSetBlendMode(context, kCGBlendModeCopy); + CGContextSetInterpolationQuality(context, kCGInterpolationNone); + CGContextDrawImage(context, rect, cgImage.get()); + CGContextRestoreGState(context); +} + +} // namespace WebCore + +#endif // ENABLE(3D_CANVAS) diff --git a/Source/WebCore/platform/graphics/cg/GraphicsContextCG.cpp b/Source/WebCore/platform/graphics/cg/GraphicsContextCG.cpp new file mode 100644 index 0000000..acd912f --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/GraphicsContextCG.cpp @@ -0,0 +1,1260 @@ +/* + * Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * 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. + */ + +#define _USE_MATH_DEFINES 1 +#include "config.h" +#include "GraphicsContextCG.h" + +#include "AffineTransform.h" +#include "FloatConversion.h" +#include "GraphicsContextPlatformPrivateCG.h" +#include "ImageBuffer.h" +#include "KURL.h" +#include "Path.h" +#include "Pattern.h" + +#include <CoreGraphics/CoreGraphics.h> +#include <wtf/MathExtras.h> +#include <wtf/OwnArrayPtr.h> +#include <wtf/RetainPtr.h> +#include <wtf/UnusedParam.h> + +#if PLATFORM(MAC) || PLATFORM(CHROMIUM) +#include "WebCoreSystemInterface.h" +#endif + +#if PLATFORM(WIN) +#include <WebKitSystemInterface/WebKitSystemInterface.h> +#endif + +#if PLATFORM(MAC) || (PLATFORM(CHROMIUM) && OS(DARWIN)) + +#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) +// Building on 10.6 or later: kCGInterpolationMedium is defined in the CGInterpolationQuality enum. +#define HAVE_CG_INTERPOLATION_MEDIUM 1 +#endif + +#if !defined(TARGETING_TIGER) && !defined(TARGETING_LEOPARD) +// Targeting 10.6 or later: use kCGInterpolationMedium. +#define WTF_USE_CG_INTERPOLATION_MEDIUM 1 +#endif + +#endif + +using namespace std; + +namespace WebCore { + +static void setCGFillColor(CGContextRef context, const Color& color, ColorSpace colorSpace) +{ + CGContextSetFillColorWithColor(context, cachedCGColor(color, colorSpace)); +} + +static void setCGStrokeColor(CGContextRef context, const Color& color, ColorSpace colorSpace) +{ + CGContextSetStrokeColorWithColor(context, cachedCGColor(color, colorSpace)); +} + +CGColorSpaceRef deviceRGBColorSpaceRef() +{ + static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB(); + return deviceSpace; +} + +CGColorSpaceRef sRGBColorSpaceRef() +{ + // FIXME: Windows should be able to use kCGColorSpaceSRGB, this is tracked by http://webkit.org/b/31363. +#if PLATFORM(WIN) || defined(BUILDING_ON_TIGER) + return deviceRGBColorSpaceRef(); +#else + static CGColorSpaceRef sRGBSpace = CGColorSpaceCreateWithName(kCGColorSpaceSRGB); + return sRGBSpace; +#endif +} + +CGColorSpaceRef linearRGBColorSpaceRef() +{ + // FIXME: Windows should be able to use kCGColorSpaceGenericRGBLinear, this is tracked by http://webkit.org/b/31363. +#if PLATFORM(WIN) || defined(BUILDING_ON_TIGER) + return deviceRGBColorSpaceRef(); +#else + static CGColorSpaceRef linearRGBSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGBLinear); + return linearRGBSpace; +#endif +} + +void GraphicsContext::platformInit(CGContextRef cgContext) +{ + m_data = new GraphicsContextPlatformPrivate(cgContext); + setPaintingDisabled(!cgContext); + if (cgContext) { + // Make sure the context starts in sync with our state. + setPlatformFillColor(fillColor(), fillColorSpace()); + setPlatformStrokeColor(strokeColor(), strokeColorSpace()); + } +} + +void GraphicsContext::platformDestroy() +{ + delete m_data; +} + +CGContextRef GraphicsContext::platformContext() const +{ + ASSERT(!paintingDisabled()); + ASSERT(m_data->m_cgContext); + return m_data->m_cgContext.get(); +} + +void GraphicsContext::savePlatformState() +{ + // Note: Do not use this function within this class implementation, since we want to avoid the extra + // save of the secondary context (in GraphicsContextPlatformPrivateCG.h). + CGContextSaveGState(platformContext()); + m_data->save(); +} + +void GraphicsContext::restorePlatformState() +{ + // Note: Do not use this function within this class implementation, since we want to avoid the extra + // restore of the secondary context (in GraphicsContextPlatformPrivateCG.h). + CGContextRestoreGState(platformContext()); + m_data->restore(); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +// Draws a filled rectangle with a stroked border. +void GraphicsContext::drawRect(const IntRect& rect) +{ + // FIXME: this function does not handle patterns and gradients + // like drawPath does, it probably should. + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + + CGContextFillRect(context, rect); + + if (strokeStyle() != NoStroke) { + // We do a fill of four rects to simulate the stroke of a border. + Color oldFillColor = fillColor(); + if (oldFillColor != strokeColor()) + setCGFillColor(context, strokeColor(), strokeColorSpace()); + CGRect rects[4] = { + FloatRect(rect.x(), rect.y(), rect.width(), 1), + FloatRect(rect.x(), rect.bottom() - 1, rect.width(), 1), + FloatRect(rect.x(), rect.y() + 1, 1, rect.height() - 2), + FloatRect(rect.right() - 1, rect.y() + 1, 1, rect.height() - 2) + }; + CGContextFillRects(context, rects, 4); + if (oldFillColor != strokeColor()) + setCGFillColor(context, oldFillColor, fillColorSpace()); + } +} + +// This is only used to draw borders. +void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2) +{ + if (paintingDisabled()) + return; + + if (strokeStyle() == NoStroke) + return; + + float width = strokeThickness(); + + FloatPoint p1 = point1; + FloatPoint p2 = point2; + bool isVerticalLine = (p1.x() == p2.x()); + + // For odd widths, we add in 0.5 to the appropriate x/y so that the float arithmetic + // works out. For example, with a border width of 3, KHTML will pass us (y1+y2)/2, e.g., + // (50+53)/2 = 103/2 = 51 when we want 51.5. It is always true that an even width gave + // us a perfect position, but an odd width gave us a position that is off by exactly 0.5. + if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) { + if (isVerticalLine) { + p1.move(0, width); + p2.move(0, -width); + } else { + p1.move(width, 0); + p2.move(-width, 0); + } + } + + if (((int)width) % 2) { + if (isVerticalLine) { + // We're a vertical line. Adjust our x. + p1.move(0.5f, 0.0f); + p2.move(0.5f, 0.0f); + } else { + // We're a horizontal line. Adjust our y. + p1.move(0.0f, 0.5f); + p2.move(0.0f, 0.5f); + } + } + + int patWidth = 0; + switch (strokeStyle()) { + case NoStroke: + case SolidStroke: + break; + case DottedStroke: + patWidth = (int)width; + break; + case DashedStroke: + patWidth = 3 * (int)width; + break; + } + + CGContextRef context = platformContext(); + + if (shouldAntialias()) + CGContextSetShouldAntialias(context, false); + + if (patWidth) { + CGContextSaveGState(context); + + // Do a rect fill of our endpoints. This ensures we always have the + // appearance of being a border. We then draw the actual dotted/dashed line. + setCGFillColor(context, strokeColor(), strokeColorSpace()); // The save/restore make it safe to mutate the fill color here without setting it back to the old color. + if (isVerticalLine) { + CGContextFillRect(context, FloatRect(p1.x() - width / 2, p1.y() - width, width, width)); + CGContextFillRect(context, FloatRect(p2.x() - width / 2, p2.y(), width, width)); + } else { + CGContextFillRect(context, FloatRect(p1.x() - width, p1.y() - width / 2, width, width)); + CGContextFillRect(context, FloatRect(p2.x(), p2.y() - width / 2, width, width)); + } + + // Example: 80 pixels with a width of 30 pixels. + // Remainder is 20. The maximum pixels of line we could paint + // will be 50 pixels. + int distance = (isVerticalLine ? (point2.y() - point1.y()) : (point2.x() - point1.x())) - 2*(int)width; + int remainder = distance % patWidth; + int coverage = distance - remainder; + int numSegments = coverage / patWidth; + + float patternOffset = 0.0f; + // Special case 1px dotted borders for speed. + if (patWidth == 1) + patternOffset = 1.0f; + else { + bool evenNumberOfSegments = !(numSegments % 2); + if (remainder) + evenNumberOfSegments = !evenNumberOfSegments; + if (evenNumberOfSegments) { + if (remainder) { + patternOffset += patWidth - remainder; + patternOffset += remainder / 2; + } else + patternOffset = patWidth / 2; + } else { + if (remainder) + patternOffset = (patWidth - remainder)/2; + } + } + + const CGFloat dottedLine[2] = { patWidth, patWidth }; + CGContextSetLineDash(context, patternOffset, dottedLine, 2); + } + + CGContextBeginPath(context); + CGContextMoveToPoint(context, p1.x(), p1.y()); + CGContextAddLineToPoint(context, p2.x(), p2.y()); + + CGContextStrokePath(context); + + if (patWidth) + CGContextRestoreGState(context); + + if (shouldAntialias()) + CGContextSetShouldAntialias(context, true); +} + +// This method is only used to draw the little circles used in lists. +void GraphicsContext::drawEllipse(const IntRect& rect) +{ + if (paintingDisabled()) + return; + + Path path; + path.addEllipse(rect); + drawPath(path); +} + + +void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) +{ + if (paintingDisabled() || strokeStyle() == NoStroke || strokeThickness() <= 0.0f) + return; + + CGContextRef context = platformContext(); + CGContextSaveGState(context); + CGContextBeginPath(context); + CGContextSetShouldAntialias(context, false); + + int x = rect.x(); + int y = rect.y(); + float w = (float)rect.width(); + float h = (float)rect.height(); + float scaleFactor = h / w; + float reverseScaleFactor = w / h; + + if (w != h) + scale(FloatSize(1, scaleFactor)); + + float hRadius = w / 2; + float vRadius = h / 2; + float fa = startAngle; + float falen = fa + angleSpan; + float start = -fa * piFloat / 180.0f; + float end = -falen * piFloat / 180.0f; + CGContextAddArc(context, x + hRadius, (y + vRadius) * reverseScaleFactor, hRadius, start, end, true); + + if (w != h) + scale(FloatSize(1, reverseScaleFactor)); + + float width = strokeThickness(); + int patWidth = 0; + + switch (strokeStyle()) { + case DottedStroke: + patWidth = (int)(width / 2); + break; + case DashedStroke: + patWidth = 3 * (int)(width / 2); + break; + default: + break; + } + + if (patWidth) { + // Example: 80 pixels with a width of 30 pixels. + // Remainder is 20. The maximum pixels of line we could paint + // will be 50 pixels. + int distance; + if (hRadius == vRadius) + distance = static_cast<int>((piFloat * hRadius) / 2.0f); + else // We are elliptical and will have to estimate the distance + distance = static_cast<int>((piFloat * sqrtf((hRadius * hRadius + vRadius * vRadius) / 2.0f)) / 2.0f); + + int remainder = distance % patWidth; + int coverage = distance - remainder; + int numSegments = coverage / patWidth; + + float patternOffset = 0.0f; + // Special case 1px dotted borders for speed. + if (patWidth == 1) + patternOffset = 1.0f; + else { + bool evenNumberOfSegments = !(numSegments % 2); + if (remainder) + evenNumberOfSegments = !evenNumberOfSegments; + if (evenNumberOfSegments) { + if (remainder) { + patternOffset += patWidth - remainder; + patternOffset += remainder / 2.0f; + } else + patternOffset = patWidth / 2.0f; + } else { + if (remainder) + patternOffset = (patWidth - remainder) / 2.0f; + } + } + + const CGFloat dottedLine[2] = { patWidth, patWidth }; + CGContextSetLineDash(context, patternOffset, dottedLine, 2); + } + + CGContextStrokePath(context); + + CGContextRestoreGState(context); +} + +static void addConvexPolygonToPath(Path& path, size_t numberOfPoints, const FloatPoint* points) +{ + ASSERT(numberOfPoints > 0); + + path.moveTo(points[0]); + for (size_t i = 1; i < numberOfPoints; ++i) + path.addLineTo(points[i]); + path.closeSubpath(); +} + +void GraphicsContext::drawConvexPolygon(size_t numberOfPoints, const FloatPoint* points, bool antialiased) +{ + if (paintingDisabled()) + return; + + if (numberOfPoints <= 1) + return; + + CGContextRef context = platformContext(); + + if (antialiased != shouldAntialias()) + CGContextSetShouldAntialias(context, antialiased); + + Path path; + addConvexPolygonToPath(path, numberOfPoints, points); + drawPath(path); + + if (antialiased != shouldAntialias()) + CGContextSetShouldAntialias(context, shouldAntialias()); +} + +void GraphicsContext::clipConvexPolygon(size_t numberOfPoints, const FloatPoint* points, bool antialias) +{ + if (paintingDisabled()) + return; + + if (numberOfPoints <= 1) + return; + + CGContextRef context = platformContext(); + + if (antialias != shouldAntialias()) + CGContextSetShouldAntialias(context, antialias); + + Path path; + addConvexPolygonToPath(path, numberOfPoints, points); + clipPath(path, RULE_NONZERO); + + if (antialias != shouldAntialias()) + CGContextSetShouldAntialias(context, shouldAntialias()); +} + +void GraphicsContext::applyStrokePattern() +{ + CGContextRef cgContext = platformContext(); + + RetainPtr<CGPatternRef> platformPattern(AdoptCF, m_state.strokePattern->createPlatformPattern(getCTM())); + if (!platformPattern) + return; + + RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0)); + CGContextSetStrokeColorSpace(cgContext, patternSpace.get()); + + const CGFloat patternAlpha = 1; + CGContextSetStrokePattern(cgContext, platformPattern.get(), &patternAlpha); +} + +void GraphicsContext::applyFillPattern() +{ + CGContextRef cgContext = platformContext(); + + RetainPtr<CGPatternRef> platformPattern(AdoptCF, m_state.fillPattern->createPlatformPattern(getCTM())); + if (!platformPattern) + return; + + RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0)); + CGContextSetFillColorSpace(cgContext, patternSpace.get()); + + const CGFloat patternAlpha = 1; + CGContextSetFillPattern(cgContext, platformPattern.get(), &patternAlpha); +} + +static inline bool calculateDrawingMode(const GraphicsContextState& state, CGPathDrawingMode& mode) +{ + bool shouldFill = state.fillPattern || state.fillColor.alpha(); + bool shouldStroke = state.strokePattern || (state.strokeStyle != NoStroke && state.strokeColor.alpha()); + bool useEOFill = state.fillRule == RULE_EVENODD; + + if (shouldFill) { + if (shouldStroke) { + if (useEOFill) + mode = kCGPathEOFillStroke; + else + mode = kCGPathFillStroke; + } else { // fill, no stroke + if (useEOFill) + mode = kCGPathEOFill; + else + mode = kCGPathFill; + } + } else { + // Setting mode to kCGPathStroke even if shouldStroke is false. In that case, we return false and mode will not be used, + // but the compiler will not complain about an uninitialized variable. + mode = kCGPathStroke; + } + + return shouldFill || shouldStroke; +} + +void GraphicsContext::drawPath(const Path& path) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + const GraphicsContextState& state = m_state; + + if (state.fillGradient || state.strokeGradient) { + // We don't have any optimized way to fill & stroke a path using gradients + // FIXME: Be smarter about this. + fillPath(path); + strokePath(path); + return; + } + + CGContextBeginPath(context); + CGContextAddPath(context, path.platformPath()); + + if (state.fillPattern) + applyFillPattern(); + if (state.strokePattern) + applyStrokePattern(); + + CGPathDrawingMode drawingMode; + if (calculateDrawingMode(state, drawingMode)) + CGContextDrawPath(context, drawingMode); +} + +static inline void fillPathWithFillRule(CGContextRef context, WindRule fillRule) +{ + if (fillRule == RULE_EVENODD) + CGContextEOFillPath(context); + else + CGContextFillPath(context); +} + +void GraphicsContext::fillPath(const Path& path) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + + CGContextBeginPath(context); + CGContextAddPath(context, path.platformPath()); + + if (m_state.fillGradient) { + CGContextSaveGState(context); + if (fillRule() == RULE_EVENODD) + CGContextEOClip(context); + else + CGContextClip(context); + CGContextConcatCTM(context, m_state.fillGradient->gradientSpaceTransform()); + m_state.fillGradient->paint(this); + CGContextRestoreGState(context); + return; + } + + if (m_state.fillPattern) + applyFillPattern(); + fillPathWithFillRule(context, fillRule()); +} + +void GraphicsContext::strokePath(const Path& path) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + + CGContextBeginPath(context); + CGContextAddPath(context, path.platformPath()); + + if (m_state.strokeGradient) { + CGContextSaveGState(context); + CGContextReplacePathWithStrokedPath(context); + CGContextClip(context); + CGContextConcatCTM(context, m_state.strokeGradient->gradientSpaceTransform()); + m_state.strokeGradient->paint(this); + CGContextRestoreGState(context); + return; + } + + if (m_state.strokePattern) + applyStrokePattern(); + CGContextStrokePath(context); +} + +void GraphicsContext::fillRect(const FloatRect& rect) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + + if (m_state.fillGradient) { + CGContextSaveGState(context); + CGContextConcatCTM(context, m_state.fillGradient->gradientSpaceTransform()); + if (hasShadow()) { + CGLayerRef layer = CGLayerCreateWithContext(context, CGSizeMake(rect.width(), rect.height()), 0); + CGContextRef layerContext = CGLayerGetContext(layer); + m_state.fillGradient->paint(layerContext); + CGContextDrawLayerAtPoint(context, CGPointMake(rect.left(), rect.top()), layer); + CGLayerRelease(layer); + } else { + CGContextClipToRect(context, rect); + m_state.fillGradient->paint(this); + } + CGContextRestoreGState(context); + return; + } + + if (m_state.fillPattern) + applyFillPattern(); + CGContextFillRect(context, rect); +} + +void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, ColorSpace colorSpace) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + Color oldFillColor = fillColor(); + ColorSpace oldColorSpace = fillColorSpace(); + + if (oldFillColor != color || oldColorSpace != colorSpace) + setCGFillColor(context, color, colorSpace); + + CGContextFillRect(context, rect); + + if (oldFillColor != color || oldColorSpace != colorSpace) + setCGFillColor(context, oldFillColor, oldColorSpace); +} + +void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + Color oldFillColor = fillColor(); + ColorSpace oldColorSpace = fillColorSpace(); + + if (oldFillColor != color || oldColorSpace != colorSpace) + setCGFillColor(context, color, colorSpace); + + Path path; + path.addRoundedRect(rect, topLeft, topRight, bottomLeft, bottomRight); + fillPath(path); + + if (oldFillColor != color || oldColorSpace != colorSpace) + setCGFillColor(context, oldFillColor, oldColorSpace); +} + +void GraphicsContext::clip(const FloatRect& rect) +{ + if (paintingDisabled()) + return; + CGContextClipToRect(platformContext(), rect); + m_data->clip(rect); +} + +void GraphicsContext::clipOut(const IntRect& rect) +{ + if (paintingDisabled()) + return; + + CGRect rects[2] = { CGContextGetClipBoundingBox(platformContext()), rect }; + CGContextBeginPath(platformContext()); + CGContextAddRects(platformContext(), rects, 2); + CGContextEOClip(platformContext()); +} + +void GraphicsContext::clipPath(const Path& path, WindRule clipRule) +{ + if (paintingDisabled()) + return; + + if (path.isEmpty()) + return; + + CGContextRef context = platformContext(); + + CGContextBeginPath(platformContext()); + CGContextAddPath(platformContext(), path.platformPath()); + + if (clipRule == RULE_EVENODD) + CGContextEOClip(context); + else + CGContextClip(context); +} + +void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness) +{ + if (paintingDisabled()) + return; + + clip(rect); + CGContextRef context = platformContext(); + + // Add outer ellipse + CGContextAddEllipseInRect(context, CGRectMake(rect.x(), rect.y(), rect.width(), rect.height())); + // Add inner ellipse. + CGContextAddEllipseInRect(context, CGRectMake(rect.x() + thickness, rect.y() + thickness, + rect.width() - (thickness * 2), rect.height() - (thickness * 2))); + + CGContextEOClip(context); +} + +void GraphicsContext::beginTransparencyLayer(float opacity) +{ + if (paintingDisabled()) + return; + CGContextRef context = platformContext(); + CGContextSaveGState(context); + CGContextSetAlpha(context, opacity); + CGContextBeginTransparencyLayer(context, 0); + m_data->beginTransparencyLayer(); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +void GraphicsContext::endTransparencyLayer() +{ + if (paintingDisabled()) + return; + CGContextRef context = platformContext(); + CGContextEndTransparencyLayer(context); + CGContextRestoreGState(context); + m_data->endTransparencyLayer(); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +void GraphicsContext::setPlatformShadow(const FloatSize& offset, float blur, const Color& color, ColorSpace colorSpace) +{ + if (paintingDisabled()) + return; + CGFloat xOffset = offset.width(); + CGFloat yOffset = offset.height(); + CGFloat blurRadius = blur; + CGContextRef context = platformContext(); + + if (!m_state.shadowsIgnoreTransforms) { + CGAffineTransform userToBaseCTM = wkGetUserToBaseCTM(context); + + CGFloat A = userToBaseCTM.a * userToBaseCTM.a + userToBaseCTM.b * userToBaseCTM.b; + CGFloat B = userToBaseCTM.a * userToBaseCTM.c + userToBaseCTM.b * userToBaseCTM.d; + CGFloat C = B; + CGFloat D = userToBaseCTM.c * userToBaseCTM.c + userToBaseCTM.d * userToBaseCTM.d; + + CGFloat smallEigenvalue = narrowPrecisionToCGFloat(sqrt(0.5 * ((A + D) - sqrt(4 * B * C + (A - D) * (A - D))))); + + // Extreme "blur" values can make text drawing crash or take crazy long times, so clamp + blurRadius = min(blur * smallEigenvalue, narrowPrecisionToCGFloat(1000.0)); + + CGSize offsetInBaseSpace = CGSizeApplyAffineTransform(offset, userToBaseCTM); + + xOffset = offsetInBaseSpace.width; + yOffset = offsetInBaseSpace.height; + } + + // Work around <rdar://problem/5539388> by ensuring that the offsets will get truncated + // to the desired integer. + static const CGFloat extraShadowOffset = narrowPrecisionToCGFloat(1.0 / 128); + if (xOffset > 0) + xOffset += extraShadowOffset; + else if (xOffset < 0) + xOffset -= extraShadowOffset; + + if (yOffset > 0) + yOffset += extraShadowOffset; + else if (yOffset < 0) + yOffset -= extraShadowOffset; + + // Check for an invalid color, as this means that the color was not set for the shadow + // and we should therefore just use the default shadow color. + if (!color.isValid()) + CGContextSetShadow(context, CGSizeMake(xOffset, yOffset), blurRadius); + else + CGContextSetShadowWithColor(context, CGSizeMake(xOffset, yOffset), blurRadius, cachedCGColor(color, colorSpace)); +} + +void GraphicsContext::clearPlatformShadow() +{ + if (paintingDisabled()) + return; + CGContextSetShadowWithColor(platformContext(), CGSizeZero, 0, 0); +} + +void GraphicsContext::setMiterLimit(float limit) +{ + if (paintingDisabled()) + return; + CGContextSetMiterLimit(platformContext(), limit); +} + +void GraphicsContext::setAlpha(float alpha) +{ + if (paintingDisabled()) + return; + CGContextSetAlpha(platformContext(), alpha); +} + +void GraphicsContext::clearRect(const FloatRect& r) +{ + if (paintingDisabled()) + return; + CGContextClearRect(platformContext(), r); +} + +void GraphicsContext::strokeRect(const FloatRect& r, float lineWidth) +{ + if (paintingDisabled()) + return; + + CGContextRef context = platformContext(); + + if (m_state.strokeGradient) { + CGContextSaveGState(context); + setStrokeThickness(lineWidth); + CGContextAddRect(context, r); + CGContextReplacePathWithStrokedPath(context); + CGContextClip(context); + m_state.strokeGradient->paint(this); + CGContextRestoreGState(context); + return; + } + + if (m_state.strokePattern) + applyStrokePattern(); + CGContextStrokeRectWithWidth(context, r, lineWidth); +} + +void GraphicsContext::setLineCap(LineCap cap) +{ + if (paintingDisabled()) + return; + switch (cap) { + case ButtCap: + CGContextSetLineCap(platformContext(), kCGLineCapButt); + break; + case RoundCap: + CGContextSetLineCap(platformContext(), kCGLineCapRound); + break; + case SquareCap: + CGContextSetLineCap(platformContext(), kCGLineCapSquare); + break; + } +} + +void GraphicsContext::setLineDash(const DashArray& dashes, float dashOffset) +{ + CGContextSetLineDash(platformContext(), dashOffset, dashes.data(), dashes.size()); +} + +void GraphicsContext::setLineJoin(LineJoin join) +{ + if (paintingDisabled()) + return; + switch (join) { + case MiterJoin: + CGContextSetLineJoin(platformContext(), kCGLineJoinMiter); + break; + case RoundJoin: + CGContextSetLineJoin(platformContext(), kCGLineJoinRound); + break; + case BevelJoin: + CGContextSetLineJoin(platformContext(), kCGLineJoinBevel); + break; + } +} + +void GraphicsContext::clip(const Path& path) +{ + if (paintingDisabled()) + return; + CGContextRef context = platformContext(); + + // CGContextClip does nothing if the path is empty, so in this case, we + // instead clip against a zero rect to reduce the clipping region to + // nothing - which is the intended behavior of clip() if the path is empty. + if (path.isEmpty()) + CGContextClipToRect(context, CGRectZero); + else { + CGContextBeginPath(context); + CGContextAddPath(context, path.platformPath()); + CGContextClip(context); + } + m_data->clip(path); +} + +void GraphicsContext::canvasClip(const Path& path) +{ + clip(path); +} + +void GraphicsContext::clipOut(const Path& path) +{ + if (paintingDisabled()) + return; + + CGContextBeginPath(platformContext()); + CGContextAddRect(platformContext(), CGContextGetClipBoundingBox(platformContext())); + CGContextAddPath(platformContext(), path.platformPath()); + CGContextEOClip(platformContext()); +} + +void GraphicsContext::scale(const FloatSize& size) +{ + if (paintingDisabled()) + return; + CGContextScaleCTM(platformContext(), size.width(), size.height()); + m_data->scale(size); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +void GraphicsContext::rotate(float angle) +{ + if (paintingDisabled()) + return; + CGContextRotateCTM(platformContext(), angle); + m_data->rotate(angle); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +void GraphicsContext::translate(float x, float y) +{ + if (paintingDisabled()) + return; + CGContextTranslateCTM(platformContext(), x, y); + m_data->translate(x, y); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +void GraphicsContext::concatCTM(const AffineTransform& transform) +{ + if (paintingDisabled()) + return; + CGContextConcatCTM(platformContext(), transform); + m_data->concatCTM(transform); + m_data->m_userToDeviceTransformKnownToBeIdentity = false; +} + +AffineTransform GraphicsContext::getCTM() const +{ + CGAffineTransform t = CGContextGetCTM(platformContext()); + return AffineTransform(t.a, t.b, t.c, t.d, t.tx, t.ty); +} + +FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& rect) +{ + // It is not enough just to round to pixels in device space. The rotation part of the + // affine transform matrix to device space can mess with this conversion if we have a + // rotating image like the hands of the world clock widget. We just need the scale, so + // we get the affine transform matrix and extract the scale. + + if (m_data->m_userToDeviceTransformKnownToBeIdentity) + return rect; + + CGAffineTransform deviceMatrix = CGContextGetUserSpaceToDeviceSpaceTransform(platformContext()); + if (CGAffineTransformIsIdentity(deviceMatrix)) { + m_data->m_userToDeviceTransformKnownToBeIdentity = true; + return rect; + } + + float deviceScaleX = sqrtf(deviceMatrix.a * deviceMatrix.a + deviceMatrix.b * deviceMatrix.b); + float deviceScaleY = sqrtf(deviceMatrix.c * deviceMatrix.c + deviceMatrix.d * deviceMatrix.d); + + CGPoint deviceOrigin = CGPointMake(rect.x() * deviceScaleX, rect.y() * deviceScaleY); + CGPoint deviceLowerRight = CGPointMake((rect.x() + rect.width()) * deviceScaleX, + (rect.y() + rect.height()) * deviceScaleY); + + deviceOrigin.x = roundf(deviceOrigin.x); + deviceOrigin.y = roundf(deviceOrigin.y); + deviceLowerRight.x = roundf(deviceLowerRight.x); + deviceLowerRight.y = roundf(deviceLowerRight.y); + + // Don't let the height or width round to 0 unless either was originally 0 + if (deviceOrigin.y == deviceLowerRight.y && rect.height()) + deviceLowerRight.y += 1; + if (deviceOrigin.x == deviceLowerRight.x && rect.width()) + deviceLowerRight.x += 1; + + FloatPoint roundedOrigin = FloatPoint(deviceOrigin.x / deviceScaleX, deviceOrigin.y / deviceScaleY); + FloatPoint roundedLowerRight = FloatPoint(deviceLowerRight.x / deviceScaleX, deviceLowerRight.y / deviceScaleY); + return FloatRect(roundedOrigin, roundedLowerRight - roundedOrigin); +} + +void GraphicsContext::drawLineForText(const IntPoint& point, int width, bool printing) +{ + if (paintingDisabled()) + return; + + if (width <= 0) + return; + + float x = point.x(); + float y = point.y(); + float lineLength = width; + + // Use a minimum thickness of 0.5 in user space. + // See http://bugs.webkit.org/show_bug.cgi?id=4255 for details of why 0.5 is the right minimum thickness to use. + float thickness = max(strokeThickness(), 0.5f); + + bool restoreAntialiasMode = false; + + if (!printing) { + // On screen, use a minimum thickness of 1.0 in user space (later rounded to an integral number in device space). + float adjustedThickness = max(thickness, 1.0f); + + // FIXME: This should be done a better way. + // We try to round all parameters to integer boundaries in device space. If rounding pixels in device space + // makes our thickness more than double, then there must be a shrinking-scale factor and rounding to pixels + // in device space will make the underlines too thick. + CGRect lineRect = roundToDevicePixels(FloatRect(x, y, lineLength, adjustedThickness)); + if (lineRect.size.height < thickness * 2.0) { + x = lineRect.origin.x; + y = lineRect.origin.y; + lineLength = lineRect.size.width; + thickness = lineRect.size.height; + if (shouldAntialias()) { + CGContextSetShouldAntialias(platformContext(), false); + restoreAntialiasMode = true; + } + } + } + + if (fillColor() != strokeColor()) + setCGFillColor(platformContext(), strokeColor(), strokeColorSpace()); + CGContextFillRect(platformContext(), CGRectMake(x, y, lineLength, thickness)); + if (fillColor() != strokeColor()) + setCGFillColor(platformContext(), fillColor(), fillColorSpace()); + + if (restoreAntialiasMode) + CGContextSetShouldAntialias(platformContext(), true); +} + +void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect) +{ + if (paintingDisabled()) + return; + + RetainPtr<CFURLRef> urlRef(AdoptCF, link.createCFURL()); + if (!urlRef) + return; + + CGContextRef context = platformContext(); + + // Get the bounding box to handle clipping. + CGRect box = CGContextGetClipBoundingBox(context); + + IntRect intBox((int)box.origin.x, (int)box.origin.y, (int)box.size.width, (int)box.size.height); + IntRect rect = destRect; + rect.intersect(intBox); + + CGPDFContextSetURLForRect(context, urlRef.get(), + CGRectApplyAffineTransform(rect, CGContextGetCTM(context))); +} + +void GraphicsContext::setImageInterpolationQuality(InterpolationQuality mode) +{ + if (paintingDisabled()) + return; + + CGInterpolationQuality quality = kCGInterpolationDefault; + switch (mode) { + case InterpolationDefault: + quality = kCGInterpolationDefault; + break; + case InterpolationNone: + quality = kCGInterpolationNone; + break; + case InterpolationLow: + quality = kCGInterpolationLow; + break; + + // Fall through to InterpolationHigh if kCGInterpolationMedium is not usable. + case InterpolationMedium: +#if USE(CG_INTERPOLATION_MEDIUM) + quality = kCGInterpolationMedium; + break; +#endif + case InterpolationHigh: + quality = kCGInterpolationHigh; + break; + } + CGContextSetInterpolationQuality(platformContext(), quality); +} + +InterpolationQuality GraphicsContext::imageInterpolationQuality() const +{ + if (paintingDisabled()) + return InterpolationDefault; + + CGInterpolationQuality quality = CGContextGetInterpolationQuality(platformContext()); + switch (quality) { + case kCGInterpolationDefault: + return InterpolationDefault; + case kCGInterpolationNone: + return InterpolationNone; + case kCGInterpolationLow: + return InterpolationLow; +#if HAVE(CG_INTERPOLATION_MEDIUM) + // kCGInterpolationMedium is known to be present in the CGInterpolationQuality enum. + case kCGInterpolationMedium: +#if USE(CG_INTERPOLATION_MEDIUM) + // Only map to InterpolationMedium if targeting a system that understands it. + return InterpolationMedium; +#else + return InterpolationDefault; +#endif // USE(CG_INTERPOLATION_MEDIUM) +#endif // HAVE(CG_INTERPOLATION_MEDIUM) + case kCGInterpolationHigh: + return InterpolationHigh; + } + return InterpolationDefault; +} + +void GraphicsContext::setAllowsFontSmoothing(bool allowsFontSmoothing) +{ + UNUSED_PARAM(allowsFontSmoothing); +#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) + CGContextRef context = platformContext(); + CGContextSetAllowsFontSmoothing(context, allowsFontSmoothing); +#endif +} + +void GraphicsContext::setPlatformTextDrawingMode(TextDrawingModeFlags mode) +{ + if (paintingDisabled()) + return; + + // Wow, wish CG had used bits here. + CGContextRef context = platformContext(); + switch (mode) { + case TextModeInvisible: + CGContextSetTextDrawingMode(context, kCGTextInvisible); + break; + case TextModeFill: + CGContextSetTextDrawingMode(context, kCGTextFill); + break; + case TextModeStroke: + CGContextSetTextDrawingMode(context, kCGTextStroke); + break; + case TextModeFill | TextModeStroke: + CGContextSetTextDrawingMode(context, kCGTextFillStroke); + break; + case TextModeClip: + CGContextSetTextDrawingMode(context, kCGTextClip); + break; + case TextModeFill | TextModeClip: + CGContextSetTextDrawingMode(context, kCGTextFillClip); + break; + case TextModeStroke | TextModeClip: + CGContextSetTextDrawingMode(context, kCGTextStrokeClip); + break; + case TextModeFill | TextModeStroke | TextModeClip: + CGContextSetTextDrawingMode(context, kCGTextFillStrokeClip); + break; + default: + break; + } +} + +void GraphicsContext::setPlatformStrokeColor(const Color& color, ColorSpace colorSpace) +{ + if (paintingDisabled()) + return; + setCGStrokeColor(platformContext(), color, colorSpace); +} + +void GraphicsContext::setPlatformStrokeThickness(float thickness) +{ + if (paintingDisabled()) + return; + CGContextSetLineWidth(platformContext(), thickness); +} + +void GraphicsContext::setPlatformFillColor(const Color& color, ColorSpace colorSpace) +{ + if (paintingDisabled()) + return; + setCGFillColor(platformContext(), color, colorSpace); +} + +void GraphicsContext::setPlatformShouldAntialias(bool enable) +{ + if (paintingDisabled()) + return; + CGContextSetShouldAntialias(platformContext(), enable); +} + +void GraphicsContext::setPlatformShouldSmoothFonts(bool enable) +{ + if (paintingDisabled()) + return; + CGContextSetShouldSmoothFonts(platformContext(), enable); +} + +#ifndef BUILDING_ON_TIGER // Tiger's setPlatformCompositeOperation() is defined in GraphicsContextMac.mm. +void GraphicsContext::setPlatformCompositeOperation(CompositeOperator mode) +{ + if (paintingDisabled()) + return; + + CGBlendMode target = kCGBlendModeNormal; + switch (mode) { + case CompositeClear: + target = kCGBlendModeClear; + break; + case CompositeCopy: + target = kCGBlendModeCopy; + break; + case CompositeSourceOver: + //kCGBlendModeNormal + break; + case CompositeSourceIn: + target = kCGBlendModeSourceIn; + break; + case CompositeSourceOut: + target = kCGBlendModeSourceOut; + break; + case CompositeSourceAtop: + target = kCGBlendModeSourceAtop; + break; + case CompositeDestinationOver: + target = kCGBlendModeDestinationOver; + break; + case CompositeDestinationIn: + target = kCGBlendModeDestinationIn; + break; + case CompositeDestinationOut: + target = kCGBlendModeDestinationOut; + break; + case CompositeDestinationAtop: + target = kCGBlendModeDestinationAtop; + break; + case CompositeXOR: + target = kCGBlendModeXOR; + break; + case CompositePlusDarker: + target = kCGBlendModePlusDarker; + break; + case CompositeHighlight: + // currently unsupported + break; + case CompositePlusLighter: + target = kCGBlendModePlusLighter; + break; + } + CGContextSetBlendMode(platformContext(), target); +} +#endif + +} diff --git a/Source/WebCore/platform/graphics/cg/GraphicsContextCG.h b/Source/WebCore/platform/graphics/cg/GraphicsContextCG.h new file mode 100644 index 0000000..5de95ef --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/GraphicsContextCG.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved. + * + * 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. + */ + +#ifndef GraphicsContextCG_h +#define GraphicsContextCG_h + +#include "GraphicsContext.h" + +typedef struct CGColorSpace *CGColorSpaceRef; + +namespace WebCore { + +CGColorSpaceRef deviceRGBColorSpaceRef(); +CGColorSpaceRef sRGBColorSpaceRef(); +CGColorSpaceRef linearRGBColorSpaceRef(); + +} + +#endif diff --git a/Source/WebCore/platform/graphics/cg/GraphicsContextPlatformPrivateCG.h b/Source/WebCore/platform/graphics/cg/GraphicsContextPlatformPrivateCG.h new file mode 100644 index 0000000..1d0a99f --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/GraphicsContextPlatformPrivateCG.h @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. + * + * 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 <wtf/RetainPtr.h> +#include <CoreGraphics/CGContext.h> + +namespace WebCore { + +class GraphicsContextPlatformPrivate { +public: + GraphicsContextPlatformPrivate(CGContextRef cgContext) + : m_cgContext(cgContext) +#if PLATFORM(WIN) + , m_hdc(0) + , m_transparencyCount(0) + , m_shouldIncludeChildWindows(false) +#endif + , m_userToDeviceTransformKnownToBeIdentity(false) + { + } + + ~GraphicsContextPlatformPrivate() + { + } + +#if PLATFORM(MAC) || PLATFORM(CHROMIUM) + // These methods do nothing on Mac. + void save() {} + void restore() {} + void flush() {} + void clip(const FloatRect&) {} + void clip(const Path&) {} + void scale(const FloatSize&) {} + void rotate(float) {} + void translate(float, float) {} + void concatCTM(const AffineTransform&) {} + void beginTransparencyLayer() {} + void endTransparencyLayer() {} +#endif + +#if PLATFORM(WIN) + // On Windows, we need to update the HDC for form controls to draw in the right place. + void save(); + void restore(); + void flush(); + void clip(const FloatRect&); + void clip(const Path&); + void scale(const FloatSize&); + void rotate(float); + void translate(float, float); + void concatCTM(const AffineTransform&); + void beginTransparencyLayer() { m_transparencyCount++; } + void endTransparencyLayer() { m_transparencyCount--; } + + HDC m_hdc; + unsigned m_transparencyCount; + bool m_shouldIncludeChildWindows; +#endif + + RetainPtr<CGContextRef> m_cgContext; + bool m_userToDeviceTransformKnownToBeIdentity; +}; + +} diff --git a/Source/WebCore/platform/graphics/cg/ImageBufferCG.cpp b/Source/WebCore/platform/graphics/cg/ImageBufferCG.cpp new file mode 100644 index 0000000..75a36e5 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageBufferCG.cpp @@ -0,0 +1,534 @@ +/* + * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org> + * Copyright (C) 2008 Apple Inc. All rights reserved. + * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved. + * + * 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" +#include "ImageBuffer.h" + +#include "Base64.h" +#include "BitmapImage.h" +#include "GraphicsContext.h" +#include "GraphicsContextCG.h" +#include "MIMETypeRegistry.h" +#include <ApplicationServices/ApplicationServices.h> +#include <wtf/Assertions.h> +#include <wtf/text/StringConcatenate.h> +#include <wtf/OwnArrayPtr.h> +#include <wtf/RetainPtr.h> +#include <wtf/Threading.h> +#include <math.h> + +#if USE(IOSURFACE_CANVAS_BACKING_STORE) +#include <IOSurface/IOSurface.h> +#endif + +#if PLATFORM(MAC) || PLATFORM(CHROMIUM) +#include "WebCoreSystemInterface.h" +#endif + +using namespace std; + +namespace WebCore { + +#if USE(IOSURFACE_CANVAS_BACKING_STORE) +static RetainPtr<IOSurfaceRef> createIOSurface(const IntSize& size) +{ + unsigned pixelFormat = 'BGRA'; + unsigned bytesPerElement = 4; + int width = size.width(); + int height = size.height(); + + unsigned long bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, size.width() * bytesPerElement); + if (!bytesPerRow) + return 0; + + unsigned long allocSize = IOSurfaceAlignProperty(kIOSurfaceAllocSize, size.height() * bytesPerRow); + if (!allocSize) + return 0; + + const void *keys[6]; + const void *values[6]; + keys[0] = kIOSurfaceWidth; + values[0] = CFNumberCreate(0, kCFNumberIntType, &width); + keys[1] = kIOSurfaceHeight; + values[1] = CFNumberCreate(0, kCFNumberIntType, &height); + keys[2] = kIOSurfacePixelFormat; + values[2] = CFNumberCreate(0, kCFNumberIntType, &pixelFormat); + keys[3] = kIOSurfaceBytesPerElement; + values[3] = CFNumberCreate(0, kCFNumberIntType, &bytesPerElement); + keys[4] = kIOSurfaceBytesPerRow; + values[4] = CFNumberCreate(0, kCFNumberLongType, &bytesPerRow); + keys[5] = kIOSurfaceAllocSize; + values[5] = CFNumberCreate(0, kCFNumberLongType, &allocSize); + + RetainPtr<CFDictionaryRef> dict(AdoptCF, CFDictionaryCreate(0, keys, values, 6, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + for (unsigned i = 0; i < 6; i++) + CFRelease(values[i]); + + return RetainPtr<IOSurfaceRef>(AdoptCF, IOSurfaceCreate(dict.get())); +} +#endif + +static void releaseImageData(void*, const void* data, size_t) +{ + fastFree(const_cast<void*>(data)); +} + +ImageBufferData::ImageBufferData(const IntSize&) + : m_data(0) +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + , m_surface(0) +#endif +{ +} + +ImageBuffer::ImageBuffer(const IntSize& size, ColorSpace imageColorSpace, RenderingMode renderingMode, bool& success) + : m_data(size) + , m_size(size) + , m_accelerateRendering(renderingMode == Accelerated) +{ +#if !USE(IOSURFACE_CANVAS_BACKING_STORE) + ASSERT(renderingMode == Unaccelerated); +#endif + success = false; // Make early return mean failure. + if (size.width() < 0 || size.height() < 0) + return; + + unsigned bytesPerRow = size.width(); + if (bytesPerRow > 0x3FFFFFFF) // Protect against overflow + return; + bytesPerRow *= 4; + m_data.m_bytesPerRow = bytesPerRow; + size_t dataSize = size.height() * bytesPerRow; + + switch (imageColorSpace) { + case ColorSpaceDeviceRGB: + m_data.m_colorSpace = deviceRGBColorSpaceRef(); + break; + case ColorSpaceSRGB: + m_data.m_colorSpace = sRGBColorSpaceRef(); + break; + case ColorSpaceLinearRGB: + m_data.m_colorSpace = linearRGBColorSpaceRef(); + break; + } + + RetainPtr<CGContextRef> cgContext; + if (!m_accelerateRendering) { + if (!tryFastCalloc(size.height(), bytesPerRow).getValue(m_data.m_data)) + return; + ASSERT(!(reinterpret_cast<size_t>(m_data.m_data) & 2)); + + m_data.m_bitmapInfo = kCGImageAlphaPremultipliedLast; + cgContext.adoptCF(CGBitmapContextCreate(m_data.m_data, size.width(), size.height(), 8, bytesPerRow, m_data.m_colorSpace, m_data.m_bitmapInfo)); + // Create a live image that wraps the data. + m_data.m_dataProvider.adoptCF(CGDataProviderCreateWithData(0, m_data.m_data, dataSize, releaseImageData)); + } else { +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + m_data.m_surface = createIOSurface(size); + cgContext.adoptCF(wkIOSurfaceContextCreate(m_data.m_surface.get(), size.width(), size.height(), m_data.m_colorSpace)); +#else + m_accelerateRendering = false; // Force to false on older platforms +#endif + } + + if (!cgContext) + return; + + m_context.set(new GraphicsContext(cgContext.get())); + m_context->scale(FloatSize(1, -1)); + m_context->translate(0, -size.height()); + success = true; +} + +ImageBuffer::~ImageBuffer() +{ +} + +GraphicsContext* ImageBuffer::context() const +{ + return m_context.get(); +} + +bool ImageBuffer::drawsUsingCopy() const +{ + return false; +} + +PassRefPtr<Image> ImageBuffer::copyImage() const +{ + // BitmapImage will release the passed in CGImage on destruction + CGImageRef ctxImage = 0; + if (!m_accelerateRendering) + ctxImage = CGBitmapContextCreateImage(context()->platformContext()); +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + else + ctxImage = wkIOSurfaceContextCreateImage(context()->platformContext()); +#endif + return BitmapImage::create(ctxImage); +} + +static CGImageRef cgImage(const IntSize& size, const ImageBufferData& data) +{ + return CGImageCreate(size.width(), size.height(), 8, 32, data.m_bytesPerRow, + data.m_colorSpace, data.m_bitmapInfo, data.m_dataProvider.get(), 0, true, kCGRenderingIntentDefault); +} + +void ImageBuffer::draw(GraphicsContext* destContext, ColorSpace styleColorSpace, const FloatRect& destRect, const FloatRect& srcRect, + CompositeOperator op, bool useLowQualityScale) +{ + if (!m_accelerateRendering) { + if (destContext == context()) { + // We're drawing into our own buffer. In order for this to work, we need to copy the source buffer first. + RefPtr<Image> copy = copyImage(); + destContext->drawImage(copy.get(), ColorSpaceDeviceRGB, destRect, srcRect, op, useLowQualityScale); + } else { + RefPtr<Image> imageForRendering = BitmapImage::create(cgImage(m_size, m_data)); + destContext->drawImage(imageForRendering.get(), styleColorSpace, destRect, srcRect, op, useLowQualityScale); + } + } else { + RefPtr<Image> copy = copyImage(); + ColorSpace colorSpace = (destContext == context()) ? ColorSpaceDeviceRGB : styleColorSpace; + destContext->drawImage(copy.get(), colorSpace, destRect, srcRect, op, useLowQualityScale); + } +} + +void ImageBuffer::drawPattern(GraphicsContext* destContext, const FloatRect& srcRect, const AffineTransform& patternTransform, + const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect) +{ + if (!m_accelerateRendering) { + if (destContext == context()) { + // We're drawing into our own buffer. In order for this to work, we need to copy the source buffer first. + RefPtr<Image> copy = copyImage(); + copy->drawPattern(destContext, srcRect, patternTransform, phase, styleColorSpace, op, destRect); + } else { + RefPtr<Image> imageForRendering = BitmapImage::create(cgImage(m_size, m_data)); + imageForRendering->drawPattern(destContext, srcRect, patternTransform, phase, styleColorSpace, op, destRect); + } + } else { + RefPtr<Image> copy = copyImage(); + copy->drawPattern(destContext, srcRect, patternTransform, phase, styleColorSpace, op, destRect); + } +} + +void ImageBuffer::clip(GraphicsContext* context, const FloatRect& rect) const +{ + CGContextRef platformContext = context->platformContext(); + RetainPtr<CGImageRef> image; + if (!m_accelerateRendering) + image.adoptCF(cgImage(m_size, m_data)); +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + else + image.adoptCF(wkIOSurfaceContextCreateImage(platformContext)); +#endif + CGContextTranslateCTM(platformContext, rect.x(), rect.y() + rect.height()); + CGContextScaleCTM(platformContext, 1, -1); + CGContextClipToMask(platformContext, FloatRect(FloatPoint(), rect.size()), image.get()); + CGContextScaleCTM(platformContext, 1, -1); + CGContextTranslateCTM(platformContext, -rect.x(), -rect.y() - rect.height()); +} + +template <Multiply multiplied> +PassRefPtr<ByteArray> getImageData(const IntRect& rect, const ImageBufferData& imageData, const IntSize& size, bool accelerateRendering) +{ + RefPtr<ByteArray> result = ByteArray::create(rect.width() * rect.height() * 4); + unsigned char* data = result->data(); + + if (rect.x() < 0 || rect.y() < 0 || rect.right() > size.width() || rect.bottom() > size.height()) + memset(data, 0, result->length()); + + int originx = rect.x(); + int destx = 0; + if (originx < 0) { + destx = -originx; + originx = 0; + } + int endx = rect.right(); + if (endx > size.width()) + endx = size.width(); + int numColumns = endx - originx; + + int originy = rect.y(); + int desty = 0; + if (originy < 0) { + desty = -originy; + originy = 0; + } + int endy = rect.bottom(); + if (endy > size.height()) + endy = size.height(); + int numRows = endy - originy; + + unsigned destBytesPerRow = 4 * rect.width(); + unsigned char* destRows = data + desty * destBytesPerRow + destx * 4; + + unsigned srcBytesPerRow; + unsigned char* srcRows; + + if (!accelerateRendering) { + srcBytesPerRow = 4 * size.width(); + srcRows = reinterpret_cast<unsigned char*>(imageData.m_data) + originy * srcBytesPerRow + originx * 4; + + for (int y = 0; y < numRows; ++y) { + for (int x = 0; x < numColumns; x++) { + int basex = x * 4; + unsigned char alpha = srcRows[basex + 3]; + if (multiplied == Unmultiplied && alpha) { + destRows[basex] = (srcRows[basex] * 255) / alpha; + destRows[basex + 1] = (srcRows[basex + 1] * 255) / alpha; + destRows[basex + 2] = (srcRows[basex + 2] * 255) / alpha; + destRows[basex + 3] = alpha; + } else + reinterpret_cast<uint32_t*>(destRows + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0]; + } + srcRows += srcBytesPerRow; + destRows += destBytesPerRow; + } + } else { +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + IOSurfaceRef surface = imageData.m_surface.get(); + IOSurfaceLock(surface, kIOSurfaceLockReadOnly, 0); + srcBytesPerRow = IOSurfaceGetBytesPerRow(surface); + srcRows = (unsigned char*)(IOSurfaceGetBaseAddress(surface)) + originy * srcBytesPerRow + originx * 4; + + for (int y = 0; y < numRows; ++y) { + for (int x = 0; x < numColumns; x++) { + int basex = x * 4; + unsigned char alpha = srcRows[basex + 3]; + if (multiplied == Unmultiplied && alpha) { + destRows[basex] = (srcRows[basex + 2] * 255) / alpha; + destRows[basex + 1] = (srcRows[basex + 1] * 255) / alpha; + destRows[basex + 2] = (srcRows[basex] * 255) / alpha; + destRows[basex + 3] = alpha; + } else { + destRows[basex] = srcRows[basex + 2]; + destRows[basex + 1] = srcRows[basex + 1]; + destRows[basex + 2] = srcRows[basex]; + destRows[basex + 3] = alpha; + } + } + srcRows += srcBytesPerRow; + destRows += destBytesPerRow; + } + IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, 0); +#else + ASSERT_NOT_REACHED(); +#endif + } + + return result.release(); +} + +PassRefPtr<ByteArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect) const +{ + if (m_accelerateRendering) + CGContextFlush(context()->platformContext()); + return getImageData<Unmultiplied>(rect, m_data, m_size, m_accelerateRendering); +} + +PassRefPtr<ByteArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect) const +{ + if (m_accelerateRendering) + CGContextFlush(context()->platformContext()); + return getImageData<Premultiplied>(rect, m_data, m_size, m_accelerateRendering); +} + +template <Multiply multiplied> +void putImageData(ByteArray*& source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, ImageBufferData& imageData, const IntSize& size, bool accelerateRendering) +{ + ASSERT(sourceRect.width() > 0); + ASSERT(sourceRect.height() > 0); + + int originx = sourceRect.x(); + int destx = destPoint.x() + sourceRect.x(); + ASSERT(destx >= 0); + ASSERT(destx < size.width()); + ASSERT(originx >= 0); + ASSERT(originx <= sourceRect.right()); + + int endx = destPoint.x() + sourceRect.right(); + ASSERT(endx <= size.width()); + + int numColumns = endx - destx; + + int originy = sourceRect.y(); + int desty = destPoint.y() + sourceRect.y(); + ASSERT(desty >= 0); + ASSERT(desty < size.height()); + ASSERT(originy >= 0); + ASSERT(originy <= sourceRect.bottom()); + + int endy = destPoint.y() + sourceRect.bottom(); + ASSERT(endy <= size.height()); + int numRows = endy - desty; + + unsigned srcBytesPerRow = 4 * sourceSize.width(); + unsigned char* srcRows = source->data() + originy * srcBytesPerRow + originx * 4; + unsigned destBytesPerRow; + unsigned char* destRows; + + if (!accelerateRendering) { + destBytesPerRow = 4 * size.width(); + destRows = reinterpret_cast<unsigned char*>(imageData.m_data) + desty * destBytesPerRow + destx * 4; + for (int y = 0; y < numRows; ++y) { + for (int x = 0; x < numColumns; x++) { + int basex = x * 4; + unsigned char alpha = srcRows[basex + 3]; + if (multiplied == Unmultiplied && alpha != 255) { + destRows[basex] = (srcRows[basex] * alpha + 254) / 255; + destRows[basex + 1] = (srcRows[basex + 1] * alpha + 254) / 255; + destRows[basex + 2] = (srcRows[basex + 2] * alpha + 254) / 255; + destRows[basex + 3] = alpha; + } else + reinterpret_cast<uint32_t*>(destRows + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0]; + } + destRows += destBytesPerRow; + srcRows += srcBytesPerRow; + } + } else { +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + IOSurfaceRef surface = imageData.m_surface.get(); + IOSurfaceLock(surface, 0, 0); + destBytesPerRow = IOSurfaceGetBytesPerRow(surface); + destRows = (unsigned char*)(IOSurfaceGetBaseAddress(surface)) + desty * destBytesPerRow + destx * 4; + + for (int y = 0; y < numRows; ++y) { + for (int x = 0; x < numColumns; x++) { + int basex = x * 4; + unsigned char alpha = srcRows[basex + 3]; + if (multiplied == Unmultiplied && alpha != 255) { + destRows[basex] = (srcRows[basex + 2] * alpha + 254) / 255; + destRows[basex + 1] = (srcRows[basex + 1] * alpha + 254) / 255; + destRows[basex + 2] = (srcRows[basex] * alpha + 254) / 255; + destRows[basex + 3] = alpha; + } else { + destRows[basex] = srcRows[basex + 2]; + destRows[basex + 1] = srcRows[basex + 1]; + destRows[basex + 2] = srcRows[basex]; + destRows[basex + 3] = alpha; + } + } + destRows += destBytesPerRow; + srcRows += srcBytesPerRow; + } + IOSurfaceUnlock(surface, 0, 0); +#else + ASSERT_NOT_REACHED(); +#endif + } +} + +void ImageBuffer::putUnmultipliedImageData(ByteArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint) +{ + if (m_accelerateRendering) + CGContextFlush(context()->platformContext()); + putImageData<Unmultiplied>(source, sourceSize, sourceRect, destPoint, m_data, m_size, m_accelerateRendering); +} + +void ImageBuffer::putPremultipliedImageData(ByteArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint) +{ + if (m_accelerateRendering) + CGContextFlush(context()->platformContext()); + putImageData<Premultiplied>(source, sourceSize, sourceRect, destPoint, m_data, m_size, m_accelerateRendering); +} + +static inline CFStringRef jpegUTI() +{ +#if PLATFORM(WIN) + static const CFStringRef kUTTypeJPEG = CFSTR("public.jpeg"); +#endif + return kUTTypeJPEG; +} + +static RetainPtr<CFStringRef> utiFromMIMEType(const String& mimeType) +{ +#if PLATFORM(MAC) + RetainPtr<CFStringRef> mimeTypeCFString(AdoptCF, mimeType.createCFString()); + return RetainPtr<CFStringRef>(AdoptCF, UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeTypeCFString.get(), 0)); +#else + ASSERT(isMainThread()); // It is unclear if CFSTR is threadsafe. + + // FIXME: Add Windows support for all the supported UTIs when a way to convert from MIMEType to UTI reliably is found. + // For now, only support PNG, JPEG, and GIF. See <rdar://problem/6095286>. + static const CFStringRef kUTTypePNG = CFSTR("public.png"); + static const CFStringRef kUTTypeGIF = CFSTR("com.compuserve.gif"); + + if (equalIgnoringCase(mimeType, "image/png")) + return kUTTypePNG; + if (equalIgnoringCase(mimeType, "image/jpeg")) + return jpegUTI(); + if (equalIgnoringCase(mimeType, "image/gif")) + return kUTTypeGIF; + + ASSERT_NOT_REACHED(); + return kUTTypePNG; +#endif +} + +String ImageBuffer::toDataURL(const String& mimeType, const double* quality) const +{ + ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType)); + + RetainPtr<CGImageRef> image; + if (!m_accelerateRendering) + image.adoptCF(CGBitmapContextCreateImage(context()->platformContext())); +#if USE(IOSURFACE_CANVAS_BACKING_STORE) + else + image.adoptCF(wkIOSurfaceContextCreateImage(context()->platformContext())); +#endif + + if (!image) + return "data:,"; + + RetainPtr<CFMutableDataRef> data(AdoptCF, CFDataCreateMutable(kCFAllocatorDefault, 0)); + if (!data) + return "data:,"; + + RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType); + ASSERT(uti); + + RetainPtr<CGImageDestinationRef> destination(AdoptCF, CGImageDestinationCreateWithData(data.get(), uti.get(), 1, 0)); + if (!destination) + return "data:,"; + + RetainPtr<CFDictionaryRef> imageProperties = 0; + if (CFEqual(uti.get(), jpegUTI()) && quality && *quality >= 0.0 && *quality <= 1.0) { + // Apply the compression quality to the image destination. + RetainPtr<CFNumberRef> compressionQuality(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, quality)); + const void* key = kCGImageDestinationLossyCompressionQuality; + const void* value = compressionQuality.get(); + imageProperties.adoptCF(CFDictionaryCreate(0, &key, &value, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + } + + CGImageDestinationAddImage(destination.get(), image.get(), imageProperties.get()); + CGImageDestinationFinalize(destination.get()); + + Vector<char> out; + base64Encode(reinterpret_cast<const char*>(CFDataGetBytePtr(data.get())), CFDataGetLength(data.get()), out); + + return makeString("data:", mimeType, ";base64,", out); +} +} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/cg/ImageBufferData.h b/Source/WebCore/platform/graphics/cg/ImageBufferData.h new file mode 100644 index 0000000..1f706ec --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageBufferData.h @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2008 Google Inc. All rights reserved. + * + * 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. + */ + +#ifndef ImageBufferData_h +#define ImageBufferData_h + +#include "Image.h" +#include <wtf/RefPtr.h> +#include <wtf/RetainPtr.h> + +typedef struct __IOSurface *IOSurfaceRef; +typedef struct CGColorSpace *CGColorSpaceRef; +typedef struct CGDataProvider *CGDataProviderRef; +typedef uint32_t CGBitmapInfo; + +namespace WebCore { + +class IntSize; + +class ImageBufferData { +public: + ImageBufferData(const IntSize&); + + void* m_data; + + RetainPtr<CGDataProviderRef> m_dataProvider; + CGBitmapInfo m_bitmapInfo; + unsigned m_bytesPerRow; + CGColorSpaceRef m_colorSpace; + RetainPtr<IOSurfaceRef> m_surface; +}; + +} // namespace WebCore + +#endif // ImageBufferData_h diff --git a/Source/WebCore/platform/graphics/cg/ImageCG.cpp b/Source/WebCore/platform/graphics/cg/ImageCG.cpp new file mode 100644 index 0000000..dfee96a --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageCG.cpp @@ -0,0 +1,349 @@ +/* + * Copyright (C) 2004, 2005, 2006 Apple Inc. All rights reserved. + * + * 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" +#include "BitmapImage.h" + +#if PLATFORM(CG) + +#include "AffineTransform.h" +#include "FloatConversion.h" +#include "FloatRect.h" +#include "GraphicsContextCG.h" +#include "ImageObserver.h" +#include "PDFDocumentImage.h" +#include "PlatformString.h" +#include <ApplicationServices/ApplicationServices.h> +#include <wtf/RetainPtr.h> + +#if PLATFORM(MAC) || PLATFORM(CHROMIUM) +#include "WebCoreSystemInterface.h" +#endif + +#if PLATFORM(WIN) +#include <WebKitSystemInterface/WebKitSystemInterface.h> +#endif + +namespace WebCore { + +bool FrameData::clear(bool clearMetadata) +{ + if (clearMetadata) + m_haveMetadata = false; + + if (m_frame) { + CGImageRelease(m_frame); + m_frame = 0; + return true; + } + return false; +} + +// ================================================ +// Image Class +// ================================================ + +BitmapImage::BitmapImage(CGImageRef cgImage, ImageObserver* observer) + : Image(observer) + , m_currentFrame(0) + , m_frames(0) + , m_frameTimer(0) + , m_repetitionCount(cAnimationNone) + , m_repetitionCountStatus(Unknown) + , m_repetitionsComplete(0) + , m_isSolidColor(false) + , m_checkedForSolidColor(false) + , 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; + m_frames[0].m_hasAlpha = true; + m_frames[0].m_haveMetadata = true; + checkForSolidColor(); +} + +// Drawing Routines + +void BitmapImage::checkForSolidColor() +{ + m_checkedForSolidColor = true; + if (frameCount() > 1) { + m_isSolidColor = false; + 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 + RetainPtr<CGContextRef> bmap(AdoptCF, CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), deviceRGBColorSpaceRef(), + 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; + } +} + +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) { + case ColorSpaceDeviceRGB: + return originalImage; + case ColorSpaceSRGB: + return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, sRGBColorSpaceRef())); + case ColorSpaceLinearRGB: + return RetainPtr<CGImageRef>(AdoptCF, CGImageCreateCopyWithColorSpace(originalImage, linearRGBColorSpaceRef())); + } + + ASSERT_NOT_REACHED(); + return originalImage; +} + +CGImageRef BitmapImage::getCGImageRef() +{ + return frameAtIndex(0); +} + +void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator compositeOp) +{ + startAnimation(); + + RetainPtr<CGImageRef> image = frameAtIndex(m_currentFrame); + if (!image) // If it's too early we won't have an image yet. + return; + + if (mayFillWithSolidColor()) { + fillWithSolidColor(ctxt, destRect, solidColor(), styleColorSpace, compositeOp); + return; + } + + float currHeight = CGImageGetHeight(image.get()); + if (currHeight <= srcRect.y()) + return; + + CGContextRef context = ctxt->platformContext(); + ctxt->save(); + + bool shouldUseSubimage = false; + + // 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; + FloatSize selfSize = currentFrameSize(); + if (srcRect.size() != selfSize) { + CGInterpolationQuality interpolationQuality = CGContextGetInterpolationQuality(context); + // 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>. + shouldUseSubimage = (interpolationQuality == kCGInterpolationHigh || interpolationQuality == kCGInterpolationDefault) && (srcRect.size() != destRect.size() || !ctxt->getCTM().isIdentityOrTranslationOrFlipped()); + float xScale = srcRect.width() / destRect.width(); + float yScale = srcRect.height() / destRect.height(); + if (shouldUseSubimage) { + 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); + + image.adoptCF(CGImageCreateWithImageInRect(image.get(), subimageRect)); + if (currHeight < srcRect.bottom()) { + ASSERT(CGImageGetHeight(image.get()) == currHeight - CGRectIntegral(srcRect).origin.y); + adjustedDestRect.setHeight(CGImageGetHeight(image.get()) / yScale); + } + } else { + adjustedDestRect.setLocation(FloatPoint(destRect.x() - srcRect.x() / xScale, destRect.y() - srcRect.y() / yScale)); + adjustedDestRect.setSize(FloatSize(selfSize.width() / xScale, selfSize.height() / yScale)); + } + + CGContextClipToRect(context, destRect); + } + + // If the image is only partially loaded, then shrink the destination rect that we're drawing into accordingly. + if (!shouldUseSubimage && currHeight < selfSize.height()) + adjustedDestRect.setHeight(adjustedDestRect.height() * currHeight / selfSize.height()); + + ctxt->setCompositeOperation(compositeOp); + + // Flip the coords. + CGContextScaleCTM(context, 1, -1); + adjustedDestRect.setY(-adjustedDestRect.bottom()); + + // Adjust the color space. + image = imageWithColorSpace(image.get(), styleColorSpace); + + // Draw the image. + CGContextDrawImage(context, adjustedDestRect, image.get()); + + ctxt->restore(); + + if (imageObserver()) + imageObserver()->didDraw(this); +} + +static void drawPatternCallback(void* info, CGContextRef context) +{ + CGImageRef image = (CGImageRef)info; + CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(0, 0, CGImageGetWidth(image), CGImageGetHeight(image))), image); +} + +void Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform, + const FloatPoint& phase, ColorSpace styleColorSpace, CompositeOperator op, const FloatRect& destRect) +{ + if (!nativeImageForCurrentFrame()) + return; + + ASSERT(patternTransform.isInvertible()); + if (!patternTransform.isInvertible()) + // Avoid a hang under CGContextDrawTiledImage on release builds. + return; + + CGContextRef context = ctxt->platformContext(); + ctxt->save(); + CGContextClipToRect(context, destRect); + ctxt->setCompositeOperation(op); + CGContextTranslateCTM(context, destRect.x(), destRect.y() + destRect.height()); + CGContextScaleCTM(context, 1, -1); + + // Compute the scaled tile size. + float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d()); + + // 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). + 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); + + CGImageRef tileImage = nativeImageForCurrentFrame(); + float h = CGImageGetHeight(tileImage); + + RetainPtr<CGImageRef> subImage; + 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()); + subImage.adoptCF(CGImageCreateWithImageInRect(tileImage, tileRect)); + } + + // Adjust the color space. + subImage = imageWithColorSpace(subImage.get(), styleColorSpace); + +#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 + // overall image buffer needs to tile with "gaps", we can't use the optimized tiling call in that case. + // FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well. + // FIXME: We cannot use CGContextDrawTiledImage with scaled tiles on Leopard, because it suffers from rounding errors. Snow Leopard is ok. + float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a()); + float w = CGImageGetWidth(tileImage); +#ifdef BUILDING_ON_LEOPARD + if (w == size().width() && h == size().height() && scaledTileWidth == tileRect.width() && scaledTileHeight == tileRect.height()) +#else + if (w == size().width() && h == size().height()) +#endif + CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), subImage.get()); + else { +#endif + + // On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image. + // 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. + static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL }; + CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY); + matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context)); + // 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); + RetainPtr<CGPatternRef> pattern(AdoptCF, CGPatternCreate(subImage.get(), CGRectMake(0, 0, tileRect.width(), tileRect.height()), + matrix, tileRect.width(), tileRect.height(), + kCGPatternTilingConstantSpacing, true, &patternCallbacks)); + if (!pattern) { + ctxt->restore(); + return; + } + + RetainPtr<CGColorSpaceRef> patternSpace(AdoptCF, CGColorSpaceCreatePattern(0)); + + CGFloat alpha = 1; + RetainPtr<CGColorRef> color(AdoptCF, CGColorCreateWithPattern(patternSpace.get(), pattern.get(), &alpha)); + CGContextSetFillColorSpace(context, patternSpace.get()); + + // FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy). + wkSetPatternBaseCTM(context, CGAffineTransformIdentity); + CGContextSetPatternPhase(context, CGSizeZero); + + CGContextSetFillColorWithColor(context, color.get()); + CGContextFillRect(context, CGContextGetClipBoundingBox(context)); + +#ifndef BUILDING_ON_TIGER + } +#endif + + ctxt->restore(); + + if (imageObserver()) + imageObserver()->didDraw(this); +} + + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/ImageSourceCG.cpp b/Source/WebCore/platform/graphics/cg/ImageSourceCG.cpp new file mode 100644 index 0000000..4ed8684 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageSourceCG.cpp @@ -0,0 +1,339 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. + * + * 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" +#include "ImageSource.h" + +#if PLATFORM(CG) +#include "ImageSourceCG.h" + +#include "IntPoint.h" +#include "IntSize.h" +#include "MIMETypeRegistry.h" +#include "SharedBuffer.h" +#include <ApplicationServices/ApplicationServices.h> +#include <wtf/UnusedParam.h> + +using namespace std; + +namespace WebCore { + +static const CFStringRef kCGImageSourceShouldPreferRGB32 = CFSTR("kCGImageSourceShouldPreferRGB32"); + +#if !PLATFORM(MAC) +size_t sharedBufferGetBytesAtPosition(void* info, void* buffer, off_t position, size_t count) +{ + SharedBuffer* sharedBuffer = static_cast<SharedBuffer*>(info); + size_t sourceSize = sharedBuffer->size(); + if (position >= sourceSize) + return 0; + + const char* source = sharedBuffer->data() + position; + size_t amount = min<size_t>(count, sourceSize - position); + memcpy(buffer, source, amount); + return amount; +} + +void sharedBufferRelease(void* info) +{ + SharedBuffer* sharedBuffer = static_cast<SharedBuffer*>(info); + sharedBuffer->deref(); +} +#endif + +ImageSource::ImageSource(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption) + : m_decoder(0) + // FIXME: m_premultiplyAlpha is ignored in cg at the moment. + , m_alphaOption(alphaOption) + , m_gammaAndColorProfileOption(gammaAndColorProfileOption) +{ +} + +ImageSource::~ImageSource() +{ + clear(true); +} + +void ImageSource::clear(bool destroyAllFrames, size_t, SharedBuffer* data, bool allDataReceived) +{ +#if !defined(BUILDING_ON_TIGER) && !defined(BUILDING_ON_LEOPARD) + // Recent versions of ImageIO discard previously decoded image frames if the client + // application no longer holds references to them, so there's no need to throw away + // the decoder unless we're explicitly asked to destroy all of the frames. + + if (!destroyAllFrames) + return; +#else + // Older versions of ImageIO hold references to previously decoded image frames. + // There is no API to selectively release some of the frames it is holding, and + // if we don't release the frames we use too much memory on large images. + // Destroying the decoder is the only way to release previous frames. + + UNUSED_PARAM(destroyAllFrames); +#endif + + if (m_decoder) { + CFRelease(m_decoder); + m_decoder = 0; + } + if (data) + setData(data, allDataReceived); +} + +static CFDictionaryRef imageSourceOptions() +{ + static CFDictionaryRef options; + + if (!options) { + const unsigned numOptions = 2; + const void* keys[numOptions] = { kCGImageSourceShouldCache, kCGImageSourceShouldPreferRGB32 }; + const void* values[numOptions] = { kCFBooleanTrue, kCFBooleanTrue }; + options = CFDictionaryCreate(NULL, keys, values, numOptions, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + } + return options; +} + +bool ImageSource::initialized() const +{ + return m_decoder; +} + +void ImageSource::setData(SharedBuffer* data, bool allDataReceived) +{ +#if PLATFORM(MAC) + if (!m_decoder) + m_decoder = CGImageSourceCreateIncremental(0); + // On Mac the NSData inside the SharedBuffer can be secretly appended to without the SharedBuffer's knowledge. We use SharedBuffer's ability + // to wrap itself inside CFData to get around this, ensuring that ImageIO is really looking at the SharedBuffer. + RetainPtr<CFDataRef> cfData(AdoptCF, data->createCFData()); + CGImageSourceUpdateData(m_decoder, cfData.get(), allDataReceived); +#else + if (!m_decoder) { + m_decoder = CGImageSourceCreateIncremental(0); + } else if (allDataReceived) { +#if !PLATFORM(WIN) + // 10.6 bug workaround: image sources with final=false fail to draw into PDF contexts, so re-create image source + // when data is complete. <rdar://problem/7874035> (<http://openradar.appspot.com/7874035>) + CFRelease(m_decoder); + m_decoder = CGImageSourceCreateIncremental(0); +#endif + } + // Create a CGDataProvider to wrap the SharedBuffer. + data->ref(); + // We use the GetBytesAtPosition callback rather than the GetBytePointer one because SharedBuffer + // does not provide a way to lock down the byte pointer and guarantee that it won't move, which + // is a requirement for using the GetBytePointer callback. + CGDataProviderDirectCallbacks providerCallbacks = { 0, 0, 0, sharedBufferGetBytesAtPosition, sharedBufferRelease }; + RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateDirect(data, data->size(), &providerCallbacks)); + CGImageSourceUpdateDataProvider(m_decoder, dataProvider.get(), allDataReceived); +#endif +} + +String ImageSource::filenameExtension() const +{ + if (!m_decoder) + return String(); + CFStringRef imageSourceType = CGImageSourceGetType(m_decoder); + return WebCore::preferredExtensionForImageSourceType(imageSourceType); +} + +bool ImageSource::isSizeAvailable() +{ + bool result = false; + CGImageSourceStatus imageSourceStatus = CGImageSourceGetStatus(m_decoder); + + // Ragnaros yells: TOO SOON! You have awakened me TOO SOON, Executus! + if (imageSourceStatus >= kCGImageStatusIncomplete) { + RetainPtr<CFDictionaryRef> image0Properties(AdoptCF, CGImageSourceCopyPropertiesAtIndex(m_decoder, 0, imageSourceOptions())); + if (image0Properties) { + CFNumberRef widthNumber = (CFNumberRef)CFDictionaryGetValue(image0Properties.get(), kCGImagePropertyPixelWidth); + CFNumberRef heightNumber = (CFNumberRef)CFDictionaryGetValue(image0Properties.get(), kCGImagePropertyPixelHeight); + result = widthNumber && heightNumber; + } + } + + return result; +} + +IntSize ImageSource::frameSizeAtIndex(size_t index) const +{ + IntSize result; + RetainPtr<CFDictionaryRef> properties(AdoptCF, CGImageSourceCopyPropertiesAtIndex(m_decoder, index, imageSourceOptions())); + if (properties) { + int w = 0, h = 0; + CFNumberRef num = (CFNumberRef)CFDictionaryGetValue(properties.get(), kCGImagePropertyPixelWidth); + if (num) + CFNumberGetValue(num, kCFNumberIntType, &w); + num = (CFNumberRef)CFDictionaryGetValue(properties.get(), kCGImagePropertyPixelHeight); + if (num) + CFNumberGetValue(num, kCFNumberIntType, &h); + result = IntSize(w, h); + } + return result; +} + +IntSize ImageSource::size() const +{ + return frameSizeAtIndex(0); +} + +bool ImageSource::getHotSpot(IntPoint& hotSpot) const +{ + RetainPtr<CFDictionaryRef> properties(AdoptCF, CGImageSourceCopyPropertiesAtIndex(m_decoder, 0, imageSourceOptions())); + if (!properties) + return false; + + int x = -1, y = -1; + CFNumberRef num = (CFNumberRef)CFDictionaryGetValue(properties.get(), CFSTR("hotspotX")); + if (!num || !CFNumberGetValue(num, kCFNumberIntType, &x)) + return false; + + num = (CFNumberRef)CFDictionaryGetValue(properties.get(), CFSTR("hotspotY")); + if (!num || !CFNumberGetValue(num, kCFNumberIntType, &y)) + return false; + + if (x < 0 || y < 0) + return false; + + hotSpot = IntPoint(x, y); + return true; +} + +int ImageSource::repetitionCount() +{ + int result = cAnimationLoopOnce; // No property means loop once. + if (!initialized()) + return result; + + RetainPtr<CFDictionaryRef> properties(AdoptCF, CGImageSourceCopyProperties(m_decoder, imageSourceOptions())); + if (properties) { + CFDictionaryRef gifProperties = (CFDictionaryRef)CFDictionaryGetValue(properties.get(), kCGImagePropertyGIFDictionary); + if (gifProperties) { + CFNumberRef num = (CFNumberRef)CFDictionaryGetValue(gifProperties, kCGImagePropertyGIFLoopCount); + if (num) { + // A property with value 0 means loop forever. + CFNumberGetValue(num, kCFNumberIntType, &result); + if (!result) + result = cAnimationLoopInfinite; + } + } else + result = cAnimationNone; // Turns out we're not a GIF after all, so we don't animate. + } + + return result; +} + +size_t ImageSource::frameCount() const +{ + return m_decoder ? CGImageSourceGetCount(m_decoder) : 0; +} + +CGImageRef ImageSource::createFrameAtIndex(size_t index) +{ + if (!initialized()) + return 0; + + RetainPtr<CGImageRef> image(AdoptCF, CGImageSourceCreateImageAtIndex(m_decoder, index, imageSourceOptions())); + CFStringRef imageUTI = CGImageSourceGetType(m_decoder); + static const CFStringRef xbmUTI = CFSTR("public.xbitmap-image"); + if (!imageUTI || !CFEqual(imageUTI, xbmUTI)) + return image.releaseRef(); + + // If it is an xbm image, mask out all the white areas to render them transparent. + const CGFloat maskingColors[6] = {255, 255, 255, 255, 255, 255}; + RetainPtr<CGImageRef> maskedImage(AdoptCF, CGImageCreateWithMaskingColors(image.get(), maskingColors)); + if (!maskedImage) + return image.releaseRef(); + + return maskedImage.releaseRef(); +} + +bool ImageSource::frameIsCompleteAtIndex(size_t index) +{ + ASSERT(frameCount()); + + // CGImageSourceGetStatusAtIndex claims that all frames of a multi-frame image are incomplete + // when we've not yet received the complete data for an image that is using an incremental data + // source (<rdar://problem/7679174>). We work around this by special-casing all frames except the + // last in an image and treating them as complete if they are present and reported as being + // incomplete. We do this on the assumption that loading new data can only modify the existing last + // frame or append new frames. The last frame is only treated as being complete if the image source + // reports it as such. This ensures that it is truly the last frame of the image rather than just + // the last that we currently have data for. + + CGImageSourceStatus frameStatus = CGImageSourceGetStatusAtIndex(m_decoder, index); + if (index < frameCount() - 1) + return frameStatus >= kCGImageStatusIncomplete; + + return frameStatus == kCGImageStatusComplete; +} + +float ImageSource::frameDurationAtIndex(size_t index) +{ + if (!initialized()) + return 0; + + float duration = 0; + RetainPtr<CFDictionaryRef> properties(AdoptCF, CGImageSourceCopyPropertiesAtIndex(m_decoder, index, imageSourceOptions())); + if (properties) { + CFDictionaryRef typeProperties = (CFDictionaryRef)CFDictionaryGetValue(properties.get(), kCGImagePropertyGIFDictionary); + if (typeProperties) { + CFNumberRef num = (CFNumberRef)CFDictionaryGetValue(typeProperties, kCGImagePropertyGIFDelayTime); + if (num) + CFNumberGetValue(num, kCFNumberFloatType, &duration); + } + } + + // Many annoying ads specify a 0 duration to make an image flash as quickly as possible. + // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify + // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082> + // for more information. + if (duration < 0.011f) + return 0.100f; + return duration; +} + +bool ImageSource::frameHasAlphaAtIndex(size_t) +{ + if (!m_decoder) + return false; + + CFStringRef imageType = CGImageSourceGetType(m_decoder); + + // Return false if there is no image type or the image type is JPEG, because + // JPEG does not support alpha transparency. + if (!imageType || CFEqual(imageType, CFSTR("public.jpeg"))) + return false; + + // FIXME: Could return false for other non-transparent image formats. + // FIXME: Could maybe return false for a GIF Frame if we have enough info in the GIF properties dictionary + // to determine whether or not a transparent color was defined. + return true; +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/ImageSourceCG.h b/Source/WebCore/platform/graphics/cg/ImageSourceCG.h new file mode 100644 index 0000000..bff8162 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageSourceCG.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * 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 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 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. + */ + +#ifndef ImageSourceCG_h +#define ImageSourceCG_h + +#include "ImageSource.h" +#include <wtf/Forward.h> + +namespace WebCore { + +String preferredExtensionForImageSourceType(const String& type); + +String MIMETypeForImageSourceType(const String& type); + +#if !PLATFORM(MAC) +size_t sharedBufferGetBytesAtPosition(void* info, void* buffer, off_t position, size_t count); +#endif + +} + +#endif // ImageSourceCG_h diff --git a/Source/WebCore/platform/graphics/cg/ImageSourceCGMac.mm b/Source/WebCore/platform/graphics/cg/ImageSourceCGMac.mm new file mode 100644 index 0000000..297e30a --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageSourceCGMac.mm @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved. + * + * 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 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 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. + */ + +#import "config.h" +#import "ImageSourceCG.h" + +#import "PlatformString.h" +#import "wtf/RetainPtr.h" + +namespace WebCore { + +String MIMETypeForImageSourceType(const String& uti) +{ + RetainPtr<CFStringRef> utiref(AdoptCF, uti.createCFString()); + RetainPtr<CFStringRef> mime(AdoptCF, UTTypeCopyPreferredTagWithClass(utiref.get(), kUTTagClassMIMEType)); + return mime.get(); +} + +String preferredExtensionForImageSourceType(const String& uti) +{ + RetainPtr<CFStringRef> type(AdoptCF, uti.createCFString()); + RetainPtr<CFStringRef> extension(AdoptCF, UTTypeCopyPreferredTagWithClass(type.get(), kUTTagClassFilenameExtension)); + return extension.get(); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/cg/ImageSourceCGWin.cpp b/Source/WebCore/platform/graphics/cg/ImageSourceCGWin.cpp new file mode 100644 index 0000000..ef69e5e --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/ImageSourceCGWin.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2008 Apple Inc. All Rights Reserved. + * + * 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 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 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" +#include "ImageSourceCG.h" + +#include "StdLibExtras.h" +#include <wtf/HashMap.h> +#include <wtf/text/StringHash.h> + +namespace WebCore { + +String MIMETypeForImageSourceType(const String& type) +{ + String mimeType; + // FIXME: This approach of taking a UTI like public.type and giving back + // a MIME type like image/type will work for common image UTIs like jpeg, + // png, tiff, gif but won't work for UTIs like: public.jpeg-2000, + // public.xbitmap-image, com.apple.quicktime-image, and others. + if (int dotLocation = type.reverseFind('.')) + mimeType = "image/" + type.substring(dotLocation + 1); + return mimeType; +} + +String preferredExtensionForImageSourceType(const String& type) +{ + if (type.isEmpty()) + return String(); + + typedef HashMap<String, String> StringMap; + DEFINE_STATIC_LOCAL(StringMap, UTIMap, ()); + if (UTIMap.isEmpty()) { + UTIMap.add("public.html", "html"); + UTIMap.add("public.jpeg", "jpeg"); + UTIMap.add("public.jpeg-2000", "jp2"); + UTIMap.add("public.plain-text", "txt"); + UTIMap.add("public.png", "png"); + UTIMap.add("public.tiff", "tiff"); + UTIMap.add("public.xbitmap-image", "xbm"); + UTIMap.add("public.xml", "xml"); + UTIMap.add("com.adobe.illustrator.ai-image", "ai"); + UTIMap.add("com.adobe.pdf", "pdf"); + UTIMap.add("com.adobe.photoshop-image", "psd"); + UTIMap.add("com.adobe.postscript", "ps"); + UTIMap.add("com.apple.icns", "icns"); + UTIMap.add("com.apple.macpaint-image", "pntg"); + UTIMap.add("com.apple.pict", "pict"); + UTIMap.add("com.apple.quicktime-image", "qtif"); + UTIMap.add("com.apple.webarchive", "webarchive"); + UTIMap.add("com.compuserve.gif", "gif"); + UTIMap.add("com.ilm.openexr-image", "exr"); + UTIMap.add("com.kodak.flashpix-image", "fpx"); + UTIMap.add("com.microsoft.bmp", "bmp"); + UTIMap.add("com.microsoft.ico", "ico"); + UTIMap.add("com.netscape.javascript-source", "js"); + UTIMap.add("com.sgi.sgi-image", "sgi"); + UTIMap.add("com.truevision.tga-image", "tga"); + } + return UTIMap.get(type); +} + +} // namespace WebCore diff --git a/Source/WebCore/platform/graphics/cg/IntPointCG.cpp b/Source/WebCore/platform/graphics/cg/IntPointCG.cpp new file mode 100644 index 0000000..95dbe5f --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/IntPointCG.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. + * + * 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" +#include "IntPoint.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +IntPoint::IntPoint(const CGPoint& p) : m_x(static_cast<int>(p.x)), m_y(static_cast<int>(p.y)) +{ +} + +IntPoint::operator CGPoint() const +{ + return CGPointMake(m_x, m_y); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/IntRectCG.cpp b/Source/WebCore/platform/graphics/cg/IntRectCG.cpp new file mode 100644 index 0000000..73fd63f --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/IntRectCG.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved. + * + * 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" +#include "IntRect.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +IntRect::operator CGRect() const +{ + return CGRectMake(x(), y(), width(), height()); +} + +IntRect enclosingIntRect(const CGRect& rect) +{ + int l = static_cast<int>(floorf(rect.origin.x)); + int t = static_cast<int>(floorf(rect.origin.y)); + int r = static_cast<int>(ceilf(CGRectGetMaxX(rect))); + int b = static_cast<int>(ceilf(CGRectGetMaxY(rect))); + return IntRect(l, t, r - l, b - t); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/IntSizeCG.cpp b/Source/WebCore/platform/graphics/cg/IntSizeCG.cpp new file mode 100644 index 0000000..d8e8c83 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/IntSizeCG.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. + * + * 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" +#include "IntSize.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +IntSize::IntSize(const CGSize& s) : m_width(static_cast<int>(s.width)), m_height(static_cast<int>(s.height)) +{ +} + +IntSize::operator CGSize() const +{ + return CGSizeMake(m_width, m_height); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/PDFDocumentImage.cpp b/Source/WebCore/platform/graphics/cg/PDFDocumentImage.cpp new file mode 100644 index 0000000..8bf04f1 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/PDFDocumentImage.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. + * + * 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. + */ + +#define _USE_MATH_DEFINES 1 +#include "config.h" +#include "PDFDocumentImage.h" + +#if PLATFORM(CG) + +#include "GraphicsContext.h" +#include "ImageObserver.h" +#include "SharedBuffer.h" +#include <wtf/MathExtras.h> +#include <wtf/RetainPtr.h> + +#if !PLATFORM(MAC) +#include "ImageSourceCG.h" +#endif + +using namespace std; + +namespace WebCore { + +PDFDocumentImage::PDFDocumentImage() + : Image(0) // PDFs don't animate + , m_document(0) + , m_rotation(0.0f) + , m_currentPage(-1) +{ +} + +PDFDocumentImage::~PDFDocumentImage() +{ + CGPDFDocumentRelease(m_document); +} + +String PDFDocumentImage::filenameExtension() const +{ + return "pdf"; +} + +IntSize PDFDocumentImage::size() const +{ + const float sina = sinf(-m_rotation); + const float cosa = cosf(-m_rotation); + const float width = m_mediaBox.size().width(); + const float height = m_mediaBox.size().height(); + const float rotWidth = width * cosa - height * sina; + const float rotHeight = width * sina + height * cosa; + + return IntSize((int)(fabsf(rotWidth) + 0.5f), (int)(fabsf(rotHeight) + 0.5f)); +} + +bool PDFDocumentImage::dataChanged(bool allDataReceived) +{ + if (allDataReceived && !m_document) { +#if PLATFORM(MAC) + // On Mac the NSData inside the SharedBuffer can be secretly appended to without the SharedBuffer's knowledge. We use SharedBuffer's ability + // to wrap itself inside CFData to get around this, ensuring that ImageIO is really looking at the SharedBuffer. + RetainPtr<CFDataRef> data(AdoptCF, this->data()->createCFData()); + RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithCFData(data.get())); +#else + // Create a CGDataProvider to wrap the SharedBuffer. + // We use the GetBytesAtPosition callback rather than the GetBytePointer one because SharedBuffer + // does not provide a way to lock down the byte pointer and guarantee that it won't move, which + // is a requirement for using the GetBytePointer callback. + CGDataProviderDirectCallbacks providerCallbacks = { 0, 0, 0, sharedBufferGetBytesAtPosition, 0 }; + RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateDirect(this->data(), this->data()->size(), &providerCallbacks)); +#endif + m_document = CGPDFDocumentCreateWithProvider(dataProvider.get()); + setCurrentPage(0); + } + return m_document; // return true if size is available +} + +void PDFDocumentImage::adjustCTM(GraphicsContext* context) const +{ + // rotate the crop box and calculate bounding box + float sina = sinf(-m_rotation); + float cosa = cosf(-m_rotation); + float width = m_cropBox.width(); + float height = m_cropBox.height(); + + // calculate rotated x and y edges of the corp box. if they're negative, it means part of the image has + // been rotated outside of the bounds and we need to shift over the image so it lies inside the bounds again + CGPoint rx = CGPointMake(width * cosa, width * sina); + CGPoint ry = CGPointMake(-height * sina, height * cosa); + + // adjust so we are at the crop box origin + const CGFloat zero = 0; + CGContextTranslateCTM(context->platformContext(), floorf(-min(zero, min(rx.x, ry.x))), floorf(-min(zero, min(rx.y, ry.y)))); + + // rotate -ve to remove rotation + CGContextRotateCTM(context->platformContext(), -m_rotation); + + // shift so we are completely within media box + CGContextTranslateCTM(context->platformContext(), m_mediaBox.x() - m_cropBox.x(), m_mediaBox.y() - m_cropBox.y()); +} + +void PDFDocumentImage::setCurrentPage(int page) +{ + if (!m_document) + return; + + if (page == m_currentPage) + return; + + if (!(page >= 0 && page < pageCount())) + return; + + m_currentPage = page; + + CGPDFPageRef cgPage = CGPDFDocumentGetPage(m_document, page + 1); + + // get media box (guaranteed) + m_mediaBox = CGPDFPageGetBoxRect(cgPage, kCGPDFMediaBox); + + // get crop box (not always there). if not, use media box + CGRect r = CGPDFPageGetBoxRect(cgPage, kCGPDFCropBox); + if (!CGRectIsEmpty(r)) + m_cropBox = r; + else + m_cropBox = m_mediaBox; + + // get page rotation angle + m_rotation = CGPDFPageGetRotationAngle(cgPage) * piFloat / 180.0f; // to radians +} + +int PDFDocumentImage::pageCount() const +{ + return m_document ? CGPDFDocumentGetNumberOfPages(m_document) : 0; +} + +void PDFDocumentImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, ColorSpace, CompositeOperator op) +{ + if (!m_document || m_currentPage == -1) + return; + + context->save(); + + context->setCompositeOperation(op); + + float hScale = dstRect.width() / srcRect.width(); + float vScale = dstRect.height() / srcRect.height(); + + // Scale and translate so the document is rendered in the correct location, + // including accounting for the fact that a GraphicsContext is always flipped + // and doing appropriate flipping. + CGContextTranslateCTM(context->platformContext(), dstRect.x() - srcRect.x() * hScale, dstRect.y() - srcRect.y() * vScale); + CGContextScaleCTM(context->platformContext(), hScale, vScale); + CGContextScaleCTM(context->platformContext(), 1, -1); + CGContextTranslateCTM(context->platformContext(), 0, -srcRect.height()); + CGContextClipToRect(context->platformContext(), CGRectIntegral(srcRect)); + + // Rotate translate image into position according to doc properties. + adjustCTM(context); + + CGContextTranslateCTM(context->platformContext(), -m_mediaBox.x(), -m_mediaBox.y()); + CGContextDrawPDFPage(context->platformContext(), CGPDFDocumentGetPage(m_document, m_currentPage + 1)); + + context->restore(); + + if (imageObserver()) + imageObserver()->didDraw(this); +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/PDFDocumentImage.h b/Source/WebCore/platform/graphics/cg/PDFDocumentImage.h new file mode 100644 index 0000000..790d620 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/PDFDocumentImage.h @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved. + * + * 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 "Image.h" + +#include "FloatRect.h" +#include "GraphicsTypes.h" + +#if PLATFORM(CG) + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + + class GraphicsContext; + + class PDFDocumentImage : public Image { + public: + static PassRefPtr<PDFDocumentImage> create() + { + return adoptRef(new PDFDocumentImage); + } + + private: + virtual ~PDFDocumentImage(); + + virtual String filenameExtension() const; + + virtual bool hasSingleSecurityOrigin() const { return true; } + + virtual bool dataChanged(bool allDataReceived); + + // FIXME: PDF Images are underreporting decoded sizes and will be unable + // to prune because these functions are not implemented yet. + virtual void destroyDecodedData(bool /*destroyAll*/ = true) { } + virtual unsigned decodedSize() const { return 0; } + + virtual IntSize size() const; + + PDFDocumentImage(); + virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, ColorSpace styleColorSpace, CompositeOperator); + + void setCurrentPage(int); + int pageCount() const; + void adjustCTM(GraphicsContext*) const; + + CGPDFDocumentRef m_document; + FloatRect m_mediaBox; + FloatRect m_cropBox; + float m_rotation; + int m_currentPage; + }; + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/PathCG.cpp b/Source/WebCore/platform/graphics/cg/PathCG.cpp new file mode 100644 index 0000000..d6a1e6e --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/PathCG.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved. + * 2006, 2008 Rob Buis <buis@kde.org> + * + * 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" +#include "Path.h" + +#if PLATFORM(CG) + +#include "AffineTransform.h" +#include "FloatRect.h" +#include "GraphicsContext.h" +#include "IntRect.h" +#include "PlatformString.h" +#include "StrokeStyleApplier.h" +#include <ApplicationServices/ApplicationServices.h> +#include <wtf/MathExtras.h> +#include <wtf/RetainPtr.h> + +namespace WebCore { + +static size_t putBytesNowhere(void*, const void*, size_t count) +{ + return count; +} + +static CGContextRef createScratchContext() +{ + CGDataConsumerCallbacks callbacks = { putBytesNowhere, 0 }; + RetainPtr<CGDataConsumerRef> consumer(AdoptCF, CGDataConsumerCreate(0, &callbacks)); + CGContextRef context = CGPDFContextCreate(consumer.get(), 0, 0); + + CGFloat black[4] = { 0, 0, 0, 1 }; + CGContextSetFillColor(context, black); + CGContextSetStrokeColor(context, black); + + return context; +} + +static inline CGContextRef scratchContext() +{ + static CGContextRef context = createScratchContext(); + return context; +} + +Path::Path() + : m_path(CGPathCreateMutable()) +{ +} + +Path::~Path() +{ + CGPathRelease(m_path); +} + +Path::Path(const Path& other) + : m_path(CGPathCreateMutableCopy(other.m_path)) +{ +} + +Path& Path::operator=(const Path& other) +{ + CGMutablePathRef path = CGPathCreateMutableCopy(other.m_path); + CGPathRelease(m_path); + m_path = path; + return *this; +} + +static void copyClosingSubpathsApplierFunction(void* info, const CGPathElement* element) +{ + CGMutablePathRef path = static_cast<CGMutablePathRef>(info); + CGPoint* points = element->points; + + switch (element->type) { + case kCGPathElementMoveToPoint: + if (!CGPathIsEmpty(path)) // to silence a warning when trying to close an empty path + CGPathCloseSubpath(path); // This is the only change from CGPathCreateMutableCopy + CGPathMoveToPoint(path, 0, points[0].x, points[0].y); + break; + case kCGPathElementAddLineToPoint: + CGPathAddLineToPoint(path, 0, points[0].x, points[0].y); + break; + case kCGPathElementAddQuadCurveToPoint: + CGPathAddQuadCurveToPoint(path, 0, points[0].x, points[0].y, points[1].x, points[1].y); + break; + case kCGPathElementAddCurveToPoint: + CGPathAddCurveToPoint(path, 0, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y); + break; + case kCGPathElementCloseSubpath: + CGPathCloseSubpath(path); + break; + } +} + +static CGMutablePathRef copyCGPathClosingSubpaths(CGPathRef originalPath) +{ + CGMutablePathRef path = CGPathCreateMutable(); + CGPathApply(originalPath, path, copyClosingSubpathsApplierFunction); + CGPathCloseSubpath(path); + return path; +} + +bool Path::contains(const FloatPoint &point, WindRule rule) const +{ + if (!boundingRect().contains(point)) + return false; + + // CGPathContainsPoint returns false for non-closed paths, as a work-around, we copy and close the path first. Radar 4758998 asks for a better CG API to use + RetainPtr<CGMutablePathRef> path(AdoptCF, copyCGPathClosingSubpaths(m_path)); + bool ret = CGPathContainsPoint(path.get(), 0, point, rule == RULE_EVENODD ? true : false); + return ret; +} + +bool Path::strokeContains(StrokeStyleApplier* applier, const FloatPoint& point) const +{ + ASSERT(applier); + + CGContextRef context = scratchContext(); + + CGContextSaveGState(context); + CGContextBeginPath(context); + CGContextAddPath(context, platformPath()); + + GraphicsContext gc(context); + applier->strokeStyle(&gc); + + bool hitSuccess = CGContextPathContainsPoint(context, point, kCGPathStroke); + CGContextRestoreGState(context); + + return hitSuccess; +} + +void Path::translate(const FloatSize& size) +{ + CGAffineTransform translation = CGAffineTransformMake(1, 0, 0, 1, size.width(), size.height()); + CGMutablePathRef newPath = CGPathCreateMutable(); + CGPathAddPath(newPath, &translation, m_path); + CGPathRelease(m_path); + m_path = newPath; +} + +FloatRect Path::boundingRect() const +{ + return CGPathGetBoundingBox(m_path); +} + +FloatRect Path::strokeBoundingRect(StrokeStyleApplier* applier) +{ + CGContextRef context = scratchContext(); + + CGContextSaveGState(context); + CGContextBeginPath(context); + CGContextAddPath(context, platformPath()); + + if (applier) { + GraphicsContext graphicsContext(context); + applier->strokeStyle(&graphicsContext); + } + + CGContextReplacePathWithStrokedPath(context); + CGRect box = CGContextIsPathEmpty(context) ? CGRectZero : CGContextGetPathBoundingBox(context); + CGContextRestoreGState(context); + + return box; +} + +void Path::moveTo(const FloatPoint& point) +{ + CGPathMoveToPoint(m_path, 0, point.x(), point.y()); +} + +void Path::addLineTo(const FloatPoint& p) +{ + CGPathAddLineToPoint(m_path, 0, p.x(), p.y()); +} + +void Path::addQuadCurveTo(const FloatPoint& cp, const FloatPoint& p) +{ + CGPathAddQuadCurveToPoint(m_path, 0, cp.x(), cp.y(), p.x(), p.y()); +} + +void Path::addBezierCurveTo(const FloatPoint& cp1, const FloatPoint& cp2, const FloatPoint& p) +{ + CGPathAddCurveToPoint(m_path, 0, cp1.x(), cp1.y(), cp2.x(), cp2.y(), p.x(), p.y()); +} + +void Path::addArcTo(const FloatPoint& p1, const FloatPoint& p2, float radius) +{ + CGPathAddArcToPoint(m_path, 0, p1.x(), p1.y(), p2.x(), p2.y(), radius); +} + +void Path::closeSubpath() +{ + CGPathCloseSubpath(m_path); +} + +void Path::addArc(const FloatPoint& p, float r, float sa, float ea, bool clockwise) +{ + // Workaround for <rdar://problem/5189233> CGPathAddArc hangs or crashes when passed inf as start or end angle + if (isfinite(sa) && isfinite(ea)) + CGPathAddArc(m_path, 0, p.x(), p.y(), r, sa, ea, clockwise); +} + +void Path::addRect(const FloatRect& r) +{ + CGPathAddRect(m_path, 0, r); +} + +void Path::addEllipse(const FloatRect& r) +{ + CGPathAddEllipseInRect(m_path, 0, r); +} + +void Path::clear() +{ + CGPathRelease(m_path); + m_path = CGPathCreateMutable(); +} + +bool Path::isEmpty() const +{ + return CGPathIsEmpty(m_path); +} + +bool Path::hasCurrentPoint() const +{ + return !isEmpty(); +} + +FloatPoint Path::currentPoint() const +{ + return CGPathGetCurrentPoint(m_path); +} + +// MARK: - +// MARK: Path Management + +struct PathApplierInfo { + void* info; + PathApplierFunction function; +}; + +static void CGPathApplierToPathApplier(void *info, const CGPathElement *element) +{ + PathApplierInfo* pinfo = (PathApplierInfo*)info; + FloatPoint points[3]; + PathElement pelement; + pelement.type = (PathElementType)element->type; + pelement.points = points; + CGPoint* cgPoints = element->points; + switch (element->type) { + case kCGPathElementMoveToPoint: + case kCGPathElementAddLineToPoint: + points[0] = cgPoints[0]; + break; + case kCGPathElementAddQuadCurveToPoint: + points[0] = cgPoints[0]; + points[1] = cgPoints[1]; + break; + case kCGPathElementAddCurveToPoint: + points[0] = cgPoints[0]; + points[1] = cgPoints[1]; + points[2] = cgPoints[2]; + break; + case kCGPathElementCloseSubpath: + break; + } + pinfo->function(pinfo->info, &pelement); +} + +void Path::apply(void* info, PathApplierFunction function) const +{ + PathApplierInfo pinfo; + pinfo.info = info; + pinfo.function = function; + CGPathApply(m_path, &pinfo, CGPathApplierToPathApplier); +} + +void Path::transform(const AffineTransform& transform) +{ + CGMutablePathRef path = CGPathCreateMutable(); + CGAffineTransform transformCG = transform; + CGPathAddPath(path, &transformCG, m_path); + CGPathRelease(m_path); + m_path = path; +} + +} + +#endif // PLATFORM(CG) diff --git a/Source/WebCore/platform/graphics/cg/PatternCG.cpp b/Source/WebCore/platform/graphics/cg/PatternCG.cpp new file mode 100644 index 0000000..94f37b2 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/PatternCG.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2006, 2007, 2008 Apple Computer, Inc. All rights reserved. + * Copyright (C) 2008 Eric Seidel <eric@webkit.org> + * + * 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" +#include "Pattern.h" + +#include "AffineTransform.h" +#include "GraphicsContext.h" + +#include <ApplicationServices/ApplicationServices.h> + +namespace WebCore { + +static void patternCallback(void* info, CGContextRef context) +{ + CGImageRef platformImage = static_cast<Image*>(info)->getCGImageRef(); + if (!platformImage) + return; + + CGRect rect = GraphicsContext(context).roundToDevicePixels( + FloatRect(0, 0, CGImageGetWidth(platformImage), CGImageGetHeight(platformImage))); + CGContextDrawImage(context, rect, platformImage); +} + +static void patternReleaseCallback(void* info) +{ + static_cast<Image*>(info)->deref(); +} + +CGPatternRef Pattern::createPlatformPattern(const AffineTransform& userSpaceTransformation) const +{ + IntRect tileRect = tileImage()->rect(); + + AffineTransform patternTransform = m_patternSpaceTransformation; + patternTransform.multiply(userSpaceTransformation); + patternTransform.scaleNonUniform(1, -1); + patternTransform.translate(0, -tileRect.height()); + + // If FLT_MAX should also be used for xStep or yStep, nothing is rendered. Using fractions of FLT_MAX also + // result in nothing being rendered. + // INT_MAX is almost correct, but there seems to be some number wrapping occurring making the fill + // pattern is not filled correctly. + // To make error of floating point less than 0.5, we use the half of the number of mantissa of float (1 << 22). + CGFloat xStep = m_repeatX ? tileRect.width() : (1 << 22); + CGFloat yStep = m_repeatY ? tileRect.height() : (1 << 22); + + // The pattern will release the tile when it's done rendering in patternReleaseCallback + tileImage()->ref(); + + const CGPatternCallbacks patternCallbacks = { 0, patternCallback, patternReleaseCallback }; + return CGPatternCreate(tileImage(), tileRect, patternTransform, xStep, yStep, + kCGPatternTilingConstantSpacing, TRUE, &patternCallbacks); +} + +} diff --git a/Source/WebCore/platform/graphics/cg/TransformationMatrixCG.cpp b/Source/WebCore/platform/graphics/cg/TransformationMatrixCG.cpp new file mode 100644 index 0000000..ec40836 --- /dev/null +++ b/Source/WebCore/platform/graphics/cg/TransformationMatrixCG.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved. + * + * 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" +#include "AffineTransform.h" +#include "TransformationMatrix.h" + +#if PLATFORM(CG) + +#include <CoreGraphics/CGAffineTransform.h> +#include "FloatConversion.h" + +namespace WebCore { + +TransformationMatrix::TransformationMatrix(const CGAffineTransform& t) +{ + setA(t.a); + setB(t.b); + setC(t.c); + setD(t.d); + setE(t.tx); + setF(t.ty); +} + +TransformationMatrix::operator CGAffineTransform() const +{ + return CGAffineTransformMake(narrowPrecisionToCGFloat(a()), + narrowPrecisionToCGFloat(b()), + narrowPrecisionToCGFloat(c()), + narrowPrecisionToCGFloat(d()), + narrowPrecisionToCGFloat(e()), + narrowPrecisionToCGFloat(f())); +} + +AffineTransform::operator CGAffineTransform() const +{ + return CGAffineTransformMake(narrowPrecisionToCGFloat(a()), + narrowPrecisionToCGFloat(b()), + narrowPrecisionToCGFloat(c()), + narrowPrecisionToCGFloat(d()), + narrowPrecisionToCGFloat(e()), + narrowPrecisionToCGFloat(f())); +} + +} + +#endif // PLATFORM(CG) |
