Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.0

0.5.0 / src / adjustment_controls.luc

## The controls for every adjustment, built from their table (adjustments.luc)
## once and shown one kind at a time: a menu row for the pages when an
## adjustment shows one set of sliders at a time, then its sliders and
## checkboxes as one ParameterPanel (one compact row each); Levels its
## histogram with handles and Auto, Curves its editor. Two places use them:
## the adjust dialog, on a layer's pixels (destructive), and the Properties
## panel, on the selected adjustment layer (live). Whoever owns them hears of
## every change through `changed` and asks `numbers` for the engine's values.
from luce_ui.ui import Text, VStack, HStack, Spacer, Menu, Command, Widget, Checkbox, CurveEditor, ParameterPanel, ParameterSpec, ParameterKind
from workspace import Workspace
from kit import Kit
from adjustments import Adjustment, adjustments, filter_table, gradient_map, curves_adjustment, blur_kind
from levels_graph import LevelsGraph
from map_colors import MapColors
from luce_std import math

## Levels: its kind, and five values per page.
let levels_kind: int = 3
## Hue/Saturation: its pages are Master, then the six ranges from Reds.
let hue_kind: int = 1
let curves_kind: int = curves_adjustment

pub class AdjustmentControls:
    ## Every kind's rows in one column; only the shown kind's are visible.
    pub let view: VStack
    let table: list[Adjustment]
    let filters: list[Adjustment]
    let rows: list[VStack]
    ## Each kind's sliders then checkboxes, one row each.
    pub let controls: list[ParameterPanel]
    ## Each kind's page menu (a one-row panel), when it has pages.
    let pagers: list[ParameterPanel?]
    ## Every kind's shown values — all pages', then the checkboxes' — and its page showing.
    var shown: list[list[float]]
    var pages: list[int]
    pub let levels: LevelsGraph
    pub let curve_editor: CurveEditor
    ## The Gradient Map's two colors.
    pub let map_colors: MapColors
    let curve_label: Text
    var curve_channel: int = 0
    ## Hue/Saturation's On Image checkbox, and the slider's value when a drag began.
    var on_image: Checkbox? = none
    var drag_base: float = 0.0
    ## The kind showing, or -1.
    pub var kind: int = -1
    ## Where Levels' histogram comes from: what shows below adjustment layer
    ## `below`, or the selected layer's pixels when -1.
    pub var below: int = -1
    ## The user changed something.
    pub var changed: func() -> unit!? = none
    pub var failed: func(str) -> unit!? = none
    let workspace: Workspace
    let kit: Kit

    pub func init(self, workspace: Workspace, kit: Kit) -> unit!:
        self.workspace = workspace
        self.kit = kit
        self.table = adjustments()
        self.filters = filter_table()
        self.rows = []
        self.controls = []
        self.pagers = []
        self.shown = []
        self.pages = []
        self.levels = LevelsGraph()
        self.levels.on_change = self.levels_moved
        self.curve_editor = CurveEditor()
        kit.keep(self.curve_editor.on_change(self.curve_changed))
        self.curve_label = Text("RGB", font = kit.font)
        self.map_colors = MapColors(workspace, kit)
        self.map_colors.changed = self.tell
        for adjustment in self.table + self.filters:
            self.build(adjustment)
        var items: list[Widget] = []
        for row in self.rows:
            items.append(row)
        self.view = VStack(items, spacing = 0.0)

    # -- Building.

    ## One kind's column, hidden until shown.
    func build(self, adjustment: Adjustment) -> unit!:
        let kind = adjustment.kind
        var items: list[Widget] = []
        var pager: ParameterPanel? = none
        if adjustment.pages.length > 0:
            let caption = "Channel" if kind == levels_kind else ("Range" if kind == 1 else "Tones")
            let pages = ParameterPanel([ParameterSpec(name = "page", label = caption, kind = ParameterKind.menu, items = adjustment.pages.join("|"), resettable = false,
                                                      doc = "The settings below are this one's.")], font = self.kit.font)
            pages.set_margin(0.0)
            self.kit.keep(pages.on_change(func (index: int) -> unit!:
                self.show_page(kind, int(pages.value(index)))))
            items.append(pages)
            pager = pages
        if kind == levels_kind:
            items.append(self.levels)
        var specs: list[ParameterSpec] = []
        var slot = 0
        for knob in adjustment.knobs:
            specs.append(self.kit.number_spec(f"k{slot}", knob.label, knob.minimum, knob.maximum, knob.value, knob.decimals, knob.suffix))
            slot += 1
        slot = 0
        for toggle in adjustment.toggles:
            specs.append(ParameterSpec(name = f"t{slot}", label = toggle.label, kind = ParameterKind.toggle, value = 1.0 if toggle.on else 0.0))
            slot += 1
        let knobs = adjustment.knobs.length
        let controls = ParameterPanel(specs, font = self.kit.font)
        controls.set_margin(0.0)
        self.kit.keep(controls.on_change(func (index: int) -> unit!:
            if index < knobs:
                self.moved(kind, index, controls.value(index))
            else:
                self.toggled(kind, index - knobs)))
        if specs.length > 0:
            items.append(controls)
        # The page menu's label lines up with the sliders' below it.
        var widest = 0
        for knob in adjustment.knobs:
            widest = widest if widest > knob.label.length else knob.label.length
        if let pages = pager:
            # "Channel", "Range" and "Tones" take at most seven.
            widest = widest if widest > 7 else 7
            let column = float(widest) * self.kit.font.advance()
            pages.set_label_width(column)
            if adjustment.knobs.length > 0:
                controls.set_label_width(column)
        if kind == hue_kind:
            # The eyedropper: a click on the image shows the range its color is in.
            let on_image = self.kit.checkbox("On Image", self.toggle_on_image)
            self.on_image = on_image
            items.append(HStack([self.kit.button("Pick Range", self.arm_range), on_image, Spacer()], spacing = 8.0))
        if kind == levels_kind:
            # Photoshop's three Auto modes.
            var modes: list[Command] = []
            var mode = 0
            for name in ["Enhance Monochromatic Contrast", "Enhance Per Channel Contrast", "Find Dark & Light Colors"]:
                let chosen = mode
                let command = Command(name, id = f"auto_levels_{mode}")
                self.kit.bind(command, func () -> unit!:
                    self.auto_levels(chosen))
                modes.append(command)
                mode += 1
            # The eyedroppers: the next click on the image sets that point.
            var droppers: list[Widget] = [Menu("Auto ▾", modes, font = self.kit.font), Spacer()]
            var point = 0
            for name in ["Black", "Gray", "White"]:
                let chosen = point
                droppers.append(self.kit.button(name, func () -> unit!:
                    self.arm_dropper(chosen)))
                point += 1
            items.append(HStack(droppers, spacing = 8.0))
        if kind == curves_kind:
            items.append(self.curves_header())
            items.append(self.curve_editor)
        if kind == gradient_map:
            items.append(self.map_colors.row)
        let row = VStack(items, spacing = 6.0)
        row.layout().set_visible(false)
        self.rows.append(row)
        self.controls.append(controls)
        self.pagers.append(pager)
        self.shown.append(adjustment.defaults())
        self.pages.append(0)

    func curves_header(self) -> Widget!:
        var channels: list[Command] = []
        var channel = 0
        for name in curve_names():
            let chosen = channel
            let command = Command(name, id = f"curve_channel_{channel}")
            self.kit.bind(command, func () -> unit!:
                self.show_curve_channel(chosen))
            channels.append(command)
            channel += 1
        return HStack([Menu("Channel ▾", channels, font = self.kit.font), self.curve_label, Spacer(), self.kit.button("Reset", self.reset_curve)], spacing = 8.0)

    ## The adjustment or filter shown for `kind`.
    pub func spec(self, kind: int) -> Adjustment:
        return self.table[kind] if kind < self.table.length else self.filters[kind - blur_kind]

    # -- Showing.

    ## Show `kind` with `values` (shown units; its defaults when empty).
    ## `staged_curves`: the canvas already holds the curves to show (a Curves
    ## layer's own); otherwise Curves starts from the identity.
    ## `map_colors`: a Gradient Map layer's six color components (empty: the
    ## foreground and background colors).
    pub func show(self, kind: int, values: list[float], staged_curves: bool = false, map_colors: list[float]? = none) -> unit!:
        self.kind = kind
        var index = 0
        for row in self.rows:
            row.layout().set_visible(index == kind)
            index += 1
        let spec = self.spec(kind)
        self.shown[kind] = values if values.length == spec.value_count() else spec.defaults()
        slot_boxes(self.controls[kind], spec.knobs.length, self.shown[kind], spec.page_count() * spec.knobs.length)
        self.show_page(kind, 0)
        if kind == gradient_map:
            self.map_colors.take(map_colors else [])
        if kind == curves_kind:
            if not staged_curves:
                var channel = 0
                while channel < 4:
                    self.workspace.canvas.reset_curve(channel)
                    channel += 1
            self.show_curve_channel(0)

    ## Show page `page` of `kind`: its values in the sliders, and for Levels
    ## the graph and the channel's histogram.
    pub func show_page(self, kind: int, page: int) -> unit!:
        let spec = self.spec(kind)
        self.pages[kind] = page
        if let pager = self.pagers[kind]:
            pager.set_value(0, float(page))
        var slot = 0
        while slot < spec.knobs.length:
            self.controls[kind].set_value(slot, self.shown[kind][page * spec.knobs.length + slot])
            slot += 1
        if kind == levels_kind:
            self.show_levels(page)
            self.load_histogram(page)

    ## One slider of `kind`'s showing page set from code, as if moved.
    pub func set_control(self, kind: int, slot: int, value: float) -> unit!:
        self.controls[kind].set_value(slot, value)
        self.moved(kind, slot, self.controls[kind].value(slot))

    ## The engine's numbers for `kind` as shown; the Gradient Map's colors,
    ## the foreground and background, after its checkbox.
    pub func numbers(self, kind: int) -> list[float]:
        var numbers = self.spec(kind).engine(self.shown[kind])
        if kind == gradient_map:
            numbers = numbers + self.map_colors.colors
        return numbers

    ## The shown values of `kind`, as they are.
    pub func values(self, kind: int) -> list[float]:
        return self.shown[kind]

    # -- Changes.

    func moved(self, kind: int, slot: int, value: float) -> unit!:
        let knobs = self.spec(kind).knobs.length
        self.shown[kind][self.pages[kind] * knobs + slot] = value
        if kind == levels_kind:
            self.show_levels(self.pages[kind])
        self.tell()

    func toggled(self, kind: int, slot: int) -> unit!:
        let spec = self.spec(kind)
        self.shown[kind][spec.page_count() * spec.knobs.length + slot] = self.controls[kind].value(spec.knobs.length + slot)
        self.tell()

    ## A Levels handle dragged: the graph's values into the page and the sliders.
    func levels_moved(self) -> unit!:
        let base = self.pages[levels_kind] * 5
        let graph = self.levels
        let values = [graph.black, graph.white, graph.gamma, graph.out_black, graph.out_white]
        var slot = 0
        for value in values:
            self.shown[levels_kind][base + slot] = value
            self.controls[levels_kind].set_value(slot, value)
            slot += 1
        self.tell()

    func show_levels(self, page: int):
        let v = self.shown[levels_kind]
        let base = page * 5
        self.levels.set_values(v[base], v[base + 2], v[base + 1], v[base + 3], v[base + 4])

    ## The histogram for Levels' page `page`: RGB shows luminosity, the others their channel.
    func load_histogram(self, page: int) -> unit!:
        let canvas = self.workspace.canvas
        let measured = self.measure()
        if not measured:
            return
        var counts: list[int] = []
        var slot = 0
        while slot < 256:
            counts.append(canvas.histogram(page, slot))
            slot += 1
        self.levels.set_counts(counts)

    ## Count what Levels works on; false when it cannot be counted (nothing drawn yet).
    func measure(self) -> bool!:
        let canvas = self.workspace.canvas
        if self.below >= 0:
            canvas.measure_histogram_below(self.below) catch _:
                return false
        else:
            canvas.measure_histogram(self.workspace.layers.selected_id()) catch _:
                return false
        return true

    ## Levels › Auto: each channel's black and white points where 0.1% of the
    ## pixels fall beyond them, as Compositor's Auto Color; RGB's are reset.
    ## Levels' Auto, one of Photoshop's three: 0 stretches the luminosity alike
    ## in every channel (Monochromatic Contrast), 1 each channel on its own
    ## (Per Channel Contrast), 2 each channel to its darkest and lightest
    ## colors, clipping more of the extremes (Find Dark & Light Colors).
    func auto_levels(self, mode: int) -> unit!:
        if not self.measure():
            self.fail("Auto: nothing to count yet")
            return
        var values = self.spec(levels_kind).defaults()
        if mode == 0:
            let ends = self.clipped_ends(0, 1000)
            values[0] = float(ends[0])
            values[1] = float(ends[1])
        else:
            var channel = 1
            while channel <= 3:
                let ends = self.clipped_ends(channel, 1000 if mode == 1 else 200)
                values[channel * 5] = float(ends[0])
                values[channel * 5 + 1] = float(ends[1])
                channel += 1
        self.shown[levels_kind] = values
        self.show_page(levels_kind, self.pages[levels_kind])
        self.tell()

    ## Wait for a click on the image: Hue/Saturation then shows the range of
    ## the color there (Reds, Yellows … Magentas; a grey keeps Master).
    func arm_range(self) -> unit!:
        self.workspace.eyedroppers.sample_for = func (color: list[float]) -> unit!:
            self.show_page(hue_kind, range_of(color))

    ## On Image, as Photoshop's targeted adjustment: a press on the canvas
    ## shows the range of the color there, and dragging right or left raises
    ## or lowers that range's saturation — its hue with Cmd (Ctrl) held.
    pub func toggle_on_image(self) -> unit!:
        if self.workspace.eyedroppers.drag_for != none:
            self.workspace.eyedroppers.drag_for = none
            return
        self.workspace.eyedroppers.drag_for = func (color: list[float], moved: float, hue: bool, first: bool) -> unit!:
            let slot = 0 if hue else 1
            if first:
                self.show_page(hue_kind, range_of(color))
                self.drag_base = self.controls[hue_kind].value(slot)
                return
            let knob = self.spec(hue_kind).knobs[slot]
            self.set_control(hue_kind, slot, math.clamp(self.drag_base + moved * 0.5, knob.minimum, knob.maximum))

    ## Off: the canvas's drags are its tools' again.
    pub func end_on_image(self) -> unit!:
        self.workspace.eyedroppers.drag_for = none
        if let box = self.on_image:
            box.set_checked(false)

    ## Wait for a click on the image: 0 sets the black point, 1 the gray, 2 the white.
    func arm_dropper(self, point: int) -> unit!:
        self.workspace.eyedroppers.sample_for = func (color: list[float]) -> unit!:
            self.set_point(point, color)

    ## Levels from a sampled color (sRGB 0..1): its channels become each
    ## channel's input black or white; for gray, each channel's gamma brings
    ## the color to its own luminosity, neutral.
    func set_point(self, point: int, color: list[float]) -> unit!:
        var values = self.shown[levels_kind]
        let gray = color[0] * 0.3 + color[1] * 0.59 + color[2] * 0.11
        var channel = 1
        while channel <= 3:
            let value = color[channel - 1] * 255.0
            let at = channel * 5
            if point == 0:
                values[at] = math.min(value, values[at + 1] - 2.0)
            elif point == 2:
                values[at + 1] = math.max(value, values[at] + 2.0)
            else:
                let spread = math.max(1.0, values[at + 1] - values[at])
                let x = math.clamp((value - values[at]) / spread, 0.001, 0.999)
                let target = math.clamp(gray, 0.001, 0.999)
                values[at + 2] = math.clamp(math.log(x) / math.log(target), 0.1, 9.99)
            channel += 1
        self.shown[levels_kind] = values
        self.show_page(levels_kind, self.pages[levels_kind])
        self.tell()

    ## The histogram bins where `channel`'s darkest and lightest pixels begin,
    ## 1/`fraction` of them clipped at each end.
    func clipped_ends(self, channel: int, fraction: int) -> list[int]!:
        let canvas = self.workspace.canvas
        var total = 0
        var slot = 0
        while slot < 256:
            total += canvas.histogram(channel, slot)
            slot += 1
        let clip = total // fraction
        var low = 0
        var counted = 0
        while low < 254 and counted + canvas.histogram(channel, low) <= clip:
            counted += canvas.histogram(channel, low)
            low += 1
        var high = 255
        counted = 0
        while high > low + 1 and counted + canvas.histogram(channel, high) <= clip:
            counted += canvas.histogram(channel, high)
            high -= 1
        return [low, high]

    # -- Curves.

    ## The editor's points become the canvas's curve for the shown channel.
    func curve_changed(self) -> unit!:
        let canvas = self.workspace.canvas
        canvas.reset_curve(self.curve_channel)
        var index = 0
        while index < self.curve_editor.point_count():
            canvas.add_curve_point(self.curve_channel, self.curve_editor.point_x(index), self.curve_editor.point_y(index))
            index += 1
        self.tell()

    ## Load the canvas's curve for `channel` into the editor.
    func show_curve_channel(self, channel: int) -> unit!:
        self.curve_channel = channel
        let canvas = self.workspace.canvas
        self.curve_editor.reset()
        var index = 0
        while index < canvas.curve_point_count(channel):
            self.curve_editor.add_point(canvas.curve_point_x(channel, index), canvas.curve_point_y(channel, index))
            index += 1
        self.curve_label.set_text(curve_names()[channel])

    func reset_curve(self) -> unit!:
        self.workspace.canvas.reset_curve(self.curve_channel)
        self.show_curve_channel(self.curve_channel)
        self.tell()

    func tell(self) -> unit!:
        if let changed = self.changed:
            changed()

    func fail(self, message: str) -> unit!:
        if let failed = self.failed:
            failed(message)

