/*
 * Copyright (C) 2003, 2004, 2005, 2006, 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. 
 */

#pragma once

#include <algorithm>
#include <cmath>
#include "AnimationUtilities.h"
#include "ColorSpace.h"
#include <wtf/FastAllocBase.h>
#include <wtf/Forward.h>
#include <wtf/MathExtras.h>
#include <wtf/Optional.h>
#include <wtf/RefPtr.h>
#include <wtf/unicode/Unicode.h>

#if USE(CG)
#include "ColorSpace.h"
typedef struct CGColor* CGColorRef;
#endif

#if PLATFORM(QT)
#include <qglobal.h>
QT_BEGIN_NAMESPACE
class QColor;
QT_END_NAMESPACE
#endif

#if PLATFORM(GTK)
typedef struct _GdkColor GdkColor;
#ifndef GTK_API_VERSION_2
typedef struct _GdkRGBA GdkRGBA;
#endif
#endif

#if PLATFORM(WX)
class wxColour;
#endif

namespace WebCore {

typedef unsigned RGBA32; // Deprecated: Type for an RGBA quadruplet. Use RGBA class instead.

class Color;

RGBA32 makeRGB(int r, int g, int b);
RGBA32 makeRGBA(int r, int g, int b, int a);

RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha);
RGBA32 colorWithOverrideAlpha(RGBA32 color, Optional<float> overrideAlpha);

RGBA32 colorWithOverrideAlpha(Color color, float overrideAlpha);
RGBA32 colorWithOverrideAlpha(Color color, Optional<float> overrideAlpha);

RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a);
RGBA32 makeRGBAFromHSLA(float h, float s, float l, float a);
RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a);

ALWAYS_INLINE int redChannel(RGBA32 color) { return (color >> 16) & 0xFF; }
ALWAYS_INLINE int greenChannel(RGBA32 color) { return (color >> 8) & 0xFF; }
ALWAYS_INLINE int blueChannel(RGBA32 color) { return color & 0xFF; }
ALWAYS_INLINE int alphaChannel(RGBA32 color) { return (color >> 24) & 0xFF; }

uint8_t roundAndClampColorChannel(int);
uint8_t roundAndClampColorChannel(float);

class RGBA {
public:
	RGBA(uint32_t value = 0) : m_integer(value) { }
    RGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha);
    RGBA(uint8_t red, uint8_t green, uint8_t blue); // opaque, alpha of 1

    uint32_t value() const { return m_integer; }

    uint8_t red() const;
    uint8_t green() const;
    uint8_t blue() const;
    uint8_t alpha() const;

    bool hasAlpha() const;

    bool isOpaque() const { return alpha() == 0xFF; }
    bool isVisible() const { return alpha(); }

private:
    friend class Color;

    unsigned m_integer { 0 };
};

typedef RGBA SimpleColor;

bool operator==(const RGBA&, const RGBA&);
bool operator!=(const RGBA&, const RGBA&);

SimpleColor makeSimpleColor(int r, int g, int b);
SimpleColor makeSimpleColor(int r, int g, int b, int a);

class Color {
    WTF_MAKE_FAST_ALLOCATED;
public:
    ALWAYS_INLINE Color()
    : rgbaAndFlags(invalidRGBAColor)
    {
    }

    // FIXME: Remove all these constructors and creation functions and replace the ones that are still needed with free functions.

    Color(RGBA color, bool valid = true)
    : rgbaAndFlags(invalidRGBAColor)
    {
        if (valid)
            setRGB(color.value());
    }

    Color(RGBA32 color, bool valid = true)
    : rgbaAndFlags(invalidRGBAColor)
    {
        if (valid)
            setRGB(color);
    }

    enum SemanticTag { Semantic };

    Color(RGBA32 color, SemanticTag)
    {
        setRGB(color);
        setIsSemantic();
    }

    Color(int r, int g, int b)
    : rgbaAndFlags(invalidRGBAColor)
    {
        setRGB(r, g, b);
    }

    Color(int r, int g, int b, int a)
    : rgbaAndFlags(invalidRGBAColor)
    {
        setRGB(makeRGBA(r, g, b, a));
    }

    Color(float r, float g, float b, float a)
    : rgbaAndFlags(invalidRGBAColor)
    {
        setRGB(makeRGBA32FromFloats(r, g, b, a));
    }

