Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.5

0.19.5 / src / widgets / hsb_field.lucb

## The HSB color picker parts (HsbField, HueStrip) and the sRGB/HSB conversions
## they and the rest of the library use.
from luce_gpu import gpu
import interop
from luce_std import math
import memory
import ownership
import layout
import result
from layout import Widget, Layout, Size, Constraints, Event
from painter import Painter
from theme import srgb_decoded
from geometry import Point
from luce_window import input

## The color picker's parts, after Photoshop's and Compositor's: a square
## whose x is saturation and y brightness for one hue (`HsbField`), and a
## vertical strip of hues (`HueStrip`). Both are drawn as shaded meshes in
## sRGB steps so the ramps look as they do everywhere else, and both emit
## `on_change` while dragged. Hue is 0..360, saturation and brightness 0..1.
pub struct HsbField: Widget:
    let box: interop.Reference[Layout]
    var side: f64
    var hue: f64
    var saturation: f64
    var brightness: f64
    var dragging: bool
    let changed: interop.Signal[unit]

    pub func init(side: f64 = 256.0) -> !:
        if not math.is_finite(side) or side < 16.0 or side > 2048.0:
            error(result.invalid, "an HSB field needs a side between 16 and 2048 points")
        let box = try layout.make_layout()
        errdefer box.release()
        try box.value().set_shrink(0.0, 0.0)
        box.value().set_cursor(input.Cursor.pointer)
        # clickable: a box receives pointer events only once it says so
        box.value().set_interactive(true)
        let changed = try interop.Signal[unit]()
        errdefer changed.release()
        self.box = box
        self.side = side
        self.hue = 0.0
        self.saturation = 0.0
        self.brightness = 0.0
        self.dragging = false
        self.changed = changed

    pub func layout() -> interop.Reference[Layout]:
        return self.box.clone()

    ## Fires on each press and drag step that picks a saturation and brightness;
    ## `set_hsb` does not fire it.
    pub func on_change(callback: interop.Callback[unit, unit]) -> interop.Reference[interop.Connection]!:
        return try self.changed.connect(callback)

    pub func hue_value() -> f64:
        return self.hue

    pub func saturation_value() -> f64:
        return self.saturation

    pub func brightness_value() -> f64:
        return self.brightness

    ## Set the shown color from code; no signal.
    pub func set_hsb(hue: f64, saturation: f64, brightness: f64) -> !:
        if not math.is_finite(hue) or not math.is_finite(saturation) or not math.is_finite(brightness):
            error(result.invalid, "HSB components must be finite")
        self.hue = wrap_hue(hue)
        self.saturation = math.clamp(saturation, 0.0, 1.0)
        self.brightness = math.clamp(brightness, 0.0, 1.0)
        self.box.value().repaint()

    pub func measure(available: Constraints) -> interop.Outcome[Size]:
        return result.success[Size](Size(self.side, self.side))

    pub func draw(target: interop.View[gpu.RenderTarget]) -> interop.Outcome[unit]:
        self.paint(target) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    func paint(target: interop.View[gpu.RenderTarget]) -> !:
        var painter = try Painter(target)
        defer painter.close()
        let size = try target.get().size()
        let cells: usize = 16
        let count = cells * cells * 6
        var points = try new Point[count] --- in memory.heap
        defer free(points) in memory.heap
        var colors = try new gpu.Color[count] --- in memory.heap
        defer free(colors) in memory.heap
        var index: usize = 0
        for row in 0..<cells:
            for column in 0..<cells:
                let x0 = (f64)column / (f64)cells
                let x1 = (f64)(column + 1) / (f64)cells
                let y0 = (f64)row / (f64)cells
                let y1 = (f64)(row + 1) / (f64)cells
                let corners: Point[4] = [Point(x0, y0), Point(x1, y0), Point(x1, y1), Point(x0, y1)]
                let order: usize[6] = [0, 1, 2, 0, 2, 3]
                for corner in order:
                    let unit_point = corners[corner]
                    points[index] = Point(unit_point.x * size.width, unit_point.y * size.height)
                    colors[index] = srgb_decoded(hsb_to_rgb(self.hue, unit_point.x, 1.0 - unit_point.y))
                    index += 1
        try painter.shaded_mesh(points, colors)
        # The marker: a white ring over a black one, at the chosen color.
        let mx = self.saturation * size.width
        let my = (1.0 - self.brightness) * size.height
        try ring(&painter, mx, my, 6.0, 0.75, gpu.Color(0.0, 0.0, 0.0))
        try ring(&painter, mx, my, 5.25, 1.5, gpu.Color(1.0, 1.0, 1.0))

    func choose(x: f64, y: f64) -> interop.Outcome[unit]:
        let bounds = self.box.value().bounds()
        if bounds.width <= 0.0 or bounds.height <= 0.0:
            return result.success[unit](())
        self.saturation = math.clamp(x / bounds.width, 0.0, 1.0)
        self.brightness = 1.0 - math.clamp(y / bounds.height, 0.0, 1.0)
        self.box.value().repaint()
        return self.changed.emit(())

    pub func event(event: Event) -> interop.Outcome[unit]:
        if event.cancelled:
            self.dragging = false
            return result.success[unit](())
        if event.kind == input.EventKind.pointer_down and event.button == 0 and event.inside:
            self.dragging = true
            return self.choose(event.x, event.y)
        if event.kind == input.EventKind.pointer_moved and self.dragging:
            return self.choose(event.x, event.y)
        if event.kind == input.EventKind.pointer_up and event.button == 0:
            self.dragging = false
        return result.success[unit](())

    pub func close():
        self.changed.close()
        self.changed.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        self.box.trace(visit, context)
        self.changed.trace(visit, context)

