Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ui

Source of release 0.19.3

0.19.3 / src / widgets / thumbnail_grid.lucb

## The ThumbnailGrid widget: a photo library's grid. Items lie in justified rows
## (justified_rows.lucb): each tile has its photo's aspect ratio (`set_aspect`;
## square until told) and is filled by its picture, and every full row spans the
## width. Badges show a rating, a pick or reject flag, a color label, an
## "edited" mark and a RAW chip for camera raws. Like TableView it is virtualized: it keeps only the aspects
## and badges of every item, and holds pictures for the items the application
## hands it, typically those near the visible range, which it reports. The row
## height scales between 48 and 640 points (command-scroll or a pinch, or
## `set_cell_size`); selection follows Finder: click, command-click, shift-click,
## arrows (with shift), command-A; a double-click or Enter activates.
from luce_gpu import gpu
from luce_window import input
import interop
from luce_std import math
import memory
import ownership
import layout
import result
import time
from layout import Widget, Layout, Size, Constraints, Event
from painter import Painter
from geometry import Point
from image import Image
from font import Font, selected_font
from theme import Theme
from widgets.table_selection import RowSelection
from widgets.justified_rows import JustifiedRows
import icons

## The smallest and largest row height, in points.
pub let thumbnail_grid_minimum: f64 = 48.0
pub let thumbnail_grid_maximum: f64 = 640.0
## The most items a grid holds.
pub let thumbnail_grid_items: i64 = 1048576

## The space between tiles and around them, in points.
let gap: f64 = 4.0
## The narrowest and widest aspect ratio a tile takes.
let thinnest: f64 = 0.2
let widest: f64 = 5.0

## Two presses on one tile within this many nanoseconds are a double-click.
let double_click: u64 = 400000000

## What the grid shows over one item's picture.
struct Badges:
    var rating: u8
    var flag: i8
    var label: u8
    var edited: bool
    var raw: bool

