Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.0

0.19.0 / src / widgets / button.lucb

## Buttons: the Button widget, its resting styles, and the cursor policy that
## follows an action's enabled state.
from luce_gpu import gpu
import interop
from luce_std import math
import ownership
import memory
import layout
import result
from layout import Widget, Layout, Size, Constraints, Event
from painter import Painter
from luce_window import input
from font import Font, selected_font
from command import Command
from cursor import CursorSource
from geometry import Point
import icons
import time

## Query shared action state without forcing a layout pass when it is enabled
## or disabled. The layout owns this policy; the action owns no widget edges.
struct ActionCursor: CursorSource:
    let action: interop.Reference[Command]

    pub func init(action: interop.Reference[Command]):
        self.action = action.clone()

    pub func cursor(position: Point, captured: bool) -> input.Cursor:
        return input.Cursor.pointer if self.action.value().is_enabled() else input.Cursor.arrow

    pub func close():
        self.action.release()

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

let action_cursor_type: interop.Type[ActionCursor] = interop.Type[ActionCursor]("Command cursor", ActionCursor.close, ActionCursor.trace, closeable = true, main_thread = true)

## How a button rests: `sunken` (the default face), `raised`, `plain` (no
## resting fill, only the hover and pressed washes) or `selected` (the accent,
## with `accent_text` on it: the active tool, an open menu title).
pub enum ButtonStyle as u8:
    sunken = 0
    raised = 1
    plain = 2
    selected = 3