pub let hsb_field_type: interop.Type[HsbField] = interop.Type[HsbField]("HsbField", HsbField.close, HsbField.trace, closeable = true, main_thread = true)

## The vertical hue strip beside the field: red at the top through the
## spectrum back to red, with a pair of arrows at the chosen hue.
pub struct HueStrip: Widget:
    let box: interop.Reference[Layout]
    var height: f64
    var hue: f64
    var dragging: bool
    let changed: interop.Signal[f64]

    pub func init(height: f64 = 256.0) -> !:
        if not math.is_finite(height) or height < 16.0 or height > 2048.0:
            error(result.invalid, "a hue strip needs a height between 16 and 2048 points")
        let box = try layout.make_layout()
        errdefer box.release()
        try box.value().set_shrink(0.0, 0.0)
        box.value().set_cursor(input.Cursor.pointer)
        # clickable: a box receives pointer events only once it says so
        box.value().set_interactive(true)
        let changed = try interop.Signal[f64]()
        errdefer changed.release()
        self.box = box
        self.height = height
        self.hue = 0.0
        self.dragging = false
        self.changed = changed

    pub func layout() -> interop.Reference[Layout]:
        return self.box.clone()

    ## Fires with the new hue, 0..360, while dragged.
    pub func on_change(callback: interop.Callback[f64, unit]) -> interop.Reference[interop.Connection]!:
        return try self.changed.connect(callback)

    pub func hue_value() -> f64:
        return self.hue

    ## Set the hue from code, wrapped into 0..360; no signal.
    pub func set_hue(hue: f64) -> !:
        if not math.is_finite(hue):
            error(result.invalid, "hue must be finite")
        self.hue = wrap_hue(hue)
        self.box.value().repaint()

    pub func measure(available: Constraints) -> interop.Outcome[Size]:
        return result.success[Size](Size(strip_width + arrow_room * 2.0, self.height))

    pub func draw(target: interop.View[gpu.RenderTarget]) -> interop.Outcome[unit]:
        self.paint(target) catch failure:
            return result.failure[unit](failure.code, failure.message)
        return result.success[unit](())

    func paint(target: interop.View[gpu.RenderTarget]) -> !:
        var painter = try Painter(target)
        defer painter.close()
        let size = try target.get().size()
        let steps: usize = 24
        var points = try new Point[steps * 6] --- in memory.heap
        defer free(points) in memory.heap
        var colors = try new gpu.Color[steps * 6] --- in memory.heap
        defer free(colors) in memory.heap
        let left = arrow_room
        let right = arrow_room + strip_width
        var index: usize = 0
        for step in 0..<steps:
            let y0 = (f64)step / (f64)steps * size.height
            let y1 = (f64)(step + 1) / (f64)steps * size.height
            let top = srgb_decoded(hsb_to_rgb(360.0 - (f64)step / (f64)steps * 360.0, 1.0, 1.0))
            let bottom = srgb_decoded(hsb_to_rgb(360.0 - (f64)(step + 1) / (f64)steps * 360.0, 1.0, 1.0))
            let corners: Point[4] = [Point(left, y0), Point(right, y0), Point(right, y1), Point(left, y1)]
            let shades: gpu.Color[4] = [top, top, bottom, bottom]
            let order: usize[6] = [0, 1, 2, 0, 2, 3]
            for corner in order:
                points[index] = corners[corner]
                colors[index] = shades[corner]
                index += 1
        try painter.shaded_mesh(points, colors)
        # The arrows either side, pointing at the chosen hue.
        let y = (1.0 - self.hue / 360.0) * size.height
        let ink = self.box.value().theme().foreground
        try painter.triangle(Point(0.0, y - 5.0), Point(left - 1.0, y), Point(0.0, y + 5.0), ink)
        try painter.triangle(Point(size.width, y - 5.0), Point(right + 1.0, y), Point(size.width, y + 5.0), ink)

    func choose(y: f64) -> interop.Outcome[unit]:
        let bounds = self.box.value().bounds()
        if bounds.height <= 0.0:
            return result.success[unit](())
        self.hue = (1.0 - math.clamp(y / bounds.height, 0.0, 1.0)) * 360.0
        if self.hue >= 360.0:
            self.hue = 0.0
        self.box.value().repaint()
        return self.changed.emit(self.hue)

    pub func event(event: Event) -> interop.Outcome[unit]:
        if event.cancelled:
            self.dragging = false
            return result.success[unit](())
        if event.kind == input.EventKind.pointer_down and event.button == 0 and event.inside:
            self.dragging = true
            return self.choose(event.y)
        if event.kind == input.EventKind.pointer_moved and self.dragging:
            return self.choose(event.y)
        if event.kind == input.EventKind.pointer_up and event.button == 0:
            self.dragging = false
        return result.success[unit](())

    pub func close():
        self.changed.close()
        self.changed.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        self.box.trace(visit, context)
        self.changed.trace(visit, context)

