dymokomi/luce-ui
Source of release 0.19.0
0.19.0 / src / widgets / thumbnail_grid.lucb
## The ThumbnailGrid widget: a photo library's grid of square cells, each showing
## a picture fitted inside it with badges for a rating, a pick or reject flag, a
## color label and an "edited" mark. Like TableView it is virtualized: it keeps
## only the counts 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 cell size 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 theme import Theme
from widgets.table_selection import RowSelection
import icons
## The smallest and largest cell side, 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
## Two presses on one cell 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
pub struct ThumbnailGrid: Widget:
let box: interop.Reference[Layout]
var pictures: (interop.Reference[Image]?)[]
var badges: Badges[]
var count: usize
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]
## The cell last pressed and when, for double-clicks.
var pressed_index: i64
var pressed_at: u64
## A grid of `count` items in cells `cell` points wide. `multiple` lets
## command-click, shift-click, shift-arrows and command-A select several.
pub func init(count: i64 = 0, cell: f64 = 160.0, multiple: bool = true) -> !:
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 picked = try RowSelection(items, multiple)
self.box = box
self.pictures = pictures
self.badges = badges
self.count = items
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.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
try self.picked.resize(items)
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
self.pictures = pictures
self.badges = badges
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
## 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.
pub func set_badges(index: i64, rating: i64, flag: i64, label: i64, edited: bool) -> !:
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)
self.box.value().invalidate()
# mark: geometry ============================================================================
## The cell side the grid aims for, in points.
pub func cell_size() -> f64:
return self.cell
## Aim for cells `cell` points wide (48–640); whole columns fill the width.
pub func set_cell_size(cell: f64):
let first = self.first_visible()
self.cell = math.clamp(cell, thumbnail_grid_minimum, thumbnail_grid_maximum)
# Keep the first visible item at the top while the cells change size.
self.scroll = math.clamp((f64)((first // self.columns())) * self.side(), 0.0, self.scroll_limit())
self.box.value().invalidate()
## How many columns fit the current width.
pub func columns() -> i64:
let width = self.box.value().bounds().width
return larger(1, (i64)(width / self.cell))
## The side of a cell as drawn: the width shared evenly by the columns.
func side() -> f64:
let width = self.box.value().bounds().width
return math.max(thumbnail_grid_minimum * 0.5, width / (f64)self.columns())
func rows() -> i64:
let columns = self.columns()
return ((i64)self.count + columns - 1) // columns
func scroll_limit() -> f64:
let content = (f64)self.rows() * self.side()
return math.max(0.0, content - self.box.value().bounds().height)
## The first item whose cell shows, and one past the last (empty when the
## grid is not laid out yet).
pub func first_visible() -> i64:
let side = self.side()
let row = (i64)(self.scroll / side)
return smaller((i64)self.count, row * self.columns())
pub func last_visible() -> i64:
let side = self.side()
let height = self.box.value().bounds().height
let row = (i64)((self.scroll + height) / side) + 1
return smaller((i64)self.count, row * self.columns())
## The item under the local point (`x`, `y`), or -1.
pub func item_at(x: f64, y: f64) -> i64:
let side = self.side()
if x < 0.0 or y < 0.0 or x >= side * (f64)self.columns():
return -1
let index = (i64)((y + self.scroll) / side) * self.columns() + (i64)(x / side)
return index if index < (i64)self.count else -1
## Scroll item `index` into view.
pub func reveal(index: i64):
if index < 0 or index >= (i64)self.count:
return
let side = self.side()
let top = (f64)(index // self.columns()) * side
let height = self.box.value().bounds().height
if top < self.scroll:
self.scroll = top
elif top + side > self.scroll + height:
self.scroll = math.max(0.0, top + side - 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 side = self.side()
let columns = self.columns()
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:
let x = (f64)(index % columns) * side
let y = (f64)(index // columns) * side - self.scroll
try self.paint_cell(&painter, index, gpu.Rect(x, y, side, side), 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 = (f64)self.rows() * side
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 cell: a frame, the picture fitted inside with a margin, the badges, and
## the selection outline.
func paint_cell(painter: Painter*, index: i64, frame: gpu.Rect, hovered: bool, theme: Theme) -> !:
let at = (usize)index
let chosen = self.picked.contains(index)
let margin = math.max(3.0, frame.width * 0.06)
let inner = gpu.Rect(frame.x + 2.0, frame.y + 2.0, frame.width - 4.0, frame.height - 4.0)
if chosen:
try painter.rectangle(inner, theme.raised)
elif hovered:
try painter.rectangle(inner, theme.hover())
let badge = self.badges[at]
let room = gpu.Rect(frame.x + margin, frame.y + margin, frame.width - margin * 2.0, frame.height - margin * 2.0)
if let held = self.pictures[at]:
let picture = held.value()
let fitted = fit(room, (f64)picture.width(), (f64)picture.height())
try painter.image(held, fitted, opacity = 0.35 if badge.flag < 0 else 1.0)
else:
try painter.rectangle(gpu.Rect(room.x + room.width * 0.1, room.y + room.height * 0.2, room.width * 0.8, room.height * 0.6), theme.sunken)
try self.paint_badges(painter, badge, room, theme)
if chosen:
let edge = 2.0 if index == self.picked.lead else 1.0
try outline(painter, inner, edge, theme.accent)
func paint_badges(painter: Painter*, badge: Badges, room: gpu.Rect, theme: Theme) -> !:
let mark = math.clamp(room.width * 0.07, 7.0, 14.0)
if badge.rating > 0:
for star in 0..<(usize)badge.rating:
let cx = room.x + mark * 0.7 + (f64)star * mark * 1.15
let cy = room.y + room.height - mark * 0.7
try paint_star(painter, cx, cy, mark * 0.55, theme.foreground)
if badge.label > 0:
try painter.rounded_rectangle(gpu.Rect(room.x + 3.0, room.y + 3.0, mark, mark), label_color(badge.label), mark * 0.25)
if badge.flag > 0:
try icons.draw_named(painter, "flag", gpu.Rect(room.x + room.width - mark * 1.6, room.y + 2.0, mark * 1.4, mark * 1.4), theme.accent)
elif badge.flag < 0:
try icons.draw_named(painter, "close", gpu.Rect(room.x + room.width - mark * 1.6, room.y + 2.0, mark * 1.4, mark * 1.4), theme.muted)
if badge.edited:
try icons.draw_named(painter, "color-correction", gpu.Rect(room.x + room.width - mark * 1.6, room.y + room.height - mark * 1.6, mark * 1.4, mark * 1.4), theme.muted)
# 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.side() * 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
let columns = self.columns()
let page = larger(1, (i64)(self.box.value().bounds().height / self.side())) * columns
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 = smaller(last, lead + columns) if lead >= 0 else 0
elif event.key == input.Key.up:
target = larger(0, lead - columns) if lead >= 0 else 0
elif event.key == input.Key.page_down:
target = smaller(last, larger(0, lead) + page)
elif event.key == input.Key.page_up:
target = 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
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
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.box.release()
func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
self.box.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
## `room` shrunk to a `width` by `height` picture's aspect, centered.
func fit(room: gpu.Rect, width: f64, height: f64) -> gpu.Rect:
if width <= 0.0 or height <= 0.0:
return room
let scale = math.min(room.width / width, room.height / height)
let w = width * scale
let h = height * scale
return gpu.Rect(room.x + (room.width - w) * 0.5, room.y + (room.height - h) * 0.5, w, h)
## 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 "fitting keeps the aspect, centered":
let fitted = fit(gpu.Rect(0.0, 0.0, 100.0, 100.0), 300.0, 200.0)
assert(fitted.width == 100.0 and math.abs(fitted.height - 200.0 / 3.0) < 1.0e-9)
assert(fitted.x == 0.0 and math.abs(fitted.y - 50.0 / 3.0) < 1.0e-9)
let tall = fit(gpu.Rect(10.0, 10.0, 80.0, 80.0), 100.0, 200.0)
assert(tall.width == 40.0 and tall.height == 80.0 and tall.x == 30.0 and tall.y == 10.0)
test "counts are checked":
_ = checked_count(-1) catch failure:
assert(failure.code == result.invalid)
recover 0
assert((try checked_count(5)) == 5)