Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-2d

Source of release 0.5.0

0.5.0 / src / brush_list.luc

## The Brushes panel's list: a row per brush with its name and a stroke drawn
## with it (its tip, size taper under pressure, angle, roundness and
## spacing), as Photoshop's stroke thumbnails, under a header per group that
## a click folds and unfolds, as Photoshop's brush folders. A click picks the
## brush; a double-click on a saved brush's name renames it there. Rows are
## addressed by brush index, whatever line they are drawn on. The list
## scrolls itself and draws only the lines in sight, so a library of a
## thousand brushes never needs a texture its whole height; strokes are drawn
## a few a frame, those in sight first, so unfolding a group of hundreds
## never stalls the window.
from luce_ui.ui import Widget, Layout, Size, Constraints, Event, Painter, Font, Image
from luce_gpu.gpu import RenderTarget, Rect
from luce_window.input import EventKind, Cursor, ScrollUnit
from brush import Brush
from luce_painting.brush_mask import BrushMask
from theme import Look
import theme
from luce_std import math
import time

## The thumbnail stroke's size in points.
pub let stroke_width: int = 196
pub let stroke_height: int = 34

## The thumbnail of `brush`: its stroke, black on white, as RGBA.
pub func stroke_thumbnail(brush: Brush, blank: BrushMask) -> bytes!:
    # A pen's press eases the size in and out when pressure drives it.
    let size = brush.dynamics[0]
    let taper = 1.0 if size.control != 1 else math.max(0.15, size.minimum)
    let diameter = math.min(14.0, math.max(3.0, brush.diameter))
    if let tip = brush.tip:
        if not tip.is_empty():
            return tip.stroke_preview(stroke_width, stroke_height, false, diameter, brush.hardness, brush.spacing, brush.angle, brush.roundness, taper)
    return blank.stroke_preview(stroke_width, stroke_height, true, diameter, brush.hardness, brush.spacing, brush.angle, brush.roundness, taper)

