/*
 * 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. 
 */

#ifndef Color_h
#define Color_h

#include "AnimationUtilities.h"
#include <wtf/FastAllocBase.h>
#include <wtf/Forward.h>
#include <wtf/Optional.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 {

class Color;

typedef unsigned RGBA32;        // RGBA quadruplet

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 makeRGBA32FromFloats(float r, float g, float b, float a);
RGBA32 makeRGBAFromHSLA(double h, double s, double l, double a);
RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a);

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

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; }

class Color {
    WTF_MAKE_FAST_ALLOCATED;
public:
    ALWAYS_INLINE Color() : m_color(0), m_valid(false) { }
    ALWAYS_INLINE Color(RGBA32 color, bool valid = true) : m_color(color), m_valid(valid) { ASSERT(!m_color || m_valid); }
    Color(int r, int g, int b) : m_color(makeRGB(r, g, b)), m_valid(true) { }
    Color(int r, int g, int b, int a) : m_color(makeRGBA(r, g, b, a)), m_valid(true) { }
    // Color is currently limited to 32bit RGBA, perhaps some day we'll support better colors
    Color(float r, float g, float b, float a) : m_color(makeRGBA32FromFloats(r, g, b, a)), m_valid(true) { }
    // Creates a new color from the specific CMYK and alpha values.
    Color(float c, float m, float y, float k, float a) : m_color(makeRGBAFromCMYKA(c, m, y, k, a)), m_valid(true) { }
    explicit Color(const String&);
    explicit Color(const char*);

    ALWAYS_INLINE Color(const Color& other) : m_color(other.m_color), m_valid(other.m_valid) { }
    ALWAYS_INLINE Color& operator=(const Color& other) { m_color = other.m_color; m_valid = other.m_valid; return *this; }

    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
    // - http://www.whatwg.org/specs/web-apps/current-work/#serialization-of-a-color
    String serialized() 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;

    void setNamedColor(const String&);

    bool isValid() const { return m_valid; }

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

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

    ALWAYS_INLINE int red() const { return redChannel(m_color); }
    ALWAYS_INLINE int green() const { return greenChannel(m_color); }
    ALWAYS_INLINE int blue() const { return blueChannel(m_color); }
    ALWAYS_INLINE int alpha() const { return alphaChannel(m_color); }
    
    RGBA32 rgb() const { return m_color; } // Preserve the alpha.
    void setRGB(int r, int g, int b) { m_color = makeRGB(r, g, b); m_valid = true; }
    void setRGB(RGBA32 rgb) { m_color = rgb; m_valid = true; }
    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 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;

private:
    RGBA32 m_color;
    bool m_valid;
};

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

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

ALWAYS_INLINE uint16_t fastDivideBy255(uint16_t value)
{
    // This is an approximate algorithm for division by 255, but it gives accurate results for 16bit values.
    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, double progress, bool blendPremultiplied = true)
{
    // We need to preserve the state of the valid flag at the end of the animation
    if (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(), progress),
                     blend(premultFrom.green(), premultTo.green(), progress),
                     blend(premultFrom.blue(), premultTo.blue(), progress),
                     blend(premultFrom.alpha(), premultTo.alpha(), progress));

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

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

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

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

} // namespace WebCore

#endif // Color_h
