Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-photo

Source of release 0.1.1

0.1.1 / src / viewer.luc

## The Viewer: the current photo, fitted to the pane on a dark backdrop. A
## picture shows at once: the photo developed with its settings when the
## library has it (library.lucb's developed picture), else the camera's
## preview. Live, the photo then loads into the develop renderer
## (luce-develop), which draws it with its settings every frame, so every
## slider shows as it moves. The Library mode is not live: the developed
## picture is the photo, nothing develops again, until an edit or a zoom past
## the picture's pixels asks for it.
##
## Zoom and pan, as luced-2d's canvas: the photo fits the pane until zoomed. Z
## (the Zoom command) or a double-click toggles 1:1, one photo pixel to one
## screen pixel, about the pointer. A mouse wheel, a touchpad pinch, or a scroll
## with command, control or option held zooms about the pointer; touchpad
## scrolling pans, as does dragging with the middle button or with the left
## (outside the crop and guide tools). Zoomed past what the viewer's develop holds, the photo loads
## again at full size in the background and swaps in.
##
## The crop tool: while it is on, the whole corrected frame shows, the part the
## crop leaves out dimmed, with thirds and handles over the crop. Drag a corner or
## an edge to size it (a chosen aspect is kept), inside it to move it; `on_crop`
## hears each change when the drag ends.
##
## The guide tool: while it is on, the photo shows as it was taken (no
## perspective) with its guides over it. Drag on the photo to draw a guide (four
## at most), drag a guide's end to move it, right-click a guide to remove it;
## `on_guides` hears every change.
from luce_ui.ui import Application, Notifier, Widget, Layout, Size, Constraints, Event, Painter, Image, Panel, Point
from luce_gpu.gpu import RenderTarget, Rect
from luce_window.input import Cursor, EventKind, ScrollUnit
from luce_std import math
from luce_std import clock
from luce_develop.renderer import Renderer
from luce_develop import renderer
import wakers
from wakers import Waker
from luce_develop.settings import Look
from thumbs import Loader
import thumbs
import library
import theme

## The longer side the develop loads a photo at, in pixels.
let develop_edge: int = 2560