## Check each of `panel`'s toggles (its rows after `knobs`) by its value, the
## values starting at `first`.
func slot_boxes(panel: ParameterPanel, knobs: int, values: list[float], first: int) -> unit!:
    var slot = knobs
    while slot < panel.count():
        panel.set_value(slot, 1.0 if values[first + slot - knobs] != 0.0 else 0.0)
        slot += 1

## The curve channels, in their index order.
func curve_names() -> list[str]:
    return ["RGB", "Red", "Green", "Blue"]

## Hue/Saturation's page for an sRGB color: 1 Reds, 2 Yellows, 3 Greens,
## 4 Cyans, 5 Blues, 6 Magentas by the nearest of their hues (every 60°),
## 0 (Master) for a grey.
pub func range_of(color: list[float]) -> int:
    let high = math.max(color[0], math.max(color[1], color[2]))
    let low = math.min(color[0], math.min(color[1], color[2]))
    let chroma = high - low
    if chroma < 0.02:
        return 0
    var hue = 0.0
    if high == color[0]:
        # Red at the top: -1..1, a magenta's below zero, so a turn is added first.
        hue = math.mod((color[1] - color[2]) / chroma + 6.0, 6.0)
    elif high == color[1]:
        hue = (color[2] - color[0]) / chroma + 2.0
    else:
        hue = (color[0] - color[1]) / chroma + 4.0
    return int(math.mod(math.round(hue) + 6.0, 6.0)) + 1