dymokomi/luce-svg
Source of release 0.9.2
0.9.2 / src / svg / colors.lucb
#==============================================================================================
#
# svg/colors - CSS colors
#
# DESCRIPTION:
# Reads every CSS color form a browser reads in SVG: `#rgb`, `#rgba`, `#rrggbb`,
# `#rrggbbaa`; the 148 named colors and `transparent`; `rgb()`/`rgba()` and
# `hsl()`/`hsla()` in the legacy comma syntax and CSS Color 4's space syntax with
# `/ alpha`; and CSS Color 4's `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()` and
# `color()` (srgb, srgb-linear, display-p3, a98-rgb, prophoto-rgb, rec2020, xyz,
# xyz-d50, xyz-d65), converted with luce-color and clipped into sRGB. Channels are
# answered as encoded sRGB in 0..1 with a straight alpha.
#
#==============================================================================================
from luce_color import lab, oklab, xyz
# `from luce_color import color as ...` does not parse yet; these two names would clash
# with locals called `color` and `space`.
from luce_color import color as color_model
import luce_color.space as color_spaces
## A color with its alpha: sRGB-encoded channels and opacity, each 0..1.
pub struct Rgba:
pub var r: f64 = 0.0
pub var g: f64 = 0.0
pub var b: f64 = 0.0
pub var a: f64 = 1.0
## The color without its alpha.
pub func rgb() -> Color:
return Color(r = self.r, g = self.g, b = self.b)
## Parse a CSS color (see the module notes), or none. `currentColor` and `none` are
## paints, not colors, so they are none here.
pub func parse_rgba(text: str) -> Rgba?:
var scanner = Scanner(data = text.bytes)
let color = scan_color(&scanner) else return none
scanner.skip_spaces()
if not scanner.at_end():
return none
return color
## Parse a CSS color without its alpha: `#rgb`, `#rrggbb`, `rgb(r, g, b)` and every other
## form parse_rgba reads. None for anything else, including `none`, `currentColor` and
## `transparent`, which are paints rather than colors.
pub func parse_color(text: str) -> Color?:
if same_folded(strings.trim(text), "transparent"):
return none
let color = parse_rgba(text) else return none
return color.rgb()
## A color at the scanner, which moves past it.
func scan_color(scanner: Scanner*) -> Rgba?:
scanner.skip_spaces()
if scanner.peek() == '#':
scanner.pos += 1
let start = scanner.pos
while hex_digit(scanner.peek()) != none:
scanner.pos += 1
return hex_rgba(scanner.data[start..<scanner.pos])
let name = scanner.identifier()
if name.length == 0:
return none
if scanner.peek() == '(':
scanner.pos += 1
return color_function(name, scanner)
if same_folded(name, "transparent"):
return Rgba(a = 0.0)
let packed = named_color(name) else return none
return Rgba(r = (f64)((packed >> 16) & 0xFF) / 255.0, g = (f64)((packed >> 8) & 0xFF) / 255.0, b = (f64)(packed & 0xFF) / 255.0)
## The 0xRRGGBB value of a named color, any case.
func named_color(name: str) -> u32?:
var lower: u8[32]
if name.length > 32:
return none
for index in 0..<name.length:
let byte = name.bytes[index]
lower[index] = byte + 32 if byte >= 'A' and byte <= 'Z' else byte
let index = find_name(color_names, (str)lower[..<name.length]) else return none
return color_values[index]
## Three, four, six or eight hex digits, the `#` already consumed.
func hex_rgba(digits: const u8[]) -> Rgba?:
let count = digits.length
if count != 3 and count != 4 and count != 6 and count != 8:
return none
let width: usize = 1 if count <= 4 else 2
var channels: f64[4] = [0.0, 0.0, 0.0, 1.0]
for index in 0..<count // width:
var channel: u32 = 0
for offset in 0..<width:
let digit = hex_digit(digits[index * width + offset]) else return none
channel = channel * 16 + digit
if width == 1:
channel *= 17
channels[index] = (f64)channel / 255.0
return Rgba(r = channels[0], g = channels[1], b = channels[2], a = channels[3])
# mark: Color functions =======================================================================
## One argument of a color function: its number, whether it was a percentage, an angle
## (in degrees) or `none`.
struct Argument:
var value: f64 = 0.0
var percent: bool = false
var angle: bool = false
var missing: bool = false
## A color function's arguments, the `(` consumed: up to four channels and an alpha,
## which follows `/` or, in the legacy syntax, a fourth comma.
struct Arguments:
var items: Argument[5] = [Argument(), Argument(), Argument(), Argument(), Argument()]
var count: usize = 0
var alpha: Argument? = none
## For `color()`, the color space's name.
var space_name: str = ""
## Whether commas separated the arguments (the legacy syntax).
var commas: bool = false
func read_arguments(scanner: Scanner*, named_space: bool) -> Arguments?:
var result = Arguments()
scanner.skip_spaces()
if named_space:
result.space_name = scanner.identifier()
var slashed = false
var commas = false
while true:
scanner.skip_spaces()
let byte = scanner.peek()
if byte == ')':
scanner.pos += 1
break
if byte == ',':
commas = true
result.commas = true
scanner.pos += 1
continue
if byte == '/':
slashed = true
scanner.pos += 1
continue
var argument = Argument()
if is_alpha(byte):
let word = scanner.identifier()
if not same_folded(word, "none"):
return none
argument.missing = true
else:
argument.value = scanner.number() else return none
if scanner.peek() == '%':
scanner.pos += 1
argument.percent = true
elif is_alpha(scanner.peek()):
let suffix = scanner.identifier()
argument.angle = true
if same_folded(suffix, "deg"):
argument.value = argument.value
elif same_folded(suffix, "grad"):
argument.value *= 0.9
elif same_folded(suffix, "rad"):
argument.value *= 180.0 / math.pi
elif same_folded(suffix, "turn"):
argument.value *= 360.0
else:
return none
if slashed:
if result.alpha != none:
return none
result.alpha = argument
elif commas and result.count == 3:
if result.alpha != none:
return none
result.alpha = argument
else:
if result.count >= 4:
return none
result.items[result.count] = argument
result.count += 1
return result
## An argument as a fraction: a percentage of 100, or the number over `full`.
func argument_fraction(argument: Argument, full: f64) -> f64:
if argument.missing:
return 0.0
return argument.value / 100.0 if argument.percent else argument.value / full
## The alpha a function gives, 1 when it gives none.
func alpha_of(arguments: Arguments) -> f64:
let alpha = arguments.alpha else return 1.0
return math.clamp(argument_fraction(alpha, 1.0), 0.0, 1.0)
## The color function `name(...)`, its `(` consumed.
func color_function(name: str, scanner: Scanner*) -> Rgba?:
let is_color = same_folded(name, "color")
let arguments = read_arguments(scanner, is_color) else return none
let alpha = alpha_of(arguments)
if arguments.count != 3:
return none
let first = arguments.items[0]
let second = arguments.items[1]
let third = arguments.items[2]
if same_folded(name, "rgb") or same_folded(name, "rgba"):
# The legacy comma syntax takes all numbers or all percentages.
if arguments.commas and (first.percent != second.percent or first.percent != third.percent):
return none
return Rgba(r = channel_byte(first), g = channel_byte(second), b = channel_byte(third), a = alpha)
if same_folded(name, "hsl") or same_folded(name, "hsla"):
let color = hsl_rgb(hue_of(first), math.clamp(argument_fraction(second, 100.0), 0.0, 1.0), math.clamp(argument_fraction(third, 100.0), 0.0, 1.0))
return Rgba(r = color.r, g = color.g, b = color.b, a = alpha)
if same_folded(name, "hwb"):
var white = math.clamp(argument_fraction(second, 100.0), 0.0, 1.0)
var black = math.clamp(argument_fraction(third, 100.0), 0.0, 1.0)
if white + black >= 1.0:
let grey = white / (white + black)
return Rgba(r = grey, g = grey, b = grey, a = alpha)
let pure = hsl_rgb(hue_of(first), 1.0, 0.5)
let scale = 1.0 - white - black
return Rgba(r = pure.r * scale + white, g = pure.g * scale + white, b = pure.b * scale + white, a = alpha)
if same_folded(name, "lab") or same_folded(name, "lch"):
let lightness = argument_fraction(first, 1.0) * 100.0 if first.percent else first.value
var a = argument_fraction(second, 1.0) * 125.0 if second.percent else second.value
var b = third.value
if same_folded(name, "lch"):
let chroma = argument_fraction(second, 1.0) * 150.0 if second.percent else second.value
let hue = hue_of(third) * math.pi / 180.0
a = chroma * math.cos(hue)
b = chroma * math.sin(hue)
elif third.percent:
b = argument_fraction(third, 1.0) * 125.0
let d50 = lab.lab_to_xyz(lab.Lab(lightness, a, b), xyz.d50)
let d65 = xyz.apply(xyz.adapt(xyz.d50, xyz.d65), d50)
return encoded_rgba(xyz.from_xyz(d65, xyz.srgb), alpha)
if same_folded(name, "oklab") or same_folded(name, "oklch"):
let lightness = argument_fraction(first, 1.0)
var a = argument_fraction(second, 1.0) * 0.4 if second.percent else second.value
var b = argument_fraction(third, 1.0) * 0.4 if third.percent else third.value
if same_folded(name, "oklch"):
let chroma = argument_fraction(second, 1.0) * 0.4 if second.percent else second.value
let hue = hue_of(third) * math.pi / 180.0
a = chroma * math.cos(hue)
b = chroma * math.sin(hue)
let value = oklab.oklab_to_xyz(color_model.Oklab(lightness, a, b))
return encoded_rgba(xyz.from_xyz(value, xyz.srgb), alpha)
if is_color:
return space_color(arguments.space_name, argument_fraction(first, 1.0), argument_fraction(second, 1.0), argument_fraction(third, 1.0), alpha)
return none
## An rgb() channel: 0..255 (rounded to a whole value, as browsers do) or a percentage.
func channel_byte(argument: Argument) -> f64:
if argument.percent:
return math.clamp(argument.value / 100.0, 0.0, 1.0)
return math.clamp(math.round(argument.value), 0.0, 255.0) / 255.0
## A hue argument in degrees, wrapped to 0..360.
func hue_of(argument: Argument) -> f64:
if argument.missing:
return 0.0
let value = math.mod(argument.value, 360.0)
return value + 360.0 if value < 0.0 else value
## HSL (hue in degrees, saturation and lightness 0..1) to encoded sRGB.
func hsl_rgb(hue: f64, saturation: f64, lightness: f64) -> Rgba:
let high = lightness * (saturation + 1.0) if lightness <= 0.5 else lightness + saturation - lightness * saturation
let low = lightness * 2.0 - high
let sixth = hue / 60.0
return Rgba(r = hue_channel(low, high, sixth + 2.0), g = hue_channel(low, high, sixth), b = hue_channel(low, high, sixth - 2.0))
func hue_channel(low: f64, high: f64, at: f64) -> f64:
var h = at
if h < 0.0:
h += 6.0
if h >= 6.0:
h -= 6.0
if h < 1.0:
return (high - low) * h + low
if h < 3.0:
return high
if h < 4.0:
return (high - low) * (4.0 - h) + low
return low
## Linear sRGB clipped into the gamut and encoded.
func encoded_rgba(linear: color_model.Color, alpha: f64) -> Rgba:
return Rgba(r = transfer.srgb_encode(math.clamp(linear.red, 0.0, 1.0)), g = transfer.srgb_encode(math.clamp(linear.green, 0.0, 1.0)),
b = transfer.srgb_encode(math.clamp(linear.blue, 0.0, 1.0)), a = alpha)
## `color(space r g b)` for the predefined spaces luce-color knows.
func space_color(name: str, r: f64, g: f64, b: f64, alpha: f64) -> Rgba?:
if same_folded(name, "xyz") or same_folded(name, "xyz-d65") or same_folded(name, "xyz-d50"):
var value = xyz.XYZ(r, g, b)
if same_folded(name, "xyz-d50"):
value = xyz.apply(xyz.adapt(xyz.d50, xyz.d65), value)
return encoded_rgba(xyz.from_xyz(value, xyz.srgb), alpha)
var source = color_spaces.srgb
if same_folded(name, "srgb"):
source = color_spaces.srgb
elif same_folded(name, "srgb-linear"):
source = color_spaces.linear_srgb
elif same_folded(name, "display-p3"):
source = color_spaces.display_p3
elif same_folded(name, "a98-rgb"):
source = color_spaces.adobe_rgb
elif same_folded(name, "prophoto-rgb"):
source = color_spaces.prophoto
elif same_folded(name, "rec2020"):
source = color_spaces.rec2020
else:
return none
let linear = xyz.convert(color_spaces.decode(color_model.Color(r, g, b), source), source.primaries, xyz.srgb)
return encoded_rgba(linear, alpha)
## The CSS named colors, sorted, with their 0xRRGGBB values in `color_values`.
let color_names: str[148] = ["aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
"bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
"burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue",
"darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey",
"darkkhaki", "darkmagenta", "darkolivegreen", "darkorange",
"darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue",
"darkslategray", "darkslategrey", "darkturquoise", "darkviolet",
"deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue",
"firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro",
"ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow",
"grey", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki",
"lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue",
"lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray",
"lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen",
"lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue",
"lightyellow", "lime", "limegreen", "linen", "magenta", "maroon",
"mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
"mediumseagreen", "mediumslateblue", "mediumspringgreen",
"mediumturquoise", "mediumvioletred", "midnightblue", "mintcream",
"mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive",
"olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
"palegreen", "paleturquoise", "palevioletred", "papayawhip",
"peachpuff", "peru", "pink", "plum", "powderblue", "purple",
"rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
"salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver",
"skyblue", "slateblue", "slategray", "slategrey", "snow",
"springgreen", "steelblue", "tan", "teal", "thistle", "tomato",
"turquoise", "violet", "wheat", "white", "whitesmoke", "yellow",
"yellowgreen"]
let color_values: u32[148] = [0xF0F8FF, 0xFAEBD7, 0x00FFFF, 0x7FFFD4, 0xF0FFFF, 0xF5F5DC, 0xFFE4C4,
0x000000, 0xFFEBCD, 0x0000FF, 0x8A2BE2, 0xA52A2A, 0xDEB887, 0x5F9EA0,
0x7FFF00, 0xD2691E, 0xFF7F50, 0x6495ED, 0xFFF8DC, 0xDC143C, 0x00FFFF,
0x00008B, 0x008B8B, 0xB8860B, 0xA9A9A9, 0x006400, 0xA9A9A9, 0xBDB76B,
0x8B008B, 0x556B2F, 0xFF8C00, 0x9932CC, 0x8B0000, 0xE9967A, 0x8FBC8F,
0x483D8B, 0x2F4F4F, 0x2F4F4F, 0x00CED1, 0x9400D3, 0xFF1493, 0x00BFFF,
0x696969, 0x696969, 0x1E90FF, 0xB22222, 0xFFFAF0, 0x228B22, 0xFF00FF,
0xDCDCDC, 0xF8F8FF, 0xFFD700, 0xDAA520, 0x808080, 0x008000, 0xADFF2F,
0x808080, 0xF0FFF0, 0xFF69B4, 0xCD5C5C, 0x4B0082, 0xFFFFF0, 0xF0E68C,
0xE6E6FA, 0xFFF0F5, 0x7CFC00, 0xFFFACD, 0xADD8E6, 0xF08080, 0xE0FFFF,
0xFAFAD2, 0xD3D3D3, 0x90EE90, 0xD3D3D3, 0xFFB6C1, 0xFFA07A, 0x20B2AA,
0x87CEFA, 0x778899, 0x778899, 0xB0C4DE, 0xFFFFE0, 0x00FF00, 0x32CD32,
0xFAF0E6, 0xFF00FF, 0x800000, 0x66CDAA, 0x0000CD, 0xBA55D3, 0x9370DB,
0x3CB371, 0x7B68EE, 0x00FA9A, 0x48D1CC, 0xC71585, 0x191970, 0xF5FFFA,
0xFFE4E1, 0xFFE4B5, 0xFFDEAD, 0x000080, 0xFDF5E6, 0x808000, 0x6B8E23,
0xFFA500, 0xFF4500, 0xDA70D6, 0xEEE8AA, 0x98FB98, 0xAFEEEE, 0xDB7093,
0xFFEFD5, 0xFFDAB9, 0xCD853F, 0xFFC0CB, 0xDDA0DD, 0xB0E0E6, 0x800080,
0x663399, 0xFF0000, 0xBC8F8F, 0x4169E1, 0x8B4513, 0xFA8072, 0xF4A460,
0x2E8B57, 0xFFF5EE, 0xA0522D, 0xC0C0C0, 0x87CEEB, 0x6A5ACD, 0x708090,
0x708090, 0xFFFAFA, 0x00FF7F, 0x4682B4, 0xD2B48C, 0x008080, 0xD8BFD8,
0xFF6347, 0x40E0D0, 0xEE82EE, 0xF5DEB3, 0xFFFFFF, 0xF5F5F5, 0xFFFF00,
0x9ACD32]
## The value of a hex digit, or none.
func hex_digit(byte: u8) -> u32?:
if is_digit(byte):
return (u32)(byte - '0')
if byte >= 'a' and byte <= 'f':
return (u32)(byte - 'a') + 10
if byte >= 'A' and byte <= 'F':
return (u32)(byte - 'A') + 10
return none