    Color(float r, float g, float b, float a, ColorSpace)
    : rgbaAndFlags(invalidRGBAColor)
    {
        setRGB(makeRGBA32FromFloats(r, g, b, a));
    }

    // Creates a new color from the specific CMYK and alpha values.
    Color(float c, float m, float y, float k, float a)
    : rgbaAndFlags(invalidRGBAColor)
    {
        setRGB(makeRGBAFromCMYKA(c, m, y, k, a));
    }

    explicit Color(WTF::HashTableDeletedValueType)
    {
        rgbaAndFlags = 0xfffffffffffffffd;
        ASSERT(!isExtended());
    }

    bool isHashTableDeletedValue() const
    {
        return rgbaAndFlags == 0xfffffffffffffffd;
    }

    explicit Color(WTF::HashTableEmptyValueType)
    {
        rgbaAndFlags = 0xffffffffffffffb;
        ASSERT(!isExtended());
    }

    Color(RGBA, ColorSpace);

    static ALWAYS_INLINE Color createUnCheked(int r, int g, int b)
    {
        RGBA32 color = 0xFF000000 | r << 16 | g << 8 | b;
        return Color(color);
    }

    static ALWAYS_INLINE Color createUnCheked(int r, int g, int b, int a)
    {
        RGBA32 color = a << 24 | r << 16 | g << 8 | b;
        return Color(color);
    }

    // Returns the color serialized according to HTML5
    // <https://html.spec.whatwg.org/multipage/scripting.html#fill-and-stroke-styles> (10 September 2015)
	String serialized() const;

    String cssText() const;

    // Returns the color serialized as either #RRGGBB or #RRGGBBAA
    // The latter format is not a valid CSS color, and should only be seen in DRT dumps.
    String nameForRenderTreeAsText() const;

    bool isValid() const { return isExtended() || (rgbaAndFlags & validRGBAColorBit); }

    // True if the color originated from a CSS semantic color name.
    bool isSemantic() const { return !isExtended() && (rgbaAndFlags & isSemanticRBGAColorBit); }

    bool isOpaque() const { return isValid() && alpha() == 255; }
    bool isVisible() const { return isValid() && alpha() > 0; }

    ALWAYS_INLINE bool hasAlpha() const { return alpha() < 255; }

    int red() const { return redChannel(rgb()); }
    int green() const { return greenChannel(rgb()); }
    int blue() const { return blueChannel(rgb()); }
    int alpha() const { return alphaChannel(rgb()); }

    WEBCORE_EXPORT double luminance() const;

    RGBA32 rgba() const;
    RGBA32 rgb() const { return rgba(); }
    void setRGB(int r, int g, int b) { setRGB(makeRGB(r, g, b)); }
    void setRGB(RGBA32);
    uint64_t asUint64() const { return rgbaAndFlags; }

    // FIXME: ExtendedColor - these should be renamed (to be clear about their parameter types, or
    // replaced with alternative accessors.
    void getRGBA(float& r, float& g, float& b, float& a) const;
    void getRGBA(double& r, double& g, double& b, double& a) const;
    void getHSL(double& h, double& s, double& l) const;

    Color light() const;
    Color dark() const;

    // This is an implementation of Porter-Duff's "source-over" equation
    Color blend(const Color&) const;
    Color blendWithWhite() const;

#if PLATFORM(QT)
    Color(const QColor&);
    operator QColor() const;
#endif

#if PLATFORM(GTK)
    Color(const GdkColor&);
    // We can't sensibly go back to GdkColor without losing the alpha value
#ifndef GTK_API_VERSION_2
    Color(const GdkRGBA&);
    operator GdkRGBA() const;
#endif
#endif

#if PLATFORM(WX)
    Color(const wxColour&);
    operator wxColour() const;
#endif

#if USE(CG)
    Color(CGColorRef);
#endif

    static bool parseHexColor(const String&, RGBA32&);
    static bool parseHexColor(const StringView&, RGBA32&);
    static bool parseHexColor(const LChar*, unsigned, RGBA32&);
    static bool parseHexColor(const UChar*, unsigned, RGBA32&);

    static const RGBA32 black = 0xFF000000;
    static const RGBA32 white = 0xFFFFFFFF;
    static const RGBA32 darkGray = 0xFF808080;
    static const RGBA32 gray = 0xFFA0A0A0;
    static const RGBA32 lightGray = 0xFFC0C0C0;
    static const RGBA32 transparent = 0x00000000;