pub class Viewer: Widget:
    let box: Layout
    let loader: Loader
    let developer: Renderer
    pub let panel: Panel
    var picture: Image? = none
    ## The photo shown, and the one on its way (ids; -1 for none).
    var shown: int = -1
    var wanted: int = -1
    ## Called when a photo's develop is ready, with its as-shot white balance
    ## and shutter time.
    pub var on_developed: func(float, float, float) -> unit!? = none
    ## The guide tool: whether it is on, the guides (x1, y1, x2, y2 each, 0..1 of
    ## the photo), the end being dragged (its x's index in `guides`, or -1), and
    ## where the photo was last drawn.
    pub var guiding: bool = false
    var guides: list[float] = []
    var dragging: int = -1
    var drawn: Rect = Rect(0.0, 0.0, 0.0, 0.0)
    ## Called with the guides after every change the user makes.
    pub var on_guides: func(list[float]) -> unit!? = none
    ## Zoom: 0 to fit, else points per pixel of the full-size photo, and the photo
    ## point (0..1) at the pane's middle.
    var zoom: float = 0.0
    var center_u: float = 0.5
    var center_v: float = 0.5
    ## The photo's file and full size, and whether its full-size develop is on its way.
    var original: str = ""
    ## Whether the photo shown develops live (the edit modes), and whether its
    ## develop was asked for.
    var live: bool = true
    var developing: bool = false
    ## Whether the picture shown is being made again (`set_pending`).
    var pending: bool = false
    ## Whether the split between before and after is being dragged.
    var splitting: bool = false
    ## Told when a preview or a develop is ready (`wake_with`), and the waker
    ## that has the develop's loading thread notify it.
    var ready: Notifier? = none
    var waker: Waker? = none
    ## A histogram is wanted once the develop next draws (`want_histogram`).
    var histogram_wanted: bool = false
    pub var on_histogram: func() -> unit!? = none
    var full_width: float = 0.0
    var full_height: float = 0.0
    var full_asked: bool = false
    ## Backing pixels per point and the pane's size, from the last draw.
    var backing: float = 1.0
    var pane: Size = Size(0.0, 0.0)
    ## A drag panning the photo, from (`pan_x`, `pan_y`); the last press, for double-clicks.
    var panning: bool = false
    var pan_x: float = 0.0
    var pan_y: float = 0.0
    var pressed_at: float = 0.0
    ## The crop tool: on, the crop (left, top, right, bottom, 0..1 of the frame),
    ## the aspect kept (width over height in pixels, 0 for none), and the part of
    ## the crop being dragged (-1 none, 0–7 corners and edges, 8 the inside).
    pub var cropping: bool = false
    var crop: list[float] = []
    var crop_aspect: float = 0.0
    var crop_part: int = -1
    var crop_from: list[float] = []
    var crop_x: float = 0.0
    var crop_y: float = 0.0
    pub var on_crop: func(list[float]) -> unit!? = none

    pub func init(self) -> unit!:
        self.box = Layout()
        self.box.set_cursor(Cursor.arrow)
        # The viewer takes the pointer (presses, drags, double-clicks), and the
        # wheel and the touchpad zoom and pan the photo, not a pane around it.
        self.box.set_interactive(true)
        self.box.set_takes_scroll(true)
        self.box.set_flex()
        self.box.set_limits(Size(240.0, 200.0), Size(16384.0, 16384.0))
        self.loader = thumbs.start(1, library.preview_edge)
        self.developer = renderer.start()
        self.panel = Panel("Viewer", self, minimum = Size(320.0, 240.0), closable = false, id = "viewer")

    ## Show photo `id`, `full_width` × `full_height` pixels at full size: its
    ## preview from `preview` at once, then the original at `original`, developed
    ## with the look set by `set_look`.
    pub func show(self, id: int, preview: str, original: str, full_width: int, full_height: int) -> unit!:
        if id == self.shown or id == self.wanted:
            self.box.invalidate()
            return
        self.wanted = id
        self.original = original
        self.full_width = float(full_width)
        self.full_height = float(full_height)
        self.full_asked = false
        self.zoom = 0.0
        self.center_u = 0.5
        self.center_v = 0.5
        self.loader.clear()
        self.loader.request(id, preview)
        self.developer.clear()
        self.developing = false
        # Comparing before and after needs the live develop, in any mode.
        if self.live or self.developer.is_comparing():
            self.go_live()

    ## The photo turned a quarter: its full size's sides swap, and it fits again.
    pub func swap_sides(self) -> unit!:
        let width = self.full_width
        self.full_width = self.full_height
        self.full_height = width
        self.zoom = 0.0
        self.center_u = 0.5
        self.center_v = 0.5
        self.box.invalidate()

    ## Develop live from now on (an edit mode), or only show pictures (Library).
    pub func set_live(self, on: bool) -> unit!:
        self.live = on
        if on:
            self.go_live()

    ## Load the photo shown into the develop, once.
    pub func go_live(self) -> unit!:
        if self.developing or self.original == "":
            return
        self.developing = true
        self.developer.open(self.original, develop_edge)

    ## The photo's picture made again (`id`, from `path`): show it, if it is
    ## the photo shown and nothing develops it live.
    pub func picture_ready(self, id: int, path: str) -> unit!:
        if self.developing or (id != self.shown and id != self.wanted):
            return
        self.wanted = id
        self.loader.request(id, path)

    ## Develop with `look` from the next frame on.
    pub func set_look(self, look: Look) -> unit!:
        self.developer.set_look(look)
        self.box.invalidate()

    ## The histogram of the develop as shown (256 bins each of red, green, blue
    ## and luma), measured now; empty when no develop is shown.
    pub func histogram(self) -> list[int]!:
        if not self.developer.has_image():
            return []
        self.developer.compute_histogram()
        var bins: list[int] = []
        for at in 0..<1024:
            bins.append(self.developer.histogram_bin(at))
        return bins

    ## Turn the guide tool on or off, showing `guides` (x1, y1, x2, y2 each).
    pub func set_guiding(self, on: bool, guides: list[float]) -> unit!:
        self.guiding = on
        self.guides = guides
        self.dragging = -1
        self.developer.show_geometry(not on)
        self.box.set_cursor(Cursor.crosshair if on else Cursor.arrow)
        self.box.invalidate()

    ## Turn the crop tool on or off, showing `crop` (left, top, right, bottom) and
    ## keeping `aspect` (0 for none).
    pub func set_cropping(self, on: bool, crop: list[float], aspect: float) -> unit!:
        self.cropping = on
        self.crop = crop
        self.crop_aspect = aspect
        self.crop_part = -1
        self.developer.show_crop(not on)
        self.box.set_cursor(Cursor.crosshair if on else Cursor.arrow)
        if on and aspect > 0.0:
            self.fit_aspect()
            self.tell_crop()
        self.box.invalidate()

    ## Keep `aspect` from now on, fitting the crop to it about its middle.
    pub func set_crop_aspect(self, aspect: float) -> unit!:
        self.crop_aspect = aspect
        if aspect > 0.0:
            self.fit_aspect()
            self.tell_crop()
        self.box.invalidate()

    ## The frame's width over its height, in pixels.
    func frame_aspect(self) -> float:
        let height = float(self.developer.height())
        return float(self.developer.width()) / height if height > 0.0 else 1.5

    ## The largest crop of the kept aspect inside the current one, about its middle.
    func fit_aspect(self):
        let frame = self.frame_aspect()
        var width = self.crop[2] - self.crop[0]
        var height = self.crop[3] - self.crop[1]
        # In pixels the crop is width·W by height·H; keep width/height·frame = aspect.
        let wanted = self.crop_aspect / frame
        if width / height > wanted:
            width = height * wanted
        else:
            height = width / wanted
        let cx = (self.crop[0] + self.crop[2]) * 0.5
        let cy = (self.crop[1] + self.crop[3]) * 0.5
        self.crop = clamp_rect([cx - width * 0.5, cy - height * 0.5, cx + width * 0.5, cy + height * 0.5])

    func tell_crop(self) -> unit!:
        if let tell = self.on_crop:
            tell(self.crop.copy())

    ## The size of the photo the develop shows, for solving guides: 0 before it loads.
    pub func photo_width(self) -> int:
        return self.developer.width()

    pub func photo_height(self) -> int:
        return self.developer.height()

    ## Show nothing.
    pub func clear(self) -> unit!:
        self.loader.clear()
        self.developer.clear()
        self.developing = false
        self.original = ""
        self.wanted = -1
        self.shown = -1
        self.picture = none
        self.box.invalidate()

    ## Take previews and develops as their threads finish them: `app` runs
    ## `take_ready` when they say so.
    pub func wake_with(self, app: Application) -> unit!:
        let notifier = app.notifier(self.take_ready)
        self.loader.wake_with(notifier)
        self.waker = wakers.wake_renderer(self.developer, notifier)
        self.ready = notifier

    ## Measure the histogram (`on_histogram`) once the develop has drawn.
    pub func want_histogram(self) -> unit!:
        self.histogram_wanted = true
        self.box.invalidate()

    ## Take in a finished preview or develop.
    func take_ready(self) -> unit!:
        let id = self.loader.take()
        if id >= 0 and id == self.wanted:
            let picture = Image(self.loader.taken_width(), self.loader.taken_height())
            picture.write(self.loader.taken_pixels())
            self.picture = picture
            self.shown = id
            self.wanted = -1
            self.box.invalidate()
        if self.developer.poll():
            if let tell = self.on_developed:
                tell(self.developer.shot_temperature(), self.developer.shot_tint(), self.developer.shot_seconds())
        # A scene loaded, or settings prepared: the next frame takes them.
        if self.developing:
            self.box.invalidate()

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

    pub func measure(self, available: Constraints) -> Size!:
        return Size(640.0, 480.0)

    pub func draw(self, target: RenderTarget) -> unit!:
        let painter = Painter(target)
        let size = target.size()
        self.backing = size.pixel_width / size.width if size.width > 0.0 else 1.0
        self.pane = Size(size.width, size.height)
        painter.rectangle(Rect(0.0, 0.0, size.width, size.height), theme.viewer_backdrop())
        # The develop under way: a photo loading, or its settings being prepared.
        let working = self.developing and (not self.developer.has_image() or self.developer.busy())
        if self.developer.has_image():
            let place = self.placement(self.developer.output_width(), self.developer.output_height())
            # Drawn even before it is ready: drawing is what sends it its settings.
            self.developer.draw(target, place.x, place.y, place.width, place.height)
        if self.developer.has_image() and self.developer.ready():
            let place = self.placement(self.developer.output_width(), self.developer.output_height())
            self.drawn = place
            if self.developer.is_comparing():
                self.draw_split(painter, place)
            if self.guiding:
                self.draw_guides(painter, place)
            if self.cropping:
                self.draw_crop(painter, place)
            if working:
                self.draw_badge(painter, place, "Developing…")
            elif self.developer.is_refining():
                self.draw_badge(painter, place, f"Grain {int(self.developer.refined_share() * 100.0)} %")
            self.ask_full(place)
            # Development watched, or grain still refining: the next frame
            # carries it on.
            if self.developer.animating():
                self.box.invalidate()
            if self.histogram_wanted:
                self.histogram_wanted = false
                if let measure = self.on_histogram:
                    measure()
            return
        let picture = self.picture else return
        let place = self.placement(float(picture.width()), float(picture.height()))
        self.drawn = place
        painter.image(picture, place)
        # Developing it live, or (the Library) its picture being made again.
        if working or self.pending:
            self.draw_badge(painter, place, "Developing…")
        # Zoomed past the picture's own pixels: develop it, at full size.
        if not self.developing and self.zoom > 0.0 and place.width * self.backing > float(picture.width()) * 1.05:
            self.go_live()

    ## What the develop is doing, at the photo's bottom left: "Developing…"
    ## until what is shown is what was asked for, then "Grain N %" while the
    ## grain is traced grain by grain.
    func draw_badge(self, painter: Painter, place: Rect, text: str) -> unit!:
        let left = math.max(place.x, 0.0) + 10.0
        let bottom = math.min(place.y + place.height, self.pane.height) - 30.0
        painter.rounded_rectangle(Rect(left, bottom, 112.0, 20.0), theme.grey(30.0), 4.0)
        painter.text(text, left + 8.0, bottom + 3.0, theme.text())

    ## Whether the photo's picture is being made again (the Library mode shows
    ## it, not a live develop): the viewer says so until the new one is in.
    pub func set_pending(self, on: bool) -> unit!:
        if on != self.pending:
            self.pending = on
            self.box.invalidate()

    ## Before and after: the photo as the camera took it (white balance and
    ## exposure, no film) left of the line, the develop right of it. The live
    ## develop only: it goes live to show it.
    pub func compare_before(self, on: bool) -> unit!:
        self.developer.compare_before(on)
        if on:
            self.go_live()
        self.box.invalidate()

    ## The line between before and after, a handle to drag it, and their names
    ## at its top.
    func draw_split(self, painter: Painter, place: Rect) -> unit!:
        let x = self.split_x()
        let top = math.max(place.y, 0.0)
        let bottom = math.min(place.y + place.height, self.pane.height)
        painter.rectangle(Rect(x - 1.0, top, 2.0, bottom - top), theme.text())
        let middle = (top + bottom) * 0.5
        painter.rounded_rectangle(Rect(x - 7.0, middle - 14.0, 14.0, 28.0), theme.text(), 7.0)
        painter.rounded_rectangle(Rect(x - 3.0, middle - 9.0, 6.0, 18.0), theme.grey(60.0), 3.0)
        for (name, left) in [("Before", x - 62.0), ("After", x + 8.0)]:
            painter.rounded_rectangle(Rect(left, top + 8.0, 54.0, 18.0), theme.grey(30.0), 4.0)
            painter.text(name, left + 6.0, top + 9.0, theme.text())

    ## Where the split line is across the pane.
    func split_x(self) -> float:
        return math.clamp(self.drawn.x + self.drawn.width * self.developer.split_at(), 0.0, self.pane.width)

    ## Drag the split line; whether the event was the line's.
    func split_event(self, event: Event) -> bool!:
        if not self.developer.is_comparing():
            self.splitting = false
            return false
        let near = math.abs(event.x - self.split_x()) <= 7.0
        if event.kind == EventKind.pointer_down and event.inside and event.button == 0 and near:
            self.splitting = true
            return true
        if self.splitting and event.kind == EventKind.pointer_moved:
            self.developer.set_split((event.x - self.drawn.x) / math.max(self.drawn.width, 1.0))
            self.box.invalidate()
            return true
        if self.splitting and event.kind == EventKind.pointer_up:
            self.splitting = false
            return true
        if event.kind == EventKind.pointer_moved and not self.panning and not self.guiding and not self.cropping:
            self.box.set_cursor(Cursor.resize_horizontal if near else Cursor.arrow)
        return false

    ## Where a `width` × `height` picture of the photo goes in the pane: fitted,
    ## or at the zoom about the center point.
    func placement(self, width: float, height: float) -> Rect:
        if self.zoom <= 0.0 or self.full_width <= 0.0:
            return fitted(self.pane.width, self.pane.height, width, height)
        # The output's share of the photo's full size: all of it, or the crop's.
        let share = width / float(self.developer.width()) if self.developer.has_image() and self.developer.width() > 0 else 1.0
        let shown_width = self.full_width * self.zoom * share
        let shown_height = shown_width * height / width
        return Rect(self.pane.width * 0.5 - self.center_u * shown_width, self.pane.height * 0.5 - self.center_v * shown_height, shown_width, shown_height)

    ## Load the full-size develop once the zoom shows more pixels than the
    ## viewer's develop has.
    func ask_full(self, place: Rect) -> unit!:
        if self.full_asked or self.original == "":
            return
        if place.width * self.backing > float(self.developer.width()) * 1.05:
            self.full_asked = true
            self.developer.open(self.original, 0)

    ## Points per full-size pixel when fitted.
    func fit_zoom(self) -> float:
        if self.full_width <= 0.0 or self.pane.width <= 0.0:
            return 1.0
        return fitted(self.pane.width, self.pane.height, self.full_width, self.full_height).width / self.full_width

    ## Zoom to `zoom` (points per full-size pixel; 0 or less than the fit fits),
    ## keeping the photo point under (`x`, `y`) where it is.
    func zoom_to(self, zoom: float, x: float, y: float) -> unit!:
        let fit = self.fit_zoom()
        let wanted = math.min(zoom, 16.0 / self.backing)
        if wanted <= fit * 1.001:
            self.zoom = 0.0
            self.center_u = 0.5
            self.center_v = 0.5
            self.box.invalidate()
            return
        let before = self.drawn
        let u = (x - before.x) / before.width if before.width > 0.0 else 0.5
        let v = (y - before.y) / before.height if before.height > 0.0 else 0.5
        self.zoom = wanted
        # The photo point (u, v) stays under (x, y): the center moves to match.
        let width = self.full_width * wanted
        let height = width * before.height / before.width if before.width > 0.0 else width
        self.center_u = u - (x - self.pane.width * 0.5) / width
        self.center_v = v - (y - self.pane.height * 0.5) / height
        self.clamp_center()
        self.box.invalidate()

    ## Keep the photo over the pane: no empty margin while it is larger than the pane.
    func clamp_center(self):
        if self.zoom <= 0.0 or self.full_width <= 0.0:
            return
        let width = self.full_width * self.zoom
        let height = self.full_height * self.zoom
        let half_u = self.pane.width * 0.5 / width
        let half_v = self.pane.height * 0.5 / height
        self.center_u = math.max(half_u, math.min(1.0 - half_u, self.center_u)) if half_u < 0.5 else 0.5
        self.center_v = math.max(half_v, math.min(1.0 - half_v, self.center_v)) if half_v < 0.5 else 0.5

    ## Watch the film develop after each change (luce-develop's renderer runs
    ## development over a couple of seconds, frame by frame).
    pub func watch_development(self, on: bool) -> unit!:
        self.developer.watch_development(on)
        self.box.invalidate()

    ## Render the film's grain grain by grain once the settings settle (the
    ## stochastic render), or show its statistics only.
    pub func refine_grain(self, on: bool) -> unit!:
        self.developer.refine_grain(on)
        self.box.invalidate()

    ## Toggle between fitting the pane and 1:1, about (`x`, `y`) (the middle when negative).
    pub func toggle_zoom(self, x: float = -1.0, y: float = -1.0) -> unit!:
        let px = x if x >= 0.0 else self.pane.width * 0.5
        let py = y if y >= 0.0 else self.pane.height * 0.5
        self.zoom_to(0.0 if self.zoom > 0.0 else 1.0 / self.backing, px, py)

    ## Move the photo by (`dx`, `dy`) points.
    func pan_by(self, dx: float, dy: float):
        if self.zoom <= 0.0:
            return
        self.center_u -= dx / (self.full_width * self.zoom)
        self.center_v -= dy / (self.full_height * self.zoom)
        self.clamp_center()
        self.box.invalidate()

    ## The crop over the frame: what it leaves out dimmed, its edge, thirds and handles.
    func draw_crop(self, painter: Painter, place: Rect) -> unit!:
        let left = place.x + self.crop[0] * place.width
        let top = place.y + self.crop[1] * place.height
        let right = place.x + self.crop[2] * place.width
        let bottom = place.y + self.crop[3] * place.height
        let shade = theme.backdrop()
        painter.rectangle(Rect(place.x, place.y, place.width, top - place.y), shade, 0.6)
        painter.rectangle(Rect(place.x, bottom, place.width, place.y + place.height - bottom), shade, 0.6)
        painter.rectangle(Rect(place.x, top, left - place.x, bottom - top), shade, 0.6)
        painter.rectangle(Rect(right, top, place.x + place.width - right, bottom - top), shade, 0.6)
        let ink = theme.text()
        for third in [1.0 / 3.0, 2.0 / 3.0]:
            let x = left + (right - left) * third
            let y = top + (bottom - top) * third
            painter.rectangle(Rect(x, top, 1.0, bottom - top), ink, 0.35)
            painter.rectangle(Rect(left, y, right - left, 1.0), ink, 0.35)
        for (x, y, w, h) in [(left, top, right - left, 1.5), (left, bottom - 1.5, right - left, 1.5), (left, top, 1.5, bottom - top), (right - 1.5, top, 1.5, bottom - top)]:
            painter.rectangle(Rect(x, y, w, h), ink)
        for (x, y) in self.handle_points(left, top, right, bottom):
            painter.rectangle(Rect(x - 4.0, y - 4.0, 8.0, 8.0), theme.accent())

    ## The handles: four corners, then the middles of the top, right, bottom and left edges.
    func handle_points(self, left: float, top: float, right: float, bottom: float) -> list[(float, float)]:
        let cx = (left + right) * 0.5
        let cy = (top + bottom) * 0.5
        return [(left, top), (right, top), (right, bottom), (left, bottom), (cx, top), (right, cy), (cx, bottom), (left, cy)]

    ## The crop part at (`x`, `y`): a handle 0–7, 8 inside, -1 outside.
    func crop_part_at(self, x: float, y: float) -> int:
        let place = self.drawn
        let left = place.x + self.crop[0] * place.width
        let top = place.y + self.crop[1] * place.height
        let right = place.x + self.crop[2] * place.width
        let bottom = place.y + self.crop[3] * place.height
        for (at, point) in self.handle_points(left, top, right, bottom).indexed():
            if math.abs(point.0 - x) <= 10.0 and math.abs(point.1 - y) <= 10.0:
                return at
        if x > left and x < right and y > top and y < bottom:
            return 8
        return -1

    ## Drag the crop's part to the photo point (`u`, `v`), from where it started.
    func drag_crop(self, u: float, v: float) -> unit!:
        let start = self.crop_from
        if self.crop_part == 8:
            let (du, dv) = (u - self.crop_x, v - self.crop_y)
            let width = start[2] - start[0]
            let height = start[3] - start[1]
            let left = math.max(0.0, math.min(1.0 - width, start[0] + du))
            let top = math.max(0.0, math.min(1.0 - height, start[1] + dv))
            self.crop = [left, top, left + width, top + height]
            return
        var edges = start.copy()
        let moves_left = self.crop_part in [0, 3, 7]
        let moves_right = self.crop_part in [1, 2, 5]
        let moves_top = self.crop_part in [0, 1, 4]
        let moves_bottom = self.crop_part in [2, 3, 6]
        if moves_left:
            edges[0] = math.min(u, edges[2] - 0.02)
        if moves_right:
            edges[2] = math.max(u, edges[0] + 0.02)
        if moves_top:
            edges[1] = math.min(v, edges[3] - 0.02)
        if moves_bottom:
            edges[3] = math.max(v, edges[1] + 0.02)
        if self.crop_aspect > 0.0:
            # Keep the aspect: the dragged side leads, the other follows from the
            # opposite corner (or the middle, for an edge).
            let wanted = self.crop_aspect / self.frame_aspect()
            let width = edges[2] - edges[0]
            let height = edges[3] - edges[1]
            if (moves_left or moves_right) and not (moves_top or moves_bottom):
                let grown = width / wanted
                let cy = (start[1] + start[3]) * 0.5
                edges[1] = cy - grown * 0.5
                edges[3] = cy + grown * 0.5
            elif (moves_top or moves_bottom) and not (moves_left or moves_right):
                let grown = height * wanted
                let cx = (start[0] + start[2]) * 0.5
                edges[0] = cx - grown * 0.5
                edges[2] = cx + grown * 0.5
            else:
                let grown_height = width / wanted
                if moves_top:
                    edges[1] = edges[3] - grown_height
                else:
                    edges[3] = edges[1] + grown_height
        self.crop = clamp_rect(edges)

    func draw_guides(self, painter: Painter, place: Rect) -> unit!:
        var at = 0
        while at + 3 < self.guides.length:
            let a = Point(place.x + self.guides[at] * place.width, place.y + self.guides[at + 1] * place.height)
            let b = Point(place.x + self.guides[at + 2] * place.width, place.y + self.guides[at + 3] * place.height)
            painter.line(a, b, 3.0, theme.backdrop())
            painter.line(a, b, 1.5, theme.accent())
            for end in [a, b]:
                painter.rectangle(Rect(end.x - 4.0, end.y - 4.0, 8.0, 8.0), theme.accent())
            at += 4

    ## The index (into `guides`) of the end within 10 points of (`x`, `y`), or -1.
    func end_near(self, x: float, y: float) -> int:
        var at = 0
        while at + 1 < self.guides.length:
            let ex = self.drawn.x + self.guides[at] * self.drawn.width
            let ey = self.drawn.y + self.guides[at + 1] * self.drawn.height
            if math.abs(ex - x) <= 10.0 and math.abs(ey - y) <= 10.0:
                return at
            at += 2
        return -1

    ## The guide (its first index) passing within 8 points of (`x`, `y`), or -1.
    func guide_near(self, x: float, y: float) -> int:
        var at = 0
        while at + 3 < self.guides.length:
            let ax = self.drawn.x + self.guides[at] * self.drawn.width
            let ay = self.drawn.y + self.guides[at + 1] * self.drawn.height
            let bx = self.drawn.x + self.guides[at + 2] * self.drawn.width
            let by = self.drawn.y + self.guides[at + 3] * self.drawn.height
            let dx = bx - ax
            let dy = by - ay
            let length = dx * dx + dy * dy
            let t = math.max(0.0, math.min(1.0, ((x - ax) * dx + (y - ay) * dy) / length)) if length > 0.0 else 0.0
            let px = ax + t * dx - x
            let py = ay + t * dy - y
            if px * px + py * py <= 64.0:
                return at
            at += 4
        return -1

    func crop_event(self, event: Event) -> unit!:
        if event.kind == EventKind.pointer_down and event.inside and event.button == 0:
            self.crop_part = self.crop_part_at(event.x, event.y)
            if self.crop_part < 0:
                return
            self.crop_from = self.crop.copy()
            let (u, v) = self.on_photo(event.x, event.y)
            self.crop_x = u
            self.crop_y = v
        elif event.kind == EventKind.pointer_moved and self.crop_part >= 0:
            let (u, v) = self.on_photo(event.x, event.y)
            self.drag_crop(u, v)
            self.box.invalidate()
        elif event.kind == EventKind.pointer_up and self.crop_part >= 0:
            self.crop_part = -1
            self.tell_crop()

    func on_photo(self, x: float, y: float) -> (float, float):
        return (math.max(0.0, math.min(1.0, (x - self.drawn.x) / self.drawn.width)), math.max(0.0, math.min(1.0, (y - self.drawn.y) / self.drawn.height)))

    func tell_guides(self) -> unit!:
        if let tell = self.on_guides:
            tell(self.guides.copy())

    pub func event(self, event: Event) -> unit!:
        if self.drawn.width <= 0.0:
            return
        if event.kind == EventKind.magnify:
            # A touchpad pinch: the magnification change, about the pointer.
            self.zoom_to(math.max(self.zoom, self.fit_zoom()) * (1.0 + event.scroll_y), event.x, event.y)
            return
        if event.kind == EventKind.scroll:
            let wheel = event.scroll_unit == ScrollUnit.lines
            if wheel and (event.shift or (event.scroll_x != 0.0 and event.scroll_y == 0.0)):
                # Shift-wheel, or a wheel tilted sideways, pans across; a notch is 40 points.
                self.pan_by((event.scroll_x if event.scroll_x != 0.0 else event.scroll_y) * 40.0, 0.0)
            elif wheel or event.meta or event.control or event.alt:
                # A notched wheel zooms about the pointer; so does any scroll with a modifier held.
                let step = 1.0 if event.scroll_unit == ScrollUnit.points else 24.0
                self.zoom_to(math.max(self.zoom, self.fit_zoom()) * math.pow(1.0025, event.scroll_y * step), event.x, event.y)
            else:
                # Touchpad scrolling pans.
                self.pan_by(event.scroll_x, event.scroll_y)
            return
        if self.split_event(event):
            return
        if self.panning:
            if event.kind == EventKind.pointer_moved:
                self.pan_by(event.x - self.pan_x, event.y - self.pan_y)
                self.pan_x = event.x
                self.pan_y = event.y
            elif event.kind == EventKind.pointer_up:
                self.panning = false
                self.box.set_cursor(Cursor.crosshair if self.guiding else Cursor.arrow)
            return
        if event.kind == EventKind.pointer_down and event.inside and event.button == 0 and self.cropping and self.crop_part_at(event.x, event.y) >= 0:
            self.crop_event(event)
            return
        if event.kind == EventKind.pointer_down and event.inside and (event.button == 2 or (event.button == 0 and not self.guiding)):
            let now = clock.timestamp()
            if event.button == 0 and now - self.pressed_at < 0.35:
                self.pressed_at = 0.0
                self.toggle_zoom(event.x, event.y)
                return
            self.pressed_at = now
            if self.zoom > 0.0:
                self.panning = true
                self.pan_x = event.x
                self.pan_y = event.y
                self.box.set_cursor(Cursor.grab)
            return
        if self.cropping:
            self.crop_event(event)
            return
        if not self.guiding:
            return
        if event.kind == EventKind.pointer_down and event.inside:
            if event.button == 1:
                let near = self.guide_near(event.x, event.y)
                if near >= 0:
                    for _step in 0..<4:
                        _ = self.guides.remove_at(near)
                    self.box.invalidate()
                    self.tell_guides()
                return
            if event.button != 0:
                return
            let end = self.end_near(event.x, event.y)
            if end >= 0:
                self.dragging = end
                return
            if self.guides.length >= 16:
                return
            let (u, v) = self.on_photo(event.x, event.y)
            self.guides = self.guides + [u, v, u, v]
            self.dragging = self.guides.length - 2
            self.box.invalidate()
        elif event.kind == EventKind.pointer_moved and self.dragging >= 0:
            let (u, v) = self.on_photo(event.x, event.y)
            self.guides[self.dragging] = u
            self.guides[self.dragging + 1] = v
            self.box.invalidate()
        elif event.kind == EventKind.pointer_up and self.dragging >= 0:
            self.dragging = -1
            # A click without a drag leaves no guide.
            var at = 0
            while at + 3 < self.guides.length:
                let dx = (self.guides[at + 2] - self.guides[at]) * self.drawn.width
                let dy = (self.guides[at + 3] - self.guides[at + 1]) * self.drawn.height
                if dx * dx + dy * dy < 100.0:
                    for _step in 0..<4:
                        _ = self.guides.remove_at(at)
                else:
                    at += 4
            self.box.invalidate()
            self.tell_guides()

    pub func close(self):
        if let waker = self.waker:
            waker.close()
        if let notifier = self.ready:
            notifier.close()
        self.loader.close()
        self.developer.close()

## `edges` (left, top, right, bottom) kept inside the frame, keeping their size.
func clamp_rect(edges: list[float]) -> list[float]:
    let width = math.min(1.0, edges[2] - edges[0])
    let height = math.min(1.0, edges[3] - edges[1])
    let left = math.max(0.0, math.min(1.0 - width, edges[0]))
    let top = math.max(0.0, math.min(1.0 - height, edges[1]))
    return [left, top, left + width, top + height]

## A `width` × `height` picture fitted, centred, into a `room_width` ×
## `room_height` pane with a margin; never larger than 1:1 in points.
func fitted(room_width: float, room_height: float, width: float, height: float) -> Rect:
    let margin = 16.0
    let free_width = room_width - margin * 2.0
    let free_height = room_height - margin * 2.0
    if free_width <= 0.0 or free_height <= 0.0 or width <= 0.0 or height <= 0.0:
        return Rect(0.0, 0.0, 0.0, 0.0)
    let scale = math.min(1.0, math.min(free_width / width, free_height / height))
    return Rect((room_width - width * scale) * 0.5, (room_height - height * scale) * 0.5, width * scale, height * scale)