/*
 * Copyright (C) 2003, 2004, 2005, 2006, 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. AND ITS CONTRIBUTORS ``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 ITS 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 "GraphicsContext.h"

#include "BidiResolver.h"
#include "BitmapImage.h"
#include "FloatRoundedRect.h"
#include "Font.h"
#include "Gradient.h"
#include "GlyphBuffer.h"
#include "ImageBuffer.h"
#include "IntRect.h"
#include "RoundedRect.h"
#include "SimpleFontData.h"
#include "TextRun.h"

#include "stdio.h"

using namespace std;

namespace WebCore {

namespace {
class TextRunIterator {
public:
	ALWAYS_INLINE TextRunIterator()
        : m_textRun(0)
        , m_offset(0)
    {
    }

	ALWAYS_INLINE TextRunIterator(const TextRun* textRun, unsigned offset)
        : m_textRun(textRun)
        , m_offset(offset)
    {
    }

	ALWAYS_INLINE TextRunIterator(const TextRunIterator& other)
        : m_textRun(other.m_textRun)
        , m_offset(other.m_offset)
    {
    }

	ALWAYS_INLINE unsigned offset() const { return m_offset; }
	ALWAYS_INLINE void increment() { m_offset++; }
	ALWAYS_INLINE bool atEnd() const { return !m_textRun || m_offset >= m_textRun->length(); }
	ALWAYS_INLINE UChar current() const { return (*m_textRun)[m_offset]; }
	ALWAYS_INLINE UCharDirection direction() const { return atEnd() ? U_OTHER_NEUTRAL : u_charDirection(current()); }

	ALWAYS_INLINE bool operator==(const TextRunIterator& other)
    {
        return m_offset == other.m_offset && m_textRun == other.m_textRun;
    }

	ALWAYS_INLINE bool operator!=(const TextRunIterator& other) { return !operator==(other); }

private:
    const TextRun* m_textRun;
    int m_offset;
};
}

template <>
inline bool BidiResolver<TextRunIterator, BidiCharacterRun>::needsContinuePastEndInternal() const
{
    return true;
}

DLL_PUBLIC GraphicsContext::GraphicsContext(PlatformGraphicsContext* platformGraphicsContext)
    : m_updatingControlTints(false)
    , m_transparencyCount(0)
	, m_pixelSnappingFactor(1)
{
    platformInit(platformGraphicsContext);
}

DLL_PUBLIC GraphicsContext::~GraphicsContext()
{
    ASSERT(m_stack.isEmpty());
    ASSERT(!m_transparencyCount);
    platformDestroy();
}

DLL_PUBLIC void GraphicsContext::save()
{
    if (UNLIKELY(paintingDisabled()))
        return;

    m_stack.append(m_state);

    savePlatformState();
}

DLL_PUBLIC void GraphicsContext::restore()
{
    if (UNLIKELY(paintingDisabled()))
        return;

    if (m_stack.isEmpty()) {
        LOG_ERROR("ERROR void GraphicsContext::restore() stack is empty");
        return;
    }
    m_state = m_stack.last();
    m_stack.removeLast();

    // Make sure we deallocate the state stack buffer when it goes empty.
    // Canvas elements will immediately save() again, but that goes into inline capacity.
    if (m_stack.isEmpty())
        m_stack.clear();

    restorePlatformState();
}

DLL_PUBLIC void GraphicsContext::setStrokeThickness(float thickness)
{
    m_state.strokeThickness = thickness;
    setPlatformStrokeThickness(thickness);
}

void GraphicsContext::setStrokeStyle(StrokeStyle style)
{
    m_state.strokeStyle = style;
    setPlatformStrokeStyle(style);
}

DLL_PUBLIC void GraphicsContext::setStrokeColor(const Color& color)
{
    m_state.strokeColor = color;
    m_state.strokeGradient.clear();
    m_state.strokePattern.clear();
    setPlatformStrokeColor(color);
}

void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color)
{
    m_state.shadowOffset = offset;
    m_state.shadowBlur = blur;
    m_state.shadowColor = color;
    setPlatformShadow(offset, blur, color);
}

void GraphicsContext::setLegacyShadow(const FloatSize& offset, float blur, const Color& color)
{
    m_state.shadowOffset = offset;
    m_state.shadowBlur = blur;
    m_state.shadowColor = color;
#if USE(CG)
    m_state.shadowsUseLegacyRadius = true;
#endif
    setPlatformShadow(offset, blur, color);
}

void GraphicsContext::clearShadow()
{
    m_state.shadowOffset = FloatSize();
    m_state.shadowBlur = 0;
    m_state.shadowColor = Color();
    clearPlatformShadow();
}

bool GraphicsContext::hasShadow() const
{
    return m_state.shadowColor.isValid() && m_state.shadowColor.alpha()
           && (m_state.shadowBlur || m_state.shadowOffset.width() || m_state.shadowOffset.height());
}

bool GraphicsContext::getShadow(FloatSize& offset, float& blur, Color& color) const
{
    offset = m_state.shadowOffset;
    blur = m_state.shadowBlur;
    color = m_state.shadowColor;

    return hasShadow();
}

bool GraphicsContext::hasBlurredShadow() const
{
    return m_state.shadowColor.isValid() && m_state.shadowColor.alpha() && m_state.shadowBlur;
}

void GraphicsContext::setFillColor(const Color& color)
{
    m_state.fillColor = color;
    m_state.fillGradient.clear();
    m_state.fillPattern.clear();
    setPlatformFillColor(color);
}

void GraphicsContext::setShouldAntialias(bool b)
{
    m_state.shouldAntialias = b;
    setPlatformShouldAntialias(b);
}

void GraphicsContext::setShouldSmoothFonts(bool b)
{
    m_state.shouldSmoothFonts = b;
    setPlatformShouldSmoothFonts(b);
}

void GraphicsContext::setShouldSubpixelQuantizeFonts(bool b)
{
    m_state.shouldSubpixelQuantizeFonts = b;
}

bool GraphicsContext::shouldSubpixelQuantizeFonts() const
{
    return m_state.shouldSubpixelQuantizeFonts;
}

void GraphicsContext::setStrokePattern(PassRefPtr<Pattern> pattern)
{
    ASSERT(pattern);
    if (!pattern) {
        setStrokeColor(Color::black);
        return;
    }
    setPlatformStrokePattern(pattern.get());
    m_state.strokeGradient.clear();
    m_state.strokePattern = pattern;
}

void GraphicsContext::setFillPattern(PassRefPtr<Pattern> pattern)
{
    ASSERT(pattern);
    if (!pattern) {
        setFillColor(Color::black);
        return;
    }
    setPlatformFillPattern(pattern.get());
    m_state.fillGradient.clear();
    m_state.fillPattern = pattern;
}

void GraphicsContext::setStrokeGradient(PassRefPtr<Gradient> gradient)
{
    ASSERT(gradient);
    if (!gradient) {
        setStrokeColor(Color::black);
        return;
    }
    setPlatformStrokeGradient(gradient.get());
    m_state.strokeGradient = gradient;
    m_state.strokePattern.clear();
}

void GraphicsContext::setFillGradient(PassRefPtr<Gradient> gradient)
{
    ASSERT(gradient);
    if (!gradient) {
        setFillColor(Color::black);
        return;
    }
    setPlatformFillGradient(gradient.get());
    m_state.fillGradient = gradient;
    m_state.fillPattern.clear();
}

DLL_PUBLIC void GraphicsContext::beginTransparencyLayer(float opacity)
{
    beginPlatformTransparencyLayer(opacity);
    ++m_transparencyCount;
}

DLL_PUBLIC void GraphicsContext::endTransparencyLayer()
{
    endPlatformTransparencyLayer();
    ASSERT(m_transparencyCount > 0);
    --m_transparencyCount;
}

#if !OS(WINCE) || (PLATFORM(QT) && !HAVE(QRAWFONT))
void GraphicsContext::drawText(const Font& font, const TextRun& run, const FloatPoint& point, int from, int to)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    font.drawText(this, run, point, from, to);
}
#endif

void GraphicsContext::drawGlyphs(const Font& font, const SimpleFontData& fontData, const GlyphBuffer& buffer, int from, int numGlyphs, const FloatPoint& point)
{
    if (paintingDisabled())
        return;

    font.drawGlyphs(this, &fontData, buffer, from, numGlyphs, point);
}

void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRun& run, const AtomicString& mark, const FloatPoint& point, int from, int to)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    font.drawEmphasisMarks(this, run, mark, point, from, to);
}

void GraphicsContext::drawBidiText(const Font& font, const TextRun& run, const FloatPoint& point)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
    bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
    bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));

    // FIXME: This ownership should be reversed. We should pass BidiRunList
    // to BidiResolver in createBidiRunsForLine.
    BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
    bidiResolver.createBidiRunsForLine(TextRunIterator(&run, run.length()));
    if (!bidiRuns.runCount())
        return;

    FloatPoint currPoint = point;
    BidiCharacterRun* bidiRun = bidiRuns.firstRun();
    while (bidiRun) {
        TextRun subrun = run.subRun(bidiRun->start(), bidiRun->stop() - bidiRun->start());
        bool isRTL = bidiRun->level() % 2;
        subrun.setDirection(isRTL ? RTL : LTR);
        subrun.setDirectionalOverride(bidiRun->dirOverride(false));

        font.drawText(this, subrun, currPoint);

        bidiRun = bidiRun->next();
        // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here.
        if (bidiRun)
            currPoint.move(font.width(subrun), 0);
    }

    bidiRuns.deleteRuns();
}

DLL_PUBLIC void GraphicsContext::drawImage(Image* image, const FloatPoint& p, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
{
    if (!image)
        return;
    drawImage(image, FloatRect(p, image->size()), FloatRect(FloatPoint(), image->size()), op, BlendModeNormal, shouldRespectImageOrientation);
}

DLL_PUBLIC void GraphicsContext::drawImage(Image* image, const FloatRect& r, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
{
    if (!image)
        return;
    drawImage(image, r, FloatRect(FloatPoint(), image->size()), op, BlendModeNormal, shouldRespectImageOrientation, useLowQualityScale);
}

void GraphicsContext::drawImage(Image* image, const FloatPoint& dest, const IntRect& srcRect, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
{
    drawImage(image, FloatRect(dest, srcRect.size()), FloatRect(srcRect), op, BlendModeNormal, shouldRespectImageOrientation);
}

void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, BlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
{
    if (UNLIKELY(paintingDisabled() || !image))
        return;

    InterpolationQuality previousInterpolationQuality = InterpolationDefault;

    if (useLowQualityScale) {
        previousInterpolationQuality = imageInterpolationQuality();
#if PLATFORM(CHROMIUM)
        setImageInterpolationQuality(InterpolationLow);
#else
        // FIXME (49002): Should be InterpolationLow
        setImageInterpolationQuality(InterpolationNone);
#endif
    }

    image->draw(this, dest, src, op, blendMode, shouldRespectImageOrientation);

    if (useLowQualityScale)
        setImageInterpolationQuality(previousInterpolationQuality);
}

void GraphicsContext::drawTiledImage(Image* image, const FloatRect& destRect, const FloatPoint& srcPoint, const FloatSize& tileSize, const FloatSize& spacing, CompositeOperator op, bool useLowQualityScale, BlendMode blendMode)
{
    if (UNLIKELY(paintingDisabled() || !image))
        return;

    if (useLowQualityScale) {
        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
        setImageInterpolationQuality(InterpolationLow);
        image->drawTiled(this, destRect, srcPoint, tileSize, spacing, op, blendMode);
        setImageInterpolationQuality(previousInterpolationQuality);
    } else
        image->drawTiled(this, destRect, srcPoint, tileSize, spacing, op, blendMode);
}

void GraphicsContext::drawTiledImage(Image* image, const FloatRect& dest, const FloatRect& srcRect,
    const FloatSize& tileScaleFactor, Image::TileRule hRule, Image::TileRule vRule, CompositeOperator op, bool useLowQualityScale)
{
    if (UNLIKELY(paintingDisabled() || !image))
        return;

    if (hRule == Image::StretchTile && vRule == Image::StretchTile) {
        // Just do a scale.
        drawImage(image, dest, srcRect, op);
        return;
    }

    if (useLowQualityScale) {
        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
        setImageInterpolationQuality(InterpolationLow);
        image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
        setImageInterpolationQuality(previousInterpolationQuality);
    } else
        image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
}

void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatPoint& p, CompositeOperator op, BlendMode blendMode)
{
    if (!image)
        return;
    drawImageBuffer(image, FloatRect(p, image->logicalSize()), FloatRect(FloatPoint(), image->logicalSize()), op, blendMode);
}

void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
{
    if (!image)
        return;
    drawImageBuffer(image, dest, FloatRect(FloatPoint(), FloatSize(image->logicalSize())), op, blendMode, useLowQualityScale);
}

void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatPoint& dest, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode)
{
    drawImageBuffer(image, FloatRect(dest, srcRect.size()), srcRect, op, blendMode);
}

void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
{
    if (UNLIKELY(paintingDisabled() || !image))
        return;

    if (useLowQualityScale) {
        InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
#if PLATFORM(CHROMIUM)
        setImageInterpolationQuality(InterpolationLow);
#else
        // FIXME (49002): Should be InterpolationLow
        setImageInterpolationQuality(InterpolationNone);
#endif
        image->draw(this, dest, src, op, blendMode, useLowQualityScale);
        setImageInterpolationQuality(previousInterpolationQuality);
    } else
        image->draw(this, dest, src, op, blendMode, useLowQualityScale);
}

void GraphicsContext::clipRoundedRect(const FloatRoundedRect& rect)
{
    if (paintingDisabled())
        return;

    Path path;
    path.addRoundedRect(rect);
    clip(path);
}

void GraphicsContext::clipOutRoundedRect(const FloatRoundedRect& rect)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    if (!rect.isRounded()) {
        clipOut(rect.rect());
        return;
    }

    Path path;
    path.addRoundedRect(rect);
    clipOut(path);
}

void GraphicsContext::clipToImageBuffer(ImageBuffer* buffer, const FloatRect& rect)
{
    if (UNLIKELY(paintingDisabled()))
        return;
    buffer->clip(this, rect);
}

#if !USE(CG) && !PLATFORM(QT) && !USE(CAIRO)
IntRect GraphicsContext::clipBounds() const
{
    ASSERT_NOT_REACHED();
    return IntRect();
}
#endif

void GraphicsContext::setTextDrawingMode(TextDrawingModeFlags mode)
{
    m_state.textDrawingMode = mode;
    if (UNLIKELY(paintingDisabled()))
        return;
    setPlatformTextDrawingMode(mode);
}

void GraphicsContext::fillRect(const FloatRect& rect, Gradient& gradient)
{
    if (UNLIKELY(paintingDisabled()))
        return;
    gradient.fill(this, rect);
}

void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, CompositeOperator op, BlendMode blendMode)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    CompositeOperator previousOperator = compositeOperation();
    setCompositeOperation(op, blendMode);
    fillRect(rect, color);
    setCompositeOperation(previousOperator);
}

void GraphicsContext::fillRoundedRect(const FloatRoundedRect& rect, const Color& color, BlendMode blendMode)
{
    if (rect.isRounded()) {
        setCompositeOperation(compositeOperation(), blendMode);
        platformFillRoundedRect(rect, color);
        setCompositeOperation(compositeOperation());
    } else
        fillRect(rect.rect(), color, compositeOperation(), blendMode);
}

#if !USE(CG) && !PLATFORM(QT) && !USE(CAIRO)
void GraphicsContext::fillRectWithRoundedHole(const FloatRect& rect, const FloatRoundedRect& roundedHoleRect, const Color& color)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    Path path;
    path.addRect(rect);

    if (!roundedHoleRect.radii().isZero())
        path.addRoundedRect(roundedHoleRect);
    else
        path.addRect(roundedHoleRect.rect());

    WindRule oldFillRule = fillRule();
    Color oldFillColor = fillColor();

    setFillRule(RULE_EVENODD);
    setFillColor(color);

    fillPath(path);

    setFillRule(oldFillRule);
    setFillColor(oldFillColor);
}
#endif

DLL_PUBLIC void GraphicsContext::setCompositeOperation(CompositeOperator compositeOperation, BlendMode blendMode)
{
    m_state.compositeOperator = compositeOperation;
    m_state.blendMode = blendMode;
    setPlatformCompositeOperation(compositeOperation, blendMode);
}

#if !USE(CG) && !USE(SKIA)
// Implement this if you want to go ahead and push the drawing mode into your native context
// immediately.
void GraphicsContext::setPlatformTextDrawingMode(TextDrawingModeFlags mode)
{
}
#endif

#if !PLATFORM(QT) && !USE(CAIRO) && !USE(SKIA) && !USE(OPENVG)
void GraphicsContext::setPlatformStrokeStyle(StrokeStyle)
{
}
#endif

#if !USE(CG)
void GraphicsContext::setPlatformShouldSmoothFonts(bool)
{
}
#endif

#if !USE(SKIA) && !USE(CG) && !USE(OPENVG) && !USE(CAIRO)
bool GraphicsContext::isAcceleratedContext() const
{
    return false;
}
#endif

void GraphicsContext::adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle penStyle)
{
    // 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, WebKit 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 (penStyle == DottedStroke || penStyle == DashedStroke) {
        if (p1.x() == p2.x()) {
            p1.setY(p1.y() + strokeWidth);
            p2.setY(p2.y() - strokeWidth);
        } else {
            p1.setX(p1.x() + strokeWidth);
            p2.setX(p2.x() - strokeWidth);
        }
    }

    if (static_cast<int>(strokeWidth) % 2) { //odd
        if (p1.x() == p2.x()) {
            // We're a vertical line.  Adjust our x.
            p1.setX(p1.x() + 0.5f);
            p2.setX(p2.x() + 0.5f);
        } else {
            // We're a horizontal line. Adjust our y.
            p1.setY(p1.y() + 0.5f);
            p2.setY(p2.y() + 0.5f);
        }
    }
}

static bool scalesMatch(AffineTransform a, AffineTransform b)
{
    return a.xScale() == b.xScale() && a.yScale() == b.yScale();
}

PassOwnPtr<ImageBuffer> GraphicsContext::createCompatibleBuffer(const FloatSize& size) const
{
    // Make the buffer larger if the context's transform is scaling it so we need a higher
    // resolution than one pixel per unit. Also set up a corresponding scale factor on the
    // graphics context.

    AffineTransform transform = getCTM(DefinitelyIncludeDeviceScale);
    FloatSize scaledSize(static_cast<int>(ceil(size.width() * transform.xScale())), static_cast<int>(ceil(size.height() * transform.yScale())));

    OwnPtr<ImageBuffer> buffer = ImageBuffer::create(scaledSize, 1, ColorSpaceSRGB, isAcceleratedContext() ? Accelerated : Unaccelerated);
    if (!buffer)
        return nullptr;

    buffer->context()->scale(FloatSize(scaledSize.width() / size.width(), scaledSize.height() / size.height()));
    buffer->context()->setImageInterpolationQuality(imageInterpolationQuality());

    return buffer.release();
}

bool GraphicsContext::isCompatibleWithBuffer(ImageBuffer* buffer) const
{
    GraphicsContext* bufferContext = buffer->context();

    return scalesMatch(getCTM(), bufferContext->getCTM()) && isAcceleratedContext() == bufferContext->isAcceleratedContext();
}

#if !USE(CG)
void GraphicsContext::platformApplyDeviceScaleFactor(float)
{
}
#endif

void GraphicsContext::applyDeviceScaleFactor(float deviceScaleFactor)
{
    scale(FloatSize(deviceScaleFactor, deviceScaleFactor));
    platformApplyDeviceScaleFactor(deviceScaleFactor);
}

void GraphicsContext::fillEllipse(const FloatRect& ellipse)
{
    platformFillEllipse(ellipse);
}

void GraphicsContext::strokeEllipse(const FloatRect& ellipse)
{
    platformStrokeEllipse(ellipse);
}

void GraphicsContext::fillEllipseAsPath(const FloatRect& ellipse)
{
    Path path;
    path.addEllipse(ellipse);
    fillPath(path);
}

void GraphicsContext::strokeEllipseAsPath(const FloatRect& ellipse)
{
    Path path;
    path.addEllipse(ellipse);
    strokePath(path);
}

#if !USE(CG) && !USE(SKIA) // append && !USE(MYPLATFORM) here to optimize ellipses on your platform.
void GraphicsContext::platformFillEllipse(const FloatRect& ellipse)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    fillEllipseAsPath(ellipse);
}

void GraphicsContext::platformStrokeEllipse(const FloatRect& ellipse)
{
    if (UNLIKELY(paintingDisabled()))
        return;

    strokeEllipseAsPath(ellipse);
}
#endif

FloatRect GraphicsContext::computeLineBoundsAndAntialiasingModeForText(const FloatPoint& point, float width, bool printing, Color& color)
{
    FloatPoint origin;
    float thickness = std::max(strokeThickness(), 0.5f);

    if (printing)
        origin = point;
    else {
        AffineTransform transform = getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);

        // This code always draws a line that is at least one-pixel line high,
        // which tends to visually overwhelm text at small scales. To counter this
        // effect, an alpha is applied to the underline color when text is at small scales.

        // Just compute scale in x dimension, assuming x and y scales are equal.
        float scale = transform.b() ? sqrtf(transform.a() * transform.a() + transform.b() * transform.b()) : transform.a();
        if (scale < 1.0) {
            static const float minimumUnderlineAlpha = 0.4f;
            float shade = scale > minimumUnderlineAlpha ? scale : minimumUnderlineAlpha;
            int alpha = color.alpha() * shade;
            color = Color(color.red(), color.green(), color.blue(), alpha);
        }

        // Don't offset line from bottom of text if scale is less than offsetUnderLineScale.
        static const float offsetUnderlineScale = 0.4f;
        float dy = scale < offsetUnderlineScale ? 0 : 1;

        // If we've increased the thickness of the line, make sure to move the location too.
        if (thickness > 1)
            dy += roundf(thickness) - 1;

        FloatPoint devicePoint = transform.mapPoint(point);
        FloatPoint deviceOrigin = FloatPoint(roundf(devicePoint.x()), ceilf(devicePoint.y()) + dy);
        origin = transform.inverse().mapPoint(deviceOrigin);
    }
    return FloatRect(origin.x(), origin.y(), width, thickness);
}

}
