1/*
2 * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "core/platform/graphics/Color.h"
28
29#include "core/platform/HashTools.h"
30#include "wtf/Assertions.h"
31#include "wtf/DecimalNumber.h"
32#include "wtf/HexNumber.h"
33#include "wtf/MathExtras.h"
34#include "wtf/text/StringBuilder.h"
35
36using namespace std;
37
38namespace WebCore {
39
40#if !COMPILER(MSVC)
41const RGBA32 Color::black;
42const RGBA32 Color::white;
43const RGBA32 Color::darkGray;
44const RGBA32 Color::gray;
45const RGBA32 Color::lightGray;
46const RGBA32 Color::transparent;
47const RGBA32 Color::stdShadowColor;
48#endif
49
50static const RGBA32 lightenedBlack = 0xFF545454;
51static const RGBA32 darkenedWhite = 0xFFABABAB;
52
53RGBA32 makeRGB(int r, int g, int b)
54{
55    return 0xFF000000 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
56}
57
58RGBA32 makeRGBA(int r, int g, int b, int a)
59{
60    return max(0, min(a, 255)) << 24 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
61}
62
63static int colorFloatToRGBAByte(float f)
64{
65    // We use lroundf and 255 instead of nextafterf(256, 0) to match CG's rounding
66    return max(0, min(static_cast<int>(lroundf(255.0f * f)), 255));
67}
68
69RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a)
70{
71    return colorFloatToRGBAByte(a) << 24 | colorFloatToRGBAByte(r) << 16 | colorFloatToRGBAByte(g) << 8 | colorFloatToRGBAByte(b);
72}
73
74RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha)
75{
76    RGBA32 rgbOnly = color & 0x00FFFFFF;
77    RGBA32 rgba = rgbOnly | colorFloatToRGBAByte(overrideAlpha) << 24;
78    return rgba;
79}
80
81static double calcHue(double temp1, double temp2, double hueVal)
82{
83    if (hueVal < 0.0)
84        hueVal++;
85    else if (hueVal > 1.0)
86        hueVal--;
87    if (hueVal * 6.0 < 1.0)
88        return temp1 + (temp2 - temp1) * hueVal * 6.0;
89    if (hueVal * 2.0 < 1.0)
90        return temp2;
91    if (hueVal * 3.0 < 2.0)
92        return temp1 + (temp2 - temp1) * (2.0 / 3.0 - hueVal) * 6.0;
93    return temp1;
94}
95
96// Explanation of this algorithm can be found in the CSS3 Color Module
97// specification at http://www.w3.org/TR/css3-color/#hsl-color with further
98// explanation available at http://en.wikipedia.org/wiki/HSL_color_space
99
100// all values are in the range of 0 to 1.0
101RGBA32 makeRGBAFromHSLA(double hue, double saturation, double lightness, double alpha)
102{
103    const double scaleFactor = nextafter(256.0, 0.0);
104
105    if (!saturation) {
106        int greyValue = static_cast<int>(lightness * scaleFactor);
107        return makeRGBA(greyValue, greyValue, greyValue, static_cast<int>(alpha * scaleFactor));
108    }
109
110    double temp2 = lightness < 0.5 ? lightness * (1.0 + saturation) : lightness + saturation - lightness * saturation;
111    double temp1 = 2.0 * lightness - temp2;
112
113    return makeRGBA(static_cast<int>(calcHue(temp1, temp2, hue + 1.0 / 3.0) * scaleFactor),
114                    static_cast<int>(calcHue(temp1, temp2, hue) * scaleFactor),
115                    static_cast<int>(calcHue(temp1, temp2, hue - 1.0 / 3.0) * scaleFactor),
116                    static_cast<int>(alpha * scaleFactor));
117}
118
119RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a)
120{
121    double colors = 1 - k;
122    int r = static_cast<int>(nextafter(256, 0) * (colors * (1 - c)));
123    int g = static_cast<int>(nextafter(256, 0) * (colors * (1 - m)));
124    int b = static_cast<int>(nextafter(256, 0) * (colors * (1 - y)));
125    return makeRGBA(r, g, b, static_cast<float>(nextafter(256, 0) * a));
126}
127
128// originally moved here from the CSS parser
129template <typename CharacterType>
130static inline bool parseHexColorInternal(const CharacterType* name, unsigned length, RGBA32& rgb)
131{
132    if (length != 3 && length != 6)
133        return false;
134    unsigned value = 0;
135    for (unsigned i = 0; i < length; ++i) {
136        if (!isASCIIHexDigit(name[i]))
137            return false;
138        value <<= 4;
139        value |= toASCIIHexValue(name[i]);
140    }
141    if (length == 6) {
142        rgb = 0xFF000000 | value;
143        return true;
144    }
145    // #abc converts to #aabbcc
146    rgb = 0xFF000000
147        | (value & 0xF00) << 12 | (value & 0xF00) << 8
148        | (value & 0xF0) << 8 | (value & 0xF0) << 4
149        | (value & 0xF) << 4 | (value & 0xF);
150    return true;
151}
152
153bool Color::parseHexColor(const LChar* name, unsigned length, RGBA32& rgb)
154{
155    return parseHexColorInternal(name, length, rgb);
156}
157
158bool Color::parseHexColor(const UChar* name, unsigned length, RGBA32& rgb)
159{
160    return parseHexColorInternal(name, length, rgb);
161}
162
163bool Color::parseHexColor(const String& name, RGBA32& rgb)
164{
165    unsigned length = name.length();
166
167    if (!length)
168        return false;
169    if (name.is8Bit())
170        return parseHexColor(name.characters8(), name.length(), rgb);
171    return parseHexColor(name.characters16(), name.length(), rgb);
172}
173
174int differenceSquared(const Color& c1, const Color& c2)
175{
176    int dR = c1.red() - c2.red();
177    int dG = c1.green() - c2.green();
178    int dB = c1.blue() - c2.blue();
179    return dR * dR + dG * dG + dB * dB;
180}
181
182String Color::serialized() const
183{
184    if (!hasAlpha()) {
185        StringBuilder builder;
186        builder.reserveCapacity(7);
187        builder.append('#');
188        appendByteAsHex(red(), builder, Lowercase);
189        appendByteAsHex(green(), builder, Lowercase);
190        appendByteAsHex(blue(), builder, Lowercase);
191        return builder.toString();
192    }
193
194    StringBuilder result;
195    result.reserveCapacity(28);
196    const char commaSpace[] = ", ";
197    const char rgbaParen[] = "rgba(";
198
199    result.append(rgbaParen, 5);
200    result.appendNumber(red());
201    result.append(commaSpace, 2);
202    result.appendNumber(green());
203    result.append(commaSpace, 2);
204    result.appendNumber(blue());
205    result.append(commaSpace, 2);
206
207    if (!alpha())
208        result.append('0');
209    else {
210        NumberToLStringBuffer buffer;
211        unsigned length = DecimalNumber(alpha() / 255.0).toStringDecimal(buffer, WTF::NumberToStringBufferLength);
212        result.append(buffer, length);
213    }
214
215    result.append(')');
216    return result.toString();
217}
218
219String Color::nameForRenderTreeAsText() const
220{
221    if (alpha() < 0xFF)
222        return String::format("#%02X%02X%02X%02X", red(), green(), blue(), alpha());
223    return String::format("#%02X%02X%02X", red(), green(), blue());
224}
225
226Color Color::light() const
227{
228    // Hardcode this common case for speed.
229    if (m_color == black)
230        return lightenedBlack;
231
232    const float scaleFactor = nextafterf(256.0f, 0.0f);
233
234    float r, g, b, a;
235    getRGBA(r, g, b, a);
236
237    float v = max(r, max(g, b));
238
239    if (v == 0.0f)
240        // Lightened black with alpha.
241        return Color(0x54, 0x54, 0x54, alpha());
242
243    float multiplier = min(1.0f, v + 0.33f) / v;
244
245    return Color(static_cast<int>(multiplier * r * scaleFactor),
246                 static_cast<int>(multiplier * g * scaleFactor),
247                 static_cast<int>(multiplier * b * scaleFactor),
248                 alpha());
249}
250
251Color Color::dark() const
252{
253    // Hardcode this common case for speed.
254    if (m_color == white)
255        return darkenedWhite;
256
257    const float scaleFactor = nextafterf(256.0f, 0.0f);
258
259    float r, g, b, a;
260    getRGBA(r, g, b, a);
261
262    float v = max(r, max(g, b));
263    float multiplier = max(0.0f, (v - 0.33f) / v);
264
265    return Color(static_cast<int>(multiplier * r * scaleFactor),
266                 static_cast<int>(multiplier * g * scaleFactor),
267                 static_cast<int>(multiplier * b * scaleFactor),
268                 alpha());
269}
270
271static int blendComponent(int c, int a)
272{
273    // We use white.
274    float alpha = a / 255.0f;
275    int whiteBlend = 255 - a;
276    c -= whiteBlend;
277    return static_cast<int>(c / alpha);
278}
279
280const int cStartAlpha = 153; // 60%
281const int cEndAlpha = 204; // 80%;
282const int cAlphaIncrement = 17; // Increments in between.
283
284Color Color::blend(const Color& source) const
285{
286    if (!alpha() || !source.hasAlpha())
287        return source;
288
289    if (!source.alpha())
290        return *this;
291
292    int d = 255 * (alpha() + source.alpha()) - alpha() * source.alpha();
293    int a = d / 255;
294    int r = (red() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.red()) / d;
295    int g = (green() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.green()) / d;
296    int b = (blue() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.blue()) / d;
297    return Color(r, g, b, a);
298}
299
300Color Color::blendWithWhite() const
301{
302    // If the color contains alpha already, we leave it alone.
303    if (hasAlpha())
304        return *this;
305
306    Color newColor;
307    for (int alpha = cStartAlpha; alpha <= cEndAlpha; alpha += cAlphaIncrement) {
308        // We have a solid color.  Convert to an equivalent color that looks the same when blended with white
309        // at the current alpha.  Try using less transparency if the numbers end up being negative.
310        int r = blendComponent(red(), alpha);
311        int g = blendComponent(green(), alpha);
312        int b = blendComponent(blue(), alpha);
313
314        newColor = Color(r, g, b, alpha);
315
316        if (r >= 0 && g >= 0 && b >= 0)
317            break;
318    }
319    return newColor;
320}
321
322void Color::getRGBA(float& r, float& g, float& b, float& a) const
323{
324    r = red() / 255.0f;
325    g = green() / 255.0f;
326    b = blue() / 255.0f;
327    a = alpha() / 255.0f;
328}
329
330void Color::getRGBA(double& r, double& g, double& b, double& a) const
331{
332    r = red() / 255.0;
333    g = green() / 255.0;
334    b = blue() / 255.0;
335    a = alpha() / 255.0;
336}
337
338void Color::getHSL(double& hue, double& saturation, double& lightness) const
339{
340    // http://en.wikipedia.org/wiki/HSL_color_space. This is a direct copy of
341    // the algorithm therein, although it's 360^o based and we end up wanting
342    // [0...1) based. It's clearer if we stick to 360^o until the end.
343    double r = static_cast<double>(red()) / 255.0;
344    double g = static_cast<double>(green()) / 255.0;
345    double b = static_cast<double>(blue()) / 255.0;
346    double max = std::max(std::max(r, g), b);
347    double min = std::min(std::min(r, g), b);
348
349    if (max == min)
350        hue = 0.0;
351    else if (max == r)
352        hue = (60.0 * ((g - b) / (max - min))) + 360.0;
353    else if (max == g)
354        hue = (60.0 * ((b - r) / (max - min))) + 120.0;
355    else
356        hue = (60.0 * ((r - g) / (max - min))) + 240.0;
357
358    if (hue >= 360.0)
359        hue -= 360.0;
360
361    // makeRGBAFromHSLA assumes that hue is in [0...1).
362    hue /= 360.0;
363
364    lightness = 0.5 * (max + min);
365    if (max == min)
366        saturation = 0.0;
367    else if (lightness <= 0.5)
368        saturation = ((max - min) / (max + min));
369    else
370        saturation = ((max - min) / (2.0 - (max + min)));
371}
372
373Color colorFromPremultipliedARGB(RGBA32 pixelColor)
374{
375    int alpha = alphaChannel(pixelColor);
376    if (alpha && alpha < 255) {
377        return Color::createUnchecked(
378            redChannel(pixelColor) * 255 / alpha,
379            greenChannel(pixelColor) * 255 / alpha,
380            blueChannel(pixelColor) * 255 / alpha,
381            alpha);
382    } else
383        return Color(pixelColor);
384}
385
386RGBA32 premultipliedARGBFromColor(const Color& color)
387{
388    unsigned pixelColor;
389
390    unsigned alpha = color.alpha();
391    if (alpha < 255) {
392        pixelColor = Color::createUnchecked(
393            (color.red() * alpha  + 254) / 255,
394            (color.green() * alpha  + 254) / 255,
395            (color.blue() * alpha  + 254) / 255,
396            alpha).rgb();
397    } else
398         pixelColor = color.rgb();
399
400    return pixelColor;
401}
402
403} // namespace WebCore
404