pub class BrushList: Widget:
    let box: Layout
    let font: Font
    ## The window's accent, for the picked row.
    let look: func() -> Look
    let row_height: float = 58.0
    let header_height: float = 24.0
    ## Each brush's name and group, by brush index.
    var names: list[str]
    var groups: list[str]
    ## The lines drawn, top down: a group's header (brush -1, its group
    ## named in `line_groups`) or a brush's row.
    var line_brushes: list[int]
    var line_groups: list[str]
    ## The folded groups.
    var folded: list[str]
    ## Strokes drawn so far, by brush index (an empty image: not yet).
    var thumbnails: map[int, Image]
    ## The picked brush, or -1.
    pub var selected: int = -1
    ## Brushes before this one are built in: they cannot be renamed.
    pub var first_saved: int = 0
    var last_row: int = -1
    var last_time: int = 0
    ## How far the list is scrolled, and the height it last drew at.
    var scroll: float = 0.0
    var shown_height: float = 0.0
    ## A brush's stroke thumbnail, RGBA stroke_width × stroke_height, asked
    ## for when its row first shows.
    pub var stroke: func(int) -> bytes!? = none
    ## A brush picked.
    pub var on_pick: func(int) -> unit!? = none
    ## A double-click on saved brush `row`'s name, at (x, y).
    pub var on_rename: func(int, float, float) -> unit!? = none

    pub func init(self, font: Font, look: func() -> Look) -> unit!:
        self.font = font
        self.look = look
        self.box = Layout()
        self.box.set_focusable(true)
        self.box.set_cursor(Cursor.pointer)
        self.box.set_flex()
        self.names = []
        self.groups = []
        self.line_brushes = []
        self.line_groups = []
        self.folded = []
        self.thumbnails = {}

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

    ## Small: the list takes the room it is given and scrolls the rest.
    pub func measure(self, available: Constraints) -> Size!:
        return Size(float(stroke_width) + 16.0, 120.0)

    ## Scroll so `y` points of the lines are at the top, kept within them.
    pub func scroll_to(self, y: float):
        let whole = self.line_top(self.line_brushes.length)
        self.scroll = math.max(0.0, math.min(y, whole - self.shown_height))
        self.box.invalidate()

    ## The brushes: their names and groups ("" for none) by brush index. A
    ## group's brushes are listed together, groups in order of first
    ## appearance; strokes are asked for again as rows show.
    pub func set_rows(self, names: list[str], groups: list[str]) -> unit!:
        self.names = names
        self.groups = groups
        self.thumbnails = {}
        if self.selected >= names.length:
            self.selected = names.length - 1
        self.arrange()

    ## Fold `group` away, or unfold it.
    pub func toggle_group(self, group: str) -> unit!:
        if group in self.folded:
            var kept: list[str] = []
            for name in self.folded:
                if name != group:
                    kept.append(name)
            self.folded = kept
        else:
            self.folded.append(group)
        self.arrange()

    ## Fold every group but those named in `open`.
    pub func fold_all_but(self, open: list[str]) -> unit!:
        var folded: list[str] = []
        for group in self.groups:
            if group != "" and not (group in open) and not (group in folded):
                folded.append(group)
        self.folded = folded
        self.arrange()

    ## Whether `group` is folded.
    pub func is_folded(self, group: str) -> bool:
        return group in self.folded

    ## The lines again from the brushes, their groups and the folds.
    func arrange(self) -> unit!:
        var order: list[str] = []
        for group in self.groups:
            if not (group in order):
                order.append(group)
        var brushes: list[int] = []
        var headers: list[str] = []
        for group in order:
            if group != "":
                brushes.append(-1)
                headers.append(group)
            if group != "" and group in self.folded:
                continue
            var index = 0
            while index < self.groups.length:
                if self.groups[index] == group:
                    brushes.append(index)
                    headers.append(group)
                index += 1
        self.line_brushes = brushes
        self.line_groups = headers
        self.box.invalidate()

    ## Where line `line` starts.
    func line_top(self, line: int) -> float:
        var top = 0.0
        var index = 0
        while index < line and index < self.line_brushes.length:
            top += self.header_height if self.line_brushes[index] < 0 else self.row_height
            index += 1
        return top

    ## Where brush `row`'s row shows, scrolled (0 when folded away).
    pub func row_top(self, row: int) -> float:
        var index = 0
        while index < self.line_brushes.length:
            if self.line_brushes[index] == row:
                return self.line_top(index) - self.scroll
            index += 1
        return 0.0

    ## Where `group`'s header starts among the lines, or 0 when none has it.
    pub func group_top(self, group: str) -> float:
        var index = 0
        while index < self.line_brushes.length:
            if self.line_brushes[index] < 0 and self.line_groups[index] == group:
                return self.line_top(index)
            index += 1
        return 0.0

    ## Where names start.
    pub func name_left(self) -> float:
        return 8.0

    ## How many strokes one frame draws.
    let strokes_per_frame: int = 6

    ## Brush `row`'s stroke, drawn now (an empty image when it has none).
    func make_thumbnail(self, row: int) -> unit!:
        var image = Image(1, 1)
        if let draw = self.stroke:
            let stroke = draw(row) catch _:
                recover b""
            if stroke.length > 0:
                image = Image(stroke_width, stroke_height)
                image.write(stroke)
        self.thumbnails[row] = image

    ## Up to `strokes_per_frame` missing strokes drawn, rows between `top` and
    ## `bottom` first; whether any row still waits for one.
    func draw_some_thumbnails(self, top: float, bottom: float) -> bool!:
        var budget = self.strokes_per_frame
        var waiting = false
        for pass in [0, 1]:
            var y = 0.0
            for row in self.line_brushes:
                let height = self.header_height if row < 0 else self.row_height
                let seen = y + height >= top and y <= bottom
                y += height
                if row < 0 or row in self.thumbnails or (pass == 0 and not seen):
                    continue
                if budget == 0:
                    waiting = true
                    continue
                self.make_thumbnail(row)
                budget -= 1
        return waiting

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        let size = target.size()
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.surface())
        let focused = self.box.contains_focus()
        self.shown_height = size.height
        let whole = self.line_top(self.line_brushes.length)
        self.scroll = math.max(0.0, math.min(self.scroll, whole - size.height))
        let waiting = self.draw_some_thumbnails(self.scroll, self.scroll + size.height)
        var top = -self.scroll
        var line = 0
        while line < self.line_brushes.length:
            let row = self.line_brushes[line]
            let height = self.header_height if row < 0 else self.row_height
            if top + height < 0.0 or top > size.height:
                top += height
                line += 1
                continue
            if row < 0:
                let group = self.line_groups[line]
                painter.rectangle(Rect(0.0, top, size.width, self.header_height), theme.surface_raised())
                let mark = "▸" if group in self.folded else "▾"
                painter.text(f"{mark} {group}", self.name_left(), top + 4.0, theme.text(), self.font)
                painter.rectangle(Rect(0.0, top + self.header_height - 1.0, size.width, 1.0), theme.border())
                top += self.header_height
                line += 1
                continue
            let picked = row == self.selected
            if picked:
                let look = self.look()
                painter.rectangle(Rect(0.0, top, size.width, self.row_height), look.accent if focused else look.selection_inactive)
            let ink = theme.on_accent() if picked and focused else theme.text()
            painter.text(self.names[row], self.name_left(), top + 5.0, ink, self.font)
            if let image = self.thumbnails[row]:
                if image.width() > 1:
                    painter.image(image, Rect(8.0, top + 20.0, float(stroke_width), float(stroke_height)))
            painter.rectangle(Rect(0.0, top + self.row_height - 1.0, size.width, 1.0), theme.border())
            top += self.row_height
            line += 1
        # The bar: a thumb as tall as the part showing, where it shows.
        if whole > size.height:
            let thumb = math.max(16.0, size.height * size.height / whole)
            let at = (size.height - thumb) * self.scroll / (whole - size.height)
            painter.rectangle(Rect(size.width - 6.0, at, 4.0, thumb), theme.border())
        painter.close()
        # The rest next frame.
        if waiting:
            self.box.invalidate()

    ## The line at `y` in the box, or -1.
    func line_at(self, y: float) -> int:
        var top = -self.scroll
        var line = 0
        while line < self.line_brushes.length:
            let bottom = top + (self.header_height if self.line_brushes[line] < 0 else self.row_height)
            if y >= top and y < bottom:
                return line
            top = bottom
            line += 1
        return -1

    pub func event(self, event: Event) -> unit!:
        if event.kind == EventKind.scroll:
            # A notched wheel moves in lines of 24 points, a touchpad by its points.
            let step = 24.0 if event.scroll_unit == ScrollUnit.lines else 1.0
            self.scroll_to(self.scroll - event.scroll_y * step)
            return
        if event.kind != EventKind.pointer_down or event.button != 0 or not event.inside:
            return
        self.box.request_focus()
        let line = self.line_at(event.y)
        if line < 0:
            return
        let row = self.line_brushes[line]
        if row < 0:
            self.toggle_group(self.line_groups[line])
            return
        let now = time.now() // 1000000
        let again = row == self.last_row and now - self.last_time <= 400
        self.last_row = row
        self.last_time = now
        self.selected = row
        self.box.invalidate()
        if again and row >= self.first_saved and event.y - self.row_top(row) < 20.0:
            self.last_row = -1
            if let rename = self.on_rename:
                rename(row, self.name_left(), self.row_top(row) + 2.0)
            return
        if let pick = self.on_pick:
            pick(row)