    bool isExtended() const;

    friend bool operator==(const Color& a, const Color& b);

private:
    void setIsSemantic() { rgbaAndFlags |= isSemanticRBGAColorBit; }

    // 0x_______00 is an ExtendedColor pointer.
    // 0x_______01 is an invalid RGBA32.
    // 0x_______11 is a valid RGBA32.
    static const uint64_t extendedColor = 0x0;
    static const uint64_t invalidRGBAColor = 0x1;
    static const uint64_t validRGBAColorBit = 0x2;
    static const uint64_t validRGBAColor = 0x3;
    static const uint64_t isSemanticRBGAColorBit = 0x4;

    void tagAsValid();
    void tagAsExtended();

    uint64_t rgbaAndFlags;
};

class OptionalColor : public Color {
public:
    OptionalColor();
    OptionalColor(const Color&);

    explicit operator bool() const;

private:
    // FIXME: Change to use Optional<Color>?
    // FIXME: Convert all callers to use Optional<Color>?
    bool m_isEngaged;
    Color m_color;
};

bool operator==(const Color&, const Color&);
bool operator!=(const Color&, const Color&);

Color colorFromPremultipliedARGB(RGBA32);
RGBA32 premultipliedARGBFromColor(const Color&);

int differenceSquared(const Color&, const Color&);

uint16_t fastDivideBy255(uint16_t);

#if USE(CG)
WEBCORE_EXPORT CGColorRef cachedCGColor(const Color&, ColorSpace);
#endif

inline RGBA::RGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha)
    : m_integer(alpha << 24 | red << 16 | green << 8 | blue)
{
}

inline RGBA::RGBA(uint8_t red, uint8_t green, uint8_t blue)
    : m_integer(0xFF000000 | red << 16 | green << 8 | blue)
{
}

inline uint8_t RGBA::red() const
{
    return m_integer >> 16;
}

inline uint8_t RGBA::green() const
{
    return m_integer >> 8;
}

inline uint8_t RGBA::blue() const
{
    return m_integer;
}

inline uint8_t RGBA::alpha() const
{
    return m_integer >> 24;
}

inline bool RGBA::hasAlpha() const
{
    return (m_integer & 0xFF000000) != 0xFF000000;
}

inline Color::Color(RGBA color, ColorSpace space)
{
    setRGB(color.m_integer);
    ASSERT_UNUSED(space, space == ColorSpaceSRGB);
}

ALWAYS_INLINE bool operator==(const Color& a, const Color& b)
{
    return a.rgbaAndFlags == b.rgbaAndFlags;
}

ALWAYS_INLINE bool operator!=(const Color& a, const Color& b)
{
    return !(a == b);
}

inline uint8_t roundAndClampColorChannel(int value)
{
    return std::max(0, std::min(255, value));
}

inline uint8_t roundAndClampColorChannel(float value)
{
    return std::max(0.f, std::min(255.f, roundf(value)));
}

ALWAYS_INLINE uint16_t fastDivideBy255(uint16_t value)
{
	// While this is an approximate algorithm for division by 255, it gives perfectly accurate results for 16-bit values.
	// FIXME: Since this gives accurate results for 16-bit values, we should get this optimization into compilers like clang.
	uint16_t approximation = value >> 8;
    uint16_t remainder = value - (approximation * 255) + 1;
    return approximation + (remainder >> 8);
}

ALWAYS_INLINE Color colorFromPremultipliedARGB(RGBA32 pixelColor)
{
    int alpha = alphaChannel(pixelColor);
    if (alpha && alpha < 255) {
        return Color::createUnCheked(
            redChannel(pixelColor) * 255 / alpha,
            greenChannel(pixelColor) * 255 / alpha,
            blueChannel(pixelColor) * 255 / alpha,
            alpha);
    } else
        return Color(pixelColor);
}

ALWAYS_INLINE RGBA32 premultipliedARGBFromColor(const Color& color)
{
    unsigned pixelColor;

    unsigned alpha = color.alpha();
    if (alpha < 255) {
        pixelColor = Color::createUnCheked(
            fastDivideBy255(color.red() * alpha + 254),
            fastDivideBy255(color.green() * alpha + 254),
            fastDivideBy255(color.blue() * alpha + 254),
            alpha).rgb();
    } else
         pixelColor = color.rgb();

    return pixelColor;
}