pub let hue_strip_type: interop.Type[HueStrip] = interop.Type[HueStrip]("HueStrip", HueStrip.close, HueStrip.trace, closeable = true, main_thread = true)

## The strip is 20 points wide with 7 points of arrow room either side, as Compositor's.
let strip_width: f64 = 20.0
let arrow_room: f64 = 7.0

func wrap_hue(hue: f64) -> f64:
    var wrapped = hue - math.floor(hue / 360.0) * 360.0
    if wrapped >= 360.0:
        wrapped = 0.0
    return wrapped

## A ring of `width` around (x, y) at `radius`, as sixteen short lines.
func ring(painter: Painter*, x: f64, y: f64, radius: f64, width: f64, color: gpu.Color) -> !:
    let sides: usize = 16
    for side in 0..<sides:
        let a = (f64)side / (f64)sides * math.pi * 2.0
        let b = (f64)(side + 1) / (f64)sides * math.pi * 2.0
        try painter.line(Point(x + math.cos(a) * radius, y + math.sin(a) * radius), Point(x + math.cos(b) * radius, y + math.sin(b) * radius), width, color)

## An sRGB color from hue (0..360), saturation and brightness (0..1).
pub func hsb_to_rgb(hue: f64, saturation: f64, brightness: f64) -> gpu.Color:
    let h = wrap_hue(hue) / 60.0
    let sector = (i64)math.floor(h)
    let f = h - (f64)sector
    let p = brightness * (1.0 - saturation)
    let q = brightness * (1.0 - saturation * f)
    let t = brightness * (1.0 - saturation * (1.0 - f))
    if sector == 0:
        return gpu.Color(brightness, t, p)
    if sector == 1:
        return gpu.Color(q, brightness, p)
    if sector == 2:
        return gpu.Color(p, brightness, t)
    if sector == 3:
        return gpu.Color(p, q, brightness)
    if sector == 4:
        return gpu.Color(t, p, brightness)
    return gpu.Color(brightness, p, q)

## Hue, saturation and brightness of an sRGB color, written to the pointers.
## A gray keeps hue 0.
pub func rgb_to_hsb(color: gpu.Color, hue: f64*, saturation: f64*, brightness: f64*):
    let top = math.max(color.red, math.max(color.green, color.blue))
    let bottom = math.min(color.red, math.min(color.green, color.blue))
    let delta = top - bottom
    *brightness = top
    *saturation = 0.0 if top <= 0.0 else delta / top
    if delta <= 0.0:
        *hue = 0.0
        return
    var h = 0.0
    if top == color.red:
        h = (color.green - color.blue) / delta
    elif top == color.green:
        h = 2.0 + (color.blue - color.red) / delta
    else:
        h = 4.0 + (color.red - color.green) / delta
    *hue = wrap_hue(h * 60.0)

test "HSB converts to RGB and back":
    let red = hsb_to_rgb(0.0, 1.0, 1.0)
    assert(red.red == 1.0 and red.green == 0.0 and red.blue == 0.0)
    let green = hsb_to_rgb(120.0, 1.0, 1.0)
    assert(green.green == 1.0 and green.red == 0.0)
    var h = 0.0
    var s = 0.0
    var b = 0.0
    rgb_to_hsb(gpu.Color(0.0, 0.0, 1.0), &h, &s, &b)
    assert(h == 240.0 and s == 1.0 and b == 1.0)
    rgb_to_hsb(gpu.Color(0.5, 0.5, 0.5), &h, &s, &b)
    assert(h == 0.0 and s == 0.0 and b == 0.5)
    let orange = hsb_to_rgb(35.0, 0.73, 0.906)
    rgb_to_hsb(orange, &h, &s, &b)
    assert(math.abs(h - 35.0) < 0.01 and math.abs(s - 0.73) < 0.001 and math.abs(b - 0.906) < 0.001)

test "the field and strip hold their state":
    var field = try HsbField(128.0)
    defer field.close()
    try field.set_hsb(400.0, 2.0, -1.0)
    assert(field.hue_value() == 40.0 and field.saturation_value() == 1.0 and field.brightness_value() == 0.0)
    var strip = try HueStrip(128.0)
    defer strip.close()
    try strip.set_hue(-30.0)
    assert(strip.hue_value() == 330.0)