Home | History | Annotate | Download | only in graphics
      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 "platform/graphics/Color.h"
     28 
     29 #include "wtf/Assertions.h"
     30 #include "wtf/DecimalNumber.h"
     31 #include "wtf/HexNumber.h"
     32 #include "wtf/MathExtras.h"
     33 #include "wtf/text/StringBuilder.h"
     34 
     35 using namespace std;
     36 
     37 namespace WebCore {
     38 
     39 #if !COMPILER(MSVC)
     40 const RGBA32 Color::black;
     41 const RGBA32 Color::white;
     42 const RGBA32 Color::darkGray;
     43 const RGBA32 Color::gray;
     44 const RGBA32 Color::lightGray;
     45 const RGBA32 Color::transparent;
     46 #endif
     47 
     48 static const RGBA32 lightenedBlack = 0xFF545454;
     49 static const RGBA32 darkenedWhite = 0xFFABABAB;
     50 
     51 RGBA32 makeRGB(int r, int g, int b)
     52 {
     53     return 0xFF000000 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
     54 }
     55 
     56 RGBA32 makeRGBA(int r, int g, int b, int a)
     57 {
     58     return max(0, min(a, 255)) << 24 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
     59 }
     60 
     61 static int colorFloatToRGBAByte(float f)
     62 {
     63     // We use lroundf and 255 instead of nextafterf(256, 0) to match CG's rounding
     64     return max(0, min(static_cast<int>(lroundf(255.0f * f)), 255));
     65 }
     66 
     67 RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a)
     68 {
     69     return colorFloatToRGBAByte(a) << 24 | colorFloatToRGBAByte(r) << 16 | colorFloatToRGBAByte(g) << 8 | colorFloatToRGBAByte(b);
     70 }
     71 
     72 RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha)
     73 {
     74     RGBA32 rgbOnly = color & 0x00FFFFFF;
     75     RGBA32 rgba = rgbOnly | colorFloatToRGBAByte(overrideAlpha) << 24;
     76     return rgba;
     77 }
     78 
     79 static double calcHue(double temp1, double temp2, double hueVal)
     80 {
     81     if (hueVal < 0.0)
     82         hueVal++;
     83     else if (hueVal > 1.0)
     84         hueVal--;
     85     if (hueVal * 6.0 < 1.0)
     86         return temp1 + (temp2 - temp1) * hueVal * 6.0;
     87     if (hueVal * 2.0 < 1.0)
     88         return temp2;
     89     if (hueVal * 3.0 < 2.0)
     90         return temp1 + (temp2 - temp1) * (2.0 / 3.0 - hueVal) * 6.0;
     91     return temp1;
     92 }
     93 
     94 // Explanation of this algorithm can be found in the CSS3 Color Module
     95 // specification at http://www.w3.org/TR/css3-color/#hsl-color with further
     96 // explanation available at http://en.wikipedia.org/wiki/HSL_color_space
     97 
     98 // all values are in the range of 0 to 1.0
     99 RGBA32 makeRGBAFromHSLA(double hue, double saturation, double lightness, double alpha)
    100 {
    101     const double scaleFactor = nextafter(256.0, 0.0);
    102 
    103     if (!saturation) {
    104         int greyValue = static_cast<int>(lightness * scaleFactor);
    105         return makeRGBA(greyValue, greyValue, greyValue, static_cast<int>(alpha * scaleFactor));
    106     }
    107 
    108     double temp2 = lightness < 0.5 ? lightness * (1.0 + saturation) : lightness + saturation - lightness * saturation;
    109     double temp1 = 2.0 * lightness - temp2;
    110 
    111     return makeRGBA(static_cast<int>(calcHue(temp1, temp2, hue + 1.0 / 3.0) * scaleFactor),
    112                     static_cast<int>(calcHue(temp1, temp2, hue) * scaleFactor),
    113                     static_cast<int>(calcHue(temp1, temp2, hue - 1.0 / 3.0) * scaleFactor),
    114                     static_cast<int>(alpha * scaleFactor));
    115 }
    116 
    117 RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a)
    118 {
    119     double colors = 1 - k;
    120     int r = static_cast<int>(nextafter(256, 0) * (colors * (1 - c)));
    121     int g = static_cast<int>(nextafter(256, 0) * (colors * (1 - m)));
    122     int b = static_cast<int>(nextafter(256, 0) * (colors * (1 - y)));
    123     return makeRGBA(r, g, b, static_cast<float>(nextafter(256, 0) * a));
    124 }
    125 
    126 // originally moved here from the CSS parser
    127 template <typename CharacterType>
    128 static inline bool parseHexColorInternal(const CharacterType* name, unsigned length, RGBA32& rgb)
    129 {
    130     if (length != 3 && length != 6)
    131         return false;
    132     unsigned value = 0;
    133     for (unsigned i = 0; i < length; ++i) {
    134         if (!isASCIIHexDigit(name[i]))
    135             return false;
    136         value <<= 4;
    137         value |= toASCIIHexValue(name[i]);
    138     }
    139     if (length == 6) {
    140         rgb = 0xFF000000 | value;
    141         return true;
    142     }
    143     // #abc converts to #aabbcc
    144     rgb = 0xFF000000
    145         | (value & 0xF00) << 12 | (value & 0xF00) << 8
    146         | (value & 0xF0) << 8 | (value & 0xF0) << 4
    147         | (value & 0xF) << 4 | (value & 0xF);
    148     return true;
    149 }
    150 
    151 bool Color::parseHexColor(const LChar* name, unsigned length, RGBA32& rgb)
    152 {
    153     return parseHexColorInternal(name, length, rgb);
    154 }
    155 
    156 bool Color::parseHexColor(const UChar* name, unsigned length, RGBA32& rgb)
    157 {
    158     return parseHexColorInternal(name, length, rgb);
    159 }
    160 
    161 bool Color::parseHexColor(const String& name, RGBA32& rgb)
    162 {
    163     unsigned length = name.length();
    164 
    165     if (!length)
    166         return false;
    167     if (name.is8Bit())
    168         return parseHexColor(name.characters8(), name.length(), rgb);
    169     return parseHexColor(name.characters16(), name.length(), rgb);
    170 }
    171 
    172 int differenceSquared(const Color& c1, const Color& c2)
    173 {
    174     int dR = c1.red() - c2.red();
    175     int dG = c1.green() - c2.green();
    176     int dB = c1.blue() - c2.blue();
    177     return dR * dR + dG * dG + dB * dB;
    178 }
    179 
    180 Color::Color(const String& name)
    181 {
    182     if (name[0] == '#') {
    183         if (name.is8Bit())
    184             m_valid = parseHexColor(name.characters8() + 1, name.length() - 1, m_color);
    185         else
    186             m_valid = parseHexColor(name.characters16() + 1, name.length() - 1, m_color);
    187     } else {
    188         setNamedColor(name);
    189     }
    190 }
    191 
    192 Color::Color(const char* name)
    193 {
    194     if (name[0] == '#') {
    195         m_valid = parseHexColor(&name[1], m_color);
    196     } else {
    197         const NamedColor* foundColor = findColor(name, strlen(name));
    198         m_color = foundColor ? foundColor->ARGBValue : 0;
    199         m_valid = foundColor;
    200     }
    201 }
    202 
    203 String Color::serialized() const
    204 {
    205     if (!hasAlpha()) {
    206         StringBuilder builder;
    207         builder.reserveCapacity(7);
    208         builder.append('#');
    209         appendByteAsHex(red(), builder, Lowercase);
    210         appendByteAsHex(green(), builder, Lowercase);
    211         appendByteAsHex(blue(), builder, Lowercase);
    212         return builder.toString();
    213     }
    214 
    215     StringBuilder result;
    216     result.reserveCapacity(28);
    217     const char commaSpace[] = ", ";
    218     const char rgbaParen[] = "rgba(";
    219 
    220     result.append(rgbaParen, 5);
    221     result.appendNumber(red());
    222     result.append(commaSpace, 2);
    223     result.appendNumber(green());
    224     result.append(commaSpace, 2);
    225     result.appendNumber(blue());
    226     result.append(commaSpace, 2);
    227 
    228     if (!alpha())
    229         result.append('0');
    230     else {
    231         NumberToLStringBuffer buffer;
    232         unsigned length = DecimalNumber(alpha() / 255.0).toStringDecimal(buffer, WTF::NumberToStringBufferLength);
    233         result.append(buffer, length);
    234     }
    235 
    236     result.append(')');
    237     return result.toString();
    238 }
    239 
    240 String Color::nameForRenderTreeAsText() const
    241 {
    242     if (alpha() < 0xFF)
    243         return String::format("#%02X%02X%02X%02X", red(), green(), blue(), alpha());
    244     return String::format("#%02X%02X%02X", red(), green(), blue());
    245 }
    246 
    247 static inline const NamedColor* findNamedColor(const String& name)
    248 {
    249     char buffer[64]; // easily big enough for the longest color name
    250     unsigned length = name.length();
    251     if (length > sizeof(buffer) - 1)
    252         return 0;
    253     for (unsigned i = 0; i < length; ++i) {
    254         UChar c = name[i];
    255         if (!c || c > 0x7F)
    256             return 0;
    257         buffer[i] = toASCIILower(static_cast<char>(c));
    258     }
    259     buffer[length] = '\0';
    260     return findColor(buffer, length);
    261 }
    262 
    263 void Color::setNamedColor(const String& name)
    264 {
    265     const NamedColor* foundColor = findNamedColor(name);
    266     m_color = foundColor ? foundColor->ARGBValue : 0;
    267     m_valid = foundColor;
    268 }
    269 
    270 Color Color::light() const
    271 {
    272     // Hardcode this common case for speed.
    273     if (m_color == black)
    274         return lightenedBlack;
    275 
    276     const float scaleFactor = nextafterf(256.0f, 0.0f);
    277 
    278     float r, g, b, a;
    279     getRGBA(r, g, b, a);
    280 
    281     float v = max(r, max(g, b));
    282 
    283     if (v == 0.0f)
    284         // Lightened black with alpha.
    285         return Color(0x54, 0x54, 0x54, alpha());
    286 
    287     float multiplier = min(1.0f, v + 0.33f) / v;
    288 
    289     return Color(static_cast<int>(multiplier * r * scaleFactor),
    290                  static_cast<int>(multiplier * g * scaleFactor),
    291                  static_cast<int>(multiplier * b * scaleFactor),
    292                  alpha());
    293 }
    294 
    295 Color Color::dark() const
    296 {
    297     // Hardcode this common case for speed.
    298     if (m_color == white)
    299         return darkenedWhite;
    300 
    301     const float scaleFactor = nextafterf(256.0f, 0.0f);
    302 
    303     float r, g, b, a;
    304     getRGBA(r, g, b, a);
    305 
    306     float v = max(r, max(g, b));
    307     float multiplier = max(0.0f, (v - 0.33f) / v);
    308 
    309     return Color(static_cast<int>(multiplier * r * scaleFactor),
    310                  static_cast<int>(multiplier * g * scaleFactor),
    311                  static_cast<int>(multiplier * b * scaleFactor),
    312                  alpha());
    313 }
    314 
    315 static int blendComponent(int c, int a)
    316 {
    317     // We use white.
    318     float alpha = a / 255.0f;
    319     int whiteBlend = 255 - a;
    320     c -= whiteBlend;
    321     return static_cast<int>(c / alpha);
    322 }
    323 
    324 const int cStartAlpha = 153; // 60%
    325 const int cEndAlpha = 204; // 80%;
    326 const int cAlphaIncrement = 17; // Increments in between.
    327 
    328 Color Color::blend(const Color& source) const
    329 {
    330     if (!alpha() || !source.hasAlpha())
    331         return source;
    332 
    333     if (!source.alpha())
    334         return *this;
    335 
    336     int d = 255 * (alpha() + source.alpha()) - alpha() * source.alpha();
    337     int a = d / 255;
    338     int r = (red() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.red()) / d;
    339     int g = (green() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.green()) / d;
    340     int b = (blue() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.blue()) / d;
    341     return Color(r, g, b, a);
    342 }
    343 
    344 Color Color::blendWithWhite() const
    345 {
    346     // If the color contains alpha already, we leave it alone.
    347     if (hasAlpha())
    348         return *this;
    349 
    350     Color newColor;
    351     for (int alpha = cStartAlpha; alpha <= cEndAlpha; alpha += cAlphaIncrement) {
    352         // We have a solid color.  Convert to an equivalent color that looks the same when blended with white
    353         // at the current alpha.  Try using less transparency if the numbers end up being negative.
    354         int r = blendComponent(red(), alpha);
    355         int g = blendComponent(green(), alpha);
    356         int b = blendComponent(blue(), alpha);
    357 
    358         newColor = Color(r, g, b, alpha);
    359 
    360         if (r >= 0 && g >= 0 && b >= 0)
    361             break;
    362     }
    363     return newColor;
    364 }
    365 
    366 void Color::getRGBA(float& r, float& g, float& b, float& a) const
    367 {
    368     r = red() / 255.0f;
    369     g = green() / 255.0f;
    370     b = blue() / 255.0f;
    371     a = alpha() / 255.0f;
    372 }
    373 
    374 void Color::getRGBA(double& r, double& g, double& b, double& a) const
    375 {
    376     r = red() / 255.0;
    377     g = green() / 255.0;
    378     b = blue() / 255.0;
    379     a = alpha() / 255.0;
    380 }
    381 
    382 void Color::getHSL(double& hue, double& saturation, double& lightness) const
    383 {
    384     // http://en.wikipedia.org/wiki/HSL_color_space. This is a direct copy of
    385     // the algorithm therein, although it's 360^o based and we end up wanting
    386     // [0...1) based. It's clearer if we stick to 360^o until the end.
    387     double r = static_cast<double>(red()) / 255.0;
    388     double g = static_cast<double>(green()) / 255.0;
    389     double b = static_cast<double>(blue()) / 255.0;
    390     double max = std::max(std::max(r, g), b);
    391     double min = std::min(std::min(r, g), b);
    392 
    393     if (max == min)
    394         hue = 0.0;
    395     else if (max == r)
    396         hue = (60.0 * ((g - b) / (max - min))) + 360.0;
    397     else if (max == g)
    398         hue = (60.0 * ((b - r) / (max - min))) + 120.0;
    399     else
    400         hue = (60.0 * ((r - g) / (max - min))) + 240.0;
    401 
    402     if (hue >= 360.0)
    403         hue -= 360.0;
    404 
    405     // makeRGBAFromHSLA assumes that hue is in [0...1).
    406     hue /= 360.0;
    407 
    408     lightness = 0.5 * (max + min);
    409     if (max == min)
    410         saturation = 0.0;
    411     else if (lightness <= 0.5)
    412         saturation = ((max - min) / (max + min));
    413     else
    414         saturation = ((max - min) / (2.0 - (max + min)));
    415 }
    416 
    417 Color colorFromPremultipliedARGB(RGBA32 pixelColor)
    418 {
    419     int alpha = alphaChannel(pixelColor);
    420     if (alpha && alpha < 255) {
    421         return Color::createUnchecked(
    422             redChannel(pixelColor) * 255 / alpha,
    423             greenChannel(pixelColor) * 255 / alpha,
    424             blueChannel(pixelColor) * 255 / alpha,
    425             alpha);
    426     } else
    427         return Color(pixelColor);
    428 }
    429 
    430 RGBA32 premultipliedARGBFromColor(const Color& color)
    431 {
    432     unsigned pixelColor;
    433 
    434     unsigned alpha = color.alpha();
    435     if (alpha < 255) {
    436         pixelColor = Color::createUnchecked(
    437             (color.red() * alpha  + 254) / 255,
    438             (color.green() * alpha  + 254) / 255,
    439             (color.blue() * alpha  + 254) / 255,
    440             alpha).rgb();
    441     } else
    442          pixelColor = color.rgb();
    443 
    444     return pixelColor;
    445 }
    446 
    447 } // namespace WebCore
    448