Files
moon-gpui/src/color/color.mbt
T

538 lines
13 KiB
MoonBit

// Colors and backgrounds, ported from gpui/src/color.rs.
//
// Deviations from GPUI:
// - Channels are `Double` (GPUI: `f32`), see geometry/units.mbt.
// - Values are immutable; `Hsla::fade_out` returns a new color instead of
// mutating in place.
// - serde (de)serialization is replaced by `Rgba::parse` / `Rgba::to_hex`.
///|
/// A color in the sRGB color space with straight (non-premultiplied) alpha.
/// Channels are in `0.0..=1.0`.
#derive(Eq, Default, Debug)
pub(all) struct Rgba {
r : Double
g : Double
b : Double
a : Double
}
///|
/// A color as hue, saturation, lightness and alpha, all in `0.0..=1.0`.
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct Hsla {
h : Double
s : Double
l : Double
a : Double
}
///|
fn clamp01(value : Double) -> Double {
if value < 0.0 {
0.0
} else if value > 1.0 {
1.0
} else {
value
}
}
///|
fn byte_at(hex : UInt32, shift : Int32) -> Double {
((hex >> shift) & 0xFF).reinterpret_as_int().to_double() / 255.0
}
///|
/// An opaque color from a `0xRRGGBB` value.
pub fn rgb(hex : UInt32) -> Rgba {
{ r: byte_at(hex, 16), g: byte_at(hex, 8), b: byte_at(hex, 0), a: 1.0, }
}
///|
/// A color from a `0xRRGGBBAA` value.
pub fn rgba(hex : UInt32) -> Rgba {
{
r: byte_at(hex, 24),
g: byte_at(hex, 16),
b: byte_at(hex, 8),
a: byte_at(hex, 0),
}
}
///|
/// Truncating float-to-byte conversion, like Rust's `(x * 255.0) as u32`.
fn channel_to_byte_trunc(value : Double) -> UInt32 {
let scaled = value * 255.0
if scaled.is_nan() || scaled <= 0.0 {
0
} else {
scaled.to_int().reinterpret_as_uint()
}
}
///|
/// Packs into `0xRRGGBBAA`, truncating each channel (GPUI's `From<Rgba> for
/// u32`).
pub fn Rgba::to_u32(self : Rgba) -> UInt32 {
(channel_to_byte_trunc(self.r) << 24) |
(channel_to_byte_trunc(self.g) << 16) |
(channel_to_byte_trunc(self.b) << 8) |
channel_to_byte_trunc(self.a)
}
///|
/// Blends `other` over `self` (straight alpha, keeps `self`'s alpha).
pub fn Rgba::blend(self : Rgba, other : Rgba) -> Rgba {
if other.a >= 1.0 {
other
} else if other.a <= 0.0 {
self
} else {
{
r: self.r * (1.0 - other.a) + other.r * other.a,
g: self.g * (1.0 - other.a) + other.g * other.a,
b: self.b * (1.0 - other.a) + other.b * other.a,
a: self.a,
}
}
}
///|
/// Replaces the alpha channel (clamped to `0.0..=1.0`).
pub fn Rgba::alpha(self : Rgba, a : Double) -> Rgba {
{ ..self, a: clamp01(a), }
}
///|
/// Multiplies the alpha channel by `factor` (clamped to `0.0..=1.0`).
pub fn Rgba::opacity(self : Rgba, factor : Double) -> Rgba {
{ ..self, a: self.a * clamp01(factor), }
}
///|
fn hex_byte(value : Double) -> String {
let byte = (value * 255.0).round().to_int()
let byte = if byte < 0 { 0 } else if byte > 255 { 255 } else { byte }
let digits = "0123456789abcdef"
let hi = digits.exact_view(start=byte / 16, end=byte / 16 + 1)
let lo = digits.exact_view(start=byte % 16, end=byte % 16 + 1)
"\{hi}\{lo}"
}
///|
/// Formats as `#rrggbbaa` (GPUI's serde representation), rounding channels.
pub fn Rgba::to_hex(self : Rgba) -> String {
"#\{hex_byte(self.r)}\{hex_byte(self.g)}\{hex_byte(self.b)}\{hex_byte(self.a)}"
}
///|
pub impl Show for Rgba with fn output(self, logger) {
logger.write_string(self.to_hex())
}
///|
#derive(Debug)
pub suberror ColorParseError {
ColorParseError(input~ : String, reason~ : String)
}
///|
fn hex_digit(input : String, c : Char) -> UInt32 raise ColorParseError {
match c {
'0'..<='9' => (c.to_int() - '0'.to_int()).reinterpret_as_uint()
'a'..<='f' => (c.to_int() - 'a'.to_int() + 10).reinterpret_as_uint()
'A'..<='F' => (c.to_int() - 'A'.to_int() + 10).reinterpret_as_uint()
_ => raise ColorParseError(input~, reason="invalid hex digit '\{c}'")
}
}
///|
/// Parses `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` (surrounding whitespace
/// allowed). Mirrors GPUI's `TryFrom<&str> for Rgba`.
pub fn Rgba::parse(input : String) -> Rgba raise ColorParseError {
let expected = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa"
let trimmed = input.trim()
guard trimmed.strip_prefix("#") is Some(hex) else {
raise ColorParseError(input~, reason=expected)
}
let digits : Array[UInt32] = []
for c in hex {
digits.push(hex_digit(input, c))
}
let (r, g, b, a) = match digits.length() {
3 | 4 => {
let dup = fn(v : UInt32) -> UInt32 { (v << 4) | v }
let a = if digits.length() == 4 { dup(digits[3]) } else { 0xff }
(dup(digits[0]), dup(digits[1]), dup(digits[2]), a)
}
6 | 8 => {
let pair = fn(i : Int32) -> UInt32 { (digits[i] << 4) | digits[i + 1] }
let a = if digits.length() == 8 { pair(6) } else { 0xff }
(pair(0), pair(2), pair(4), a)
}
_ => raise ColorParseError(input~, reason=expected)
}
rgba((r << 24) | (g << 16) | (b << 8) | a)
}
///|
/// Converts to the HSL representation.
pub fn Rgba::to_hsla(self : Rgba) -> Hsla {
let r = self.r
let g = self.g
let b = self.b
let max = @cmp.maximum(r, @cmp.maximum(g, b))
let min = @cmp.minimum(r, @cmp.minimum(g, b))
let delta = max - min
let l = (max + min) / 2.0
let s = if l == 0.0 || l == 1.0 {
0.0
} else if l < 0.5 {
delta / (2.0 * l)
} else {
delta / (2.0 - 2.0 * l)
}
let h = if delta == 0.0 {
0.0
} else if max == r {
rem_euclid((g - b) / delta, 6.0) / 6.0
} else if max == g {
((b - r) / delta + 2.0) / 6.0
} else {
((r - g) / delta + 4.0) / 6.0
}
{ h, s, l, a: self.a, }
}
///|
fn rem_euclid(value : Double, modulus : Double) -> Double {
let r = value % modulus
if r < 0.0 {
r + modulus.abs()
} else {
r
}
}
///|
/// Converts to RGB.
pub fn Hsla::to_rgb(self : Hsla) -> Rgba {
let h = self.h
let s = self.s
let l = self.l
let c = (1.0 - (2.0 * l - 1.0).abs()) * s
let x = c * (1.0 - (h * 6.0 % 2.0 - 1.0).abs())
let m = l - c / 2.0
let cm = c + m
let xm = x + m
let (r, g, b) = match (h * 6.0).floor().to_int() {
0 | 6 => (cm, xm, m)
1 => (xm, cm, m)
2 => (m, cm, xm)
3 => (m, xm, cm)
4 => (xm, m, cm)
_ => (cm, m, xm)
}
{ r: clamp01(r), g: clamp01(g), b: clamp01(b), a: self.a, }
}
///|
/// Creates a color, clamping each channel to `0.0..=1.0`.
pub fn hsla(h : Double, s : Double, l : Double, a : Double) -> Hsla {
{ h: clamp01(h), s: clamp01(s), l: clamp01(l), a: clamp01(a), }
}
///|
pub fn black() -> Hsla {
{ h: 0.0, s: 0.0, l: 0.0, a: 1.0, }
}
///|
pub fn transparent_black() -> Hsla {
{ h: 0.0, s: 0.0, l: 0.0, a: 0.0, }
}
///|
pub fn transparent_white() -> Hsla {
{ h: 0.0, s: 0.0, l: 1.0, a: 0.0, }
}
///|
pub fn opaque_grey(lightness : Double, opacity : Double) -> Hsla {
{ h: 0.0, s: 0.0, l: clamp01(lightness), a: clamp01(opacity), }
}
///|
pub fn white() -> Hsla {
{ h: 0.0, s: 0.0, l: 1.0, a: 1.0, }
}
///|
pub fn red() -> Hsla {
{ h: 0.0, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn blue() -> Hsla {
{ h: 0.6666666667, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn green() -> Hsla {
{ h: 0.3333333333, s: 1.0, l: 0.25, a: 1.0, }
}
///|
pub fn yellow() -> Hsla {
{ h: 0.1666666667, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn Hsla::is_transparent(self : Hsla) -> Bool {
self.a == 0.0
}
///|
pub fn Hsla::is_opaque(self : Hsla) -> Bool {
self.a == 1.0
}
///|
/// Blends `other` over `self` in RGB space.
pub fn Hsla::blend(self : Hsla, other : Hsla) -> Hsla {
if other.a >= 1.0 {
other
} else if other.a <= 0.0 {
self
} else {
self.to_rgb().blend(other.to_rgb()).to_hsla()
}
}
///|
pub fn Hsla::grayscale(self : Hsla) -> Hsla {
{ ..self, s: 0.0, }
}
///|
/// Reduces alpha by `factor` (`0.0` keeps the color, `1.0` makes it fully
/// transparent). Returns a new color; GPUI mutates in place.
pub fn Hsla::fade_out(self : Hsla, factor : Double) -> Hsla {
{ ..self, a: self.a * (1.0 - clamp01(factor)), }
}
///|
/// Multiplies alpha by `factor` (clamped to `0.0..=1.0`).
pub fn Hsla::opacity(self : Hsla, factor : Double) -> Hsla {
{ ..self, a: self.a * clamp01(factor), }
}
///|
/// Replaces alpha (clamped to `0.0..=1.0`).
pub fn Hsla::alpha(self : Hsla, a : Double) -> Hsla {
{ ..self, a: clamp01(a), }
}
///|
/// `hsla(h°, s%, l%, a)`, matching GPUI's `Display for Hsla`.
pub impl Show for Hsla with fn output(self, logger) {
let fmt2 = fn(v : Double) -> String {
let scaled = (v * 100.0).round() / 100.0
scaled.to_string()
}
logger.write_string(
"hsla(\{fmt2(self.h * 360.0)}, \{fmt2(self.s * 100.0)}%, \{fmt2(self.l * 100.0)}%, \{fmt2(self.a)})",
)
}
// ---------------------------------------------------------------------------
// Backgrounds
// ---------------------------------------------------------------------------
///|
/// Which kind of fill a `Background` describes.
#derive(Eq, Debug)
pub(all) enum BackgroundTag {
Solid
LinearGradient
PatternSlash
Checkerboard
}
///|
/// The color space gradients are interpolated in.
#derive(Eq, Debug)
pub(all) enum ColorSpace {
Srgb
Oklab
}
///|
pub impl Default for BackgroundTag with fn default() {
Solid
}
///|
pub impl Default for ColorSpace with fn default() {
Srgb
}
///|
pub impl Show for ColorSpace with fn output(self, logger) {
match self {
Srgb => logger.write_string("sRGB")
Oklab => logger.write_string("Oklab")
}
}
///|
/// A color stop of a linear gradient; `percentage` is in `0.0..=1.0`.
#derive(Eq, Default, Debug)
pub(all) struct LinearColorStop {
color : Hsla
percentage : Double
}
///|
pub fn linear_color_stop(color : Hsla, percentage : Double) -> LinearColorStop {
{ color, percentage, }
}
///|
pub fn LinearColorStop::opacity(
self : LinearColorStop,
factor : Double,
) -> LinearColorStop {
{ ..self, color: self.color.opacity(factor), }
}
///|
/// A fill: solid color, two-stop linear gradient, or pattern.
///
/// Mirrors GPUI's GPU-facing `#[repr(C)]` layout: the meaning of
/// `gradient_angle_or_pattern_height` and `colors` depends on `tag`.
#derive(Eq, Default, Debug)
pub(all) struct Background {
tag : BackgroundTag
color_space : ColorSpace
solid : Hsla
gradient_angle_or_pattern_height : Double
colors : (LinearColorStop, LinearColorStop)
}
///|
pub fn solid_background(color : Hsla) -> Background {
{ ..Default::default(), solid: color, }
}
///|
/// A linear gradient at `angle` degrees between two stops.
pub fn linear_gradient(
angle : Double,
from : LinearColorStop,
to : LinearColorStop,
) -> Background {
{
..Default::default(),
tag: LinearGradient,
gradient_angle_or_pattern_height: angle,
colors: (from, to),
}
}
///|
/// Diagonal stripes of `width` separated by `interval` (both in `0.0..=1.0`
/// of the pattern height, packed as GPUI's shader expects).
pub fn pattern_slash(
color : Hsla,
width : Double,
interval : Double,
) -> Background {
let width_scaled = (width * 255.0).to_int()
let interval_scaled = (interval * 255.0).to_int()
let height = (width_scaled * 0xFFFF + interval_scaled).to_double()
{
..Default::default(),
tag: PatternSlash,
solid: color,
gradient_angle_or_pattern_height: height,
}
}
///|
pub fn checkerboard(color : Hsla, size : Double) -> Background {
{
..Default::default(),
tag: Checkerboard,
solid: color,
gradient_angle_or_pattern_height: size,
}
}
///|
pub fn Hsla::to_background(self : Hsla) -> Background {
solid_background(self)
}
///|
pub fn Rgba::to_background(self : Rgba) -> Background {
solid_background(self.to_hsla())
}
///|
pub fn Background::as_solid(self : Background) -> Hsla? {
if self.tag == Solid {
Some(self.solid)
} else {
None
}
}
///|
pub fn Background::with_color_space(
self : Background,
color_space : ColorSpace,
) -> Background {
{ ..self, color_space, }
}
///|
pub fn Background::opacity(self : Background, factor : Double) -> Background {
{
..self,
solid: self.solid.opacity(factor),
colors: (self.colors.0.opacity(factor), self.colors.1.opacity(factor)),
}
}
///|
pub fn Background::is_transparent(self : Background) -> Bool {
match self.tag {
Solid | PatternSlash | Checkerboard => self.solid.is_transparent()
LinearGradient =>
self.colors.0.color.is_transparent() &&
self.colors.1.color.is_transparent()
}
}
// ---------------------------------------------------------------------------
// Conversions standing in for GPUI's `impl Into<Hsla>` parameters.
// ---------------------------------------------------------------------------
///|
/// Anything usable where GPUI takes `impl Into<Hsla>`: `Hsla` and `Rgba`.
pub(open) trait IntoHsla {
fn into_hsla(Self) -> Hsla
}
///|
pub impl IntoHsla for Hsla with fn into_hsla(self) {
self
}
///|
pub impl IntoHsla for Rgba with fn into_hsla(self) {
self.to_hsla()
}