dymokomi/luce-ui
Source of release 0.19.6
0.19.6 / 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. With
## `set_drag_kind` the selection drags out to the window's drop areas taking that kind,
## as the items' indices, the lead's picture following the pointer. `set_flow` turns
## it into a filmstrip: lanes of tiles that scroll sideways (strip_lanes.lucb), always
## or while it is twice as wide as tall.
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
from widgets.strip_lanes import StripLanes
from widgets.drag_gesture import DragGesture
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
## Which way a grid lays out and scrolls (`ThumbnailGrid.set_flow`): `vertical` in
## rows across its width, scrolling down; `horizontal` in lanes along its height,
## scrolling sideways like a filmstrip; `automatic` horizontal while the grid is at
## least twice as wide as tall, else vertical.
pub enum GridFlow as u8:
vertical = 0
horizontal = 1
automatic = 2
## 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 (vertical) and lanes (horizontal), and what they were laid out
## for: a size, a row height, a flow, and whether an aspect changed since.
var rows: JustifiedRows
var lanes: StripLanes
var flow_asked: GridFlow
var across: bool
var laid_width: f64
var laid_height: f64
var laid_cell: f64
var stale: bool
var picked: RowSelection
var cell: f64
## How far the content is scrolled along the flow: down, or sideways.
var scroll: f64
let selected: interop.Signal[i64]
let activated: interop.Signal[i64]
let resized: interop.Signal[i64]
let dropped: interop.Signal[unit]
## Told the first visible item when the range on screen changes (`on_visible`).
let visible: interop.Signal[i64]
## The range last told: `first_visible`, `last_visible`; -1 before the first draw.
var shown_first: i64
var shown_last: i64
let font: interop.Reference[Font]
## The cell last pressed and when, for double-clicks.
var pressed_index: i64
var pressed_at: u64
var gesture: DragGesture
## 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 visible = try interop.Signal[i64]()
errdefer visible.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()
var lanes = try StripLanes.make(items)
errdefer lanes.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.lanes = lanes
self.flow_asked = GridFlow.vertical
self.across = false
self.laid_width = -1.0
self.laid_height = -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.visible = visible
self.shown_first = -1
self.shown_last = -1
self.font = selected_text
self.pressed_index = -1
self.pressed_at = 0
self.gesture = DragGesture()
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()
var lanes = try StripLanes.make(items)
errdefer lanes.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.lanes.destroy()
self.pictures = pictures
self.badges = badges
self.aspects = aspects
self.rows = rows
self.lanes = lanes
self.stale = true
self.count = items
self.clamp_scroll()
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 (in the horizontal flow, its
## lanes' height, capped to fit the grid's height).
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.start_of(first) - gap, 0.0, self.scroll_limit())
self.box.value().invalidate()
## The flow asked for (`set_flow`).
pub func flow() -> GridFlow:
return self.flow_asked
## Lay out and scroll as `flow` says (vertical until told). The selection's lead,
## or else the first item on screen, stays in view when the flow changes, now or
## when an automatic grid is resized past 2:1.
pub func set_flow(flow: GridFlow):
self.flow_asked = flow
self.arranged()
self.box.value().invalidate()
## Whether the grid is laid out sideways now: its flow is horizontal, or
## automatic and the grid twice as wide as tall.
pub func is_horizontal() -> bool:
self.arranged()
return self.across
## About how many items a row holds (in the horizontal flow, how many lanes the
## strip has): for prefetching a few rows around the screen.
pub func columns() -> i64:
self.arranged()
if self.across:
return (i64)self.lanes.lanes
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 items out again when the row height, the flow, an aspect or the side
## the flow lays out across (the width, or the height when horizontal) changed.
## A new size or flow moves the tiles, so the view follows an anchor: the lead,
## when the flow turns or the lead was on screen, else the first item that was.
func arranged():
let bounds = self.box.value().bounds()
let across = self.flow_asked == GridFlow.horizontal or (self.flow_asked == GridFlow.automatic and bounds.height > 0.0 and bounds.width >= bounds.height * 2.0)
let turned = across != self.across
let resized = bounds.height != self.laid_height if across else bounds.width != self.laid_width
if not self.stale and not turned and not resized and self.cell == self.laid_cell:
return
let moved = self.laid_cell > 0.0 and (turned or resized)
var anchor: i64 = -1
var leading = false
if moved:
let lead = self.picked.lead
leading = lead >= 0 and lead < (i64)self.count and (turned or (lead >= self.first_laid() and lead < self.last_laid()))
anchor = lead if leading else self.first_laid()
if across:
self.lanes.arrange(self.aspects, bounds.height, self.cell, gap)
else:
self.rows.arrange(self.aspects, bounds.width, self.cell, gap)
self.across = across
self.laid_width = bounds.width
self.laid_height = bounds.height
self.laid_cell = self.cell
self.stale = false
if turned:
self.scroll = 0.0
if anchor < 0 or anchor >= (i64)self.count:
return
if leading:
self.scroll = self.revealing(anchor)
else:
self.scroll = math.max(0.0, self.start_of(anchor) - gap)
## The length of the scrolled side: the height, or the width when horizontal.
func extent() -> f64:
let bounds = self.box.value().bounds()
return bounds.width if self.across else bounds.height
func content() -> f64:
return self.lanes.content if self.across else self.rows.content
## Keep the scroll within the content, laid out first: laying out may move it.
func clamp_scroll():
let limit = self.scroll_limit()
self.scroll = math.clamp(self.scroll, 0.0, limit)
func scroll_limit() -> f64:
self.arranged()
return math.max(0.0, self.content() - self.extent())
## Where item `index`'s tile is in the content, unscrolled.
func placed(index: i64) -> gpu.Rect:
if self.across:
return gpu.Rect(self.lanes.x_of(index), self.lanes.top_of(self.lanes.lane_of(index)), self.lanes.width_of(index), self.lanes.lane_height)
let row = self.rows.row_of(index)
return gpu.Rect(self.rows.x_of(index), self.rows.top_of(row), self.rows.width_of(index), self.rows.height_of(row))
## Where item `index`'s tile starts and ends along the flow.
func start_of(index: i64) -> f64:
let place = self.placed(index)
return place.x if self.across else place.y
func end_of(index: i64) -> f64:
let place = self.placed(index)
return place.x + place.width if self.across else place.y + place.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()
return self.first_laid()
pub func last_visible() -> i64:
self.arranged()
return self.last_laid()
## `last_visible` in the layout as it is.
func last_laid() -> i64:
if self.across:
return self.lanes.end_before(self.scroll + self.extent())
let row = self.rows.row_at(self.scroll + self.extent())
return self.rows.end_of(row) if row >= 0 else 0
## `first_visible` in the layout as it is, without laying out again.
func first_laid() -> i64:
if self.across:
# none before the strip is first arranged (a new count drops the lanes)
if self.lanes.lanes == 0:
return 0
return smaller(self.lanes.first_after(self.scroll), (i64)self.count)
let row = self.rows.row_at(self.scroll)
return self.rows.first_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()
if self.across:
return self.lanes.item_at(x + self.scroll, y)
return self.rows.item_at(x, y + self.scroll)
## Where item `index`'s tile is, in local points (empty for no such item).
pub func item_rect(index: i64) -> gpu.Rect:
if index < 0 or index >= (i64)self.count:
return gpu.Rect()
self.arranged()
return self.tile(index)
func tile(index: i64) -> gpu.Rect:
let place = self.placed(index)
if self.across:
return gpu.Rect(place.x - self.scroll, place.y, place.width, place.height)
return gpu.Rect(place.x, place.y - self.scroll, place.width, place.height)
## Scroll item `index` into view.
pub func reveal(index: i64):
if index < 0 or index >= (i64)self.count:
return
self.arranged()
self.scroll = self.revealing(index)
self.box.value().invalidate()
## The least scroll from here that shows item `index`.
func revealing(index: i64) -> f64:
let start = self.start_of(index) - gap
let end = self.end_of(index) + gap
let extent = self.extent()
if start < self.scroll:
return math.max(0.0, start)
if end > self.scroll + extent:
return math.max(0.0, end - extent)
return self.scroll
# 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)
## Let the selection be dragged out (`Layout.start_drag`) as items of `kind`: the
## selected items' indices, in order. "" stops it.
pub func set_drag_kind(kind: str) -> !:
try self.gesture.set_kind(kind)
## Called with the first item on screen whenever the range on screen changes: a
## scroll, a resize, a new cell size or count, `reveal`. Read the range with
## `first_visible` and `last_visible` to hand the grid the pictures it needs
## (`set_image`) and let the others go (`keep_images`). It is called once the grid
## has drawn, so it may set images, which show on the next frame.
pub func on_visible(callback: interop.Callback[i64, unit]) -> interop.Reference[interop.Connection]!:
return try self.visible.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)
let first = self.first_visible()
let last = self.last_visible()
if first != self.shown_first or last != self.shown_last:
self.shown_first = first
self.shown_last = last
return self.visible.emit(first)
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.clamp_scroll()
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)
# The scroll bar: along the right edge, or the bottom when horizontal.
let content = self.content()
let extent = size.width if self.across else size.height
if content > extent and extent > 0.0:
let thumb = math.max(24.0, extent * extent / content)
let position = self.scroll / math.max(1.0, content - extent) * math.max(0.0, extent - thumb)
if self.across:
try painter.rectangle(gpu.Rect(position, math.max(0.0, size.height - 6.0), thumb, 4.0), theme.border)
else:
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)
let reselected = self.picked.lead != lead_before or self.picked.count() != count_before or outcome == 4
if reselected:
self.box.value().repaint()
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 reselected:
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:
self.gesture.cancel()
return 0
match event.kind:
.pointer_moved:
# The hovered tile is lit: a move draws only when it reaches another.
self.box.value().hover_part(self.item_at(event.x, event.y))
if self.gesture.moved(event.x, event.y):
try self.start_drag()
.pointer_up:
if event.button == 0:
let alone = self.gesture.release()
if alone >= 0:
try self.picked.only(alone)
self.box.value().repaint()
return 4
.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.arranged()
# A filmstrip has nothing to scroll down: a vertical wheel scrolls it sideways.
let delta = event.scroll_x + event.scroll_y if self.across else event.scroll_y
self.scroll = math.clamp(self.scroll - delta * scale, 0.0, self.scroll_limit())
self.box.value().repaint()
.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)
self.gesture.press(event.x, event.y, -1)
return 4
elif self.picked.contains(index) and self.picked.count() > 1 and self.gesture.enabled():
# Kept for a drag of them all; the item alone if none follows.
self.picked.lead = index
else:
try self.picked.only(index)
let alone = index if self.picked.count() > 1 and not event.shift and self.picked.contains(index) and self.gesture.enabled() else -1
self.gesture.press(event.x, event.y, alone)
self.reveal(index)
return 1 if repeated else 0
## The selection, dragged out: the items' indices and the lead's picture.
func start_drag() -> !:
if self.picked.count() == 0:
return
let chosen = try self.picked.rows()
defer free(chosen) in memory.heap
var image: interop.Reference[Image]? = none
if self.picked.lead >= 0 and (usize)self.picked.lead < self.count:
image = self.pictures[(usize)self.picked.lead]
try self.box.value().start_drag(self.gesture.dragged_kind(), chosen, image)
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()
if self.across:
return try self.strip_key(event)
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
return try self.moved_to(target, event.shift)
## Keys in the horizontal flow: left and right by one item, up and down to the
## nearest item in the lane above or below (by one in a single-lane strip), page
## keys by a screen sideways.
func strip_key(event: Event) -> i64!:
let lead = self.picked.lead
let last = (i64)self.count - 1
let single = self.lanes.lanes == 1
var target: i64 = -1
if event.key == input.Key.right or (single and event.key == input.Key.down):
target = smaller(last, lead + 1)
elif event.key == input.Key.left or (single and event.key == input.Key.up):
target = larger(0, lead - 1)
elif event.key == input.Key.down:
target = self.lane_step(lead, 1, 0.0) if lead >= 0 else 0
elif event.key == input.Key.up:
target = self.lane_step(lead, -1, 0.0) if lead >= 0 else 0
elif event.key == input.Key.page_down:
target = self.lane_step(larger(0, lead), 0, self.extent())
elif event.key == input.Key.page_up:
target = self.lane_step(larger(0, lead), 0, -self.extent())
elif event.key == input.Key.home:
target = 0
elif event.key == input.Key.end:
target = last
return try self.moved_to(target, event.shift)
## Move the lead to `target` (none when -1), extending the selection with shift.
func moved_to(target: i64, shift: bool) -> i64!:
if target < 0:
return 0
if shift:
try self.picked.extend(target)
else:
try self.picked.only(target)
self.reveal(target)
return 0
## The item `lanes` lanes from `item` (clamped to the first and last) and `along`
## points sideways, nearest its middle; `item` itself when there is none.
func lane_step(item: i64, lanes: i64, along: f64) -> i64:
let lane = larger(0, smaller((i64)self.lanes.lanes - 1, self.lanes.lane_of(item) + lanes))
let middle = self.lanes.x_of(item) + self.lanes.width_of(item) * 0.5 + along
let found = self.lanes.nearest_in(lane, middle)
return found if found >= 0 else item
## 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.lanes.destroy()
self.count = 0
self.picked.close()
self.gesture.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.visible.close()
self.visible.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)
self.visible.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)