Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.0

0.5.0 / src / color_picker.luc

## The color picker dialog, after Photoshop's, and the small widgets it is
## built from: a swatch well, the new-over-current preview and the row of
## recent colors. The picker edits the foreground or background color in
## HSB, RGB, Lab, OkLCh or hex, sampling from the canvas while open.
from luce_ui.ui import Widget, Layout, Size, Constraints, Event, Painter, Font, Dialog, ShadedField, NumberField, TextField, Text, Button, ButtonStyle, HStack, VStack, Spacer, Rule
from luce_gpu.gpu import RenderTarget, Rect, Color
from luce_window.input import EventKind, Cursor
from interop import Connection
from workspace import Workspace
from hex_color import parse_hex, hex_of_srgb
from luce_color import color as science, hsl, lab, oklab, space, transfer
import theme
from luce_std import math

## A color shown in a rounded well.
pub class Swatch: Widget:
    let box: Layout
    pub var color: Color = Color(0.0, 0.0, 0.0)
    let side: float

    pub func init(self, side: float) -> unit!:
        self.side = side
        self.box = Layout()

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        return Size(self.side, self.side)

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        painter.rounded_rectangle(Rect(0.0, 0.0, self.side, self.side), theme.border(), 5.0)
        painter.rounded_rectangle(Rect(1.0, 1.0, self.side - 2.0, self.side - 2.0), self.color, 4.0)
        painter.close()

    pub func event(self, event: Event) -> unit!:
        _ = event

## Photoshop's new-over-current preview: the color being chosen above the one
## the picker opened with. Clicking the lower half goes back to it.
pub class PreviewPair: Widget:
    let box: Layout
    pub var current: Color = Color(0.0, 0.0, 0.0)
    pub var original: Color = Color(0.0, 0.0, 0.0)
    pub var on_revert: func() -> unit!? = none
    let side: float

    pub func init(self, side: float) -> unit!:
        self.side = side
        self.box = Layout()
        self.box.set_cursor(Cursor.pointer)
        # Clickable: a box only gets pointer events once it says so.
        self.box.set_interactive(true)

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        return Size(self.side, self.side)

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        painter.rounded_rectangle(Rect(0.0, 0.0, self.side, self.side), theme.border(), 5.0)
        let half = math.floor(self.side * 0.5)
        painter.rounded_rectangle(Rect(1.0, 1.0, self.side - 2.0, half - 1.0), self.current, 4.0, 1.0, 3)
        painter.rounded_rectangle(Rect(1.0, half, self.side - 2.0, self.side - half - 1.0), self.original, 4.0, 1.0, 12)
        painter.close()

    pub func event(self, event: Event) -> unit!:
        if event.kind == EventKind.pointer_down and event.button == 0 and event.inside and event.y >= self.side * 0.5:
            if let revert = self.on_revert:
                revert()

## The history: the colors committed most recently, newest first, one row of
## small swatches. Clicking one picks it.
pub class RecentColors: Widget:
    let box: Layout
    let workspace: Workspace
    pub var on_pick: func(str) -> unit!? = none
    let cell: float = 18.0
    let gap: float = 4.0

    pub func init(self, workspace: Workspace) -> unit!:
        self.workspace = workspace
        self.box = Layout()
        self.box.set_cursor(Cursor.pointer)
        # Clickable: a box only gets pointer events once it says so.
        self.box.set_interactive(true)

    pub func layout(self) -> Layout:
        return self.box

    pub func measure(self, available: Constraints) -> Size!:
        return Size((self.cell + self.gap) * 16.0 - self.gap, self.cell)

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        var index = 0
        while index < 16:
            let x = float(index) * (self.cell + self.gap)
            painter.rounded_rectangle(Rect(x, 0.0, self.cell, self.cell), theme.border(), 4.0)
            if index < self.workspace.colors.recent.length:
                painter.rounded_rectangle(Rect(x + 1.0, 1.0, self.cell - 2.0, self.cell - 2.0), linear_of(srgb_of(self.workspace.colors.recent[index])), 3.0)
            else:
                painter.rounded_rectangle(Rect(x + 1.0, 1.0, self.cell - 2.0, self.cell - 2.0), theme.surface(), 3.0)
            index += 1
        painter.close()

    pub func event(self, event: Event) -> unit!:
        if event.kind != EventKind.pointer_down or event.button != 0 or not event.inside:
            return
        let index = int(math.floor(event.x / (self.cell + self.gap)))
        if index >= 0 and index < self.workspace.colors.recent.length:
            if let pick = self.on_pick:
                pick(self.workspace.colors.recent[index])