inline Color blend(const Color& from, const Color& to, const BlendingContext& context, bool blendPremultiplied = true)
{
    // We need to preserve the state of the valid flag at the end of the animation
    if (context.progress == 1 && !to.isValid())
        return Color();
    
    if (blendPremultiplied) {
        // Contrary to the name, RGBA32 actually stores ARGB, so we can initialize Color directly from premultipliedARGBFromColor().
        // Also, premultipliedARGBFromColor() bails on zero alpha, so special-case that.
        Color premultFrom = from.alpha() ? premultipliedARGBFromColor(from) : 0;
        Color premultTo = to.alpha() ? premultipliedARGBFromColor(to) : 0;

        Color premultBlended(blend(premultFrom.red(), premultTo.red(), context),
                     blend(premultFrom.green(), premultTo.green(), context),
                     blend(premultFrom.blue(), premultTo.blue(), context),
                     blend(premultFrom.alpha(), premultTo.alpha(), context));

        return Color(colorFromPremultipliedARGB(premultBlended.rgb()));
    }

    return Color(blend(from.red(), to.red(), context),
                 blend(from.green(), to.green(), context),
                 blend(from.blue(), to.blue(), context),
                 blend(from.alpha(), to.alpha(), context));
}

inline Color blendWithoutPremultiply(const Color& from, const Color& to, const BlendingContext& context)
{
    // We need to preserve the state of the valid flag at the end of the animation
    if (context.progress == 1 && !to.isValid())
        return Color();

    return Color(blend(from.red(), to.red(), context),
                 blend(from.green(), to.green(), context),
                 blend(from.blue(), to.blue(), context),
                 blend(from.alpha(), to.alpha(), context));
}

#if USE(CG)
CGColorRef cachedCGColor(const Color&);
#endif

inline RGBA32 colorWithOverrideAlpha(RGBA32 color, Optional<float> overrideAlpha)
{
    return overrideAlpha ? colorWithOverrideAlpha(color, overrideAlpha.value()) : color;
}

inline RGBA32 colorWithOverrideAlpha(Color color, Optional<float> overrideAlpha)
{
    return overrideAlpha ? colorWithOverrideAlpha(color, overrideAlpha.value()) : color.rgba();
}

inline RGBA32 Color::rgba() const
{
    // FIXME: We should ASSERT(!isExtended()) here, or produce
    // an RGBA32 equivalent for an ExtendedColor. Ideally the former,
    // so we can audit all the rgb() call sites to handle extended.
    return static_cast<RGBA32>(rgbaAndFlags >> 32);
}

inline void Color::setRGB(RGBA32 rgb)
{
    rgbaAndFlags = static_cast<uint64_t>(rgb) << 32;
    tagAsValid();
}

inline void Color::tagAsValid()
{
    rgbaAndFlags |= validRGBAColor;
}

inline void Color::tagAsExtended()
{
    // FIXME: Is this method necessary? Will colors ever change from RGBA32 to Extended?
    // Valid colors should not change type.
    ASSERT(!isValid());
    rgbaAndFlags &= ~(invalidRGBAColor);
}

inline bool Color::isExtended() const
{
    return !(rgbaAndFlags & invalidRGBAColor);
}

inline RGBA32 makeRGB(int r, int g, int b)
{
    return makeRGBA(r, g, b, 0xFF);
}

inline RGBA32 makeRGBA(int r, int g, int b, int a)
{
    return std::max(0, std::min(a, 255)) << 24 | std::max(0, std::min(r, 255)) << 16 | std::max(0, std::min(g, 255)) << 8 | std::max(0, std::min(b, 255));
}

inline SimpleColor makeSimpleColor(int r, int g, int b)
{
    return makeSimpleColor(r, g, b, 0xFF);
}

inline SimpleColor makeSimpleColor(int r, int g, int b, int a)
{
    return SimpleColor(static_cast<unsigned>(clampTo(a, 0, 0xFF) << 24 | clampTo(r, 0, 0xFF) << 16 | clampTo(g, 0, 0xFF) << 8 | clampTo(b, 0, 0xFF)));
}

} // namespace WebCore