## A push button with a text label, an icon, or both, clicked by the pointer or
## by Space or Enter while focused. Built on a Command, it takes the command's
## label, enabled state and trigger instead of its own.
pub struct Button: Widget:
    let box: interop.Reference[Layout]
    var caption: interop.Owned[str]
    let font: interop.Reference[Font]
    let clicked: interop.Signal[unit]
    let action: interop.Reference[Command]?
    var pressed: bool
    var pressed_key: input.Key
    ## A luciaos-assets icon drawn before the text, or alone when there is no text.
    var glyph: interop.Owned[str]
    var style: ButtonStyle
    ## A press held this long (nanoseconds) and let go is a hold, not a click,
    ## once something listens for holds: a tool group's flyout.
    let holding: interop.Signal[unit]
    var holds: bool
    var pressed_at: u64
    var hold_fired: bool
    ## A small corner mark: more choices behind this button (a tool group).
    var grouped: bool

    ## `text` and `action` are exclusive; `icon` names a luciaos-assets icon.
    pub func init(text: str = "", font: interop.Reference[Font]? = none, action: interop.Reference[Command]? = none, icon: str = "") -> !:
        if action != none and text != "":
            error(result.invalid, "a button takes either text or an action")
        if icon != "" and not icons.known(icon):
            error(result.invalid, "unknown icon name")
        var selected = try selected_font(font)
        errdefer selected.release()
        _ = try selected.value().measure(text)
        let box = try layout.make_layout()
        errdefer box.release()
        try box.value().set_shrink(vertical = 0.0)
        box.value().set_focusable(true)
        box.value().set_cursor(input.Cursor.pointer)
        if let command = action:
            let cursor = try interop.Reference[ActionCursor].adopt(new ActionCursor(command) in memory.heap, action_cursor_type, memory.heap)
            defer cursor.release()
            let policy = cursor.as_interface[CursorSource](cursor.value())
            defer policy.release()
            try box.value().set_cursor_source(policy)
        let signal = try interop.Signal[unit]()
        errdefer signal.release()
        let holding = try interop.Signal[unit]()
        errdefer holding.release()
        self.caption = try interop.copy_text(text)
        errdefer self.caption.release()
        self.glyph = try interop.copy_text(icon)
        self.style = ButtonStyle.sunken
        self.clicked = signal
        self.holding = holding
        self.holds = false
        self.pressed_at = 0
        self.hold_fired = false
        self.grouped = false
        self.pressed = false
        self.pressed_key = input.Key.unknown
        self.box = box
        self.font = selected
        self.action = action
        if let command = action:
            _ = command.clone()

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

    ## The label: the action's text for an action button, else the caption.
    pub func text() -> interop.Owned[str]:
        if let action = self.action:
            return action.value().text()
        return self.caption.clone()

    pub func set_text(text: str) -> !:
        if self.action != none:
            error(result.invalid, "an action button takes its label from the action")
        _ = try self.font.value().measure(text)
        let replacement = try interop.copy_text(text)
        let previous_caption = self.caption
        self.caption = replacement
        previous_caption.release()
        self.box.value().invalidate()

    ## Change how the button rests; `selected` marks it as the active choice.
    pub func set_style(style: ButtonStyle):
        if style == self.style:
            return
        self.style = style
        self.box.value().invalidate()

    pub func style_of() -> ButtonStyle:
        return self.style

    ## Show `icon` (a luciaos-assets name) instead: a tool group's current tool.
    pub func set_icon(icon: str) -> !:
        if icon != "" and not icons.known(icon):
            error(result.invalid, "unknown icon name")
        let replacement = try interop.copy_text(icon)
        let previous = self.glyph
        self.glyph = replacement
        previous.release()
        self.box.value().invalidate()

    ## Mark the button as the face of a group, with a small corner triangle.
    pub func set_grouped(grouped: bool):
        self.grouped = grouped
        self.box.value().invalidate()

    ## A press held a moment (400 ms): instead of a click, this, while still
    ## held — `poll_hold` each frame fires it (or letting go after the moment).
    pub func on_hold(callback: interop.Callback[unit, unit]) -> interop.Reference[interop.Connection]!:
        self.holds = true
        return try self.holding.connect(callback)

    ## Called each frame: a press held long enough fires the hold now, while
    ## the button is still down (a flyout opens under the pointer).
    pub func poll_hold() -> interop.Outcome[unit]:
        if not self.pressed or not self.holds or self.hold_fired or self.pressed_key != input.Key.unknown:
            return result.success[unit](())
        if time.since(self.pressed_at) < 400000000:
            return result.success[unit](())
        self.hold_fired = true
        return self.holding.emit(())

    ## For an action button this connects to the action's trigger, so the callback
    ## also runs when the action fires from a shortcut or menu.
    pub func on_click(callback: interop.Callback[unit, unit]) -> interop.Reference[interop.Connection]!:
        if let action = self.action:
            return try action.value().on_trigger(callback)
        return try self.clicked.connect(callback)

    ## Activate the button as a click would: trigger its action or emit its click
    ## signal. Does nothing while the button or its action is disabled.
    pub func click() -> interop.Outcome[unit]:
        if not self.is_enabled():
            return result.success[unit](())
        if let action = self.action:
            return action.value().trigger()
        return self.clicked.emit(())

    func is_enabled() -> bool:
        let action = self.action else return self.box.value().is_enabled()
        return self.box.value().is_enabled() and action.value().is_enabled()

    ## The icon's side: the row height less a little air.
    func glyph_size() -> f64:
        return self.box.value().theme().row_height(self.font) - 6.0

    pub func measure(available: Constraints) -> interop.Outcome[Size]:
        let caption = self.text()
        defer caption.release()
        var width = self.font.value().measure(caption.value) catch failure:
            return result.failure[Size](failure.code, failure.message)
        if self.glyph.value.length > 0:
            width += self.glyph_size() + (self.font.value().advance() * 0.5 if caption.value.length > 0 else 0.0)
        return result.success[Size](Size(width + self.box.value().theme().inset(self.font) * 2.0, self.box.value().theme().row_height(self.font)))

    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 theme = self.box.value().theme()
        let pressing = self.pressed and (self.pressed_key != input.Key.unknown or self.box.value().contains_pointer())
        # Held for a hold: keep frames coming so `poll_hold` sees the moment pass.
        if self.pressed and self.holds and not self.hold_fired:
            self.box.value().invalidate()
        let hovering = self.is_enabled() and self.box.value().contains_pointer()
        let resting = theme.accent if self.style == ButtonStyle.selected else (theme.raised if self.style == ButtonStyle.raised else theme.button)
        var color = resting
        if self.style == ButtonStyle.selected:
            color = resting
        elif pressing and self.is_enabled():
            color = theme.pressed
        elif hovering:
            color = theme.button_hover
        # A plain button shows only the washes: nothing at rest.
        if self.style != ButtonStyle.plain or pressing or hovering:
            try painter.rounded_rectangle(gpu.Rect(width = size.width, height = size.height), color, theme.control_radius)
        if self.box.value().is_focused():
            # A focus ring: the accent behind, the face inset by its width.
            try painter.rounded_rectangle(gpu.Rect(width = size.width, height = size.height), theme.accent, theme.control_radius)
            try painter.rounded_rectangle(gpu.Rect(1.5, 1.5, size.width - 3.0, size.height - 3.0), color, math.max(0.0, theme.control_radius - 1.5))
        let caption = self.text()
        defer caption.release()
        let ink = theme.accent_text if self.style == ButtonStyle.selected else (theme.foreground if self.is_enabled() else theme.muted)
        var x = theme.inset(self.font)
        if self.glyph.value.length > 0:
            let side = self.glyph_size()
            # An icon alone sits in the middle of its square; before text it takes the inset.
            if caption.value.length == 0:
                x = math.max(0.0, (size.width - side) * 0.5)
            try icons.draw_named(&painter, self.glyph.value, gpu.Rect(x, math.max(0.0, (size.height - side) * 0.5), side, side), ink)
            x += side + (self.font.value().advance() * 0.5 if caption.value.length > 0 else 0.0)
        if caption.value.length > 0:
            try painter.text(caption.value, x, math.max(0.0, (size.height - self.font.value().height()) * 0.5), color = ink, font = self.font)
        if self.grouped:
            # The group's mark: a small triangle in the bottom-right corner.
            try painter.triangle(Point(size.width - 3.0, size.height - 8.0), Point(size.width - 3.0, size.height - 3.0), Point(size.width - 8.0, size.height - 3.0), ink)

    pub func event(event: Event) -> interop.Outcome[unit]:
        if event.kind == input.EventKind.pointer_moved and not event.cancelled:
            return result.success[unit](())
        if event.cancelled:
            self.pressed = false
            self.pressed_key = input.Key.unknown
        elif event.kind == input.EventKind.pointer_down and event.button == 0 and event.inside:
            self.pressed = true
            self.pressed_key = input.Key.unknown
            self.pressed_at = time.now()
            self.hold_fired = false
            # The loop may rest while the pointer stays still: wake it when the hold is due.
            if self.holds:
                layout.wake_at(self.pressed_at + 400000000)
        elif event.kind == input.EventKind.pointer_up and event.button == 0:
            let activate = self.pressed and self.pressed_key == input.Key.unknown and event.inside
            self.pressed = false
            self.box.value().invalidate()
            if activate and self.hold_fired:
                return result.success[unit](())
            if activate and self.holds and time.since(self.pressed_at) >= 400000000:
                return self.holding.emit(())
            if activate:
                return self.click()
        elif event.kind == input.EventKind.key_down and not event.repeated and (event.key == input.Key.space or event.key == input.Key.enter):
            self.pressed = true
            self.pressed_key = event.key
        elif event.kind == input.EventKind.key_up and (event.key == input.Key.space or event.key == input.Key.enter):
            let activate = self.pressed and self.pressed_key == event.key
            if self.pressed_key != event.key:
                return result.success[unit](())
            self.pressed = false
            self.pressed_key = input.Key.unknown
            self.box.value().invalidate()
            if activate:
                return self.click()
        self.box.value().invalidate()
        return result.success[unit](())

    pub func close():
        if let action = self.action:
            action.release()
        self.font.release()
        self.clicked.close()
        self.clicked.release()
        self.holding.close()
        self.holding.release()
        self.caption.release()
        self.glyph.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        if let action = self.action:
            action.trace(visit, context)
        self.font.trace(visit, context)
        self.box.trace(visit, context)
        self.caption.trace(visit, context)
        self.glyph.trace(visit, context)
        self.clicked.trace(visit, context)
        self.holding.trace(visit, context)

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