## The color picker after Photoshop's: a 256-point field and a strip, the
## strip's channel chosen by the radio beside each field (H, S, B, R, G, B, L,
## a, b, and OkLCh's L, C, h — the field plots the other two of that model,
## OkLCh planes gamut-mapped by chroma so they stay displayable), a new-over-current
## preview, HSB / RGB / Lab / hex fields, the history, OK and Cancel; a canvas
## click samples while it is open. Color maths is luce-color's: HSB through
## `hsl`, Lab through `space`/`lab` against sRGB's white. Changes apply to the
## palette at once; Cancel puts the color back.
pub class ColorPicker:
    pub let dialog: Dialog
    let workspace: Workspace
    let field: ShadedField
    let strip: ShadedField
    let preview: PreviewPair
    let recent: RecentColors
    let title: Text
    ## The twelve channel fields in the order H, S, B, R, G, B, L, a, b, oL, oC, oh, and their radios.
    let channels: list[NumberField]
    let radios: list[Button]
    let hex: TextField
    let connections: list[Connection]
    var background: bool = false
    var before: str = ""
    ## The color being edited, sRGB encoded 0..1.
    var red: float = 0.0
    var green: float = 0.0
    var blue: float = 0.0
    ## Which channel the strip runs along, 0..11 as `channels`.
    var mode: int = 0
    var syncing: bool = false
    pub var closed: func() -> unit!? = none
    ## Called with the hex the user committed with OK.
    pub var committed: func(str) -> unit!? = none
    ## Editing some other color than the palette's (`open_for`): every change
    ## goes here, and Cancel sends the color it started from.
    var target: func(str) -> unit!? = none

    pub func init(self, workspace: Workspace, font: Font) -> unit!:
        self.workspace = workspace
        self.connections = []
        self.field = ShadedField(256.0, 256.0)
        self.strip = ShadedField(20.0, 256.0)
        self.preview = PreviewPair(64.0)
        self.preview.on_revert = self.revert
        self.recent = RecentColors(workspace)
        self.recent.on_pick = self.pick_recent
        self.title = Text("Foreground Color", font = font)
        self.channels = []
        self.radios = []
        let names = ["H", "S", "B", "R", "G", "B", "L", "a", "b", "oL", "oC", "oh"]
        let suffixes = ["°", "%", "%", "", "", "", "", "", "", "", "", "°"]
        var index = 0
        while index < 12:
            let chosen = index
            let radio = Button(names[index], font = font)
            radio.layout().set_size(24.0, 22.0)
            self.connections.append(radio.on_click(func () -> unit!:
                self.choose_mode(chosen)))
            self.radios.append(radio)
            let channel = NumberField(0.0, channel_low(index), channel_high(index), 1.0 if index != 10 else 0.5, decimals = 0 if index != 10 else 1, suffix = suffixes[index], font = font, cells = 6.0)
            self.connections.append(channel.on_change(func (value: float) -> unit!:
                _ = value
                self.channel_changed(chosen)))
            self.channels.append(channel)
            index += 1
        self.hex = TextField("#000000", font = font, cells = 9.0)
        self.connections.append(self.hex.on_commit(func (value: str) -> unit!:
            self.hex_committed(value)))
        self.connections.append(self.field.on_change(self.field_changed))
        self.connections.append(self.strip.on_change(self.strip_changed))
        let ok = Button("OK", font = font)
        let cancel = Button("Cancel", font = font)
        self.connections.append(ok.on_click(func () -> unit!:
            self.finish(true)))
        self.connections.append(cancel.on_click(func () -> unit!:
            self.finish(false)))
        let buttons = VStack([ok, cancel], spacing = 8.0)
        buttons.layout().set_limits(Size(90.0, 0.0), Size(90.0, 16384.0))
        # Two columns of channel rows, Photoshop's arrangement: HSB and RGB left, Lab and hex right.
        let left = VStack([self.channel_row(0), self.channel_row(1), self.channel_row(2), Rule(), self.channel_row(3), self.channel_row(4), self.channel_row(5)], spacing = 4.0)
        let hash_label = Text("#", font = font, muted = true)
        hash_label.layout().set_limits(Size(24.0, 0.0), Size(24.0, 16384.0))
        let right = VStack([self.channel_row(6), self.channel_row(7), self.channel_row(8), Rule(), self.channel_row(9), self.channel_row(10), self.channel_row(11), Rule(), HStack([hash_label, self.hex], spacing = 6.0)], spacing = 4.0)
        let side = VStack([HStack([self.preview, buttons], spacing = 16.0), HStack([left, right], spacing = 14.0),
                           Text("Click canvas to sample", font = font, muted = true), Spacer()], spacing = 12.0)
        side.layout().set_limits(Size(300.0, 256.0), Size(300.0, 16384.0))
        self.dialog = Dialog([self.title, HStack([self.field, self.strip, side], spacing = 14.0),
                              HStack([Text("Recent", font = font, muted = true), self.recent, Spacer()], spacing = 10.0)], width = 660.0)

    func channel_row(self, index: int) -> HStack!:
        return HStack([self.radios[index], self.channels[index]], spacing = 4.0)

    pub func is_open(self) -> bool:
        return self.dialog.is_open()

    ## Open for any color, `hex` to start from, titled `title`: each change is
    ## sent to `changed` at once (a layer style's color), Cancel sends `hex`.
    pub func open_for(self, title: str, hex: str, changed: func(str) -> unit!) -> unit!:
        self.target = changed
        self.before = hex
        self.title.set_text(title)
        let original = srgb_of(hex)
        self.preview.original = linear_of(original)
        self.show(original)
        self.dialog.open()

    ## Open for the foreground or the background color, seeded from the palette.
    pub func open(self, background: bool) -> unit!:
        self.target = none
        self.background = background
        self.before = self.workspace.colors.color_hex(background)
        self.title.set_text("Background Color" if background else "Foreground Color")
        self.workspace.colors.sampling = true
        self.workspace.colors.sampling_background = background
        let original = srgb_of(self.before)
        self.preview.original = linear_of(original)
        self.show(original)
        self.dialog.open()

    ## The palette changed under the picker (a canvas click sampled): show it.
    pub func sync(self) -> unit!:
        if self.is_open():
            self.show(srgb_of(self.workspace.colors.color_hex(self.background)))

    pub func finish(self, keep: bool) -> unit!:
        if let send = self.target:
            if not keep:
                send(self.before)
            self.target = none
        elif not keep:
            self.workspace.colors.set_color_hex(self.before, self.background)
        self.workspace.colors.sampling = false
        self.dialog.hide()
        if keep:
            if let remember = self.committed:
                remember(hex_of(Color(self.red, self.green, self.blue)))
        if let done = self.closed:
            done()

    func revert(self) -> unit!:
        self.take(srgb_of(self.before))

    func pick_recent(self, hex: str) -> unit!:
        self.take(srgb_of(hex))

    # -- The model: an sRGB color seen through three channel triples.

    func hsv(self) -> hsl.HSV:
        return hsl.to_hsv(science.Color(self.red, self.green, self.blue))

    func lab_of(self) -> lab.Lab:
        return space.to_lab(science.Color(self.red, self.green, self.blue), space.srgb)

    ## OkLCh of the color, lightness and chroma scaled by 100 for the fields.
    func oklch_of(self) -> lab.LCh:
        let polar = lab.oklab_to_oklch(science.to_oklab(space.decode(science.Color(self.red, self.green, self.blue), space.srgb)))
        return lab.LCh(polar.l * 100.0, polar.c * 100.0, polar.h)

    ## Channel `index` of the color, in the units the fields show.
    func channel_value(self, index: int) -> float:
        if index < 3:
            let h = self.hsv()
            return [h.h, h.s * 100.0, h.v * 100.0][index]
        if index < 6:
            return [self.red, self.green, self.blue][index - 3] * 255.0
        if index < 9:
            let l = self.lab_of()
            return [l.l, l.a, l.b][index - 6]
        let o = self.oklch_of()
        return [o.l, o.c, o.h][index - 9]

    ## The color with channel `index` set to `value` (field units), in gamut.
    ## The hue `value` at full saturation and brightness.
    func pure_hue(self, value: float) -> science.Color:
        var h = self.hsv()
        h = set_hsv(h, 0, value)
        h = set_hsv(h, 1, self.high(1))
        h = set_hsv(h, 2, self.high(2))
        return hsl.from_hsv(h)

    func with_channel(self, index: int, value: float) -> science.Color:
        return self.with_both(index, value, index, value)

    ## The channels a field's axes carry for the strip channel `mode`: (x, y),
    ## y running downwards from the channel's high end.
    func axes(self) -> list[int]:
        return [[1, 2], [0, 2], [0, 1], [5, 4], [5, 3], [3, 4], [7, 8], [8, 6], [7, 6], [11, 10], [11, 9], [10, 9]][self.mode]

    func low(self, index: int) -> float:
        return channel_low(index)

    func high(self, index: int) -> float:
        return channel_high(index)

    ## The color at field position (u, v) for the current strip channel.
    func at(self, u: float, v: float) -> science.Color:
        let pair = self.axes()
        let x = self.low(pair[0]) + (self.high(pair[0]) - self.low(pair[0])) * u
        let y = self.high(pair[1]) - (self.high(pair[1]) - self.low(pair[1])) * v
        return self.with_both(pair[0], x, pair[1], y)

    ## The color with two channels of one model replaced at once (the same
    ## channel twice replaces one), clamped into sRGB.
    func with_both(self, first_index: int, first_value: float, second_index: int, second_value: float) -> science.Color:
        if first_index < 3:
            var h = self.hsv()
            h = set_hsv(h, first_index, first_value)
            h = set_hsv(h, second_index, second_value)
            return hsl.from_hsv(h)
        if first_index < 6:
            var c = science.Color(self.red, self.green, self.blue)
            c = set_rgb(c, first_index, first_value)
            c = set_rgb(c, second_index, second_value)
            return c
        if first_index < 9:
            var l = self.lab_of()
            l = set_lab(l, first_index, first_value)
            l = set_lab(l, second_index, second_value)
            return space.clamp(space.from_lab(l, space.srgb))
        var o = self.oklch_of()
        o = set_oklch(o, first_index, first_value)
        o = set_oklch(o, second_index, second_value)
        # OkLCh edits leave the gamut easily; give up chroma, keep lightness and hue.
        return space.encode(oklab.to_srgb(lab.LCh(o.l / 100.0, o.c / 100.0, o.h)), space.srgb)

    # -- Showing the model.

    ## Show `color` (sRGB encoded) in every control without echoing.
    func show(self, color: science.Color) -> unit!:
        self.red = math.max(0.0, math.min(1.0, color.red))
        self.green = math.max(0.0, math.min(1.0, color.green))
        self.blue = math.max(0.0, math.min(1.0, color.blue))
        self.syncing = true
        var index = 0
        while index < 12:
            self.channels[index].set_value(self.channel_value(index))
            self.radios[index].set_style(ButtonStyle.selected if index == self.mode else ButtonStyle.sunken)
            index += 1
        self.hex.set_text(hex_of(Color(self.red, self.green, self.blue)))
        self.preview.current = linear_of(science.Color(self.red, self.green, self.blue))
        self.preview.layout().invalidate()
        self.shade()
        self.syncing = false

    ## Recompute the field's and strip's colors and markers for the strip channel.
    func shade(self) -> unit!:
        let pair = self.axes()
        var grid: list[Color] = []
        var row = 0
        while row <= 16:
            var column = 0
            while column <= 16:
                grid.append(linear_of(space.clamp(self.at(float(column) / 16.0, float(row) / 16.0))))
                column += 1
            row += 1
        self.field.set_grid(grid, 17)
        let ux = (self.channel_value(pair[0]) - self.low(pair[0])) / (self.high(pair[0]) - self.low(pair[0]))
        let vy = (self.high(pair[1]) - self.channel_value(pair[1])) / (self.high(pair[1]) - self.low(pair[1]))
        self.field.set_marker(ux, vy)
        var ramp: list[Color] = []
        var step = 0
        while step <= 32:
            let value = self.high(self.mode) - (self.high(self.mode) - self.low(self.mode)) * float(step) / 32.0
            # The hue strip shows pure hues, as Photoshop's does, so it reads as a
            # rainbow even while the color is white, grey or black.
            let shade = linear_of(space.clamp(self.pure_hue(value) if self.mode == 0 else self.with_channel(self.mode, value)))
            ramp.append(shade)
            ramp.append(shade)
            step += 1
        self.strip.set_grid(ramp, 2)
        self.strip.set_marker(0.5, (self.high(self.mode) - self.channel_value(self.mode)) / (self.high(self.mode) - self.low(self.mode)))

    # -- Edits.

    ## An edit in the picker: the palette takes it, and the other controls follow.
    func take(self, color: science.Color) -> unit!:
        if self.syncing:
            return
        let clamped = space.clamp(color)
        let hex = hex_of(Color(clamped.red, clamped.green, clamped.blue))
        if let send = self.target:
            send(hex)
        else:
            self.workspace.colors.set_color_hex(hex, self.background)
        self.show(clamped)

    func choose_mode(self, mode: int) -> unit!:
        self.mode = mode
        self.show(science.Color(self.red, self.green, self.blue))

    func field_changed(self) -> unit!:
        self.take(self.at(self.field.u(), self.field.v()))

    func strip_changed(self) -> unit!:
        let value = self.high(self.mode) - (self.high(self.mode) - self.low(self.mode)) * self.strip.v()
        self.take(self.with_channel(self.mode, value))

    func channel_changed(self, index: int) -> unit!:
        if self.syncing:
            return
        self.take(self.with_channel(index, self.channels[index].value()))

    func hex_committed(self, value: str) -> unit!:
        let trimmed = value.trim()
        self.take(srgb_of(trimmed if trimmed[..<1] == "#" else "#" + trimmed))

    pub func close(self):
        for connection in self.connections:
            connection.disconnect()
        self.connections.clear()