pub struct ThumbnailGrid: Widget:
    let box: interop.Reference[Layout]
    var pictures: (interop.Reference[Image]?)[]
    var badges: Badges[]
    var aspects: f32[]
    var count: usize
    ## The rows, and what they were laid out for: a width, a row height, and
    ## whether an aspect changed since.
    var rows: JustifiedRows
    var laid_width: f64
    var laid_cell: f64
    var stale: bool
    var picked: RowSelection
    var cell: f64
    var scroll: f64
    let selected: interop.Signal[i64]
    let activated: interop.Signal[i64]
    let resized: interop.Signal[i64]
    let dropped: interop.Signal[unit]
    let font: interop.Reference[Font]
    ## The cell last pressed and when, for double-clicks.
    var pressed_index: i64
    var pressed_at: u64

    ## A grid of `count` items in rows `cell` points tall. `multiple` lets
    ## command-click, shift-click, shift-arrows and command-A select several;
    ## `font` sets the badges' text.
    pub func init(count: i64 = 0, cell: f64 = 160.0, multiple: bool = true, font: interop.Reference[Font]? = none) -> !:
        var selected_text = try selected_font(font)
        errdefer selected_text.release()
        let box = try layout.make_layout()
        errdefer box.release()
        box.value().set_focusable(true)
        box.value().set_takes_scroll(true)
        box.value().set_cursor(input.Cursor.pointer)
        try box.value().set_flex()
        try box.value().set_limits(Size(120.0, 120.0), Size(16384.0, 16384.0))
        let selected = try interop.Signal[i64]()
        errdefer selected.release()
        let activated = try interop.Signal[i64]()
        errdefer activated.release()
        let resized = try interop.Signal[i64]()
        errdefer resized.release()
        let dropped = try interop.Signal[unit]()
        errdefer dropped.release()
        let items = try checked_count(count)
        let pictures = try new (interop.Reference[Image]?)[items] in memory.heap
        errdefer free(pictures) in memory.heap
        let badges = try new Badges[items] in memory.heap
        errdefer free(badges) in memory.heap
        let aspects = try new f32[items] in memory.heap
        errdefer free(aspects) in memory.heap
        for at in 0..<items:
            aspects[at] = 1.0
        var rows = try JustifiedRows.make(items)
        errdefer rows.destroy()
        let picked = try RowSelection(items, multiple)
        self.box = box
        self.pictures = pictures
        self.badges = badges
        self.aspects = aspects
        self.count = items
        self.rows = rows
        self.laid_width = -1.0
        self.laid_cell = -1.0
        self.stale = true
        self.picked = picked
        self.cell = math.clamp(cell, thumbnail_grid_minimum, thumbnail_grid_maximum)
        self.scroll = 0.0
        self.selected = selected
        self.activated = activated
        self.resized = resized
        self.dropped = dropped
        self.font = selected_text
        self.pressed_index = -1
        self.pressed_at = 0

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

    # mark: the items ===========================================================================

    ## How many items the grid shows.
    pub func item_count() -> i64:
        return (i64)self.count

    ## Show `count` items. Items still in range keep their pictures, badges and
    ## selection; the rest are dropped.
    pub func set_count(count: i64) -> !:
        let items = try checked_count(count)
        let pictures = try new (interop.Reference[Image]?)[items] in memory.heap
        errdefer free(pictures) in memory.heap
        let badges = try new Badges[items] in memory.heap
        errdefer free(badges) in memory.heap
        let aspects = try new f32[items] in memory.heap
        errdefer free(aspects) in memory.heap
        var rows = try JustifiedRows.make(items)
        errdefer rows.destroy()
        try self.picked.resize(items)
        for at in 0..<items:
            aspects[at] = self.aspects[at] if at < self.count else 1.0
        for at in 0..<self.count:
            if at < items:
                pictures[at] = self.pictures[at]
                badges[at] = self.badges[at]
            elif let held = self.pictures[at]:
                held.release()
        free(self.pictures) in memory.heap
        free(self.badges) in memory.heap
        free(self.aspects) in memory.heap
        self.rows.destroy()
        self.pictures = pictures
        self.badges = badges
        self.aspects = aspects
        self.rows = rows
        self.stale = true
        self.count = items
        self.scroll = math.clamp(self.scroll, 0.0, self.scroll_limit())
        self.box.value().invalidate()

    ## Show `picture` in item `index`'s cell; the grid keeps a reference to it.
    pub func set_image(index: i64, picture: interop.Reference[Image]) -> !:
        let at = try self.checked(index)
        let kept = picture.clone()
        if let held = self.pictures[at]:
            held.release()
        self.pictures[at] = kept
        self.box.value().invalidate()

    ## Forget item `index`'s picture: its cell shows an empty frame.
    pub func clear_image(index: i64) -> !:
        let at = try self.checked(index)
        if let held = self.pictures[at]:
            held.release()
        self.pictures[at] = none
        self.box.value().invalidate()

    ## Whether item `index` has a picture.
    pub func has_image(index: i64) -> bool:
        if index < 0 or index >= (i64)self.count:
            return false
        return self.pictures[(usize)index] != none

    ## Forget the pictures of every item outside `first..<last`: what a library
    ## calls after scrolling, with a margin around the visible range.
    pub func keep_images(first: i64, last: i64):
        for at in 0..<self.count:
            if (i64)at < first or (i64)at >= last:
                if let held = self.pictures[at]:
                    held.release()
                    self.pictures[at] = none

    ## Give item `index`'s tile the aspect ratio `ratio` (width over height, kept
    ## within 1:5 and 5:1): its photo's, as shown.
    pub func set_aspect(index: i64, ratio: f64) -> !:
        let at = try self.checked(index)
        if not math.is_finite(ratio) or ratio <= 0.0:
            error(result.invalid, "a thumbnail's aspect ratio must be positive")
        let kept = (f32)math.clamp(ratio, thinnest, widest)
        if kept != self.aspects[at]:
            self.aspects[at] = kept
            self.stale = true
            self.box.value().invalidate()

    ## Item `index`'s badges: `rating` 0–5 stars, `flag` 1 picked, -1 rejected
    ## (drawn faded), 0 neither; `label` 0 none, 1–7 red, orange, yellow, green,
    ## blue, purple, grey; `edited` marks a photo with adjustments, `raw` a camera raw.
    pub func set_badges(index: i64, rating: i64, flag: i64, label: i64, edited: bool, raw: bool = false) -> !:
        let at = try self.checked(index)
        if rating < 0 or rating > 5 or flag < -1 or flag > 1 or label < 0 or label > 7:
            error(result.invalid, "thumbnail badges are out of range")
        self.badges[at] = Badges(rating = (u8)rating, flag = (i8)flag, label = (u8)label, edited = edited, raw = raw)
        self.box.value().invalidate()

    # mark: geometry ============================================================================

    ## The row height the grid aims for, in points.
    pub func cell_size() -> f64:
        return self.cell

    ## Aim for rows `cell` points tall (48–640), keeping the first visible item
    ## in view while the tiles change size.
    pub func set_cell_size(cell: f64):
        let first = self.first_visible()
        self.cell = math.clamp(cell, thumbnail_grid_minimum, thumbnail_grid_maximum)
        self.arranged()
        if first >= 0 and first < (i64)self.count:
            self.scroll = math.clamp(self.rows.top_of(self.rows.row_of(first)) - gap, 0.0, self.scroll_limit())
        self.box.value().invalidate()

    ## About how many items a row holds: for prefetching a few rows around the screen.
    pub func columns() -> i64:
        self.arranged()
        if self.rows.rows == 0:
            return larger(1, (i64)(self.box.value().bounds().width / self.cell))
        return larger(1, ((i64)self.count + (i64)self.rows.rows - 1) // (i64)self.rows.rows)

    ## Lay the rows out again when the width, the row height or an aspect changed.
    func arranged():
        let width = self.box.value().bounds().width
        if not self.stale and width == self.laid_width and self.cell == self.laid_cell:
            return
        self.rows.arrange(self.aspects, width, self.cell, gap)
        self.laid_width = width
        self.laid_cell = self.cell
        self.stale = false

    func scroll_limit() -> f64:
        self.arranged()
        return math.max(0.0, self.rows.content - self.box.value().bounds().height)

    ## The first item whose tile shows, and one past the last (empty when the
    ## grid is not laid out yet).
    pub func first_visible() -> i64:
        self.arranged()
        let row = self.rows.row_at(self.scroll)
        return self.rows.first_of(row) if row >= 0 else 0

    pub func last_visible() -> i64:
        self.arranged()
        let row = self.rows.row_at(self.scroll + self.box.value().bounds().height)
        return self.rows.end_of(row) if row >= 0 else 0

    ## The item under the local point (`x`, `y`), or -1.
    pub func item_at(x: f64, y: f64) -> i64:
        self.arranged()
        return self.rows.item_at(x, y + self.scroll)

    ## Where item `index`'s tile is, in local points.
    func tile(index: i64) -> gpu.Rect:
        let row = self.rows.row_of(index)
        return gpu.Rect(self.rows.x_of(index), self.rows.top_of(row) - self.scroll, self.rows.width_of(index), self.rows.height_of(row))

    ## Scroll item `index` into view.
    pub func reveal(index: i64):
        if index < 0 or index >= (i64)self.count:
            return
        self.arranged()
        let row = self.rows.row_of(index)
        let top = self.rows.top_of(row) - gap
        let bottom = self.rows.top_of(row) + self.rows.height_of(row) + gap
        let height = self.box.value().bounds().height
        if top < self.scroll:
            self.scroll = math.max(0.0, top)
        elif bottom > self.scroll + height:
            self.scroll = math.max(0.0, bottom - height)
        self.box.value().invalidate()

    # mark: selection ===========================================================================

    ## The lead selected item (the one last clicked or moved to), or -1.
    pub func selected_index() -> i64:
        return self.picked.lead

    pub func is_selected(index: i64) -> bool:
        return self.picked.contains(index)

    pub func selected_count() -> i64:
        return (i64)self.picked.count()

    ## Select item `index` alone (-1 for none) and scroll it into view. No signal.
    pub func select(index: i64) -> !:
        try self.picked.only(index)
        self.reveal(index)

    ## Mark item `index` selected or not, keeping the lead. No signal.
    pub func mark(index: i64, on: bool) -> !:
        try self.picked.mark(index, on)
        self.box.value().invalidate()

    pub func select_all():
        self.picked.all()
        self.box.value().invalidate()

    ## Called with the lead item whenever the user changes the selection.
    pub func on_select(callback: interop.Callback[i64, unit]) -> interop.Reference[interop.Connection]!:
        return try self.selected.connect(callback)

    ## Called with the item a double-click or Enter opens.
    pub func on_activate(callback: interop.Callback[i64, unit]) -> interop.Reference[interop.Connection]!:
        return try self.activated.connect(callback)

    ## Called with the new cell size (rounded points) when the user zooms the grid.
    pub func on_resize(callback: interop.Callback[i64, unit]) -> interop.Reference[interop.Connection]!:
        return try self.resized.connect(callback)

    ## Called when files are dropped on the grid; `drop_count` and `drop_path`
    ## on its layout name them. Dropping is enabled by connecting.
    pub func on_drop(callback: interop.Callback[unit, unit]) -> interop.Reference[interop.Connection]!:
        self.box.value().set_drop_target(true)
        return try self.dropped.connect(callback)

    # mark: drawing =============================================================================

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

    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()
        try painter.rectangle(gpu.Rect(width = size.width, height = size.height), theme.background)
        self.scroll = math.clamp(self.scroll, 0.0, self.scroll_limit())
        let hovered = self.item_at(self.box.value().pointer_position().x, self.box.value().pointer_position().y) if self.box.value().contains_pointer() else -1
        var index = self.first_visible()
        let last = self.last_visible()
        while index < last:
            try self.paint_tile(&painter, index, self.tile(index), index == hovered, theme)
            index += 1
        if self.box.value().is_focused():
            try painter.rectangle(gpu.Rect(width = size.width, height = 1.0), theme.accent)
        let content = self.rows.content
        if content > size.height and size.height > 0.0:
            let thumb = math.max(24.0, size.height * size.height / content)
            let position = self.scroll / math.max(1.0, content - size.height) * math.max(0.0, size.height - thumb)
            try painter.rectangle(gpu.Rect(math.max(0.0, size.width - 6.0), position, 4.0, thumb), theme.border)

    ## One tile: the picture filling it (cropped to the tile should their shapes
    ## differ), the badges over it, and the selection's frame around it.
    func paint_tile(painter: Painter*, index: i64, frame: gpu.Rect, hovered: bool, theme: Theme) -> !:
        let at = (usize)index
        let chosen = self.picked.contains(index)
        let badge = self.badges[at]
        if let held = self.pictures[at]:
            let picture = held.value()
            try painter.image(held, frame, source = cover(frame, picture.width(), picture.height()), opacity = 0.35 if badge.flag < 0 else 1.0)
        else:
            try painter.rectangle(frame, theme.sunken)
        if hovered and not chosen:
            try painter.rectangle(frame, theme.foreground, opacity = 0.08)
        try self.paint_badges(painter, badge, frame, theme)
        if chosen:
            let edge = 3.0 if index == self.picked.lead else 2.0
            try outline(painter, gpu.Rect(frame.x - edge, frame.y - edge, frame.width + edge * 2.0, frame.height + edge * 2.0), edge, theme.accent)

    ## The badges inside `room`, each on a dark chip so it reads over any photo.
    func paint_badges(painter: Painter*, badge: Badges, room: gpu.Rect, theme: Theme) -> !:
        let mark = math.clamp(room.height * 0.07, 7.0, 14.0)
        let chip = gpu.Color(0.0, 0.0, 0.0)
        if badge.rating > 0:
            let stars = (f64)badge.rating
            try painter.rounded_rectangle(gpu.Rect(room.x + 3.0, room.y + room.height - mark * 1.4 - 3.0, mark * (0.5 + stars * 1.15), mark * 1.4), chip, mark * 0.3, opacity = 0.5)
            for star in 0..<(usize)badge.rating:
                let cx = room.x + 3.0 + mark * 0.82 + (f64)star * mark * 1.15
                let cy = room.y + room.height - mark * 0.7 - 3.0
                try paint_star(painter, cx, cy, mark * 0.55, theme.foreground)
        var left = room.x + 4.0
        if badge.label > 0:
            try painter.rounded_rectangle(gpu.Rect(left, room.y + 4.0, mark, mark), label_color(badge.label), mark * 0.25)
            left += mark + 4.0
        if badge.raw and room.width > mark * 6.0:
            # A RAW chip in the top-left corner, beside the label.
            let height = self.font.value().line_height()
            let width = try self.font.value().measure("RAW") + 8.0
            try painter.rounded_rectangle(gpu.Rect(left, room.y + 3.0, width, height), chip, 3.0, opacity = 0.65)
            try painter.text("RAW", left + 4.0, room.y + 3.0 + math.floor((height - self.font.value().height()) * 0.5), theme.foreground, self.font)
        let corner = gpu.Rect(room.x + room.width - mark * 1.8 - 3.0, room.y + 3.0, mark * 1.8, mark * 1.8)
        if badge.flag != 0:
            try painter.rounded_rectangle(corner, chip, mark * 0.3, opacity = 0.5)
            try icons.draw_named(painter, "flag" if badge.flag > 0 else "close", gpu.Rect(corner.x + mark * 0.2, corner.y + mark * 0.2, mark * 1.4, mark * 1.4), theme.accent if badge.flag > 0 else theme.foreground)
        if badge.edited:
            let place = gpu.Rect(corner.x, room.y + room.height - mark * 1.8 - 3.0, mark * 1.8, mark * 1.8)
            try painter.rounded_rectangle(place, chip, mark * 0.3, opacity = 0.5)
            try icons.draw_named(painter, "color-correction", gpu.Rect(place.x + mark * 0.2, place.y + mark * 0.2, mark * 1.4, mark * 1.4), theme.foreground)

    # mark: input ===============================================================================

    pub func event(event: Event) -> interop.Outcome[unit]:
        let lead_before = self.picked.lead
        let count_before = self.picked.count()
        let outcome = self.handle(event) catch failure:
            return result.failure[unit](failure.code, failure.message)
        if outcome == 1:
            return self.activated.emit(self.picked.lead)
        if outcome == 2:
            return self.resized.emit((i64)(self.cell + 0.5))
        if outcome == 3:
            return self.dropped.emit(())
        if self.picked.lead != lead_before or self.picked.count() != count_before or outcome == 4:
            return self.selected.emit(self.picked.lead)
        return result.success[unit](())

    ## What an event did: 0 nothing to report (or only a selection change, found
    ## by comparing), 1 activate, 2 resized, 3 dropped, 4 the selection changed
    ## without changing its lead or count.
    func handle(event: Event) -> i64!:
        if event.cancelled:
            return 0
        match event.kind:
            .pointer_moved:
                self.box.value().invalidate()
            .drop:
                return 3
            .magnify:
                self.set_cell_size(self.cell * (1.0 + event.scroll_y))
                return 2
            .scroll:
                if event.meta or event.control:
                    let steps = event.scroll_y if event.scroll_unit == input.ScrollUnit.lines else event.scroll_y / 20.0
                    self.set_cell_size(self.cell * math.pow(1.1, steps))
                    return 2
                let scale = 1.0 if event.scroll_unit == input.ScrollUnit.points else self.cell * 0.5
                self.scroll = math.clamp(self.scroll - event.scroll_y * scale, 0.0, self.scroll_limit())
                self.box.value().invalidate()
            .pointer_down:
                if (event.button == 0 or event.button == 1) and event.inside:
                    return try self.press(event)
            .key_down:
                return try self.key(event)
            _:
                return 0
        return 0

    func press(event: Event) -> i64!:
        let index = self.item_at(event.x, event.y)
        if index < 0:
            if event.button == 0 and not (event.shift or event.meta or event.control):
                try self.picked.only(-1)
                self.box.value().invalidate()
            return 0
        if event.button == 1:
            # A right-click on a selected item keeps the selection for its menu.
            if not self.picked.contains(index):
                try self.select(index)
            return 0
        let moment = time.now()
        let repeated = index == self.pressed_index and moment - self.pressed_at < double_click
        self.pressed_index = -1 if repeated else index
        self.pressed_at = moment
        if event.shift:
            try self.picked.extend(index)
        elif event.meta or event.control:
            try self.picked.toggle(index)
            return 4
        else:
            try self.picked.only(index)
        self.reveal(index)
        return 1 if repeated else 0

    func key(event: Event) -> i64!:
        let lead = self.picked.lead
        if event.key == input.Key.enter and lead >= 0:
            return 1
        if self.count == 0:
            return 0
        if event.key == input.Key.a and (event.meta or event.control):
            self.select_all()
            return 4
        self.arranged()
        let page = larger(1, (i64)(self.box.value().bounds().height / self.cell))
        let last = (i64)self.count - 1
        var target: i64 = -1
        if event.key == input.Key.right:
            target = smaller(last, lead + 1)
        elif event.key == input.Key.left:
            target = larger(0, lead - 1)
        elif event.key == input.Key.down:
            target = self.row_step(lead, 1) if lead >= 0 else 0
        elif event.key == input.Key.up:
            target = self.row_step(lead, -1) if lead >= 0 else 0
        elif event.key == input.Key.page_down:
            target = self.row_step(larger(0, lead), page)
        elif event.key == input.Key.page_up:
            target = self.row_step(larger(0, lead), -page)
        elif event.key == input.Key.home:
            target = 0
        elif event.key == input.Key.end:
            target = last
        if target < 0:
            return 0
        if event.shift:
            try self.picked.extend(target)
        else:
            try self.picked.only(target)
        self.reveal(target)
        return 0

    ## The item `rows` rows from `item` (clamped to the first and last rows)
    ## nearest below its middle.
    func row_step(item: i64, rows: i64) -> i64:
        let row = self.rows.row_of(item)
        let target = larger(0, smaller((i64)self.rows.rows - 1, row + rows))
        if target == row:
            return item
        return self.rows.nearest_in(target, self.rows.x_of(item) + self.rows.width_of(item) * 0.5)

    func checked(index: i64) -> usize!:
        if index < 0 or index >= (i64)self.count:
            error(result.invalid, "no such thumbnail")
        return (usize)index

    pub func close():
        for at in 0..<self.count:
            if let held = self.pictures[at]:
                held.release()
        free(self.pictures) in memory.heap
        free(self.badges) in memory.heap
        free(self.aspects) in memory.heap
        self.rows.destroy()
        self.count = 0
        self.picked.close()
        self.selected.close()
        self.selected.release()
        self.activated.close()
        self.activated.release()
        self.resized.close()
        self.resized.release()
        self.dropped.close()
        self.dropped.release()
        self.font.release()
        self.box.release()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        self.box.trace(visit, context)
        self.font.trace(visit, context)
        self.selected.trace(visit, context)
        self.activated.trace(visit, context)
        self.resized.trace(visit, context)
        self.dropped.trace(visit, context)
        for at in 0..<self.count:
            if let held = self.pictures[at]:
                held.trace(visit, context)

func smaller(a: i64, b: i64) -> i64:
    return a if a < b else b

func larger(a: i64, b: i64) -> i64:
    return a if a > b else b

func checked_count(count: i64) -> usize!:
    if count < 0 or count > thumbnail_grid_items:
        error(result.invalid, "a thumbnail grid holds 0 to 1048576 items")
    return (usize)count

## The part of a `width` × `height` picture that fills `frame` without
## stretching: all of it when the shapes match, else its middle, cropped.
func cover(frame: gpu.Rect, width: i64, height: i64) -> gpu.Region:
    let wide = (u32)larger(0, width)
    let high = (u32)larger(0, height)
    if wide == 0 or high == 0 or frame.width <= 0.0 or frame.height <= 0.0:
        return gpu.Region(width = wide, height = high)
    let wanted = frame.width / frame.height
    let have = (f64)wide / (f64)high
    if have > wanted:
        let used = (u32)math.max(1.0, (f64)high * wanted)
        return gpu.Region(x = (wide - used) // 2, width = used, height = high)
    let used = (u32)math.max(1.0, (f64)wide / wanted)
    return gpu.Region(y = (high - used) // 2, width = wide, height = used)

## A frame `edge` points thick just inside `rectangle`.
func outline(painter: Painter*, rectangle: gpu.Rect, edge: f64, color: gpu.Color) -> !:
    try painter.rectangle(gpu.Rect(rectangle.x, rectangle.y, rectangle.width, edge), color)
    try painter.rectangle(gpu.Rect(rectangle.x, rectangle.y + rectangle.height - edge, rectangle.width, edge), color)
    try painter.rectangle(gpu.Rect(rectangle.x, rectangle.y, edge, rectangle.height), color)
    try painter.rectangle(gpu.Rect(rectangle.x + rectangle.width - edge, rectangle.y, edge, rectangle.height), color)

## A five-pointed star of outer radius `radius` centered on (`cx`, `cy`).
func paint_star(painter: Painter*, cx: f64, cy: f64, radius: f64, color: gpu.Color) -> !:
    var points: Point[10]
    for at in 0..<(usize)10:
        let angle = -math.pi * 0.5 + (f64)at * math.pi / 5.0
        let reach = radius if at % 2 == 0 else radius * 0.45
        points[at] = Point(cx + math.cos(angle) * reach, cy + math.sin(angle) * reach)
    for at in 0..<(usize)10:
        try painter.triangle(Point(cx, cy), points[at], points[(at + 1) % 10], color)

## A color label's swatch, after Lightroom's and Capture One's: red, orange,
## yellow, green, blue, purple, grey (linear light).
pub func label_color(label: u8) -> gpu.Color:
    return match label:
        1 => gpu.Color(0.72, 0.06, 0.05)
        2 => gpu.Color(0.85, 0.30, 0.03)
        3 => gpu.Color(0.85, 0.66, 0.05)
        4 => gpu.Color(0.10, 0.45, 0.10)
        5 => gpu.Color(0.05, 0.22, 0.75)
        6 => gpu.Color(0.35, 0.08, 0.55)
        7 => gpu.Color(0.30, 0.30, 0.30)
        _ => gpu.Color(0.0, 0.0, 0.0, 0.0)

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

test "covering crops the middle of a picture of another shape":
    let wide = cover(gpu.Rect(0.0, 0.0, 100.0, 100.0), 300, 200)
    assert(wide.x == 50 and wide.y == 0 and wide.width == 200 and wide.height == 200)
    let tall = cover(gpu.Rect(0.0, 0.0, 200.0, 100.0), 100, 200)
    assert(tall.x == 0 and tall.y == 75 and tall.width == 100 and tall.height == 50)
    let same = cover(gpu.Rect(0.0, 0.0, 150.0, 100.0), 300, 200)
    assert(same.x == 0 and same.y == 0 and same.width == 300 and same.height == 200)

test "counts are checked":
    _ = checked_count(-1) catch failure:
        assert(failure.code == result.invalid)
        recover 0
    assert((try checked_count(5)) == 5)