Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

119 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later
// SPDX-FileCopyrightText: 2026 Jareer Abdullah and Concat contributors

import { I18n } from "../i18n.slint";
import { Theme, Fmt, Glyph, Icon, Payload, Tip } from "../primitives/primitives.slint";
import { Pane, PaneScroll } from "pane.slint";
import { HairlineSplitter } from "splitter.slint";
import { PaneKind, PaneSwitcher } from "pane-switcher.slint";
import { TextAlignment } from "../timeline/model.slint";
import { CatalogueEntryData, Library } from "../inspector/clip-inspector.slint";
import { SearchField } from "../inspector/controls.slint";
import { Select } from "../primitives/select.slint";
import { Wave } from "../primitives/wave.slint";
import { ContextMenu, MenuItemData } from "../primitives/context-menu.slint";
import { SourcePreview } from "source-preview.slint";
import { Sounds, SoundList, VoiceList } from "audio-page.slint";

export { SourcePreview }

// The library pane: a strip of pages across the top, then a narrow category
// sidebar and the browsing area beside it. Media is the bin; Audio keeps
// the user's own sounds across projects; Text adds a
// title; Transitions, Effects and Filters each browse a catalogue;
// Adjustments lays a layer that grades everything beneath it and keeps the
// user's LUTs; Templates saves the project as one.

export enum MediaKind { video, audio, image }

/// What the sidebar has narrowed the bin to. `all` is not "no filter": it is
/// the row that is highlighted when every import is on, which is why it is a
/// value here and not the absence of one. `speech` is the Generated group's
/// shelf: what the editor read aloud, which the Media rows leave out.
export enum MediaFilter { all, video, audio, images, speech, processed }

/// One look a title can be given, as the Text page's Presets shelf shows
/// it: enough of the style to draw the name in it. Published by Rust from
/// the preset list; the id is what is placed, and ids are stable for ever
/// because project files store them.
export struct TextPresetData {
    id: string,
    name: string,
    /// The writing its face is made for: "Latin", "Japanese", "Hebrew".
    language: string,
    /// What the card draws in the look: "Aa", or a word of its own writing.
    sample: string,
    family: string,
    weight: int,
    italic: bool,
    fill: color,
    plate: color,
    plated: bool,
    stroke: color,
    /// as a fraction of the frame; zero for none
    stroke-width: float,
    align: TextAlignment,
}

export struct MediaItemData {
    id: int,
    name: string,
    kind: MediaKind,
    /// seconds; ignored for a still, which shows its format where a time
    /// would go
    duration: float,
    /// The file's format, lower-case, as the stamp on a still: "png", "jpg".
    format: string,
    /// The artwork, once something has produced it — the first frame of a
    /// filmstrip for footage, a drawn waveform for audio. Empty until then,
    /// which is what the tinted fallback below is for. Nothing decodes yet, so
    /// today it is always empty; the seam is here so the card does not have to
    /// be rewritten the day it isn't.
    thumbnail: image,
    /// The audio envelope as SVG path commands in a 1x1 viewbox, or empty.
    /// Same shape, same source and same normalisation as a timeline clip's:
    /// a file should look like itself wherever it is drawn.
    wave: string,
    selected: bool,
    /// Where the file is in the order of the selection, from 1, or 0 when
    /// it is not selected: the number a phone's pick wears, and the order
    /// Add lays the picks down in.
    pick: int,
}

// ── the page strip ───────────────────────────────────────────────────────────