func set_hsv(h: hsl.HSV, index: int, value: float) -> hsl.HSV:
    var out = h
    if index == 0:
        out.h = value
    elif index == 1:
        out.s = value / 100.0
    else:
        out.v = value / 100.0
    return out

func set_rgb(c: science.Color, index: int, value: float) -> science.Color:
    var out = c
    if index == 3:
        out.red = value / 255.0
    elif index == 4:
        out.green = value / 255.0
    else:
        out.blue = value / 255.0
    return out

func set_oklch(o: lab.LCh, index: int, value: float) -> lab.LCh:
    var out = o
    if index == 9:
        out.l = value
    elif index == 10:
        out.c = value
    else:
        out.h = value
    return out

## The fields' ranges: H°, S %, B %, R, G, B (0..255), L*, a*, b*, Ok L×100, Ok C×100, Ok h°.
func channel_low(index: int) -> float:
    return [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -128.0, -128.0, 0.0, 0.0, 0.0][index]

func channel_high(index: int) -> float:
    return [360.0, 100.0, 100.0, 255.0, 255.0, 255.0, 100.0, 127.0, 127.0, 100.0, 40.0, 360.0][index]

func set_lab(l: lab.Lab, index: int, value: float) -> lab.Lab:
    var out = l
    if index == 6:
        out.l = value
    elif index == 7:
        out.a = value
    else:
        out.b = value
    return out

## The linear color the GPU draws for an sRGB-encoded one.
pub func linear_of(color: science.Color) -> Color:
    return Color(transfer.srgb_decode(color.red), transfer.srgb_decode(color.green), transfer.srgb_decode(color.blue))

## The sRGB components of "#rrggbb"; black for anything else.
func srgb_of(hex: str) -> science.Color:
    let values = parse_hex(hex) else return science.Color(0.0, 0.0, 0.0)
    return science.Color(values[0], values[1], values[2])

## "#rrggbb" for an sRGB-encoded color.
func hex_of(color: Color) -> str:
    return hex_of_srgb(color.red, color.green, color.blue)