component LibraryTab inherits Rectangle {
    in property <string> label;
    /// The page's mark, drawn over the label: a chip has the height for two
    /// lines and only ever needed one, so the second is where the mark goes.
    in property <Glyph> glyph;
    in property <bool> current;

    callback clicked();

    // flex-auto, not flex-1: the label is the basis and only the surplus is
    // shared, so "Transitions" is never crammed to make room for padding
    // around "Text". A Slint layout distributes spare width on top of each
    // child's own preferred width, which is the same rule.
    horizontal-stretch: 1;
    border-radius: Theme.r-sm;
    // The current page is a chip lifted out of the track. Slint has no
    // box-shadow, so the value step carries the lift alone — which is why this
    // is `field` and not the lighter `field-hover`, whose job is to answer the
    // pointer.
    background: root.current ? Theme.field : Colors.transparent;

    animate background { duration: 120ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    // The mark and the label share one tint, so a chip lights up as one thing
    // under the pointer and not as a glyph that answers and a word that
    // follows.
    property <brush> tint: (root.current || touch.has-hover) ? Theme.fg : Theme.fg-muted;

    animate tint { duration: 140ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    // Two lines in the 40px a chip gets inside the strip: 13px of mark, 2px of
    // air, then the label at fs-sm, with 6px above and below so the two
    // lines sit in the chip rather than against its edges. The strip is 52px
    // so the three pane headers keep one edge across the window (see
    // PaneHeader).
    VerticalLayout {
        padding-top: 6px;
        padding-bottom: 6px;
        padding-left: 6px;
        padding-right: 6px;
        spacing: 2px;
        alignment: center;

        HorizontalLayout {
            alignment: center;
            Icon {
                glyph: root.glyph;
                size: 13px;
                tint: root.tint;
            }
        }

        Text {
            text: root.label;
            color: root.tint;
            font-size: Theme.fs-sm;
            horizontal-alignment: center;
            vertical-alignment: center;
            overflow: elide;
        }
    }

    drag := DragArea {
        // The one style there is, so the payload names no preset — only what
        // the drop should build.
        data: Payload.of("text:default:Title");
        drag-image: Payload.preview("text:default:Title");
        drag-image-offset-x: -8;
        drag-image-offset-y: -4;
        allow-copy: true;

        touch := TouchArea {
            mouse-cursor: pointer;
            clicked => {
                root.clicked();
            }
        }
    }
}

// One end of the page strip: a slim button that moves the chips along by
// most of a track, fading the chips out under itself so a chip half under
// it reads as continuing rather than cut.
component StripEnd inherits Rectangle {
    in property <Glyph> glyph;
    in property <brush> fade;

    callback clicked();

    y: 0;
    width: 22px;
    background: root.fade;

    Rectangle {
        x: root.glyph == Glyph.chevron-left ? 2px : parent.width - self.width - 2px;
        y: (parent.height - self.height) / 2;
        width: 16px;
        height: 16px;
        border-radius: Theme.r-xs;
        background: touch.has-hover ? Theme.field-hover : Theme.field;

        Icon {
            x: (parent.width - self.width) / 2;
            y: (parent.height - self.height) / 2;
            glyph: root.glyph;
            size: 10px;
            weight: 2.4;
            tint: touch.has-hover ? Theme.fg : Theme.fg-muted;
        }
    }

    touch := TouchArea {
        mouse-cursor: pointer;
        clicked => { root.clicked(); }
    }
}

// ── the category sidebar ─────────────────────────────────────────────────────

// The heading over a list of category rows, and the control that collapses
// them. The rows are not its children: whoever places it also places them,
// under an `if` on the open state — the same split `Section`/`SectionHeader`
// uses in primitives/panel.slint, because dropping a body out of the layout is
// what collapsing means and an `if` is what does it.
component CategoryHeading inherits Rectangle {
    in property <string> title;
    in property <bool> open: true;

    callback toggled();

    height: 26px;
    border-radius: Theme.r-sm;
    background: heading.has-hover ? Theme.field : Colors.transparent;

    animate background { duration: 100ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    HorizontalLayout {
        padding-left: 6px;
        padding-right: 6px;
        spacing: 4px;

        VerticalLayout {
            alignment: center;
            Icon {
                glyph: root.open ? Glyph.chevron-down : Glyph.chevron-right;
                size: 10px;
                tint: heading.has-hover ? Theme.fg : Theme.fg-muted;
            }
        }

        Text {
            horizontal-stretch: 1;
            text: root.title;
            color: heading.has-hover ? Theme.fg : Theme.fg-muted;
            font-size: Theme.fs-sm;
            font-weight: Theme.weight-title;
            vertical-alignment: center;
            overflow: elide;
        }
    }

    heading := TouchArea {
        mouse-cursor: pointer;
        clicked => {
            root.toggled();
        }
    }
}

component CategoryRow inherits Rectangle {
    in property <string> label;
    /// -1 hides the count entirely; 0 shows nothing either, since an empty
    /// bin needs no zero beside every row to say so.
    in property <int> count: -1;
    in property <bool> current;

    callback clicked();

    height: 24px;
    border-radius: Theme.r-sm;
    background: root.current ? Theme.field-active
        : touch.has-hover ? Theme.field
        : Colors.transparent;

    animate background { duration: 100ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    HorizontalLayout {
        // Indented past the group heading's chevron, so the rows read as
        // hanging off it rather than sitting beside it.
        padding-left: 18px;
        padding-right: 6px;
        spacing: 4px;

        Text {
            horizontal-stretch: 1;
            text: root.label;
            color: root.current ? Theme.fg : Theme.fg-muted;
            font-size: Theme.fs-sm;
            vertical-alignment: center;
            overflow: elide;
        }

        if root.count > 0: Text {
            text: "\{root.count}";
            color: Theme.fg-dim;
            font-family: Theme.font-technical;
            font-size: Theme.fs-xs;
            vertical-alignment: center;
        }
    }

    touch := TouchArea {
        mouse-cursor: pointer;
        clicked => {
            root.clicked();
        }
    }
}

// ── the drop zone ────────────────────────────────────────────────────────────

// The import button, whose dashed border says "you may also drop files here".
//
// Slint's Path has no stroke-dash-array and a Rectangle border is solid, so
// the dashes are subtracted rather than drawn: a solid rounded border, then
// short rectangles in the button's own ground colour laid over it. That keeps
// the corner radii exactly round — a hand-drawn dashed rounded rect has to
// approximate the arcs — and leaves one place to change the border colour.
//
// The dash counts are fixed and their pitch follows the width, rather than the
// other way round. A count derived from the width would tear down and rebuild
// every rectangle on every frame of a splitter drag; a pitch that drifts a
// pixel between panel sizes is not visible.
component ImportButton inherits Rectangle {
    in property <bool> busy;
    // Reused by the templates page as "save as template", so the words and
    // the mark are parameters with the import ones as defaults.
    in property <string> label: I18n.t("mediaPane.import");
    in property <string> busy-label: I18n.t("mediaPane.importing");
    in property <Glyph> glyph: Glyph.import;

    callback clicked();

    /// where the straight runs start, i.e. clear of the rounded corners
    property <length> inset: Theme.r;
    property <length> run-h: Math.max(0px, root.width - 2 * root.inset);
    property <length> run-v: Math.max(0px, root.height - 2 * root.inset);

    /// A dash and the gap after it, in pixels — the rhythm the whole outline
    /// is cut to.
    ///
    /// The counts are derived from it rather than fixed. Fixed counts, say 14
    /// across and 3 down, make the pitch whatever the button's width makes
    /// it: on a 300px button that is a 4px gap every 20px across and a 3.7px
    /// gap every 7.3px down — two different dashed lines meeting at the
    /// corners, which makes the outline read as a mistake rather than as a
    /// style. Counting instead of spacing puts both axes on one rhythm, and
    /// the rounding spreads the remainder evenly over the run rather than
    /// leaving it all at one end.
    property <length> pitch: 8px;
    property <int> dashes-h: Math.max(1, Math.round(root.run-h / root.pitch));
    property <int> dashes-v: Math.max(1, Math.round(root.run-v / root.pitch));
    property <length> pitch-h: root.run-h / root.dashes-h;
    property <length> pitch-v: root.run-v / root.dashes-v;
    // Half of it, so dash and gap are the same length on both axes — which is
    // the whole of what "even" means in a dashed line.
    property <length> bite-h: root.pitch-h / 2;
    property <length> bite-v: root.pitch-v / 2;
    property <brush> ground: (touch.has-hover && !root.busy) ? Theme.field : Theme.panel;

    height: 36px;
    border-width: 1px;
    border-radius: Theme.r;
    border-color: (touch.has-hover && !root.busy) ? Theme.accent : Theme.line-strong;
    background: root.ground;
    opacity: root.busy ? 0.4 : 1.0;

    animate background, border-color { duration: 120ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    HorizontalLayout {
        alignment: center;
        // Shoulders on the words, so a button sized to its own label — the
        // media page's, which is one word — still reads as a zone to drop on
        // rather than as the text with a box drawn round it.
        padding-left: 18px;
        padding-right: 18px;
        spacing: 8px;

        VerticalLayout {
            alignment: center;
            Icon {
                glyph: root.glyph;
                size: 14px;
                tint: touch.has-hover ? Theme.fg : Theme.fg-muted;
            }
        }

        Text {
            text: root.busy ? root.busy-label : root.label;
            color: touch.has-hover ? Theme.fg : Theme.fg-muted;
            font-size: Theme.fs;
            vertical-alignment: center;
        }
    }

    // The bites. Two runs across, two down; each run is divided into equal
    // pitches and one bite is centred in each.
    // Both axes pinned on every bite: an element given only one coordinate is
    // centred on the other axis by default, which drew the top run's dashes
    // across the middle of the button.
    for step in root.dashes-h: Rectangle {
        x: root.inset + (step + 0.5) * root.pitch-h - root.bite-h / 2;
        y: 0;
        width: root.bite-h;
        height: 1px;
        background: root.ground;
    }
    for step in root.dashes-h: Rectangle {
        x: root.inset + (step + 0.5) * root.pitch-h - root.bite-h / 2;
        y: root.height - 1px;
        width: root.bite-h;
        height: 1px;
        background: root.ground;
    }
    for step in root.dashes-v: Rectangle {
        x: 0;
        y: root.inset + (step + 0.5) * root.pitch-v - root.bite-v / 2;
        width: 1px;
        height: root.bite-v;
        background: root.ground;
    }
    for step in root.dashes-v: Rectangle {
        x: root.width - 1px;
        y: root.inset + (step + 0.5) * root.pitch-v - root.bite-v / 2;
        width: 1px;
        height: root.bite-v;
        background: root.ground;
    }

    touch := TouchArea {
        enabled: !root.busy;
        mouse-cursor: pointer;
        clicked => {
            root.clicked();
        }
    }
}

// ── one card ─────────────────────────────────────────────────────────────────

export component MediaCard inherits Rectangle {
    in property <MediaItemData> item;
    /// The cross that takes the file out of the bin, shown while the card
    /// is under the pointer. Off on a phone, where a finger on a card is a
    /// hover for as long as it presses and the cross would sit under it.
    in property <bool> removable: true;

    /// Faded while it is in the air, so the ghost on the timeline reads as
    /// this card moved rather than as a second copy of it.
    opacity: drag.dragging ? 0.45 : 1.0;

    /// modifier-held click: add to or remove from the selection
    callback clicked(additive: bool);
    /// double click: put it on the timeline at the playhead
    callback activated();
    callback removed();
    /// right click, with where on the card it landed: the menu opens there
    callback context(x: length, y: length);

    property <color> mark: root.item.kind == MediaKind.audio ? Theme.kind-audio
        : root.item.kind == MediaKind.image ? Theme.kind-image
        : Theme.kind-video;
    property <color> well: root.item.kind == MediaKind.audio ? Theme.kind-audio-well
        : root.item.kind == MediaKind.image ? Theme.kind-image-well
        : Theme.kind-video-well;
    property <Glyph> badge: root.item.kind == MediaKind.audio ? Glyph.music
        : root.item.kind == MediaKind.image ? Glyph.image
        : Glyph.film;

    /// modifier state at the moment of the press — `clicked` does not carry it
    property <bool> additive;

    // The whole card is the drag handle: dragging one onto the timeline is
    // how material gets into an edit. The DragArea only intercepts once the
    // press has travelled far enough to be a drag, so the TouchArea inside
    // keeps its click and its double-click.
    drag := DragArea {
        // Copy, not move: the bin keeps the file. A DragArea whose data is
        // empty never starts a drag, which is the whole of the opt-out.
        data: Payload.of("media:\{root.item.id}");
        // The chip under the cursor. Same payload as the data, so what is
        // drawn and what would be dropped cannot come apart.
        drag-image: Payload.preview("media:\{root.item.id}");
        // Below and right of the cursor, not under it: the hot spot is where
        // the drop lands, and a chip centred on it would cover the very lane
        // edge you are aiming at. Negative, because the offset is measured
        // into the image — see the DragArea docs.
        drag-image-offset-x: -8;
        drag-image-offset-y: -4;
        allow-copy: true;

        // Everything is *inside* the card's TouchArea rather than beside it. A
        // sibling would lose its hover the moment the pointer crossed onto the
        // remove button — the button is the topmost hit, so nothing behind it
        // is told the pointer is there any more, and a control revealed on
        // hover would blink itself out of existence. An ancestor TouchArea is
        // marked hovered on the way down to its children, before any of them
        // can take the event, so it keeps the hover the whole time; a
        // descendant that grabs a press still stops the press from reaching it.
        card := TouchArea {
            mouse-cursor: pointer;
            pointer-event(event) => {
                // The right button asks for the menu and does nothing
                // else, on the release rather than the press, for the
                // reasons the lanes give beside their own.
                if (event.button == PointerEventButton.right) {
                    if (event.kind == PointerEventKind.up) {
                        root.context(self.mouse-x, self.mouse-y);
                    }
                    return;
                }
                if (event.kind == PointerEventKind.down) {
                    root.additive = event.modifiers.shift || event.modifiers.control
                        || event.modifiers.meta;
                }
            }
            clicked => {
                root.clicked(root.additive);
            }
            double-clicked => {
                root.activated();
            }

            thumb := Rectangle {
                // aspect-video, and the card's height is derived from the same
                // ratio, so the label lands exactly under it. y pinned: with only
                // a height set, the default would centre the tile over the label.
                y: 0;
                height: root.width * 9 / 16;
                border-radius: Theme.r;
                // The kind's darker hue as the ground, so a card whose artwork has
                // not arrived is already colour-coded rather than a black hole.
                background: root.well;
                border-width: root.item.selected ? 2px : 1px;
                border-color: root.item.selected ? Theme.accent
                    : card.has-hover ? Theme.line-strong
                    : Theme.line;
                clip: true;

                if root.item.thumbnail.width > 0: Image {
                    // Sized by hand for the same reason the sidebar is: a
                    // conditional element gets no default fill from its parent.
                    width: parent.width;
                    height: parent.height;
                    source: root.item.thumbnail;
                    // Cover, not contain: letterboxing an 88px thumbnail spends
                    // most of it on bars, and a crop reads better at this size.
                    image-fit: cover;
                }

                // Sound draws itself. The envelope and the duration stamp between
                // them already say "this is an audio file", so there is no mark on
                // top of them — a badge over a waveform is the same fact twice,
                // and the one that costs the tile its whole middle.
                if root.item.wave != "": Wave {
                    x: 0;
                    y: 0;
                    width: parent.width;
                    height: parent.height;
                    commands: root.item.wave;
                    tint: root.mark;
                }

                // What everything else shows before its artwork exists. Large and
                // faint on purpose: at the badge's own size and colour it read as
                // a corner mark duplicated into the middle of the tile rather than
                // as a placeholder.
                if root.item.thumbnail.width == 0 && root.item.wave == "": Icon {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    glyph: root.badge;
                    size: 26px;
                    tint: root.mark.with-alpha(0.32);
                }

                // No corner kind badge, on purpose: the artwork already says
                // what kind a card is — footage carries a duration stamp, audio
                // is a waveform, a still says its format — so a badge would
                // repeat information the card gives away at a glance.

                // Duration, bottom right, on its own scrim because what is behind
                // it is a video frame and cannot be relied on for contrast.
                Rectangle {
                    x: parent.width - self.width - 4px;
                    y: parent.height - self.height - 4px;
                    width: stamp.width + 7px;
                    height: stamp.height + 2px;
                    border-radius: Theme.r-xs;
                    background: Theme.scrim;

                    stamp := Text {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        text: root.item.kind == MediaKind.image
                            ? (root.item.format == "" ? "still" : root.item.format)
                            : Fmt.short-duration(root.item.duration);
                        color: Theme.on-scrim;
                        font-family: Theme.font-technical;
                        font-size: Theme.fs-xs;
                    }
                }

                // The card that is playing, or on the monitor: how far it has
                // got, as a line across it, and a sound's play or pause in
                // the middle - a second click does the other.
                if SourcePreview.row == root.item.id: Rectangle {
                    x: parent.width * Math.clamp(SourcePreview.progress, 0, 1) - 1px;
                    y: 0;
                    width: 2px;
                    height: parent.height;
                    background: Theme.accent;
                }
                if SourcePreview.row == root.item.id && root.item.kind == MediaKind.audio: Rectangle {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    width: 26px;
                    height: 26px;
                    border-radius: 13px;
                    background: Theme.scrim;

                    Icon {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        glyph: SourcePreview.playing ? Glyph.pause : Glyph.play;
                        size: 12px;
                        tint: Theme.on-scrim;
                    }
                }

                // Hover-only: a permanent delete button on every card in a
                // full bin is one bin's worth of invitations to lose work.
                if card.has-hover && root.removable: Rectangle {
                    x: parent.width - self.width - 4px;
                    y: 4px;
                    width: 18px;
                    height: 18px;
                    border-radius: Theme.r-xs;
                    background: remove.has-hover ? Theme.danger : Theme.scrim;

                    Icon {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        glyph: Glyph.close;
                        size: 10px;
                        tint: Theme.on-scrim;
                    }

                    remove := TouchArea {
                        mouse-cursor: pointer;
                        clicked => {
                            root.removed();
                        }
                    }
                }
            }

            Text {
                y: thumb.height + 4px;
                width: root.width;
                height: 14px;
                text: root.item.name;
                color: root.item.selected ? Theme.fg : Theme.fg-muted;
                font-size: Theme.fs-sm;
                vertical-alignment: center;
                overflow: elide;
            }

            // The chip the drag will carry, shown from the press itself.
            // A DragArea only takes over once the pointer has travelled,
            // so without this the first few pixels of every drag showed
            // nothing in the hand; it sits where the drag image will, so
            // the hand-over is a continuation rather than a jump.
            if card.pressed && !drag.dragging: Image {
                x: card.mouse-x + 8px;
                y: card.mouse-y + 4px;
                source: Payload.preview("media:\{root.item.id}");
            }
        }
    }
}

// ── the card grid ────────────────────────────────────────────────────────────

// `grid-cols-[repeat(auto-fill,minmax(88px,1fr))]`, arithmetic instead of a
// layout: Slint has no auto-fill grid, and a GridLayout wants its cells named
// at compile time, which a model cannot do.
component MediaGrid inherits Rectangle {
    in property <[MediaItemData]> items;
    /// A floor under the grid's own height, so the empty page below the last
    /// row still belongs to it.
    ///
    /// Without it the grid is exactly as tall as its cards, and the only
    /// pixels left to press are the 8px seams between them — a marquee you
    /// have to thread a needle to start, which is no marquee at all. The
    /// timeline has this for free: its lanes run the width of the pane and
    /// most of one is empty. This is the bin's version of that empty lane.
    in property <length> page-floor;

    callback clicked(id: int, additive: bool);
    callback activated(id: int);
    callback removed(id: int);
    /// Right-click on a card. Rust fills the menu and bumps `menu-token`;
    /// where it opens is decided here, because only this side knows where
    /// the pointer was. The token is gated the way the lanes gate theirs:
    /// it is one number for the whole window, and only the grid that
    /// asked opens on it.
    callback context(id: int);
    callback menu-selected(id: string);
    in property <[MenuItemData]> menu-items;
    in property <length> menu-height;
    in property <int> menu-token;
    property <bool> asked;
    property <int> own-token;
    changed menu-token => {
        if (root.asked) {
            root.asked = false;
            root.own-token = root.menu-token;
        }
    }
    /// A press on the gutter between the cards, before any band.
    callback pressed();
    /// A marquee closed over the grid, given as the block of cells it caught:
    /// the two corners inclusive, and the column count they were measured
    /// against. A block and not a list of ids, because the cards are placed by
    /// arithmetic rather than by a layout — the geometry lives on this side,
    /// so this side is what resolves it, and a rectangle of cells is the whole
    /// answer without a model to carry it. An empty block — `to` before
    /// `from` on either axis — is a press that caught nothing, which for a
    /// plain band is how the selection gets cleared.
    callback band-selected(columns: int, from-col: int, to-col: int,
        from-row: int, to-row: int, additive: bool);

    property <length> gap: 8px;
    property <length> min-card: 88px;

    property <int> cols: Math.max(1,
        Math.floor((root.width + root.gap) / (root.min-card + root.gap)));
    property <length> card-w: (root.width - (root.cols - 1) * root.gap) / root.cols;
    /// thumbnail + the 4px gap + one line of label
    property <length> card-h: root.card-w * 9 / 16 + 4px + 14px;
    property <int> rows: Math.ceil(root.items.length / root.cols);
    /// One card and the gutter after it — what a column, or a row, advances by.
    property <length> col-pitch: root.card-w + root.gap;
    property <length> row-pitch: root.card-h + root.gap;

    property <length> cards-h:
        root.rows > 0 ? root.rows * root.row-pitch - root.gap : 0px;

    height: Math.max(root.cards-h, root.page-floor);

    // Which cards a band's edges touch. The grid is arithmetic, so there is no
    // need to ask every card for its rect and test them one by one: an edge
    // maps straight to a column, and the four answers are the block. The
    // tests are strict on both sides (`left < right && right > left`), so a
    // band that stops exactly on a gutter catches neither of the cards it
    // runs between.
    pure function first-col(edge: length) -> int {
        return Math.max(0, Math.floor((edge - root.card-w) / root.col-pitch) + 1);
    }
    pure function last-col(edge: length) -> int {
        return Math.min(root.cols - 1, Math.ceil(edge / root.col-pitch) - 1);
    }
    pure function first-row(edge: length) -> int {
        return Math.max(0, Math.floor((edge - root.card-h) / root.row-pitch) + 1);
    }
    pure function last-row(edge: length) -> int {
        return Math.min(root.rows - 1, Math.ceil(edge / root.row-pitch) - 1);
    }

    // Pressing the background drags a selection band. Declared first, so the
    // cards take their own presses and what is left to press is the gutter
    // between them.
    //
    // Committed on release rather than as it sweeps — the timeline's band is
    // the same gesture in the same window and does the same, for the reason
    // written there: selecting live looks busy and makes a mistaken sweep hard
    // to back out of. It also keeps the bin off the pointer-rate path, which
    // it has no cheap publish for: re-deriving the selection on every move
    // would mean republishing the whole list at pointer rate.
    //
    // A press that never moves closes an empty band, which is a click on empty
    // space and clears the selection — the same event doing the same job, so
    // there is no second handler that could disagree with this one about what
    // a press on the background means.
    //
    // It fills the root, which is why `page-floor` exists: the surface this
    // gesture is made on is the grid's box, and a box drawn tight around the
    // cards has nothing in it but seams.
    band := TouchArea {
        property <bool> drawing;
        property <bool> additive;
        property <length> from-x;
        property <length> from-y;
        property <length> to-x;
        property <length> to-y;

        pointer-event(event) => {
            if (event.kind == PointerEventKind.down) {
                root.pressed();
                self.additive = event.modifiers.shift;
                self.from-x = self.mouse-x;
                self.from-y = self.mouse-y;
                self.to-x = self.mouse-x;
                self.to-y = self.mouse-y;
                self.drawing = true;
            } else if (event.kind == PointerEventKind.up
                || event.kind == PointerEventKind.cancel) {
                if (self.drawing) {
                    self.drawing = false;
                    root.band-selected(
                        root.cols,
                        root.first-col(Math.min(self.from-x, self.to-x)),
                        root.last-col(Math.max(self.from-x, self.to-x)),
                        root.first-row(Math.min(self.from-y, self.to-y)),
                        root.last-row(Math.max(self.from-y, self.to-y)),
                        self.additive);
                }
            }
        }

        moved => {
            self.to-x = self.mouse-x;
            self.to-y = self.mouse-y;
        }
    }

    for entry[index] in root.items: MediaCard {
        x: Math.mod(index, root.cols) * (root.card-w + root.gap);
        y: Math.floor(index / root.cols) * (root.card-h + root.gap);
        width: root.card-w;
        height: root.card-h;
        item: entry;

        clicked(additive) => {
            root.clicked(entry.id, additive);
        }
        activated => {
            root.activated(entry.id);
        }
        removed => {
            root.removed(entry.id);
        }
        context(x, y) => {
            // Captured before the round trip, and `asked` goes up first:
            // the call below publishes before it returns, so the token
            // can arrive inside it.
            menu.request-x = self.x + x;
            menu.request-y = self.y + y;
            root.asked = true;
            root.context(entry.id);
        }
    }

    // The band being drawn, declared last so it lies over the cards it is
    // closing on. Same wash and same edge as the timeline's: one gesture, one
    // look, wherever in the window it is made.
    if band.drawing: Rectangle {
        x: Math.min(band.from-x, band.to-x);
        y: Math.min(band.from-y, band.to-y);
        width: Math.max(band.from-x, band.to-x) - Math.min(band.from-x, band.to-x);
        height: Math.max(band.from-y, band.to-y) - Math.min(band.from-y, band.to-y);
        background: Theme.accent-soft;
        border-width: 1px;
        border-color: Theme.accent;
    }

    // Over everything, like the lanes' one: a PopupWindow is its own layer,
    // but the element that places it has to be able to measure the grid.
    menu := ContextMenu {
        x: 0;
        y: 0;
        width: parent.width;
        height: parent.height;
        items: root.menu-items;
        menu-height: root.menu-height;
        token: root.own-token;
        selected(id) => { root.menu-selected(id); }
    }
}

// ── the catalogue pages ──────────────────────────────────────────────────────

// One entry of the transitions or effects catalogue. Display data only: the
// id is what Rust is handed when a card is applied, and ids are stable
// forever because project files store them.
struct CatalogueItemData {
    id: string,
    label: string,
    /// False keeps the card browsable with a "Soon" badge, the honest version
    /// of a disabled control, for anything listed before the engine can do
    /// it.
    enabled: bool,
    /// The rendered preview, for effects; empty for transitions and filters,
    /// whose tiles carry a mark on a sunken ground instead.
    art: image,
    /// What that tile shows when there is no artwork. Carried per entry rather
    /// than fixed by the card, because a transition and an audio filter are
    /// both artless and are not the same thing.
    glyph: Glyph,
}

// A catalogue card: preview tile, label under it, and the apply affordance —
// a plus on hover when it works, a "Soon" badge when it does not.
component CatalogueCard inherits Rectangle {
    in property <CatalogueItemData> item;
    in property <Glyph> glyph: root.item.glyph;
    /// A card that shows before it adds: a click is `auditioned`, and only
    /// a double-click or the plus is `applied`. Otherwise a click applies.
    in property <bool> auditions;
    /// This card's look is the one being shown; it draws itself picked.
    in property <bool> auditioning;
    /// What this card leaves on the timeline when it is dragged there, or
    /// empty for a page whose entries are applied to the selection rather than
    /// placed — a DragArea with no data never starts a drag, so one property
    /// is the whole difference between a draggable page and a clickable one.
    in property <string> payload;

    callback applied();
    callback auditioned();

    /// An entry with no artwork is a compact card: the name sits inside the
    /// tile, there is no mark and no caption, and the tile is half as tall.
    /// Transitions and audio effects have nothing to show but their name,
    /// and a name in a box says it in a third of the room.
    in property <bool> compact;

    property <float> sweep: card.has-hover ? 1.0 : 0.0;
    animate sweep { duration: 1.2s; easing: ease-in-out; iteration-count: -1; }

    property <float> shimmer: card.has-hover ? 1.0 : 0.0;
    animate shimmer { duration: 1.5s; easing: ease-in-out; iteration-count: -1; }

    opacity: drag.dragging ? 0.45 : 1.0;

    drag := DragArea {
        data: Payload.of(root.payload);
        // Empty on a click-only page, where it resolves to an empty image and
        // draws nothing — the same one property that decides whether the card
        // drags at all.
        drag-image: Payload.preview(root.payload);
        drag-image-offset-x: -8;
        drag-image-offset-y: -4;
        allow-copy: true;

        card := TouchArea {
            enabled: root.item.enabled;
            mouse-cursor: root.item.enabled ? pointer : default;
            // On a showing card the second click of a double-click lands
            // here first and takes the showing off; the add that follows
            // is what the gesture meant, and Rust drops the showing anyway.
            clicked => {
                if (root.auditions) { root.auditioned(); } else { root.applied(); }
            }
            double-clicked => {
                if (root.auditions) { root.applied(); }
            }

            tile := Rectangle {
                y: 0;
                height: root.compact ? root.height : root.width;
                border-radius: Theme.r;
                background: root.compact && card.has-hover && root.item.enabled
                    ? Theme.field : Theme.well;
                border-width: root.auditioning ? 2px : 1px;
                border-color: root.auditioning ? Theme.accent
                    : (card.has-hover && root.item.enabled)
                    ? Theme.line-strong : Theme.line;
                clip: true;

                if root.item.art.width > 0: Image {
                    x: 0;
                    y: 0;
                    width: parent.width;
                    height: parent.height;
                    source: root.item.art;
                    image-fit: cover;
                }

                if root.compact: Text {
                    x: 6px;
                    y: 0;
                    width: parent.width - 12px;
                    height: parent.height;
                    text: root.item.label;
                    color: root.item.enabled ? Theme.fg : Theme.fg-dim;
                    font-size: Theme.fs-sm;
                    horizontal-alignment: center;
                    vertical-alignment: center;
                    wrap: word-wrap;
                    overflow: elide;
                }

                if !root.compact && root.item.art.width == 0: Icon {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    glyph: root.item.glyph;
                    size: 22px;
                    tint: Theme.fg-dim;
                }

                // Transitions: animated sweep line / wipe overlay across card image
                if (root.glyph == Glyph.transition || root.item.glyph == Glyph.transition) && card.has-hover: Rectangle {
                    x: 0;
                    y: 0;
                    width: parent.width * root.sweep;
                    height: parent.height;
                    background: Theme.accent-soft;

                    Rectangle {
                        x: parent.width - 2px;
                        y: 0;
                        width: 2px;
                        height: parent.height;
                        background: Theme.accent;
                    }
                }

                // Effects: subtle live shimmer effect on hover across thumbnail
                if (root.glyph == Glyph.sparkle || root.item.glyph == Glyph.sparkle) && card.has-hover: Rectangle {
                    x: -parent.width + (2 * parent.width * root.shimmer);
                    y: 0;
                    width: parent.width;
                    height: parent.height;
                    background: @linear-gradient(90deg,
                        transparent 0%,
                        transparent 25%,
                        Theme.accent-soft 50%,
                        transparent 75%,
                        transparent 100%);
                }

                if !root.item.enabled: Rectangle {
                    x: parent.width - self.width - 4px;
                    y: parent.height - self.height - 4px;
                    width: soon.width + 8px;
                    height: soon.height + 2px;
                    border-radius: Theme.r-xs;
                    background: Theme.scrim;

                    soon := Text {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        text: I18n.t("mediaPane.soon");
                        color: Theme.on-scrim;
                        font-size: Theme.fs-xs;
                    }
                }

                // The plus is its own touch area, so that on a showing
                // card it adds where the tile around it only shows. Always
                // there and shown on hover, rather than made on hover: it
                // has to keep itself on screen while the pointer is over
                // it, whether or not the tile still counts that as hovered.
                Rectangle {
                    x: parent.width - self.width - 4px;
                    y: parent.height - self.height - 4px;
                    width: 20px;
                    height: 20px;
                    border-radius: Theme.r-xs;
                    background: plus.has-hover ? Theme.accent : Theme.scrim;
                    visible: root.item.enabled && (card.has-hover || plus.has-hover);

                    plus := TouchArea {
                        mouse-cursor: pointer;
                        clicked => { root.applied(); }
                    }

                    Icon {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        glyph: Glyph.plus;
                        size: 11px;
                        tint: plus.has-hover ? Theme.on-accent : Theme.on-scrim;
                    }
                }
            }

            if !root.compact: Text {
                x: 0;
                y: tile.height + 4px;
                width: root.width;
                height: 14px;
                text: root.item.label;
                color: Theme.fg-muted;
                font-size: Theme.fs-sm;
                vertical-alignment: center;
                overflow: elide;
            }
        }
    }
}

// One preset, as a card: its sample - "Aa", or a word of its own writing -
// drawn in its look, on a dark
// square so a white title reads as it will on footage, with the plate
// behind it when the look has one. The same two letters at the same size
// on every card so the looks compare - a caption preset is small on the
// frame, but its card is about its face and colours, not its size - the
// names being underneath.
component PresetCard inherits Rectangle {
    in property <TextPresetData> preset;

    callback applied();

    opacity: drag.dragging ? 0.45 : 1.0;

    /// One size for every sample, a good third of the tile: large enough
    /// that a stroke and a face are told apart at a glance.
    property <length> sample-size: root.width * 0.36;

    drag := DragArea {
        data: Payload.of("text:\{root.preset.id}:\{root.preset.name}");
        drag-image: Payload.preview("text:\{root.preset.id}:\{root.preset.name}");
        drag-image-offset-x: -8;
        drag-image-offset-y: -4;
        allow-copy: true;

        touch := TouchArea {
            mouse-cursor: pointer;
            clicked => { root.applied(); }
            double-clicked => { root.applied(); }

            tile := Rectangle {
                y: 0;
                height: root.width;
                border-radius: Theme.r;
                background: Theme.sample-ground;
                border-width: 1px;
                border-color: touch.has-hover ? Theme.line-strong : Theme.line;
                clip: true;

                if root.preset.plated: Rectangle {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    width: Math.min(parent.width - 8px, sample.preferred-width + 14px);
                    height: sample.preferred-height + 6px;
                    border-radius: Theme.r-xs;
                    background: root.preset.plate;
                }

                sample := Text {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    width: Math.min(parent.width - 12px, self.preferred-width);
                    text: root.preset.sample;
                    color: root.preset.fill;
                    font-family: root.preset.family;
                    font-weight: root.preset.weight;
                    font-italic: root.preset.italic;
                    font-size: root.sample-size;
                    stroke: root.preset.stroke;
                    stroke-width: root.preset.stroke-width > 0 ? 1px : 0px;
                    horizontal-alignment: center;
                    overflow: elide;
                }

                if touch.has-hover: Rectangle {
                    x: parent.width - self.width - 4px;
                    y: parent.height - self.height - 4px;
                    width: 20px;
                    height: 20px;
                    border-radius: Theme.r-xs;
                    background: Theme.scrim;

                    Icon {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        glyph: Glyph.plus;
                        size: 11px;
                        tint: Theme.on-scrim;
                    }
                }
            }

            Text {
                x: 0;
                y: tile.height + 4px;
                width: root.width;
                height: 14px;
                text: root.preset.name;
                color: Theme.fg-muted;
                font-size: Theme.fs-sm;
                vertical-alignment: center;
                overflow: elide;
            }
        }
    }
}

// A shelf of the effect catalogue, as Rust narrows it - searched, shelved
// and starred by the same `Library` view the inspector reads - with the
// same auto-fill arithmetic as MediaGrid. Each entry carries its card,
// drawn by the package's own shader (concat_host::cards).
export component ShelfGrid inherits Rectangle {
    in property <[CatalogueEntryData]> entries;
    /// The mark for an entry with no artwork; see CatalogueItemData.
    in property <Glyph> glyph: Glyph.sparkle;
    /// Names the page for the timeline: "filter" makes every card here a drag
    /// source that leaves a layer clip, and empty leaves the page click-only.
    in property <string> payload-kind;

    callback applied(id: string, label: string);
    /// See CatalogueCard: a shelf whose cards show before they add.
    in property <bool> auditions;
    in property <string> auditioning;
    callback auditioned(id: string);

    property <length> gap: 8px;
    property <length> min-card: 88px;
    /// Name-only cards, half the height: for a shelf whose entries have no
    /// picture - sound. A picture shelf keeps its card shape while a card
    /// is still being drawn, its glyph standing in.
    in property <bool> compact;

    property <int> cols: Math.max(1,
        Math.floor((root.width + root.gap) / (root.min-card + root.gap)));
    property <length> card-w: (root.width - (root.cols - 1) * root.gap) / root.cols;
    property <length> card-h: root.compact ? root.card-w / 2
        : root.card-w + 4px + 14px;
    property <int> rows: Math.ceil(root.entries.length / root.cols);

    height: root.rows > 0 ? root.rows * (root.card-h + root.gap) - root.gap : 0px;

    for entry[index] in root.entries: CatalogueCard {
        x: Math.mod(index, root.cols) * (root.card-w + root.gap);
        y: Math.floor(index / root.cols) * (root.card-h + root.gap);
        width: root.card-w;
        height: root.card-h;
        item: {
            id: entry.id,
            label: entry.name,
            enabled: true,
            art: entry.art,
            glyph: root.glyph,
        };
        compact: root.compact;
        payload: root.payload-kind == "" ? ""
            : "\{root.payload-kind}:\{entry.id}:\{entry.name}";
        auditions: root.auditions;
        auditioning: root.auditions && root.auditioning == entry.id;

        auditioned => { root.auditioned(entry.id); }
        applied => { root.applied(entry.id, entry.name); }
    }
}

// The Adjustments page's one card: an adjustment layer, the colour panel's
// package at its defaults over everything beneath it. Dragged onto a lane
// it lands there; a click or its plus lays it at the playhead. One cell of
// the same grid the other shelves use, so it sits like their cards do.
component AdjustmentShelf inherits Rectangle {
    in property <image> art;
    callback placed(label: string);

    /// What the lane calls the layer, in the interface's language.
    property <string> name: I18n.t("mediaPane.adjustment");

    property <length> gap: 8px;
    property <length> min-card: 88px;
    property <int> cols: Math.max(1,
        Math.floor((root.width + root.gap) / (root.min-card + root.gap)));
    property <length> card-w: (root.width - (root.cols - 1) * root.gap) / root.cols;

    height: root.card-w + 4px + 14px;

    CatalogueCard {
        x: 0;
        y: 0;
        width: root.card-w;
        height: parent.height;
        item: {
            id: "concat.adjust",
            label: I18n.t("mediaPane.adjustmentLayer"),
            enabled: true,
            art: root.art,
            glyph: Glyph.sun,
        };
        payload: "filter:concat.adjust:\{root.name}";
        auditions: false;
        applied => { root.placed(root.name); }
    }
}

// The search over a shelf. The field owns its own text once typed in - a
// TextInput assigns to `text`, and an assignment replaces the binding
// declared on it - so the box is put back by hand when Rust clears the
// query, which picking a shelf does.
//
// A shelf that reads packages off disk puts its reload in front of the
// field: a square the field's own height, so the row is one control tall
// and the button takes no line of its own.
export component ShelfSearch inherits HorizontalLayout {
    in property <int> shelf;
    in property <string> placeholder;
    /// Show the reload square, for the shelves custom packages land on.
    in property <bool> reloads;
    callback reload();

    // A little over a standard control: the field leads the page, and the
    // square beside it would be cramped at 28px.
    property <length> field-height: Theme.h + 6px;

    padding-bottom: 8px;
    spacing: 6px;

    if root.reloads: Rectangle {
        width: root.field-height;
        height: root.field-height;
        border-radius: Theme.r-sm;
        background: reload-touch.has-hover ? Theme.field-hover : Theme.field;
        border-width: 1px;
        border-color: Theme.line;

        Icon {
            x: (parent.width - self.width) / 2;
            y: (parent.height - self.height) / 2;
            glyph: Glyph.reset;
            size: 14px;
            tint: reload-touch.has-hover ? Theme.fg : Theme.fg-muted;
        }

        reload-touch := TouchArea {
            mouse-cursor: pointer;
            clicked => { root.reload(); }
        }

        Tip {
            text: I18n.t("mediaPane.reloadCustomEffects");
            active: reload-touch.has-hover;
        }
    }

    SearchField {
        height: root.field-height;
        text: Library.view(root.shelf).query;
        placeholder: root.placeholder;
        edited(text) => { Library.query-changed(root.shelf, text); }
        property <string> held: Library.view(root.shelf).query;
        changed held => { self.text = self.held; }
    }
}

component CategoryPill inherits Rectangle {
    in property <string> text;
    in property <bool> selected;
    callback clicked();
    /// A finger went down on the pill, then slid `dx` across the window
    /// since: the strip's to scroll by. A pill takes the press, so the
    /// strip under it never hears a drag that starts on one (#415).
    callback drag-started();
    callback dragged(dx: length);

    height: 24px;
    border-radius: 12px;
    background: root.selected ? Theme.accent
        : touch.has-hover ? Theme.field-hover
        : Theme.field;

    animate background { duration: 120ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

    HorizontalLayout {
        padding-left: 10px;
        padding-right: 10px;
        alignment: center;

        Text {
            text: root.text;
            color: root.selected ? Theme.on-accent
                : touch.has-hover ? Theme.fg
                : Theme.fg-muted;
            font-size: Theme.fs-xs;
            font-weight: root.selected ? Theme.weight-title : 400;
            vertical-alignment: center;
        }
    }

    touch := TouchArea {
        // Measured across the window, not the pill: the strip moves the
        // pill along with the finger, and the pill's own coordinates would
        // read the slide as no slide at all.
        property <length> start;
        property <bool> slid;
        mouse-cursor: pointer;
        pointer-event(event) => {
            if (event.kind == PointerEventKind.down) {
                self.start = root.absolute-position.x + self.mouse-x;
                self.slid = false;
                root.drag-started();
            }
        }
        moved => {
            if (self.pressed) {
                let dx = root.absolute-position.x + self.mouse-x - self.start;
                if (Math.abs(dx) > 8px) {
                    self.slid = true;
                }
                if (self.slid) {
                    root.dragged(dx);
                }
            }
        }
        clicked => {
            if (!self.slid) {
                root.clicked();
            }
        }
    }
}

export component CategoryPillBar inherits Rectangle {
    in property <[string]> categories: [
        "All",
        "Featured",
        "Retro & Film",
        "Optical & Lens",
        "Distortion & Glitch",
        "Party & Club",
        "Light & Shadow",
    ];
    in property <string> current: "All";
    callback picked(category: string);

    height: 30px;
    clip: true;

    property <length> offset: 0px;
    property <length> content-width: row.preferred-width;
    property <length> max-scroll: Math.max(0px, root.content-width - root.width);
    property <length> press-x: 0px;
    property <length> press-offset: 0px;

    touch := TouchArea {
        pointer-event(event) => {
            if (event.kind == PointerEventKind.down) {
                root.press-x = touch.mouse-x;
                root.press-offset = root.offset;
            }
        }
        moved => {
            if (touch.pressed) {
                root.offset = Math.max(-root.max-scroll, Math.min(0px, root.press-offset + touch.mouse-x - root.press-x));
            }
        }
        scroll-event(event) => {
            root.offset = Math.max(-root.max-scroll, Math.min(0px, root.offset + event.delta-x + event.delta-y));
            return EventResult.accept;
        }

        row := HorizontalLayout {
            x: Math.max(-root.max-scroll, Math.min(0px, root.offset));
            y: 3px;
            height: 24px;
            spacing: 6px;

            for cat in root.categories: CategoryPill {
                drag-started => { root.press-offset = root.offset; }
                dragged(dx) => {
                    root.offset = Math.max(-root.max-scroll, Math.min(0px, root.press-offset + dx));
                }
                text: cat;
                selected: root.current == cat || (root.current == "" && cat == "All" && Library.view(1).group < 0);
                clicked => {
                    root.picked(cat);
                }
            }
        }
    }
}

// A kind's shelves as a strip of pills, All first: the phone's way to the
// desktop's shelf strip. Without it a phone showed the first shelf alone,
// and the first shelf of transitions holds a Dissolve and nothing else
// (#415).
export component GroupPillBar inherits Rectangle {
    /// `Library.view`'s shelf: 0 filters, 1 effects, 2 audio, 3 transitions.
    in property <int> shelf;
    in property <[string]> groups;

    height: 30px;
    clip: true;

    property <int> current: Library.view(root.shelf).group;
    property <length> offset: 0px;
    property <length> max-scroll: Math.max(0px, row.preferred-width - root.width);
    property <length> press-x: 0px;
    property <length> press-offset: 0px;

    touch := TouchArea {
        pointer-event(event) => {
            if (event.kind == PointerEventKind.down) {
                root.press-x = touch.mouse-x;
                root.press-offset = root.offset;
            }
        }
        moved => {
            if (touch.pressed) {
                root.offset = Math.max(-root.max-scroll, Math.min(0px, root.press-offset + touch.mouse-x - root.press-x));
            }
        }
        scroll-event(event) => {
            root.offset = Math.max(-root.max-scroll, Math.min(0px, root.offset + event.delta-x + event.delta-y));
            return EventResult.accept;
        }

        row := HorizontalLayout {
            x: Math.max(-root.max-scroll, Math.min(0px, root.offset));
            y: 3px;
            height: 24px;
            spacing: 6px;

            CategoryPill {
                text: I18n.t("common.all");
                selected: root.current < 0;
                clicked => { Library.group-changed(root.shelf, -1); }
                drag-started => { root.press-offset = root.offset; }
                dragged(dx) => {
                    root.offset = Math.max(-root.max-scroll, Math.min(0px, root.press-offset + dx));
                }
            }
            for label[index] in root.groups: CategoryPill {
                drag-started => { root.press-offset = root.offset; }
                dragged(dx) => {
                    root.offset = Math.max(-root.max-scroll, Math.min(0px, root.press-offset + dx));
                }
                text: label;
                selected: root.current == index;
                clicked => { Library.group-changed(root.shelf, index); }
            }
        }
    }
}

// The Presets shelf: the same auto-fill arithmetic as the other grids.
export component PresetGrid inherits Rectangle {
    in property <[TextPresetData]> items;

    callback applied(id: string);

    property <length> gap: 8px;
    property <length> min-card: 88px;
    property <int> cols: Math.max(1,
        Math.floor((root.width + root.gap) / (root.min-card + root.gap)));
    property <length> card-w: (root.width - (root.cols - 1) * root.gap) / root.cols;
    // A square tile, then the name under it.
    property <length> card-h: root.card-w + 4px + 14px;
    property <int> rows: Math.ceil(root.items.length / root.cols);

    height: root.rows > 0 ? root.rows * (root.card-h + root.gap) - root.gap : 0px;

    for entry[index] in root.items: PresetCard {
        x: Math.mod(index, root.cols) * (root.card-w + root.gap);
        y: Math.floor(index / root.cols) * (root.card-h + root.gap);
        width: root.card-w;
        height: root.card-h;
        preset: entry;

        applied => { root.applied(entry.id); }
    }
}

// ── the stickers page ────────────────────────────────────────────────────────

/// One figure the Shapes shelf offers: its id, which the document stores,
/// the name under its card, and the outline the card draws, on lucide's 24
/// grid like every other mark in the app.
struct ShapeCardData {
    id: string,
    label: string,
    commands: string,
}

// One figure, as a card: its outline in ink on a square tile, the name
// underneath. The outline and not a filled figure, so the card says which
// shape and not which colour - the colour is the clip's to set.
component ShapeCard inherits Rectangle {
    in property <ShapeCardData> shape;

    callback placed();

    opacity: drag.dragging ? 0.45 : 1.0;

    property <string> payload: "shape:\{root.shape.id}:\{root.shape.label}";

    drag := DragArea {
        data: Payload.of(root.payload);
        drag-image: Payload.preview(root.payload);
        drag-image-offset-x: -8;
        drag-image-offset-y: -4;
        allow-copy: true;

        touch := TouchArea {
            mouse-cursor: pointer;
            clicked => { root.placed(); }
            double-clicked => { root.placed(); }

            tile := Rectangle {
                y: 0;
                height: root.width;
                border-radius: Theme.r;
                background: Theme.field;
                border-width: 1px;
                border-color: touch.has-hover ? Theme.line-strong : Theme.line;

                Path {
                    x: (parent.width - self.width) / 2;
                    y: (parent.height - self.height) / 2;
                    width: parent.width * 0.5;
                    height: self.width;
                    viewbox-width: 24;
                    viewbox-height: 24;
                    commands: root.shape.commands;
                    fill: transparent;
                    stroke: touch.has-hover ? Theme.fg : Theme.fg-muted;
                    // Lucide's weight on the 24 grid, scaled with the
                    // mark, the way `Stroked` does it.
                    stroke-width: self.width * 1.6 / 24;
                    stroke-line-cap: round;
                    stroke-line-join: round;
                }

                if touch.has-hover: Rectangle {
                    x: parent.width - self.width - 4px;
                    y: parent.height - self.height - 4px;
                    width: 20px;
                    height: 20px;
                    border-radius: Theme.r-xs;
                    background: Theme.scrim;

                    Icon {
                        x: (parent.width - self.width) / 2;
                        y: (parent.height - self.height) / 2;
                        glyph: Glyph.plus;
                        size: 11px;
                        tint: Theme.on-scrim;
                    }
                }
            }

            Text {
                x: 0;
                y: tile.height + 4px;
                width: root.width;
                height: 14px;
                text: root.shape.label;
                color: Theme.fg-muted;
                font-size: Theme.fs-sm;
                vertical-alignment: center;
                overflow: elide;
            }
        }
    }
}

// The Shapes shelf: the figures a shape clip can be, with the same
// auto-fill arithmetic as PresetGrid.
export component ShapeGrid inherits Rectangle {
    /// Placed by a click; a drag carries the same payload itself.
    callback placed(shape: string, label: string);

    // The ids are written into project files, so they are stable for ever;
    // see ShapeKind in concat-project.
    property <[ShapeCardData]> shapes: [
        { id: "square", label: I18n.t("mediaPane.shapeSquare"), commands: "M4 4h16v16H4z" },
        { id: "circle", label: I18n.t("mediaPane.shapeCircle"),
            commands: "M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0" },
        { id: "triangle", label: I18n.t("mediaPane.shapeTriangle"), commands: "M12 4l9 16H3z" },
        { id: "parallelogram", label: I18n.t("mediaPane.shapeParallelogram"),
            commands: "M8 5h13l-5 14H3z" },
        { id: "trapezoid", label: I18n.t("mediaPane.shapeTrapezoid"), commands: "M8 5h8l5 14H3z" },
        { id: "line", label: I18n.t("mediaPane.shapeLine"), commands: "M3 12h18" },
        { id: "arrow", label: I18n.t("mediaPane.shapeArrow"), commands: "M3 12h18 M15 6l6 6-6 6" },
    ];

    property <length> gap: 8px;
    property <length> min-card: 88px;
    property <int> cols: Math.max(1,
        Math.floor((root.width + root.gap) / (root.min-card + root.gap)));
    property <length> card-w: (root.width - (root.cols - 1) * root.gap) / root.cols;
    // A square tile, then the name under it.
    property <length> card-h: root.card-w + 4px + 14px;
    property <int> rows: Math.ceil(root.shapes.length / root.cols);

    height: root.rows > 0 ? root.rows * (root.card-h + root.gap) - root.gap : 0px;

    for entry[index] in root.shapes: ShapeCard {
        x: Math.mod(index, root.cols) * (root.card-w + root.gap);
        y: Math.floor(index / root.cols) * (root.card-h + root.gap);
        width: root.card-w;
        height: root.card-h;
        shape: entry;

        placed => { root.placed(entry.id, entry.label); }
    }
}

// ── the pane ─────────────────────────────────────────────────────────────────

// Centred placeholder for a page with nothing on it.
component Empty inherits VerticalLayout {
    in property <Glyph> glyph;
    in property <string> text;

    padding: 16px;
    padding-top: 32px;
    spacing: 8px;

    HorizontalLayout {
        alignment: center;
        Icon {
            glyph: root.glyph;
            size: 28px;
            tint: Theme.fg-dim;
        }
    }

    Text {
        text: root.text;
        color: Theme.fg-dim;
        font-size: Theme.fs;
        horizontal-alignment: center;
        wrap: word-wrap;
    }
}

export component MediaPane inherits Rectangle {
    /// The bin, already narrowed to `filter`. Filtering happens on the Rust
    /// side because a Slint model cannot be filtered in the language, and
    /// filtering inside the `for` would leave holes in the grid's indices.
    in property <[MediaItemData]> items;
    in property <int> count-all;
    in property <int> count-video;
    in property <int> count-audio;
    in property <int> count-images;
    /// What the editor made, by origin; not in `count-all`.
    in property <int> count-speech;
    in property <int> count-processed;
    /// how many of the whole bin are selected, not how many of `items` are
    in property <int> selected-count;
    in property <bool> importing;

    /// What the bin is narrowed to. Rust's: a row of the sidebar reports
    /// its pick and the answer comes back here, so the editor can narrow
    /// the bin itself - to all its media, for a file it just made.
    in property <MediaFilter> filter: MediaFilter.all;
    /// See Editor.media-jump-token: turn to the Media page.
    in property <int> jump-token;
    changed jump-token => { root.tab = 0; }

    callback import-media();
    callback filter-changed(filter: MediaFilter);
    /// The sort dropdown beside the import button picked a new order.
    callback sort-changed(index: int);
    /// A press on the bin's floor; see Editor.blur.
    callback floor-pressed();
    callback select(id: int, additive: bool);
    /// A marquee closed over the card grid — see MediaGrid.band-selected.
    callback band-selected(columns: int, from-col: int, to-col: int,
        from-row: int, to-row: int, additive: bool);
    callback remove(id: int);
    callback remove-selected();
    /// double-clicked: place it on the timeline at the playhead
    callback activate(id: int);
    /// right-clicked: the card's menu, filled by Rust; see MediaGrid.context
    callback context(id: int);
    callback menu-selected(id: string);
    in property <[MenuItemData]> menu-items;
    in property <length> menu-height;
    in property <int> menu-token;

    /// The looks the Text page's Styles shelf offers.
    in property <[TextPresetData]> presets;
    /// The looks for other writing, on the Languages shelf beside Styles.
    in property <[TextPresetData]> language-presets;
    /// The effect catalogue's shelves, as Rust narrows them by the
    /// `Library` view: what the Effects, Filters and Transitions pages show.
    in property <[CatalogueEntryData]> catalogue-effects;
    in property <[CatalogueEntryData]> catalogue-audio;
    in property <[CatalogueEntryData]> catalogue-filters;
    in property <[CatalogueEntryData]> catalogue-transitions;
    in property <[string]> effect-groups;
    in property <[string]> audio-groups;
    in property <[string]> filter-groups;
    in property <[string]> transition-groups;
    /// Text page: add a title at the playhead, in the look `preset` names.
    callback add-text(preset: string);
    /// Stickers page: add the figure `shape` names at the playhead, as a
    /// clip called `label`.
    callback add-shape(shape: string, label: string);
    /// Catalogue pages: apply to the selected clip; Rust validates & explains.
    callback apply-effect(effect-id: string);
    callback apply-transition(transition-id: string);
    /// Filters page: lay the look down as a layer at the playhead.
    callback apply-filter(filter-id: string, label: string);
    /// Filters page: a single click shows the look over the whole picture
    /// without laying it down; `audition` is the id being shown, or empty.
    callback audition-filter(filter-id: string);
    in property <string> audition;
    /// Audio page: add a voice or room to the selected clip's sound.
    callback apply-audio(effect-id: string);
    /// Templates page: open the save-as-template flow for this project.
    callback save-template();
    /// Adjustments page: bring in `.cube` tables as looks of the user's own.
    callback import-lut();
    /// Adjustments page: lay an adjustment layer at the playhead, called
    /// `label`.
    callback add-adjustment(label: string);
    /// Adjustments page: a LUT onto the selected clip, or with nothing
    /// selected, laid as a layer at the playhead.
    callback apply-lut(lut-id: string, label: string);
    /// The user's LUTs, for the Adjustments page's shelf.
    in property <[CatalogueEntryData]> catalogue-luts;
    /// The adjustment layer's card.
    in property <image> adjustment-art;
    /// Effects and Filters pages: read the user's effects folder again.
    callback reload-packages();

    /// The corner button: show something else in this pane's seat.
    callback pane-picked(kind: PaneKind);
    /// Which seat this pane is in. It travels no further than the corner
    /// button, whose drag payload has to say where it is being taken from.
    in property <int> pane-seat;
    /// False when this is the last panel on screen. Travels the same way, and
    /// only greys the one row that would close it.
    in property <bool> pane-removable: true;
    /// That row was used.
    callback pane-removed();

    property <int> tab;
    /// The Audio page is up, or not: a drop of sound files on the window
    /// goes into the library while it is.
    changed tab => { Sounds.shown(root.tab == 8); }
    /// The Audio page's shelf: 0 = Mine, 10 = Voices, 11 = Styles. 1 was
    /// Concat's own sounds, off the page until their list is published (#60).
    property <int> audio-category;
    property <bool> sounds-open: true;
    property <bool> voices-open: true;
    /// How far left the page strip can be pushed: nothing, while its chips
    /// fit. See `strip`.
    property <length> strip-floor: Math.min(0px, strip.width - strip.content-width);
    property <bool> categories-open: true;
    property <bool> generated-open: true;
    property <bool> text-open: true;
    /// 0 = Styles, 1 = Languages
    property <int> text-category;
    property <bool> stickers-open: true;
    property <bool> transitions-open: true;
    property <bool> effects-open: true;
    property <bool> filters-open: true;
    property <bool> adjustments-open: true;
    /// 0 = Adjustment layer, 1 = LUTs
    property <int> adjustments-category;
    property <bool> templates-open: true;
    /// The Effects page shows the sound's shelves rather than the
    /// picture's: whichever heading's row was picked last.
    property <bool> audio-shelf;
    property <bool> audio-open: true;
    /// The shelf the Effects page is reading from, in `Library`'s numbers.
    property <int> effects-shelf: root.audio-shelf ? 2 : 1;

    /// The category column. In-out, because it is dragged.
    in-out property <length> sidebar-w: 104px;
    /// Narrow enough to be a real squeeze, wide enough that a category name
    /// still says which category.
    in property <length> min-sidebar: 76px;
    /// Where the column was when the divider went down. A drag is one pointer,
    /// so one slot is enough.
    property <length> press-sidebar;

    /// The sidebar as it is actually drawn — see `headers-w` in the timeline
    /// pane, which has the same problem for the same reason. A library
    /// dropped into a narrow seat would otherwise hand the card grid a
    /// negative width.
    property <length> sidebar: Math.max(0px,
        Math.min(root.sidebar-w, root.width / 2));

    // The catalogues. The ids are written into project files, so they are
    // stable forever - pick them like you mean them. The effect artwork is a
    // rendered preview, each effect's real FFmpeg chain run over one source
    // still. Transitions used to be two hand-written lists here; they are
    // now packages like any other effect, browsed the same way through
    // `catalogue-transitions`/`transition-groups` below.

    function narrow(to: MediaFilter) {
        root.filter-changed(to);
    }

    Pane {
        // The page strip. Its bottom edge is the pane's full-width divider,
        // which is why the hairline is a child of this row and not a border on
        // the pill below it.
        Rectangle {
            height: 52px;

            Rectangle {
                y: parent.height - 1px;
                height: 1px;
                background: Theme.line;
            }

            HorizontalLayout {
                // 4px above and below, not the 8px at the sides: the chips
                // carry a mark over their label and their own air around
                // both, and those need the room within the 52px the strip
                // shares with the other panes' headers.
                padding-top: 4px;
                padding-bottom: 4px;
                padding-left: 8px;
                padding-right: 8px;
                spacing: 8px;

                // The chips sit straight on the header, in its own colour:
                // no sunken track and no border, so the strip reads as the
                // pane's top bar and not as a box set into it. The current
                // page's chip is the only lift.
                track := Rectangle {
                    border-radius: Theme.r;
                    clip: true;

                    // The chips share the track's width while they fit, and
                    // run past its end when they do not: seven pages in a
                    // narrow seat would otherwise be seven labels elided to
                    // nothing. What runs past is reached by the two end
                    // buttons below, not a scrollbar - a bar under a row of
                    // chips 40px tall is a second row where there is no room
                    // for one.
                    strip := Flickable {
                        x: 0;
                        y: 0;
                        width: parent.width;
                        height: parent.height;
                        // A chip is clicked, not flicked: a Flickable that
                        // took the drag would take it off the chips, and
                        // the buttons do the moving.
                        interactive: false;
                        content-width: Math.max(self.width, chips.preferred-width);
                        content-height: self.height;

                        animate content-x { duration: 180ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }

                        // A seat widened while the strip was scrolled would
                        // keep the chips pushed left of a track that now
                        // has room for them.
                        changed width => {
                            self.content-x = Math.max(root.strip-floor, Math.min(0px, self.content-x));
                        }

                        chips := HorizontalLayout {
                            x: 0;
                            y: 0;
                            width: strip.content-width;
                            height: strip.height;
                            padding: 2px;
                            spacing: 2px;

                        LibraryTab {
                            glyph: Glyph.film;
                            label: I18n.t("common.media");
                            current: root.tab == 0;
                            clicked => { root.tab = 0; }
                        }
                        // Beside Media, where CapCut keeps it: the page
                        // number is the last one handed out, not the place.
                        LibraryTab {
                            glyph: Glyph.music;
                            label: I18n.t("common.audio");
                            current: root.tab == 8;
                            clicked => { root.tab = 8; }
                        }
                        LibraryTab {
                            glyph: Glyph.text-mark;
                            label: I18n.t("common.text");
                            current: root.tab == 1;
                            clicked => { root.tab = 1; }
                        }
                        LibraryTab {
                            glyph: Glyph.sticker;
                            label: I18n.t("mediaPane.stickers");
                            current: root.tab == 2;
                            clicked => { root.tab = 2; }
                        }
                        LibraryTab {
                            glyph: Glyph.transition;
                            label: I18n.t("mediaPane.transitions");
                            current: root.tab == 3;
                            clicked => { root.tab = 3; }
                        }
                        LibraryTab {
                            glyph: Glyph.sparkle;
                            label: I18n.t("common.effects");
                            current: root.tab == 4;
                            clicked => { root.tab = 4; }
                        }
                        LibraryTab {
                            glyph: Glyph.filter;
                            label: I18n.t("mediaPane.filters");
                            current: root.tab == 5;
                            clicked => { root.tab = 5; }
                        }
                        // Beside Filters, where CapCut keeps it: the page
                        // number is the last one handed out, not the place.
                        LibraryTab {
                            glyph: Glyph.sun;
                            label: I18n.t("mediaPane.adjustments");
                            current: root.tab == 7;
                            clicked => { root.tab = 7; }
                        }
                        LibraryTab {
                            glyph: Glyph.slot;
                            label: I18n.t("mediaPane.templates");
                            current: root.tab == 6;
                            clicked => { root.tab = 6; }
                        }
                        }
                    }

                    // The end buttons, over the strip, each there only while
                    // there is something past its end to go to.
                    if strip.content-x < 0px: StripEnd {
                        x: 0;
                        height: parent.height;
                        glyph: Glyph.chevron-left;
                        fade: @linear-gradient(90deg, Theme.panel 60%, transparent);
                        clicked => {
                            strip.content-x = Math.min(0px, strip.content-x + strip.width * 0.6);
                        }
                    }
                    if strip.content-x > root.strip-floor: StripEnd {
                        x: parent.width - self.width;
                        height: parent.height;
                        glyph: Glyph.chevron-right;
                        fade: @linear-gradient(270deg, Theme.panel 60%, transparent);
                        clicked => {
                            strip.content-x = Math.max(root.strip-floor, strip.content-x - strip.width * 0.6);
                        }
                    }
                }

                // Outside the sunken track, not in it: the track holds the
                // pages of *this* view and this button changes which view the
                // pane is, which is a different question about a different
                // thing.
                VerticalLayout {
                    alignment: center;
                    PaneSwitcher {
                        kind: PaneKind.media;
                        seat: root.pane-seat;
                        removable: root.pane-removable;
                        picked(kind) => { root.pane-picked(kind); }
                        removed => { root.pane-removed(); }
                    }
                }
            }
        }

        // The page: category sidebar, hairline, browsing area. Positioned by
        // hand for the reason the workspace is — the sidebar is a fixed column
        // and the rest is the remainder, and saying that directly is shorter
        // than a layout plus the stretch factors that would express it.
        body := Rectangle {
            vertical-stretch: 1;

            // The divider is the grab handle, exactly as it is between the
            // track column and the lanes. The sidebar is the only fixed
            // column in the window that could not be resized, and it is the
            // one carrying the longest labels — "Transitions", a category
            // name — so it was also the one most likely to be wrong for a
            // given page at a given window width.
            HairlineSplitter {
                x: root.sidebar;
                y: 0;
                height: parent.height;

                pressed => { root.press-sidebar = root.sidebar-w; }
                moved(delta) => {
                    // Floored so the labels keep their room, and capped at
                    // half the pane so the grid it is squeezing always has
                    // more of the pane than the list of what to put in it.
                    root.sidebar-w = Math.max(root.min-sidebar,
                        Math.min(parent.width / 2, root.press-sidebar + delta));
                }
            }

            Rectangle {
                // Pinned: an element with an explicit width but no x is
                // CENTRED in its parent by Slint's default geometry, and this
                // column spent two rounds of debugging drifting into the card
                // grid because of exactly that. Every element in this file
                // that sets one dimension must pin the other axis too.
                x: 0;
                width: root.sidebar;
                clip: true;

                // One group per page, each behind its own `if`.
                //
                // These were plain children with a `visible` toggle and a
                // height of zero when hidden, to keep a tab switch from
                // re-instantiating anything. That was wrong in a way that only
                // showed up on the later tabs: a zero-height child still takes
                // its share of the layout's `spacing`, so every group started
                // one pixel lower for each hidden row above it, and Templates
                // sat a dozen pixels below Media. A conditional group costs a
                // rebuild on a tab switch — which the pages themselves already
                // pay, a few lines down — and cannot drift.
                VerticalLayout {
                    x: 0;
                    y: 0;
                    width: parent.width;
                    alignment: start;
                    padding: 4px;

                    if root.tab == 0: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("common.media");
                            open: root.categories-open;
                            toggled => { root.categories-open = !root.categories-open; }
                        }
                        if root.categories-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.allMedia");
                            count: root.count-all;
                            current: root.filter == MediaFilter.all;
                            clicked => { root.narrow(MediaFilter.all); }
                        }
                        if root.categories-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("common.video");
                            count: root.count-video;
                            current: root.filter == MediaFilter.video;
                            clicked => { root.narrow(MediaFilter.video); }
                        }
                        if root.categories-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("common.audio");
                            count: root.count-audio;
                            current: root.filter == MediaFilter.audio;
                            clicked => { root.narrow(MediaFilter.audio); }
                        }
                        if root.categories-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.images");
                            count: root.count-images;
                            current: root.filter == MediaFilter.images;
                            clicked => { root.narrow(MediaFilter.images); }
                        }

                        // What the editor made rather than the user
                        // imported, one shelf per origin. A voice read
                        // aloud is here and not under Audio, so the sound
                        // the user brought stays tellable from the sound
                        // the app wrote.
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.generated");
                            open: root.generated-open;
                            toggled => { root.generated-open = !root.generated-open; }
                        }
                        if root.generated-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("common.speech");
                            count: root.count-speech;
                            current: root.filter == MediaFilter.speech;
                            clicked => { root.narrow(MediaFilter.speech); }
                        }
                        // A clip's sound written out as it played, from
                        // the clip's own menu: a file of its own, apart
                        // from the import it was cut from.
                        if root.generated-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.processed");
                            count: root.count-processed;
                            current: root.filter == MediaFilter.processed;
                            clicked => { root.narrow(MediaFilter.processed); }
                        }
                    }

                    // Audio: the user's own sounds.
                    if root.tab == 8: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("sounds.sounds");
                            open: root.sounds-open;
                            toggled => { root.sounds-open = !root.sounds-open; }
                        }
                        if root.sounds-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("sounds.mine");
                            count: Sounds.mine.length;
                            current: root.audio-category == 0;
                            clicked => { root.audio-category = 0; }
                        }
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("voices.voices");
                            open: root.voices-open;
                            toggled => { root.voices-open = !root.voices-open; }
                        }
                        if root.voices-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("voices.voices");
                            count: Sounds.voices-saved.length;
                            current: root.audio-category == 10;
                            clicked => { root.audio-category = 10; }
                        }
                        if root.voices-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("voices.styles");
                            current: root.audio-category == 11;
                            clicked => { root.audio-category = 11; }
                        }
                    }

                    if root.tab == 1: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("common.text");
                            open: root.text-open;
                            toggled => { root.text-open = !root.text-open; }
                        }
                        if root.text-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.styles");
                            current: root.text-category == 0;
                            clicked => { root.text-category = 0; }
                        }
                        // Beside Styles: the looks for other writing.
                        if root.text-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.languages");
                            current: root.text-category == 1;
                            clicked => { root.text-category = 1; }
                        }
                    }

                    // Stickers: the one shelf there is, Shapes, so its row
                    // is always the current one. Pictures and animated
                    // stickers are shelves for another day.
                    if root.tab == 2: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.stickers");
                            open: root.stickers-open;
                            toggled => { root.stickers-open = !root.stickers-open; }
                        }
                        if root.stickers-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.shapes");
                            current: true;
                        }
                    }

                    if root.tab == 3: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.transitions");
                            open: root.transitions-open;
                            toggled => { root.transitions-open = !root.transitions-open; }
                        }
                        if root.transitions-open: VerticalLayout {
                            spacing: 1px;
                            // Every shelf at once, first and the default.
                            CategoryRow {
                                height: 24px;
                                label: I18n.t("common.all");
                                current: Library.view(3).group == -1;
                                clicked => { Library.group-changed(3, -1); }
                            }
                            for label[index] in root.transition-groups: CategoryRow {
                                height: 24px;
                                label: label;
                                current: Library.view(3).group == index;
                                clicked => { Library.group-changed(3, index); }
                            }
                        }
                    }

                    // The picture's shelves and the sound's, from the
                    // catalogue's own groups, on one page called Effects.
                    if root.tab == 4: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.videoEffects");
                            open: root.effects-open;
                            toggled => { root.effects-open = !root.effects-open; }
                        }
                        if root.effects-open: VerticalLayout {
                            spacing: 1px;
                            // Every shelf at once, first and the default.
                            CategoryRow {
                                height: 24px;
                                label: I18n.t("common.all");
                                current: !root.audio-shelf && Library.view(1).group == -1;
                                clicked => { 
                                    root.audio-shelf = false;
                                    Library.group-changed(1, -1);
                                 }
                            }
                            for label[index] in root.effect-groups: CategoryRow {
                                height: 24px;
                                label: label;
                                current: !root.audio-shelf && Library.view(1).group == index;
                                clicked => {
                                    root.audio-shelf = false;
                                    Library.group-changed(1, index);
                                }
                            }
                        }
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.audioEffects");
                            open: root.audio-open;
                            toggled => { root.audio-open = !root.audio-open; }
                        }
                        if root.audio-open: VerticalLayout {
                            spacing: 1px;
                            // Every shelf at once, first and the default.
                            CategoryRow {
                                height: 24px;
                                label: I18n.t("common.all");
                                current: root.audio-shelf && Library.view(2).group == -1;
                                clicked => { 
                                    root.audio-shelf = true;
                                    Library.group-changed(2, -1);
                                 }
                            }
                            for label[index] in root.audio-groups: CategoryRow {
                                height: 24px;
                                label: label;
                                current: root.audio-shelf && Library.view(2).group == index;
                                clicked => {
                                    root.audio-shelf = true;
                                    Library.group-changed(2, index);
                                }
                            }
                        }
                    }

                    // Filters are colour looks, the way every video editor's
                    // users understand the word. What a voice or a room does
                    // to the sound is on the Effects page.
                    if root.tab == 5: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.filters");
                            open: root.filters-open;
                            toggled => { root.filters-open = !root.filters-open; }
                        }
                        if root.filters-open: VerticalLayout {
                            spacing: 1px;
                            // Every shelf at once, first and the default.
                            CategoryRow {
                                height: 24px;
                                label: I18n.t("common.all");
                                current: Library.view(0).group == -1;
                                clicked => { Library.group-changed(0, -1); }
                            }
                            for label[index] in root.filter-groups: CategoryRow {
                                height: 24px;
                                label: label;
                                current: Library.view(0).group == index;
                                clicked => { Library.group-changed(0, index); }
                            }
                        }
                    }

                    // Adjustments: the layer that grades everything beneath
                    // it, and the user's own tables beside it.
                    if root.tab == 7: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.adjustments");
                            open: root.adjustments-open;
                            toggled => { root.adjustments-open = !root.adjustments-open; }
                        }
                        if root.adjustments-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.adjustmentLayer");
                            current: root.adjustments-category == 0;
                            clicked => { root.adjustments-category = 0; }
                        }
                        if root.adjustments-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.luts");
                            count: root.catalogue-luts.length;
                            current: root.adjustments-category == 1;
                            clicked => { root.adjustments-category = 1; }
                        }
                    }

                    if root.tab == 6: VerticalLayout {
                        spacing: 1px;
                        CategoryHeading {
                            height: 26px;
                            title: I18n.t("mediaPane.templates");
                            open: root.templates-open;
                            toggled => { root.templates-open = !root.templates-open; }
                        }
                        if root.templates-open: CategoryRow {
                            height: 24px;
                            label: I18n.t("mediaPane.myTemplates");
                            current: true;
                        }
                    }
                }
            }

            pages := PaneScroll {
                x: root.sidebar + 1px;
                width: Math.max(0px, parent.width - root.sidebar - 1px);
                height: parent.height;

                if root.tab == 0: HorizontalLayout {
                    padding: 8px;
                    spacing: 8px;
                    // Import holds the left edge at the width its own word
                    // needs; sort and filter are pushed against the right by
                    // the gap between, which is the only part of the row with
                    // any give in it.
                    ImportButton {
                        // The row holds one other control, and two controls
                        // side by side at two different heights read as two
                        // rows that failed to line up.
                        height: Theme.h;
                        horizontal-stretch: 0;
                        busy: root.importing;
                        clicked => { root.import-media(); }
                    }
                    Rectangle { horizontal-stretch: 1; }
                    // Sort, and sort only: narrowing the bin by kind is the
                    // sidebar's, where each kind carries its count and the
                    // current one stays lit. A second control saying the same
                    // thing from the other side of the panel can only ever
                    // agree with it or contradict it.
                    //
                    // Marked rather than worded: at the end of a row this
                    // narrow, "Sort: Added" costs more room than it earns, and
                    // the list behind it still spells all three out.
                    Select {
                        horizontal-stretch: 0;
                        width: self.natural-width;
                        options: [I18n.t("mediaPane.sortAdded"), I18n.t("mediaPane.sortName"),
                            I18n.t("mediaPane.sortType")];
                        icons: [Glyph.clock, Glyph.text-mark, Glyph.tag];
                        current: 0;
                        changed(index) => { root.sort-changed(index); }
                    }
                }

                // Only worth a row when a multiple selection exists — one
                // selected card is deleted from the card itself.
                if root.tab == 0 && root.selected-count > 1: HorizontalLayout {
                    padding-left: 8px;
                    padding-right: 8px;
                    padding-bottom: 8px;

                    Rectangle {
                        height: 28px;
                        background: Theme.well;
                        border-radius: Theme.r;

                        HorizontalLayout {
                            padding-left: 10px;
                            padding-right: 4px;
                            spacing: 8px;

                            Text {
                                horizontal-stretch: 1;
                                text: "\{root.selected-count} selected";
                                color: Theme.fg-muted;
                                font-size: Theme.fs-sm;
                                vertical-alignment: center;
                                overflow: elide;
                            }

                            VerticalLayout {
                                alignment: center;
                                Rectangle {
                                    width: wipe.width + 16px;
                                    height: 20px;
                                    border-radius: Theme.r-xs;
                                    background: bin.has-hover ? Theme.danger-soft
                                        : Colors.transparent;

                                    wipe := Text {
                                        x: (parent.width - self.width) / 2;
                                        y: (parent.height - self.height) / 2;
                                        text: I18n.t("common.delete");
                                        color: Theme.danger;
                                        font-size: Theme.fs-sm;
                                    }

                                    bin := TouchArea {
                                        mouse-cursor: pointer;
                                        clicked => { root.remove-selected(); }
                                    }
                                }
                            }
                        }
                    }
                }

                if root.tab == 0 && root.items.length == 0: Empty {
                    glyph: Glyph.import;
                    text: root.filter == MediaFilter.speech
                        ? I18n.t("mediaPane.nothingReadAloudYet")
                        : root.filter == MediaFilter.processed
                        ? I18n.t("mediaPane.nothingRenderedYetRight")
                        : root.count-all > 0
                        ? I18n.t("mediaPane.nothingKindProject")
                        : I18n.t("mediaPane.dropToImport");
                }

                if root.tab == 0 && root.items.length > 0: HorizontalLayout {
                    padding-left: 8px;
                    padding-right: 8px;
                    padding-bottom: 8px;

                    MediaGrid {
                        horizontal-stretch: 1;
                        items: root.items;
                        // Whatever the page has left after the rows above it:
                        // the import row is 8 + 36 + 8, the delete strip 28
                        // and its own 8, and this row keeps 8 under itself.
                        // Counted rather than measured, because reading a
                        // sibling's laid-out height from inside the layout
                        // that assigns it is a binding loop waiting to happen.
                        page-floor: Math.max(0px, pages.height - 52px
                            - (root.selected-count > 1 ? 36px : 0px) - 8px);

                        menu-items: root.menu-items;
                        menu-height: root.menu-height;
                        menu-token: root.menu-token;

                        pressed => { root.floor-pressed(); }
                        clicked(id, additive) => { root.select(id, additive); }
                        activated(id) => { root.activate(id); }
                        removed(id) => { root.remove(id); }
                        context(id) => { root.context(id); }
                        menu-selected(id) => { root.menu-selected(id); }
                        band-selected(columns, from-col, to-col, from-row, to-row, additive) => {
                            root.band-selected(columns, from-col, to-col,
                                from-row, to-row, additive);
                        }
                    }
                }

                // Mine: the user's own sounds, copied in and kept across
                // projects. The import is the page's head, and its rows
                // are the sounds, newest first.
                if root.tab == 8 && root.audio-category == 0: VerticalLayout {
                    padding: 8px;
                    spacing: 8px;

                    ImportButton {
                        label: I18n.t("sounds.importSounds");
                        busy: Sounds.importing;
                        clicked => { Sounds.import(); }
                    }
                    if Sounds.mine.length > 0: Text {
                        text: I18n.t("sounds.mineHint");
                        color: Theme.fg-muted;
                        font-size: Theme.fs-sm;
                        wrap: word-wrap;
                    }
                    SoundList {
                        items: Sounds.mine;
                    }
                }

                // Voices: the user's saved clones and the models' own
                // speakers, or the styles; a click opens Text to speech
                // on one.
                if root.tab == 8 && root.audio-category >= 10: VerticalLayout {
                    padding: 8px;
                    spacing: 8px;

                    if root.audio-category == 10: Text {
                        text: I18n.t("voices.hint");
                        color: Theme.fg-muted;
                        font-size: Theme.fs-sm;
                        wrap: word-wrap;
                    }
                    VoiceList {
                        styles: root.audio-category == 11;

                        // A recording of the user's own kept as a voice,
                        // brought in as Mine brings in a sound.
                        if root.audio-category == 10: VerticalLayout {
                            padding-top: 4px;
                            padding-bottom: 6px;
                            ImportButton {
                                label: I18n.t("voices.importVoice");
                                clicked => { Sounds.voice-import(); }
                            }
                        }
                    }
                }

                if root.tab == 8 && root.audio-category == 0 && Sounds.mine.length == 0: Empty {
                    glyph: Glyph.music;
                    text: I18n.t("sounds.noSoundsYet");
                }

                // The looks. Each card is a title in that look, placed at
                // the playhead on a click or dragged onto a lane; a preset
                // that brings a font installs it on the way.
                if root.tab == 1: HorizontalLayout {
                    padding: 8px;

                    PresetGrid {
                        horizontal-stretch: 1;
                        items: root.text-category == 1 ? root.language-presets : root.presets;
                        applied(id) => { root.add-text(id); }
                    }
                }

                // The figures. Each card is one shape, placed at the
                // playhead on a click or dragged onto a lane.
                if root.tab == 2: HorizontalLayout {
                    padding: 8px;

                    ShapeGrid {
                        horizontal-stretch: 1;
                        placed(shape, label) => { root.add-shape(shape, label); }
                    }
                }

                if root.tab == 3: VerticalLayout {
                    padding: 8px;

                    ShelfSearch {
                        shelf: 3;
                        placeholder: I18n.t1("common.searchKind", I18n.t("mediaPane.transition"));
                    }
                    ShelfGrid {
                        entries: root.catalogue-transitions;
                        glyph: Glyph.transition;
                        // Transitions apply directly on single-click — no audition overlay.
                        auditions: false;
                        applied(id, label) => { root.apply-transition(id); }
                    }
                }

                if root.tab == 4: VerticalLayout {
                    padding: 8px;

                    // A package folder written while the app runs - the
                    // user's own effect, or one shared with them - is read
                    // in from the square before the search, without a
                    // restart. No category pills: the search finds an
                    // effect, and the room goes to the cards.
                    ShelfSearch {
                        shelf: root.effects-shelf;
                        placeholder: root.audio-shelf
                            ? I18n.t1("common.searchKind", I18n.t("common.audioEffect"))
                            : I18n.t1("common.searchKind", I18n.t("common.effect"));
                        reloads: true;
                        reload => { root.reload-packages(); }
                    }
                    ShelfGrid {
                        entries: root.audio-shelf ? root.catalogue-audio : root.catalogue-effects;
                        glyph: root.audio-shelf ? Glyph.waveform : Glyph.sparkle;
                        // A sound has no picture: its cards are the compact kind.
                        compact: root.audio-shelf;
                        // A picture effect is a layer on the timeline, as a
                        // filter is: dragged onto the lanes, it works on
                        // everything beneath it for as long as it runs. Short
                        // of a drag, a click shows it over the monitor and a
                        // double-click or the plus lays it at the playhead.
                        // It is no longer put on the selected clip: that was
                        // a second way to the same picture, found by
                        // selecting a clip and then hunting for its tab.
                        // A sound effect still goes on the selected clip - a
                        // voice changed, not the music under it.
                        auditions: !root.audio-shelf;
                        auditioning: root.audio-shelf ? "" : root.audition;
                        auditioned(id) => { root.audition-filter(id); }
                        // A sound effect dragged onto the lanes is a sound
                        // layer: it treats everything heard under it for as
                        // long as it runs. A click still puts it on the
                        // selected clip.
                        payload-kind: root.audio-shelf ? "audio-filter" : "filter";
                        applied(id, label) => {
                            if (root.audio-shelf) {
                                root.apply-audio(id);
                            } else {
                                root.apply-filter(id, label);
                            }
                        }
                    }
                }

                if root.tab == 5: VerticalLayout {
                    padding: 8px;

                    // A filter is a layer over a span of the timeline,
                    // dragged onto the lanes like a piece of media - the
                    // payload says so. Short of a drag, a click shows the
                    // look over the monitor, and a double-click or the
                    // card's plus lays it at the playhead.
                    // A table of the user's own is not here: it is the
                    // Adjustments page's, imported and listed there.
                    ShelfSearch {
                        shelf: 0;
                        placeholder: I18n.t1("common.searchKind", I18n.t("mediaPane.filter"));
                        reloads: true;
                        reload => { root.reload-packages(); }
                    }
                    ShelfGrid {
                        entries: root.catalogue-filters;
                        payload-kind: "filter";
                        auditions: true;
                        auditioning: root.audition;
                        auditioned(id) => { root.audition-filter(id); }
                        applied(id, label) => { root.apply-filter(id, label); }
                    }
                }

                // The adjustment layer: a look built by hand, over a span of
                // the timeline, treating everything beneath it.
                if root.tab == 7 && root.adjustments-category == 0: VerticalLayout {
                    padding: 8px;
                    spacing: 8px;

                    Text {
                        text: I18n.t("mediaPane.adjustmentLayerHint");
                        color: Theme.fg-muted;
                        font-size: Theme.fs-sm;
                        wrap: word-wrap;
                    }
                    AdjustmentShelf {
                        art: root.adjustment-art;
                        placed(label) => { root.add-adjustment(label); }
                    }
                }

                // The user's LUTs. A table from any grading tool comes in
                // here; a click puts it on the selected clip, as an effect
                // goes on, and a drag lays it on the lanes as a layer -
                // the payload says so.
                if root.tab == 7 && root.adjustments-category == 1: VerticalLayout {
                    padding: 8px;
                    spacing: 8px;

                    ImportButton {
                        label: I18n.t("mediaPane.importALut");
                        glyph: Glyph.import;
                        clicked => { root.import-lut(); }
                    }
                    if root.catalogue-luts.length > 0: Text {
                        text: I18n.t("mediaPane.lutsHint");
                        color: Theme.fg-muted;
                        font-size: Theme.fs-sm;
                        wrap: word-wrap;
                    }
                    ShelfGrid {
                        entries: root.catalogue-luts;
                        glyph: Glyph.sun;
                        payload-kind: "filter";
                        auditions: false;
                        applied(id, label) => { root.apply-lut(id, label); }
                    }
                }

                if root.tab == 7 && root.adjustments-category == 1
                    && root.catalogue-luts.length == 0: Empty {
                    glyph: Glyph.sun;
                    text: I18n.t("mediaPane.noLutsYet");
                }

                // Templates: the save affordance, then the gallery of saved
                // templates, which shows its empty state until one is saved.
                if root.tab == 6: HorizontalLayout {
                    padding: 8px;

                    ImportButton {
                        label: I18n.t("mediaPane.saveProjectTemplate");
                        glyph: Glyph.slot;
                        clicked => { root.save-template(); }
                    }
                }

                if root.tab == 6: Empty {
                    glyph: Glyph.slot;
                    text: I18n.t("mediaPane.noTemplatesYetMark");
                }
            }
        }
    }
}