Skip to content

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

110 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 } from "../theme/theme.slint";
import { Glyph, Icon } from "../icons.slint";
import {
    IconButton,
    Row,
    Section,
    SectionBody,
    SectionHeader,
} from "../primitives/panel.slint";
import { Button } from "../primitives/modal.slint";
import { SegmentedControl } from "../primitives/segmented-control.slint";
import { Select } from "../primitives/select.slint";
import { SpeedGraph, SpeedRamp } from "speed-ramp.slint";
import {
    Check,
    ColourField,
    HelpButton,
    InspectorFmt,
    Note,
    Param,
    ParamFormat,
    Rail,
    ResetButton,
    SearchField,
    Subhead,
    Switch,
    SwitchRow,
} from "controls.slint";
import {
    ColorWheel,
    CurveData,
    CurveEditor,
    CurveGroupData,
    WheelData,
    WheelGroupData,
} from "grading.slint";
import {
    Backdrop,
    BackdropData,
    ClipField,
    ClipKind,
    Keyframes,
    SelectedClipData,
    SelectedTransitionData,
} from "../timeline/model.slint";

// The editor's clip inspector: one panel, three tabs. Adjust is direct
// controls; Effects and Audio are each a PresetStack over their chain. A
// filter is a layer on the lanes and gets FilterPanel, not a chain.

/// One parameter a preset exposes. `value` doubles as the default in the
/// catalogue: applying a preset copies the row, and double-click restores
/// `default-value`.
/// One package on a library shelf. Published by Rust from the effect
/// catalogue; the id is what Rust is handed back when the row is clicked, and
/// ids are stable forever because project files store them.
export struct CatalogueEntryData {
    id: string,
    name: string,
    /// Starred, so it shows under the star chip whatever shelf it is on.
    favourite: bool,
    /// The shelf's label, and its index into the kind's group list.
    category: string,
    group: int,
    description: string,
    /// The card's still: an author's own, else the one drawn by the
    /// package's shader. Empty while that is still being drawn, and for a
    /// sound.
    art: image,
}

/// What one effect library is currently showing.
export struct LibraryViewData {
    /// The words in its search box.
    query: string,
    /// Which shelf is selected, as an index into the kind's group list.
    group: int,
    /// The star is down: only favourites show, whatever shelf they are on.
    favourites: bool,
    /// Active category filter (e.g. "All", "Featured", "Retro & Film", etc.).
    category: string,
}

/// The three effect libraries' view state and the verbs that change it.
///
/// A global for the same reason `Keyframes` is one: the state belongs to
/// Rust - which does the searching, shelving and starring before the model
/// is published - and threading nine properties and four callbacks down
/// through the workspace to reach three sibling panels would be a lot of
/// plumbing for a fact that has one owner.
export global Library {
    /// One view per shelf, indexed by the numbers `PresetStack.shelf` uses:
    /// 0 filters, 1 effects, 2 audio, 3 transitions.
    in property <[LibraryViewData]> views;

    /// The search box was typed in.
    callback query-changed(shelf: int, text: string);
    /// A shelf was picked from the strip.
    callback group-changed(shelf: int, index: int);
    /// The star chip was pressed.
    callback favourites-changed(shelf: int, on: bool);
    /// A category pill was selected.
    callback category-changed(shelf: int, category: string);
    /// A package was starred or unstarred. Not per shelf: a star is a fact
    /// about the package, and it is remembered across sessions.
    callback favourite(id: string, on: bool);

    pure public function view(shelf: int) -> LibraryViewData {
        if (Library.views.length < 4) {
            return { query: "", group: 0, favourites: false, category: "" };
        }
        return Library.views[shelf];
    }
}

/// One link of the selected clip's chain, in chain order.
export struct AppliedEntryData {
    id: string,
    name: string,
    /// False bypasses the link without losing what was dialled into it.
    on: bool,
    /// False when no package answers to the id: the row still shows, so the
    /// link can be removed, but it has no knobs and renders nothing.
    known: bool,
}

/// One knob of one link. Flat rather than nested in the entry so a value
/// changing under a drag rewrites one small row and not the whole link.
export struct AppliedParamData {
    /// Which link, as an index into the applied list.
    entry: int,
    /// The manifest's key; what Rust is handed back with the new value.
    key: string,
    label: string,
    /// The subhead this knob sits under; empty for none. Rows that share
    /// one in a run share one subhead.
    group: string,
    /// The unit the manifest gives the value: `%`, `K`, `EV`, or nothing.
    unit: string,
    min: float,
    max: float,
    step: float,
    default-value: float,
    value: float,
    fmt: ParamFormat,
    /// The knob can carry keys - the Adjust panel's can, a chain's cannot
    /// yet - and, when it can, the same four facts a ClipKeyData holds:
    /// it rides at all, a key sits under the playhead, and there is one
    /// behind or ahead to step to.
    keyable: bool,
    keyed: bool,
    here: bool,
    prev: bool,
    next: bool,
}

/// One knob of a transition that is a choice among a few - Push's
/// direction - drawn as segments: a direction is picked, not dialled.
export struct TransitionChoiceData {
    key: string,
    label: string,
    options: [string],
    /// The value each option stores, in the same order.
    values: [float],
    current: int,
}

/// One colour knob of one link - a key's screen colour - drawn as a swatch
/// that opens the picker, with the hex beside it.
export struct ColourKnobData {
    /// Which link, as an index into the applied list.
    entry: int,
    /// The manifest's key; what Rust is handed back with the new colour.
    key: string,
    label: string,
    value: color,
}

/// The favourites chip: a star that filters the shelf down to what is on it.
component StarChip inherits Rectangle {
    in property <bool> on;

    callback clicked();

    width: 26px;
    height: 26px;
    border-radius: 13px;
    background: root.on ? Theme.accent-soft
        : touch.has-hover ? Theme.field-hover
        : Theme.field;

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

    Icon {
        glyph: Glyph.sparkle;
        size: 12px;
        filled: root.on;
        tint: root.on ? Theme.accent : Theme.fg-muted;
    }

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

/// A chain and its library: the links applied to the selected clip, each
/// with a control per parameter its package declares, and under it the
/// shelves of packages that can be added. One component serves effects,
/// filters and audio alike — the data says which.
export component PresetStack inherits VerticalLayout {
    /// lower-case singular, for labels and placeholders
    in property <string> noun: I18n.t("common.effect");
    in property <string> library-title: I18n.t("clipInspector.effectLibrary");
    in property <[string]> group-labels;
    in property <[CatalogueEntryData]> catalogue;
    /// Owned by Rust: a chain is edited by index, and Slint models cannot be
    /// spliced from the language.
    in property <[AppliedEntryData]> applied;
    in property <[AppliedParamData]> params;
    /// The links' wheels and curves, a group a link that has any.
    in property <[WheelGroupData]> wheel-groups;
    in property <[CurveGroupData]> curve-groups;
    /// The links' colour knobs, a row each.
    in property <[ColourKnobData]> colours;

    /// Which of the three libraries this is: 0 filters, 1 effects, 2 audio.
    /// The index its view state and its callbacks are keyed by.
    in property <int> shelf;

    /// Which shelf is showing, which words are in the search box, and
    /// whether the star is down. Owned by Rust, because the list below is:
    /// the catalogue arrives already narrowed by all three, and a control
    /// showing one thing while the list shows another is the bug that
    /// arrangement is there to make impossible.
    property <LibraryViewData> view: Library.view(root.shelf);
    property <int> group: root.view.group;
    property <string> query: root.view.query;
    property <bool> favourites-only: root.view.favourites;

    callback add(id: string);
    callback toggle(index: int);
    callback move-by(index: int, delta: int);
    callback remove(index: int);
    /// One knob moved. The value lands on the echo; `commit` makes it real.
    callback set-param(index: int, key: string, value: float);
    /// A colour knob picked, likewise.
    callback set-colour(index: int, key: string, value: color);
    /// A curve's point moved, or put down when `point` is -1, or taken off.
    callback curve-point(index: int, key: string, point: int, x: float, y: float);
    callback curve-remove(index: int, key: string, point: int);
    callback commit();

    // The grid. Three columns at the inspector's width, which puts a tile at
    // about 70px - wide enough for "Voice Focus" on two lines and narrow
    // enough that a shelf of twenty is four rows rather than seven.
    property <int> columns: 3;
    property <length> pad: Theme.pad;
    property <length> cell-gap: 8px;
    property <length> cell-w: (root.width - 2 * root.pad
        - (root.columns - 1) * root.cell-gap) / root.columns;
    property <length> cell-h: 64px;
    property <int> rows: ceil(root.catalogue.length / root.columns);

    /// Links that belong to another section's controls - the audio
    /// treatments, which have switches of their own - and so are not shown
    /// as cards here. Three at most; the scan is as deep as the list.
    in property <[string]> hidden: [];
    /// Whether the stack offers the library at all. Off for the picture's
    /// chains, whose libraries are the Library pane's Effects and Filters
    /// pages: the stack is then the chain alone, with a word on where to
    /// find more when it is empty.
    in property <bool> library: true;
    /// The words for an empty chain without a library.
    in property <string> empty-note;

    pure function is-hidden(id: string) -> bool {
        return root.hidden.length > 0 && (root.hidden[0] == id
            || (root.hidden.length > 1 && root.hidden[1] == id)
            || (root.hidden.length > 2 && root.hidden[2] == id)
            || (root.hidden.length > 3 && root.hidden[3] == id));
    }

    function in-chain(id: string) -> bool {
        // A real member test wants a model lookup Slint cannot express, so
        // this scans the first eight links, which is deeper than a chain
        // gets before it stops being a chain and starts being a problem.
        return root.applied.length > 0 && (root.applied[0].id == id
            || (root.applied.length > 1 && root.applied[1].id == id)
            || (root.applied.length > 2 && root.applied[2].id == id)
            || (root.applied.length > 3 && root.applied[3].id == id)
            || (root.applied.length > 4 && root.applied[4].id == id)
            || (root.applied.length > 5 && root.applied[5].id == id)
            || (root.applied.length > 6 && root.applied[6].id == id)
            || (root.applied.length > 7 && root.applied[7].id == id));
    }

    Section {
        first: true;

        SectionHeader {
            title: root.library-title;
            HelpButton {
                text: I18n.t("clipInspector.chainRunsTopBottom");
            }
        }

        if !root.library && root.applied.length == 0: Note {
            text: root.empty-note;
        }

        // What is on the chain, first and in its own library: a link is a
        // card with its knobs, its bypass and its place in the order, and
        // it sits where it was picked from rather than in a list of its
        // own that says nothing about what kind of thing it is.
        VerticalLayout {
            padding-left: Theme.pad;
            padding-right: Theme.pad;

            for item[index] in root.applied: link := VerticalLayout {
                property <bool> hidden: root.is-hidden(item.id);
                /// Folded to its header: a long chain stays scannable, and
                /// what is dialled in stays put.
                property <bool> open: true;
                padding-bottom: self.hidden ? 0px : 8px;

                if !self.hidden: Rectangle {
                    border-radius: Theme.r;
                    background: Theme.raised;
                    border-width: 1px;
                    border-color: head-touch.has-hover ? Theme.line-strong : Theme.line;

                    animate border-color { duration: 120ms; }

                    VerticalLayout {
                        padding-bottom: link.open ? 10px : 0px;
                        spacing: 6px;

                        // The header: the link's switch, its name - which
                        // folds the card - and its place in the order.
                        Rectangle {
                            height: 38px;

                            head-touch := TouchArea {
                                mouse-cursor: pointer;
                                clicked => { link.open = !link.open; }
                            }

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

                                VerticalLayout {
                                    alignment: center;
                                    // The switch flips itself on a click, which
                                    // ends a binding; it is set again whenever
                                    // the document says otherwise - an undo.
                                    switch := Switch {
                                        property <bool> held: item.on;
                                        checked: self.held;
                                        changed held => { self.checked = self.held; }
                                        toggled(on) => { root.toggle(index); }
                                    }
                                }

                                Text {
                                    horizontal-stretch: 1;
                                    text: item.name;
                                    color: !item.known ? Theme.fg-dim
                                        : item.on ? Theme.fg : Theme.fg-muted;
                                    font-size: Theme.fs;
                                    font-weight: Theme.weight-title;
                                    vertical-alignment: center;
                                    overflow: elide;
                                }

                                if !item.known: Text {
                                    text: I18n.t("clipInspector.notInstalled");
                                    color: Theme.fg-dim;
                                    font-size: Theme.fs-xs;
                                    vertical-alignment: center;
                                }

                                // Order and removal stay quiet beside the
                                // name; a chain of one has no order.
                                if root.applied.length > 1: IconButton {
                                    glyph: Glyph.chevron-up;
                                    label: I18n.t1("clipInspector.moveUp", "\{item.name}");
                                    enabled: index > 0;
                                    idle: Theme.fg-dim;
                                    clicked => { root.move-by(index, -1); }
                                }

                                if root.applied.length > 1: IconButton {
                                    glyph: Glyph.chevron-down;
                                    label: I18n.t1("clipInspector.moveDown", "\{item.name}");
                                    enabled: index < root.applied.length - 1;
                                    idle: Theme.fg-dim;
                                    clicked => { root.move-by(index, 1); }
                                }

                                IconButton {
                                    glyph: Glyph.trash;
                                    label: I18n.t1("clipInspector.remove", "\{item.name}");
                                    idle: Theme.fg-dim;
                                    danger: true;
                                    clicked => { root.remove(index); }
                                }

                                VerticalLayout {
                                    alignment: center;
                                    Icon {
                                        glyph: link.open ? Glyph.chevron-down : Glyph.chevron-right;
                                        size: 12px;
                                        tint: Theme.fg-dim;
                                    }
                                }
                                Rectangle { width: 4px; }
                            }
                        }

                        if link.open && item.known: Rectangle {
                            height: 1px;
                            background: Theme.line;
                        }

                        // One control per parameter the package declares. The
                    // knob writes to its own `value`, which drops a binding,
                    // so the row re-seeds it whenever Rust republishes the
                    // parameter — a new clip, an undo — and the control
                    // never shows a number that is not the document's.
                    for p in root.params: Rectangle {
                            property <AppliedParamData> data: p;
                            visible: link.open && p.entry == index;
                            height: link.open && p.entry == index ? knob.preferred-height : 0;
                            opacity: item.on ? 1.0 : 0.5;
                            changed data => { knob.value = self.data.value; }

                            knob := Param {
                                // A slider and the number, rather than the
                                // number alone: an effect is dialled by eye.
                                rail: true;
                                label: p.label;
                                value: p.value;
                                minimum: p.min;
                                maximum: p.max;
                                step: p.step;
                                default-value: p.default-value;
                                fmt: p.fmt;
                                unit: p.unit;
                                enabled: item.on;
                                changed(v) => {
                                    root.set-param(index, p.key, v);
                                    root.commit();
                                }
                            }
                        }

                        // The link's colours: a swatch that opens the
                        // picker, and the hex, typed as well as read.
                        for c in root.colours: Rectangle {
                            visible: link.open && c.entry == index;
                            height: link.open && c.entry == index ? swatch.preferred-height : 0;

                            swatch := ColourField {
                                label: c.label;
                                value: c.value;
                                alpha: false;
                                changed(colour) => {
                                    root.set-colour(index, c.key, colour);
                                    root.commit();
                                }
                            }
                        }

                        // The link's wheels, three in a row, and its curves.
                        for g in root.wheel-groups: Rectangle {
                            visible: link.open && g.entry == index;
                            height: link.open && g.entry == index ? trio.preferred-height : 0;

                            trio := HorizontalLayout {
                                padding-left: Theme.pad;
                                padding-right: Theme.pad;
                                spacing: 8px;

                                for w in g.wheels: ColorWheel {
                                    data: w;
                                    enabled: item.on;
                                    moved(x, y) => {
                                        root.set-param(index, w.key + ".x", x);
                                        root.set-param(index, w.key + ".y", y);
                                        root.commit();
                                    }
                                    master-changed(v) => {
                                        root.set-param(index, w.key + ".m", v);
                                        root.commit();
                                    }
                                }
                            }
                        }
                        for g in root.curve-groups: Rectangle {
                            visible: link.open && g.entry == index;
                            height: link.open && g.entry == index ? graph.preferred-height : 0;

                            graph := CurveEditor {
                                padding-left: Theme.pad;
                                padding-right: Theme.pad;
                                curves: g.curves;
                                enabled: item.on;
                                point(key, point, x, y) => {
                                    root.curve-point(index, key, point, x, y);
                                    root.commit();
                                }
                                remove(key, point) => {
                                    root.curve-remove(index, key, point);
                                    root.commit();
                                }
                            }
                        }
                    }
                }
            }
        }

        // A breath between the section's title and its search.
        if root.library: Rectangle {
            height: 6px;
        }

        if root.library: Row {
            search := SearchField {
                text: root.query;
                placeholder: I18n.t1("common.searchKind", "\{root.noun}");
                edited(text) => { Library.query-changed(root.shelf, text); }
                // 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 and pressing the
                // star both do.
                property <string> held: root.query;
                changed held => { self.text = self.held; }
            }
        }

        // Air between the field and the strip under it: two rows butted
        // together read as one control, and they are not.
        if root.library: Rectangle {
            height: 8px;
        }

        // The star and the shelves. Favourites is not one more shelf: it
        // cuts across all of them, so it is a chip beside the strip rather
        // than a segment inside it, and it takes the strip's place when it
        // is on because a shelf inside a starred set is a filter of a filter
        // nobody asked for.
        if root.library: HorizontalLayout {
            padding-left: root.pad;
            padding-right: root.pad;
            spacing: 6px;
            height: 26px;

            StarChip {
                on: root.favourites-only;
                clicked => { Library.favourites-changed(root.shelf, !root.favourites-only); }
            }

            // The shelves as pills on the panel, the Library pane's way,
            // rather than a dark segmented track: picking one also leaves
            // the starred set, since a shelf is a different question. All
            // leads them, and is where a library opens.
            for label[i] in [I18n.t("common.all")]: Rectangle {
                property <bool> picked: !root.favourites-only && root.group == -1;
                border-radius: 13px;
                background: self.picked ? Theme.accent
                    : all-touch.has-hover ? Theme.field-hover : Theme.field;
                min-width: all-text.preferred-width + 20px;
                horizontal-stretch: 0;

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

                all-text := Text {
                    text: label;
                    color: parent.picked ? Theme.on-accent
                        : all-touch.has-hover ? Theme.fg : Theme.fg-muted;
                    font-size: Theme.fs-sm;
                    font-weight: parent.picked ? Theme.weight-title : 400;
                    vertical-alignment: center;
                    horizontal-alignment: center;
                }

                all-touch := TouchArea {
                    mouse-cursor: pointer;
                    clicked => {
                        if (root.favourites-only) {
                            Library.favourites-changed(root.shelf, false);
                        }
                        Library.group-changed(root.shelf, -1);
                    }
                }
            }

            for label[i] in root.group-labels: Rectangle {
                property <bool> picked: !root.favourites-only && root.group == i;
                border-radius: 13px;
                background: self.picked ? Theme.accent
                    : pill-touch.has-hover ? Theme.field-hover : Theme.field;
                min-width: pill-text.preferred-width + 20px;
                horizontal-stretch: 0;

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

                pill-text := Text {
                    text: label;
                    color: parent.picked ? Theme.on-accent
                        : pill-touch.has-hover ? Theme.fg : Theme.fg-muted;
                    font-size: Theme.fs-sm;
                    font-weight: parent.picked ? Theme.weight-title : 400;
                    vertical-alignment: center;
                    horizontal-alignment: center;
                }

                pill-touch := TouchArea {
                    mouse-cursor: pointer;
                    clicked => {
                        if (root.favourites-only) {
                            Library.favourites-changed(root.shelf, false);
                        }
                        Library.group-changed(root.shelf, i);
                    }
                }
            }

            Rectangle { horizontal-stretch: 1; }
        }

        if root.library: Rectangle {
            height: 6px;
        }

        // The shelf itself, as tiles rather than rows.
        //
        // Rust hands this list over already searched, shelved and starred,
        // which is the whole reason a grid is possible: a cell's place is
        // its index, and an index only means a place when every entry in the
        // model is one that shows. Filtering in Slint - the `visible: false`
        // trick a vertical list can get away with - would leave holes in the
        // grid where the hidden ones were.
        if root.library: Rectangle {
            height: root.rows * (root.cell-h + root.cell-gap);

            for entry[index] in root.catalogue: tile := Rectangle {
                property <bool> in-chain: root.in-chain(entry.id);

                x: root.pad + mod(index, root.columns) * (root.cell-w + root.cell-gap);
                y: floor(index / root.columns) * (root.cell-h + root.cell-gap);
                width: root.cell-w;
                height: root.cell-h;
                // Borderless surfaces rather than drawn boxes: the grid reads
                // as one shelf, and the one on the clip is the one that
                // stands out, tinted and outlined in the accent.
                border-radius: Theme.r;
                border-width: 1px;
                border-color: tile.in-chain ? Theme.accent : Colors.transparent;
                background: tile.in-chain ? Theme.accent-soft
                    : tile-touch.has-hover ? Theme.field
                    : Theme.raised;

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

                // A mark for the shelf it is on, over its name: what kind
                // of change it makes, at a glance, while the word says
                // which one.
                VerticalLayout {
                    x: 4px;
                    width: parent.width - 8px;
                    alignment: center;
                    spacing: 5px;

                    HorizontalLayout {
                        alignment: center;
                        // The mark in a round badge of its own, which fills
                        // with the accent once the effect is on the clip.
                        Rectangle {
                            width: 28px;
                            height: 28px;
                            border-radius: 14px;
                            background: tile.in-chain ? Theme.accent
                                : tile-touch.has-hover ? Theme.field-active : Theme.field;

                            animate background { duration: 120ms; }

                            Icon {
                                glyph: tile.in-chain ? Glyph.check
                                    : entry.category == "Voice" ? Glyph.mic
                                    : entry.category == "Tone" ? Glyph.sliders
                                    : entry.category == "Clean" ? Glyph.wand
                                    : Glyph.waveform;
                                size: 14px;
                                tint: tile.in-chain ? Theme.on-accent
                                    : tile-touch.has-hover ? Theme.fg : Theme.fg-muted;
                            }
                        }
                    }

                    Text {
                        text: entry.name;
                        color: tile.in-chain ? Theme.accent : Theme.fg;
                        font-size: Theme.fs-sm;
                        horizontal-alignment: center;
                        overflow: elide;
                    }
                }

                // The star rides the tile's corner and takes its own clicks,
                // so starring is never a step on the way to applying.
                star := Rectangle {
                    x: parent.width - self.width - 2px;
                    y: 2px;
                    width: 15px;
                    height: 15px;
                    border-radius: Theme.r-xs;
                    visible: entry.favourite || tile-touch.has-hover || star-touch.has-hover;
                    background: star-touch.has-hover ? Theme.field-active : Colors.transparent;

                    Icon {
                        glyph: Glyph.sparkle;
                        size: 10px;
                        filled: entry.favourite;
                        tint: entry.favourite ? Theme.accent : Theme.fg-dim;
                    }

                    star-touch := TouchArea {
                        mouse-cursor: pointer;
                        clicked => { Library.favourite(entry.id, !entry.favourite); }
                    }
                }

                tile-touch := TouchArea {
                    // Below the star in the tree, so the star's own area wins
                    // the clicks that land on it.
                    enabled: !tile.in-chain;
                    mouse-cursor: pointer;
                    clicked => { root.add(entry.id); }
                }
            }
        }

        if root.catalogue.length == 0: HorizontalLayout {
            padding-left: Theme.pad;
            padding-right: Theme.pad;
            padding-top: 2px;

            Text {
                text: root.favourites-only
                    ? I18n.t("clipInspector.nothingStarredYetHover")
                    : I18n.t1("clipInspector.noMatchesThat", "\{root.noun}");
                color: Theme.fg-dim;
                font-size: Theme.fs-sm;
                wrap: word-wrap;
            }
        }
    }
}

/// One treatment: a switch, its name, one line saying what it does, and
/// its knobs under that while it is on.
component Processor inherits VerticalLayout {
    in property <string> label;
    in property <string> note;
    in property <bool> on;
    /// Where the treatment sits on the chain, or -1: which knobs are its.
    in property <int> entry;
    in property <[AppliedParamData]> params;

    callback toggled();
    callback set-param(index: int, key: string, value: float);
    callback commit();

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

    SwitchRow {
        label: root.label;
        checked: root.on;
        toggled(value) => { root.toggled(); }
    }

    // Under the switch and inside its padding, so the sentence reads as this
    // row's own rather than as a note about the section.
    HorizontalLayout {
        padding-left: Theme.pad;
        padding-right: Theme.pad;

        Text {
            text: root.note;
            color: Theme.fg-dim;
            font-size: Theme.fs-sm;
            wrap: word-wrap;
        }
    }

    // The knobs, re-seeded the way PresetStack's are; see there.
    for p in root.params: Rectangle {
        property <AppliedParamData> data: p;
        visible: root.on && p.entry == root.entry;
        height: root.on && p.entry == root.entry ? knob.preferred-height : 0;
        changed data => { knob.value = self.data.value; }

        knob := Param {
            label: p.label;
            value: p.value;
            minimum: p.min;
            maximum: p.max;
            step: p.step;
            default-value: p.default-value;
            fmt: p.fmt;
            unit: p.unit;
            changed(v) => {
                root.set-param(root.entry, p.key, v);
                root.commit();
            }
        }
    }
}

/// The three treatments a sound clip almost always wants, promoted out of
/// the effect library and onto the tab itself.
///
/// They are ordinary links of the audio chain - the same packages the
/// library lists, added and removed by the same callbacks - and nothing here
/// knows what they do. What they get is a switch instead of a search: a
/// person opening the Sound tab to fix a noisy lavalier should not have to
/// know that "Reduce noise" is filed under a shelf.
///
/// Each one's knobs sit under its switch while it is on; the library
/// below leaves these three out of its cards, so a control is in one
/// place.
export component ProcessorRows inherits VerticalLayout {
    in property <[AppliedEntryData]> applied;
    in property <[AppliedParamData]> params;

    callback add(id: string);
    callback remove(index: int);
    callback set-param(index: int, key: string, value: float);
    callback commit();

    /// Where a package sits on the chain, or -1. The same eight-deep scan
    /// PresetStack does, and for the same reason: Slint has no lookup.
    pure function at(id: string) -> int {
        return root.applied.length > 0 && root.applied[0].id == id ? 0
            : root.applied.length > 1 && root.applied[1].id == id ? 1
            : root.applied.length > 2 && root.applied[2].id == id ? 2
            : root.applied.length > 3 && root.applied[3].id == id ? 3
            : root.applied.length > 4 && root.applied[4].id == id ? 4
            : root.applied.length > 5 && root.applied[5].id == id ? 5
            : root.applied.length > 6 && root.applied[6].id == id ? 6
            : root.applied.length > 7 && root.applied[7].id == id ? 7
            : -1;
    }

    function toggle(id: string) {
        if (root.at(id) >= 0) {
            root.remove(root.at(id));
        } else {
            root.add(id);
        }
    }

    Section {
        SectionHeader {
            title: I18n.t("clipInspector.treatments");
        }

        SectionBody {
            Processor {
                label: I18n.t("clipInspector.normalizeLoudness");
                note: I18n.t("clipInspector.bringsClipBroadcastLevel");
                on: root.at("concat.loudness") >= 0;
                entry: root.at("concat.loudness");
                params: root.params;
                toggled => { root.toggle("concat.loudness"); }
                set-param(index, key, value) => { root.set-param(index, key, value); }
                commit => { root.commit(); }
            }

            Processor {
                label: I18n.t("clipInspector.reduceNoise");
                note: I18n.t("clipInspector.takesRoomsHissHum");
                on: root.at("concat.denoise") >= 0;
                entry: root.at("concat.denoise");
                params: root.params;
                toggled => { root.toggle("concat.denoise"); }
                set-param(index, key, value) => { root.set-param(index, key, value); }
                commit => { root.commit(); }
            }

            Processor {
                label: I18n.t("clipInspector.enhanceVoice");
                note: I18n.t("clipInspector.liftsSpeechOutMix");
                on: root.at("concat.enhance-voice") >= 0;
                entry: root.at("concat.enhance-voice");
                params: root.params;
                toggled => { root.toggle("concat.enhance-voice"); }
                set-param(index, key, value) => { root.set-param(index, key, value); }
                commit => { root.commit(); }
            }
        }
    }
}

// The clip's own tabs, one panel each. The tab strip follows the kind (see
// config-pane): a still has picture but no sound, so it gets Video and not
// Audio or Speed; a sound clip is the reverse. Every panel here is a set of
// fields on the selected clip; the chains have their own stacks.
//
// Local editing state is assigned rather than bound. A control writes to its
// own `value` as it is dragged, and an assignment in Slint replaces whatever
// binding the parent declared on that property — so binding these straight
// to `selected` would work exactly once and then go deaf to the model. They
// are seeded instead, on init and whenever the selection changes under us.

// One way of removing the background, as a line: a tick, the name, and
// whatever trails on the right - a reset, when the block has one.
component RemovalBlock inherits HorizontalLayout {
    in property <string> title;
    in property <bool> on;

    callback toggled(on: bool);

    padding-left: Theme.pad;
    padding-right: Theme.pad;
    spacing: 8px;
    min-height: Theme.h;

    VerticalLayout {
        alignment: center;
        Check {
            checked: root.on;
            toggled(on) => { root.toggled(on); }
        }
    }

    head := Rectangle {
        horizontal-stretch: 1;
        Text {
            x: 0;
            width: parent.width;
            height: parent.height;
            text: root.title;
            color: Theme.fg;
            font-size: Theme.fs;
            font-weight: Theme.weight-title;
            vertical-alignment: center;
            overflow: elide;
        }

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

    VerticalLayout {
        alignment: center;
        HorizontalLayout {
            spacing: 2px;
            @children
        }
    }
}

// A brush in the custom cutout's tray. The smart ones wear a spark, since
// the glyph is the same brush either way and what differs is whether it
// listens to the mask.
component ToolButton inherits Rectangle {
    in property <Glyph> glyph;
    in property <bool> smart;
    in property <string> label;
    in property <bool> checked;

    callback clicked();

    width: 30px;
    height: 30px;

    IconButton {
        x: 0;
        width: 30px;
        glyph: root.glyph;
        label: root.label;
        checked: root.checked;
        icon-size: 15px;
        clicked => { root.clicked(); }
    }

    if root.smart: Icon {
        x: parent.width - self.width - 2px;
        y: 2px;
        glyph: Glyph.sparkle;
        size: 8px;
        tint: root.checked ? Theme.accent : Theme.fg-muted;
    }
}

// The cutout model at work, while it runs: the masks are found in the
// background and the picture is shown as shot until they are.
component AnalysisRow inherits Row {
    in property <float> progress;
    /// The model is still being downloaded; the frames come after.
    in property <bool> fetching;

    label: I18n.t("clipInspector.analysis");
    Text {
        text: root.fetching
            ? I18n.t1("clipInspector.fetchingTheModel", "\{Math.round(root.progress * 100)}")
            : I18n.t1("clipInspector.findingTheSubject", "\{Math.round(root.progress * 100)}");
        color: Theme.fg-muted;
        font-size: Theme.fs;
        vertical-alignment: center;
    }
}

/// The stabilization analysis at work on the clip's media: the camera's
/// movement measured frame by frame, the clip shown as shot until it is.
component StabilizeRow inherits Row {
    in property <float> progress;

    label: I18n.t("clipInspector.analysis");
    Text {
        text: I18n.t1("clipInspector.measuringShake", "\{Math.round(root.progress * 100)}");
        color: Theme.fg-muted;
        font-size: Theme.fs;
        vertical-alignment: center;
    }
}

/// Enhance at work on the clip's media: the model on its way, then the
/// frames, one by one, into the copy the clip will show.
component EnhanceRow inherits Row {
    in property <float> progress;
    in property <bool> fetching;

    label: I18n.t("common.enhance");
    Text {
        text: root.fetching
            ? I18n.t1("clipInspector.fetchingTheModel", "\{Math.round(root.progress * 100)}")
            : I18n.t1("clipInspector.enhancing", "\{Math.round(root.progress * 100)}");
        color: Theme.fg-muted;
        font-size: Theme.fs;
        vertical-alignment: center;
    }
}

/// Reverse at work on the clip's media: the span read forwards and written
/// back, into the copy the clip will show.
component ReverseRow inherits Row {
    in property <float> progress;

    label: I18n.t("common.reverse");
    Text {
        text: I18n.t1("clipInspector.reversing", "\{Math.round(root.progress * 100)}");
        color: Theme.fg-muted;
        font-size: Theme.fs;
        vertical-alignment: center;
    }
}

// A rule between blocks inside one section, inset to the section's padding
// where a Section's own hairline runs edge to edge.
component Hairline inherits HorizontalLayout {
    padding-left: Theme.pad;
    padding-right: Theme.pad;
    Rectangle {
        height: 1px;
        background: Theme.line;
    }
}

/// The rows that choose a background: what kind, then the one knob that
/// kind has - a blur's softness, a colour, which still. The timeline's in
/// the Details panel, a clip's own in its Video panel, where one more kind
/// leads the list: the timeline's, followed.
export component BackgroundRows inherits VerticalLayout {
    /// The selected clip's own rather than the timeline's.
    in property <bool> own;

    property <BackdropData> data: root.own ? Backdrop.clip : Backdrop.timeline;
    property <int> picked: root.data.mode;
    property <int> kind: root.data.mode;
    // Seeded rather than bound: the knob writes it as it is dragged.
    property <float> amount;
    init => { root.amount = root.data.amount; }
    changed data => { root.amount = root.data.amount; }

    property <[string]> kinds: [
        I18n.t("clipInspector.backgroundNone"),
        I18n.t("clipInspector.backgroundBlur"),
        I18n.t("common.color"),
        I18n.t("clipInspector.backgroundImage"),
    ];

    Row {
        label: I18n.t("clipInspector.background");
        Select {
            options: root.kinds;
            // Set again whenever the kind changes: a press assigns `current`
            // inside the control and ends a plain binding (#250).
            property <int> shown: root.picked;
            current: self.shown;
            changed shown => { self.current = self.shown; }
            changed(index) => {
                Backdrop.set-mode(root.own, index);
            }
        }
    }

    if root.kind == 1: Param {
        label: I18n.t("clipInspector.softness");
        value <=> root.amount;
        minimum: 0;
        maximum: 1;
        step: 0.01;
        default-value: 0.5;
        fmt: ParamFormat.fraction;
        unit: "%";
        unit-scale: 100;
        changed(v) => { Backdrop.set-amount(root.own, v); }
    }

    if root.kind == 2: ColourField {
        label: I18n.t("common.color");
        value: root.data.colour;
        alpha: false;
        changed(colour) => { Backdrop.set-colour(root.own, colour); }
    }

    if root.kind == 3 && Backdrop.stills.length > 0: Row {
        label: I18n.t("clipInspector.still");
        Select {
            options: Backdrop.stills;
            property <int> still: root.data.still;
            current: self.still;
            changed still => { self.current = self.still; }
            placeholder: I18n.t("clipInspector.pickStill");
            changed(index) => { Backdrop.set-still(root.own, index); }
        }
    }

    if root.kind == 3 && Backdrop.stills.length == 0: Note {
        text: I18n.t("clipInspector.noStillsInBin");
    }
}

/// Video: how the picture sits in the frame, how solid it is, and whether
/// its background is keyed out.
export component VideoPanel inherits VerticalLayout {
    in property <SelectedClipData> selected;
    /// The picture's chain and its knobs, for the cutout section: keying is
    /// a package on the chain like any effect, and this panel only gives
    /// it a switch and a name.
    in property <[AppliedEntryData]> applied;
    in property <[AppliedParamData]> params;
    /// The chain's colour knobs: the key's screen colour among them.
    in property <[ColourKnobData]> colours;
    /// Fit and Fill under Transform, and the clip's Background section:
    /// the desk's. A phone has them on a Canvas sheet of their own.
    in property <bool> canvas: true;
    /// The custom cutout's brush; see Editor.
    in property <int> brush-tool;
    in property <float> brush-size;
    in property <bool> painting;
    /// Whether the Mask section is here: the phone gives the mask a tool
    /// and a sheet of its own instead.
    in property <bool> mask-section: true;

    callback set(field: ClipField, value: float);
    /// A control gesture finished: the accumulated change becomes one command.
    callback commit();
    callback chain-add(id: string);
    callback chain-remove(index: int);
    callback chain-set-param(index: int, key: string, value: float);
    callback chain-set-colour(index: int, key: string, value: color);
    /// The cutout: its mode (0 off, 1 automatic, 2 custom), and the brush.
    callback cutout-mode(mode: int);
    callback cutout-tool(index: int);
    callback cutout-size(size: float);
    callback cutout-painting(on: bool);
    /// What the automatic cutout keeps: 0 auto, 1 person, 2 object.
    callback cutout-subject(index: int);
    callback cutout-clear();

    /// A shape is a figure, not footage: there is no background to take
    /// away and nothing to crop off its edges, so those sections stay out
    /// of its panel.
    property <bool> figure: root.selected.kind == ClipKind.shape;

    /// Which keyer is on the chain, and where: -1 for none. Scans the first
    /// eight links, as PresetStack does, for want of a model lookup.
    pure function keyer-at(id: string) -> int {
        return root.applied.length > 0 && root.applied[0].id == id ? 0
            : root.applied.length > 1 && root.applied[1].id == id ? 1
            : root.applied.length > 2 && root.applied[2].id == id ? 2
            : root.applied.length > 3 && root.applied[3].id == id ? 3
            : root.applied.length > 4 && root.applied[4].id == id ? 4
            : root.applied.length > 5 && root.applied[5].id == id ? 5
            : root.applied.length > 6 && root.applied[6].id == id ? 6
            : root.applied.length > 7 && root.applied[7].id == id ? 7
            : -1;
    }
    /// Where the chroma key is on the chain, -1 for nowhere; its screen
    /// colour is a knob of its own, drawn below as a swatch.
    property <int> keyer-index: root.keyer-at("concat.chroma-key");
    /// 0 off, 1 on: whether the chroma key is.
    property <int> keyer: root.keyer-index >= 0 ? 1 : 0;
    /// The Mode row: 0 off, 1 automatic, 2 custom, 3 chroma key. A key on
    /// the chain wins, since a cutout under a key would be two removals at
    /// once.
    property <int> removal: root.keyer == 1 ? 3 : root.selected.cutout;
    property <bool> masked: root.removal == 1 || root.removal == 2;

    /// Puts one removal on and the others off: 0 none, 1 auto, 2 custom,
    /// 3 chroma key. The key comes off the chain before anything else goes
    /// on, and the cutout is set or cleared to match.
    function remove-by(index: int) {
        if (root.keyer-index >= 0) {
            root.chain-remove(root.keyer-index);
        }
        root.cutout-mode(index == 1 ? 1 : index == 2 ? 2 : 0);
        if (index == 3) {
            root.chain-add("concat.chroma-key");
        }
        root.commit();
    }

    property <float> scale;
    property <float> offset-x;
    property <float> offset-y;
    property <float> rotation;
    property <float> stretch-x;
    property <float> stretch-y;
    property <float> alpha;
    property <float> crop-left;
    property <float> crop-top;
    property <float> crop-right;
    property <float> crop-bottom;
    property <float> feather;
    property <float> mask-x;
    property <float> mask-y;
    property <float> mask-width;
    property <float> mask-height;
    property <float> mask-rotation;
    property <float> mask-roundness;
    property <float> mask-feather;
    property <float> smoothness;
    property <float> max-zoom;
    /// The mask's shape, as the picker orders them: -1 for none.
    property <int> mask: root.selected.mask;
    property <[string]> mask-names: [
        I18n.t("mask.linear"),
        I18n.t("mask.mirror"),
        I18n.t("mask.circle"),
        I18n.t("mask.rectangle"),
        I18n.t("mask.heart"),
        I18n.t("mask.star")
    ];

    function seed() {
        root.feather = root.selected.cutout-feather;
        root.smoothness = root.selected.stabilize-smoothness;
        root.max-zoom = root.selected.stabilize-max-zoom;
        root.mask-x = root.selected.mask-x;
        root.mask-y = root.selected.mask-y;
        root.mask-width = root.selected.mask-width;
        root.mask-height = root.selected.mask-height;
        root.mask-rotation = root.selected.mask-rotation;
        root.mask-roundness = root.selected.mask-roundness;
        root.mask-feather = root.selected.mask-feather;
        root.scale = root.selected.scale;
        root.offset-x = root.selected.offset-x;
        root.offset-y = root.selected.offset-y;
        root.rotation = root.selected.rotation;
        root.stretch-x = root.selected.stretch-x;
        root.stretch-y = root.selected.stretch-y;
        root.alpha = root.selected.opacity;
        root.crop-left = root.selected.crop-left;
        root.crop-top = root.selected.crop-top;
        root.crop-right = root.selected.crop-right;
        root.crop-bottom = root.selected.crop-bottom;
    }

    property <[string]> blends: [
        I18n.t("clipInspector.normal"),
        I18n.t("clipInspector.multiply"),
        I18n.t("clipInspector.screen"),
        I18n.t("clipInspector.add"),
        I18n.t("clipInspector.lighten"),
        I18n.t("clipInspector.darken")
    ];

    init => { root.seed(); }
    changed selected => { root.seed(); }

    Section {
        first: true;
        transform := SectionHeader {
            title: I18n.t("clipInspector.transform");
            collapsible: true;
            summary: "\{Math.round(root.scale * 100)}% · \{Math.round(root.rotation)}°";
            HelpButton {
                text: I18n.t("clipInspector.scalePositionFractionsOutput");
            }
        }

        if transform.open: SectionBody {

            Param {
                label: I18n.t("common.scale");
                keyable: true;
                field: ClipField.scale;
                value <=> root.scale;
                minimum: 0.05;
                maximum: 8;
                step: 0.01;
                default-value: 1;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.scale, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.positionX");
                keyable: true;
                field: ClipField.offset-x;
                value <=> root.offset-x;
                minimum: -1;
                maximum: 1;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.centred;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.offset-x, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.positionY");
                keyable: true;
                field: ClipField.offset-y;
                value <=> root.offset-y;
                minimum: -1;
                maximum: 1;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.centred;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.offset-y, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.rotation");
                keyable: true;
                field: ClipField.rotation;
                value <=> root.rotation;
                minimum: -180;
                maximum: 180;
                step: 1;
                default-value: 0;
                fmt: ParamFormat.degrees;
                unit: "°";
                changed(v) => { root.set(ClipField.rotation, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.width");
                value <=> root.stretch-x;
                minimum: 0.1;
                maximum: 4;
                step: 0.01;
                default-value: 1;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.stretch-x, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.height");
                value <=> root.stretch-y;
                minimum: 0.1;
                maximum: 4;
                step: 0.01;
                default-value: 1;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.stretch-y, v); root.commit(); }
            }

            // The picture sized to the frame in one press: the whole of it
            // inside, or the frame covered - what a landscape shot in a
            // vertical cut needs one way or the other.
            if root.canvas && Backdrop.can-frame: Row {
                label: I18n.t("common.size");
                Button {
                    label: I18n.t("clipInspector.fit");
                    glyph: Glyph.fit;
                    horizontal-stretch: 1;
                    clicked => { Backdrop.frame(false); }
                }
                Button {
                    label: I18n.t("clipInspector.fill");
                    glyph: Glyph.maximize;
                    horizontal-stretch: 1;
                    clicked => { Backdrop.frame(true); }
                }
            }
        }
    }

    // What fills the frame where this picture does not reach: the
    // timeline's background, or one of the clip's own. Only on the lowest
    // picture lane, which is where a background is drawn.
    if root.canvas && Backdrop.clip-has: Section {
        canvas := SectionHeader {
            title: I18n.t("phone.canvas");
            collapsible: true;
            HelpButton {
                text: I18n.t("clipInspector.canvasHelp");
            }
        }

        if canvas.open: SectionBody {
            BackgroundRows {
                own: true;
            }
            // As in CapCut: this clip's background for every picture on
            // the main lane, which is how the timeline's is set.
            Button {
                label: I18n.t("clipInspector.applyToAll");
                block: true;
                clicked => { Backdrop.apply-to-all(); }
            }
        }
    }

    Section {
        blend := SectionHeader {
            title: I18n.t("clipInspector.blend");
            collapsible: true;
            summary: "\{Math.round(root.alpha * 100)}% · "
                + root.blends[Math.max(0, Math.min(root.selected.blend, root.blends.length - 1))];
        }

        if blend.open: SectionBody {
            Param {
                label: I18n.t("common.opacity");
                keyable: true;
                field: ClipField.opacity;
                value <=> root.alpha;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 1;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.opacity, v); root.commit(); }
            }

            Row {
                label: I18n.t("common.mode");
                Select {
                    options: root.blends;
                    current: root.selected.blend;
                    changed(index) => { root.set(ClipField.blend, index); root.commit(); }
                }
            }

            SwitchRow {
                label: I18n.t("clipInspector.flipHorizontal");
                checked: root.selected.flip-h;
                toggled(on) => { root.set(ClipField.flip-h, on ? 1 : 0); root.commit(); }
            }

            SwitchRow {
                label: I18n.t("clipInspector.flipVertical");
                checked: root.selected.flip-v;
                toggled(on) => { root.set(ClipField.flip-v, on ? 1 : 0); root.commit(); }
            }
        }
    }

    // The camera's shake taken out: the media's movement is measured once
    // in the background, and the correction is worked out from it live, so
    // the sliders answer at once. Footage only.
    if root.selected.kind == ClipKind.video: Section {
        stabilize := SectionHeader {
            title: I18n.t("clipInspector.stabilize");
            collapsible: true;
            switchable: true;
            on: root.selected.stabilize;
            switched(on) => {
                root.set(ClipField.stabilize, on ? 1 : 0);
                root.commit();
            }
            summary: !root.selected.stabilize ? I18n.t("common.off")
                : root.selected.stabilize-progress >= 0
                    ? I18n.t1("clipInspector.measuringShake", "\{Math.round(root.selected.stabilize-progress * 100)}")
                : root.selected.stabilize-zoom > 0
                    ? I18n.t1("clipInspector.zoomPercent", "\{Math.round(root.selected.stabilize-zoom * 100)}")
                : "";
            HelpButton {
                text: I18n.t("clipInspector.stabilizeHelp");
            }
        }

        if stabilize.open && root.selected.stabilize: SectionBody {
            Param {
                label: I18n.t("clipInspector.smoothness");
                value <=> root.smoothness;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 0.5;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.stabilize-smoothness, v); root.commit(); }
            }

            Param {
                label: I18n.t("clipInspector.maxZoom");
                value <=> root.max-zoom;
                minimum: 1;
                maximum: 1.5;
                step: 0.01;
                default-value: 1.2;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.stabilize-max-zoom, v); root.commit(); }
            }

            SwitchRow {
                label: I18n.t("clipInspector.tripod");
                checked: root.selected.stabilize-tripod;
                toggled(on) => { root.set(ClipField.stabilize-tripod, on ? 1 : 0); root.commit(); }
            }

            if root.selected.stabilize-progress >= 0: StabilizeRow {
                progress: root.selected.stabilize-progress;
            }
            if root.selected.stabilize-progress < 0 && root.selected.stabilize-zoom > 0: Note {
                text: root.selected.stabilize-needed > root.selected.stabilize-zoom + 0.005
                    ? I18n.t2("clipInspector.stabilizeEased",
                        "\{Math.round(root.selected.stabilize-zoom * 100)}",
                        "\{Math.round(root.selected.stabilize-needed * 100)}")
                    : I18n.t1("clipInspector.stabilizeZoom", "\{Math.round(root.selected.stabilize-zoom * 100)}");
            }
        }
    }

    // The background taken away, one of three ways, each a block with a
    // tick: automatic and custom cut by the mask the cutout model finds
    // for the person in the picture - custom with strokes painted on the
    // monitor over it - and chroma key drops a colour. A key is the chroma
    // package on the chain, which is why its knobs read from the chain's
    // own rows. One at a time: ticking a block unticks the others.
    if !root.figure: Section {
        cutout := SectionHeader {
            title: I18n.t("clipInspector.removeBackground");
            collapsible: true;
            // On is whichever removal is set; going on picks the custom one
            // when strokes are waiting for it, the automatic one otherwise.
            switchable: true;
            on: root.removal != 0;
            switched(on) => {
                root.remove-by(!on ? 0 : root.selected.cutout-strokes > 0 ? 2 : 1);
            }
            summary: root.removal == 0 ? I18n.t("common.off")
                : root.removal == 1 ? I18n.t("clipInspector.autoRemoval")
                : root.removal == 2 ? I18n.t("clipInspector.customRemoval") : I18n.t("clipInspector.chromaKey");
            HelpButton {
                text: I18n.t("clipInspector.autoRemovalKeepsWhat");
            }
        }

        if cutout.open: SectionBody {

            RemovalBlock {
                title: I18n.t("clipInspector.autoRemoval");
                on: root.removal == 1;
                toggled(on) => { root.remove-by(on ? 1 : 0); }
            }

            if root.removal == 1: Row {
                label: I18n.t("clipInspector.subject");
                Select {
                    options: [I18n.t("common.auto"), I18n.t("clipInspector.person"), I18n.t("clipInspector.object")];
                    current: root.selected.cutout-subject;
                    changed(index) => { root.cutout-subject(index); }
                }
            }
            if root.removal == 1: Param {
                label: I18n.t("clipInspector.feather");
                value <=> root.feather;
                minimum: 0;
                maximum: 0.1;
                step: 0.002;
                default-value: 0.01;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.cutout-feather, v); root.commit(); }
            }
            if root.removal == 1 && root.selected.cutout-progress >= 0: AnalysisRow {
                progress: root.selected.cutout-progress;
                fetching: root.selected.cutout-fetching;
            }
            if root.removal == 1 && root.selected.cutout-progress < 0 && root.selected.cutout-empty: Note {
                text: I18n.t("clipInspector.nothingFoundKeepPicture");
            }

            Hairline { }

            RemovalBlock {
                title: I18n.t("clipInspector.customRemoval");
                on: root.removal == 2;
                toggled(on) => { root.remove-by(on ? 2 : 0); }
                ResetButton {
                    dirty: root.removal == 2 && root.selected.cutout-strokes > 0;
                    reset => { root.cutout-clear(); }
                }
            }
        // The brushes, in the order everyone expects: the two that follow the mask,
        // then the two that do as they are told. Picking one starts the
        // painting; Apply ends it.
        if root.removal == 2: HorizontalLayout {
                padding-left: Theme.pad;
                padding-right: Theme.pad;
                spacing: 6px;
                ToolButton {
                    glyph: Glyph.brush;
                    smart: true;
                    label: I18n.t("clipInspector.smartBrush");
                    checked: root.painting && root.brush-tool == 0;
                    clicked => { root.cutout-tool(0); root.cutout-painting(true); }
                }

                ToolButton {
                    glyph: Glyph.eraser;
                    smart: true;
                    label: I18n.t("clipInspector.smartEraser");
                    checked: root.painting && root.brush-tool == 2;
                    clicked => { root.cutout-tool(2); root.cutout-painting(true); }
                }

                Rectangle {
                    width: 1px;
                    height: 18px;
                    background: Theme.line;
                }

                ToolButton {
                    glyph: Glyph.brush;
                    label: I18n.t("clipInspector.brush");
                    checked: root.painting && root.brush-tool == 1;
                    clicked => { root.cutout-tool(1); root.cutout-painting(true); }
                }

                ToolButton {
                    glyph: Glyph.eraser;
                    label: I18n.t("clipInspector.eraser");
                    checked: root.painting && root.brush-tool == 3;
                    clicked => { root.cutout-tool(3); root.cutout-painting(true); }
                }

                Rectangle {
                    horizontal-stretch: 1;
                }
            }
            if root.removal == 2: Param {
                label: I18n.t("common.size");
                value: root.brush-size;
                minimum: 0.005;
                maximum: 0.5;
                step: 0.005;
                default-value: 0.06;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.cutout-size(v); }
            }
            if root.removal == 2: Param {
                label: I18n.t("clipInspector.feather");
                value <=> root.feather;
                minimum: 0;
                maximum: 0.1;
                step: 0.002;
                default-value: 0.01;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.cutout-feather, v); root.commit(); }
            }
            if root.removal == 2 && root.selected.cutout-progress >= 0: AnalysisRow {
                progress: root.selected.cutout-progress;
                fetching: root.selected.cutout-fetching;
            }
            if root.removal == 2: Row {
                label: root.selected.cutout-strokes == 1 ? I18n.t("clipInspector.oneStroke")
                    : I18n.t1("clipInspector.strokes", "\{root.selected.cutout-strokes}");
                Rectangle {
                    horizontal-stretch: 1;
                }

                Button {
                    label: I18n.t("common.apply");
                    primary: true;
                    enabled: root.painting;
                    clicked => { root.cutout-painting(false); }
                }
            }

            Hairline { }

            RemovalBlock {
                title: I18n.t("clipInspector.chromaKey");
                on: root.keyer > 0;
                toggled(on) => { root.remove-by(on ? 3 : 0); }
            }

            // The screen's colour: broadcast green to begin with, any
            // colour at all from the picker.
            for c in root.colours: Rectangle {
                visible: root.keyer-index >= 0 && c.entry == root.keyer-index;
                height: root.keyer-index >= 0 && c.entry == root.keyer-index
                    ? swatch.preferred-height : 0;

                swatch := ColourField {
                    label: I18n.t("common.color");
                    value: c.value;
                    alpha: false;
                    changed(colour) => {
                        root.chain-set-colour(root.keyer-index, c.key, colour);
                        root.commit();
                    }
                }
            }

            // The keyer's own knobs, re-seeded from the chain the way the
        // stack's rows are; see PresetStack.
        for p in root.params: Rectangle {
                property <AppliedParamData> data: p;
                visible: root.keyer-index >= 0 && p.entry == root.keyer-index;
                height: root.keyer-index >= 0 && p.entry == root.keyer-index
                    ? knob.preferred-height : 0;
                changed data => { knob.value = self.data.value; }

                knob := Param {
                    label: p.label;
                    value: p.value;
                    minimum: p.min;
                    maximum: p.max;
                    step: p.step;
                    default-value: p.default-value;
                    fmt: p.fmt;
                    unit: p.unit;
                    changed(v) => {
                        root.chain-set-param(root.keyer-index, p.key, v);
                        root.commit();
                    }
                }
            }
        }
    }

    // The mask: a shape that keeps part of the picture, CapCut's Mask.
    // The row of shapes picks one - the first, None, takes it off - and
    // the numbers below place, size, turn and soften it, each keyable.
    // Drawn on the picture as it is seen, so it moves with the clip; the
    // monitor shows its outline with grips to drag while this is open.
    if root.mask-section
        && (root.selected.kind == ClipKind.video || root.selected.kind == ClipKind.image): Section {
        mask-header := SectionHeader {
            title: I18n.t("mask.title");
            collapsible: true;
            summary: root.mask < 0 ? I18n.t("common.none")
                : root.mask-names[Math.min(root.mask, root.mask-names.length - 1)]
                    + (root.selected.mask-invert ? " · " + I18n.t("mask.invert") : "");
        }

        if mask-header.open: SectionBody {
            HorizontalLayout {
                padding-left: Theme.pad;
                padding-right: Theme.pad;
                spacing: 4px;
                ToolButton {
                    glyph: Glyph.close;
                    label: I18n.t("common.none");
                    checked: root.mask < 0;
                    clicked => { root.set(ClipField.mask-shape, -1); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-linear;
                    label: root.mask-names[0];
                    checked: root.mask == 0;
                    clicked => { root.set(ClipField.mask-shape, 0); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-mirror;
                    label: root.mask-names[1];
                    checked: root.mask == 1;
                    clicked => { root.set(ClipField.mask-shape, 1); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-circle;
                    label: root.mask-names[2];
                    checked: root.mask == 2;
                    clicked => { root.set(ClipField.mask-shape, 2); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-rectangle;
                    label: root.mask-names[3];
                    checked: root.mask == 3;
                    clicked => { root.set(ClipField.mask-shape, 3); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-heart;
                    label: root.mask-names[4];
                    checked: root.mask == 4;
                    clicked => { root.set(ClipField.mask-shape, 4); root.commit(); }
                }
                ToolButton {
                    glyph: Glyph.mask-star;
                    label: root.mask-names[5];
                    checked: root.mask == 5;
                    clicked => { root.set(ClipField.mask-shape, 5); root.commit(); }
                }
            }

            if root.mask >= 0: SwitchRow {
                label: I18n.t("mask.invert");
                checked: root.selected.mask-invert;
                toggled(on) => { root.set(ClipField.mask-invert, on ? 1 : 0); root.commit(); }
            }

            if root.mask >= 0: Param {
                label: I18n.t("common.positionX");
                keyable: true;
                field: ClipField.mask-x;
                value <=> root.mask-x;
                minimum: -1;
                maximum: 1;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.centred;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-x, v); root.commit(); }
            }

            if root.mask >= 0: Param {
                label: I18n.t("common.positionY");
                keyable: true;
                field: ClipField.mask-y;
                value <=> root.mask-y;
                minimum: -1;
                maximum: 1;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.centred;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-y, v); root.commit(); }
            }

            // A line has no size, and a mirror only its thickness.
            if root.mask >= 2: Param {
                label: I18n.t("common.width");
                keyable: true;
                field: ClipField.mask-width;
                value <=> root.mask-width;
                minimum: 0.01;
                maximum: 4;
                step: 0.01;
                default-value: 0.66;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-width, v); root.commit(); }
            }

            if root.mask >= 1: Param {
                label: root.mask == 1 ? I18n.t("mask.thickness") : I18n.t("common.height");
                keyable: true;
                field: ClipField.mask-height;
                value <=> root.mask-height;
                minimum: 0.01;
                maximum: 4;
                step: 0.01;
                default-value: root.mask == 1 ? 0.33 : 0.66;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-height, v); root.commit(); }
            }

            if root.mask >= 0: Param {
                label: I18n.t("common.rotation");
                keyable: true;
                field: ClipField.mask-rotation;
                value <=> root.mask-rotation;
                minimum: -180;
                maximum: 180;
                step: 1;
                default-value: 0;
                fmt: ParamFormat.degrees;
                unit: "°";
                changed(v) => { root.set(ClipField.mask-rotation, v); root.commit(); }
            }

            if root.mask == 3: Param {
                label: I18n.t("mask.roundness");
                keyable: true;
                field: ClipField.mask-roundness;
                value <=> root.mask-roundness;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-roundness, v); root.commit(); }
            }

            if root.mask >= 0: Param {
                label: I18n.t("clipInspector.feather");
                keyable: true;
                field: ClipField.mask-feather;
                value <=> root.mask-feather;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.mask-feather, v); root.commit(); }
            }
        }
    }

    // What is cut off the source before it is fitted. Fractions of the
    // source's own edges, so a crop survives a change of output size.
    if !root.figure: Section {
        crop := SectionHeader {
            title: I18n.t("clipInspector.crop");
            collapsible: true;
            summary: (root.crop-left == 0 && root.crop-top == 0
                && root.crop-right == 0 && root.crop-bottom == 0) ? I18n.t("common.none")
                : "\{Math.round(root.crop-left * 100)} · \{Math.round(root.crop-top * 100)} · \{Math.round(root.crop-right * 100)} · \{Math.round(root.crop-bottom * 100)}";
        }

        if crop.open: SectionBody {
            Param {
                label: I18n.t("common.left");
                value <=> root.crop-left;
                minimum: 0;
                maximum: 0.9;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.crop-left, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.top");
                value <=> root.crop-top;
                minimum: 0;
                maximum: 0.9;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.crop-top, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.right");
                value <=> root.crop-right;
                minimum: 0;
                maximum: 0.9;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.crop-right, v); root.commit(); }
            }

            Param {
                label: I18n.t("common.bottom");
                value <=> root.crop-bottom;
                minimum: 0;
                maximum: 0.9;
                step: 0.005;
                default-value: 0;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.crop-bottom, v); root.commit(); }
            }
        }
    }
}

/// One half of Enhance's before and after: a label over the picture,
/// fitted whole into a fixed height so the pair reads the same on a phone
/// as in the desktop inspector, and nothing in the layout leans on the
/// picture's own size.
component PreviewHalf inherits VerticalLayout {
    in property <string> label;
    in property <image> source;

    padding-left: Theme.pad;
    padding-right: Theme.pad;
    spacing: 4px;

    Text {
        text: root.label;
        color: Theme.fg-muted;
        font-size: Theme.fs-sm;
    }
    Rectangle {
        height: 150px;
        background: Theme.well;
        border-radius: Theme.r-sm;
        clip: true;

        Image {
            width: parent.width;
            height: parent.height;
            source: root.source;
            image-fit: contain;
        }
    }
}

/// Enhance: the picture restored and enlarged by the model, into a copy the
/// clip then shows.
///
/// The header's tick never starts minutes of work by itself: it turns the
/// section on - its settings, its preview and its button come alive - and,
/// once there is a copy, switches the clip between the copy and its
/// original without running the model again. The run is the button's:
/// Enhance, Enhance again once there is a copy, and Terminate while one is
/// going.
///
/// Below the tick, what the run is made with - Size and Strength - and a
/// preview of the frame under the playhead at those settings, so the
/// person judges the look, and what a whole run will cost, in seconds
/// rather than after minutes of their machine. Strength is the answer to
/// the waxen, "plastic" faces a full-strength enhancer is known for: it
/// blends the model's answer back towards the original.
export component EnhancePanel inherits VerticalLayout {
    in property <SelectedClipData> selected;

    /// The tick: the section on or off, and the copy shown or not.
    callback enhance-set(on: bool);
    /// 0 Auto, 1 once, 2 twice, 3 four times.
    callback enhance-size(index: int);
    callback enhance-strength(strength: float);
    callback enhance-preview();
    /// The button: a run with the settings as they are, or, while this
    /// clip's run is going, its end.
    callback enhance-run();

    /// This clip's run is going: the button stops it rather than starts one.
    property <bool> running: root.selected.enhance-progress >= 0;
    /// The section is ticked: everything under the header answers.
    property <bool> live: root.selected.enhance-on;

    property <float> strength;

    init => {
        root.strength = root.selected.enhance-strength;
    }
    // Put back on every publish: a click on the row takes its binding, and
    // the next clip's file may not take the size this one showed.
    changed selected => {
        root.strength = root.selected.enhance-strength;
        sizes.current = root.selected.enhance-size;
    }

    Section {
        first: true;
        SectionHeader {
            title: I18n.t("common.enhance");
            switchable: true;
            on: root.selected.enhance-on;
            switched(on) => { root.enhance-set(on); }
            HelpButton {
                text: I18n.t("clipInspector.enhanceExplain");
            }
        }

        SectionBody {
            if root.running: EnhanceRow {
                progress: root.selected.enhance-progress;
                fetching: root.selected.enhance-fetching;
            }
            if !root.running && root.selected.enhance-linked: Note {
                text: root.selected.enhance-on
                    ? I18n.t("clipInspector.enhanceShowingCopy")
                    : I18n.t("clipInspector.enhanceShowingOriginal");
            }

            // A dropdown, as the inspector's other choices of one are:
            // the sizes past the longest side the model can take are
            // listed greyed, and the note under the row says why.
            Row {
                label: I18n.t("clipInspector.enhanceSize");
                sizes := Select {
                    options: [
                        I18n.t1("clipInspector.enhanceAuto", "\{root.selected.enhance-auto}x"),
                        "1x",
                        "2x",
                        "4x",
                    ];
                    disabled: [
                        false,
                        false,
                        !root.selected.enhance-fits-2x,
                        !root.selected.enhance-fits-4x,
                    ];
                    current: root.selected.enhance-size;
                    enabled: root.live;
                    changed(index) => { root.enhance-size(index); }
                }
            }
            if root.selected.enhance-size-note != "": Note {
                text: root.selected.enhance-size-note;
            }

            Param {
                label: I18n.t("clipInspector.enhanceStrength");
                value <=> root.strength;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 0.75;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                enabled: root.live;
                changed(v) => { root.enhance-strength(v); }
            }
            Note {
                text: I18n.t("clipInspector.enhanceStrengthExplain");
            }

            Row {
                Button {
                    label: I18n.t("clipInspector.enhancePreview");
                    enabled: root.live && !root.selected.enhance-busy;
                    clicked => { root.enhance-preview(); }
                }
                Rectangle { horizontal-stretch: 1; }
                // One button for the run, whatever stage it is at. While
                // this clip's run goes it is the way to stop it, even though
                // the model is then busy; otherwise it waits for the model.
                Button {
                    primary: !root.running;
                    danger: root.running;
                    label: root.running ? I18n.t("clipInspector.enhanceTerminate")
                        : root.selected.enhance-linked ? I18n.t("clipInspector.enhanceAgain")
                        : I18n.t("clipInspector.enhanceRun");
                    enabled: root.running || (root.live && !root.selected.enhance-busy);
                    clicked => { root.enhance-run(); }
                }
            }
            if root.selected.enhance-previewing: Note {
                text: root.selected.enhance-preview-fetch >= 0
                    ? I18n.t1("clipInspector.fetchingTheModel",
                        "\{Math.round(root.selected.enhance-preview-fetch * 100)}")
                    : I18n.t("clipInspector.enhancePreviewing");
            }

            if root.selected.enhance-preview: PreviewHalf {
                label: I18n.t("clipInspector.enhanceBefore");
                source: root.selected.enhance-before;
            }
            if root.selected.enhance-preview: PreviewHalf {
                label: I18n.t1("clipInspector.enhanceAfter", "\{Math.round(root.strength * 100)}");
                source: root.selected.enhance-after;
            }
            if root.selected.enhance-preview: Note {
                text: root.selected.enhance-estimate;
            }
        }
    }
}

/// A transition picked on its own on the lanes: what it is, the clip it
/// rides into, its length, and the way to take it off. Its own panel and
/// not a section of the clip's, since it belongs to the cut between two
/// clips rather than to either of them.
export component TransitionPanel inherits VerticalLayout {
    in property <SelectedTransitionData> transition;
    /// The package's own knobs, numbers and choices, as set on this cut.
    in property <[AppliedParamData]> knobs;
    in property <[TransitionChoiceData]> choices;

    /// Taken off, leaving a plain cut.
    callback remove();
    /// Set to a new length - clamped as applying one is, so this can never
    /// ask for more than the cut can give it.
    callback duration-set(seconds: float);
    /// One of the package's knobs moved.
    callback param-set(key: string, value: float);

    property <float> duration;

    init => { root.duration = root.transition.duration; }
    changed transition => { root.duration = root.transition.duration; }

    Section {
        SectionHeader {
            title: I18n.t("clipInspector.transition");
            summary: root.transition.name + " · "
                + InspectorFmt.format(ParamFormat.seconds2, root.transition.duration);
        }

        SectionBody {
            HorizontalLayout {
                padding-left: Theme.pad;
                padding-right: Theme.pad;
                padding-bottom: 6px;
                spacing: 4px;

                VerticalLayout {
                    horizontal-stretch: 1;
                    alignment: center;

                    Text {
                        text: root.transition.name;
                        color: Theme.fg;
                        font-size: Theme.fs;
                        font-weight: Theme.weight-title;
                        overflow: elide;
                    }

                    Text {
                        text: I18n.t1("clipInspector.transitionInto", root.transition.into);
                        color: Theme.fg-muted;
                        font-size: Theme.fs-sm;
                        overflow: elide;
                    }
                }

                VerticalLayout {
                    alignment: center;
                    IconButton {
                        glyph: Glyph.trash;
                        label: I18n.t1("clipInspector.remove", root.transition.name);
                        danger: true;
                        clicked => { root.remove(); }
                    }
                }
            }

            Param {
                label: I18n.t("common.duration");
                value <=> root.duration;
                minimum: 0.05;
                maximum: 5;
                step: 0.05;
                default-value: 0.5;
                fmt: ParamFormat.seconds2;
                changed(v) => { root.duration-set(v); }
            }

            for choice in root.choices: VerticalLayout {
                padding-left: Theme.pad;
                padding-right: Theme.pad;
                padding-top: 4px;
                padding-bottom: 4px;
                spacing: 4px;

                Text {
                    text: choice.label;
                    color: Theme.fg-muted;
                    font-size: Theme.fs-sm;
                }
                SegmentedControl {
                    options: choice.options;
                    current: choice.current;
                    changed(index) => { root.param-set(choice.key, choice.values[index]); }
                }
            }

            for p in root.knobs: Rectangle {
                property <AppliedParamData> data: p;
                height: knob.preferred-height;
                changed data => { knob.value = self.data.value; }

                knob := Param {
                    unit: p.unit;
                    label: p.label;
                    value: p.value;
                    minimum: p.min;
                    maximum: p.max;
                    step: p.step;
                    default-value: p.default-value;
                    fmt: p.fmt;
                    changed(v) => { root.param-set(p.key, v); }
                }
            }
        }
    }
}

/// Audio: the level, the fades, and whether the pitch follows the speed.
/// The voice and room chain sits under it in the same tab; see config-pane.
///
/// The fader for level works in decibels, not linear gain. Linear puts every
/// useful setting in the bottom sixth of the travel; decibels is both how the
/// ear works and how anyone mixing thinks.
export component AudioPanel inherits VerticalLayout {
    in property <SelectedClipData> selected;
    /// The media's audio tracks, one label each. A recording that kept the
    /// desktop and the microphone apart has two, and gets a row to choose
    /// which one this clip plays; a file with one has nothing to choose and
    /// shows no row.
    in property <[string]> audio-tracks;
    /// The Source section has something to offer: a choice of audio track.
    /// A file's colour range used to sit here too and is the media's now,
    /// in the bin card's menu: it is a fact about the file, not the cut.
    property <bool> choosing: !root.selected.batch-volume && root.audio-tracks.length > 1;

    callback set(field: ClipField, value: float);
    callback commit();

    /// A fade longer than half the clip would overlap the other one.
    property <float> fade-limit: Math.max(0.1, Math.min(10, root.selected.duration / 2));

    property <float> level;
    property <float> fade-in;
    property <float> fade-out;

    function seed() {
        root.level = InspectorFmt.to-decibels(root.selected.volume);
        root.fade-in = root.selected.fade-in;
        root.fade-out = root.selected.fade-out;
    }

    init => { root.seed(); }
    changed selected => { root.seed(); }

    if root.choosing: Section {
        first: true;
        source := SectionHeader {
            title: I18n.t("clipInspector.source");
            collapsible: true;
            summary: (root.selected.audio-track >= 0
                && root.selected.audio-track < root.audio-tracks.length)
                ? root.audio-tracks[root.selected.audio-track] : "";
        }
        if source.open: SectionBody {
        if root.audio-tracks.length > 1: Row {
            label: I18n.t("clipInspector.audioTrack");
            Select {
                options: root.audio-tracks;
                current: root.selected.audio-track;
                changed(index) => {
                    root.set(ClipField.audio-track, index);
                    root.commit();
                }
            }
        }
        }
    }

    Section {
        first: !root.choosing;
        volume := SectionHeader {
            title: I18n.t("clipInspector.volume");
            collapsible: true;
            summary: InspectorFmt.format(ParamFormat.gain, root.level);

            ResetButton {
                dirty: root.level != 0 || Keyframes.row(ClipField.volume).keyed;
                reset => {
                    Keyframes.clear(ClipField.volume);
                    root.set(ClipField.volume, 1);
                    root.commit();
                }
            }
        }

        if volume.open: SectionBody {
            Param {
                label: I18n.t("common.level");
                keyable: !root.selected.batch-volume;
                field: ClipField.volume;
                rail: true;
                value <=> root.level;
            // The bottom is silence, not -60. +24 at the top because quiet
            // material genuinely needs it — a distant lavalier is routinely
            // 15-20 dB under, and a limit that cannot fix that is in the
            // wrong place.
            minimum: -60;
                maximum: 24;
                step: 0.5;
                default-value: 0;
                fmt: ParamFormat.gain;
                changed(v) => {
                    root.set(ClipField.volume, InspectorFmt.from-decibels(v));
                    root.commit();
                }
            }
        }
    }

    if !root.selected.batch-volume: Section {
        fades := SectionHeader {
            title: I18n.t("clipInspector.fades");
            collapsible: true;
            summary: (root.fade-in == 0 && root.fade-out == 0) ? I18n.t("common.none")
                : InspectorFmt.format(ParamFormat.seconds2, root.fade-in)
                + " / " + InspectorFmt.format(ParamFormat.seconds2, root.fade-out);

            ResetButton {
                dirty: root.fade-in != 0 || root.fade-out != 0;
                reset => {
                    root.set(ClipField.fade-in, 0);
                    root.set(ClipField.fade-out, 0);
                    root.commit();
                }
            }
        }

        if fades.open: SectionBody {
            Param {
                label: I18n.t("clipInspector.fadeIn");
                rail: true;
                value <=> root.fade-in;
                minimum: 0;
                maximum: root.fade-limit;
                step: 0.05;
                fmt: ParamFormat.seconds2;
                unit: "s";
                changed(v) => { root.set(ClipField.fade-in, v); root.commit(); }
            }

            Param {
                label: I18n.t("clipInspector.fadeOut");
                rail: true;
                value <=> root.fade-out;
                minimum: 0;
                maximum: root.fade-limit;
                step: 0.05;
                fmt: ParamFormat.seconds2;
                unit: "s";
                changed(v) => { root.set(ClipField.fade-out, v); root.commit(); }
            }
        }
    }

    // Whether the voice keeps its pitch when the rate is not 1. Here and
    // not on the Speed tab: the rate is the clip's, but what it does to the
    // sound is the sound's business, beside the level it is mixed at.
    if !root.selected.batch-volume: Section {
        SectionHeader {
            title: I18n.t("clipInspector.pitch");
        }

        SectionBody {
            SwitchRow {
                label: I18n.t("clipInspector.changePitchWithSpeed");
                checked: !root.selected.preserve-pitch;
                toggled(on) => {
                    root.set(ClipField.preserve-pitch, on ? 0 : 1);
                    root.commit();
                }
            }
        }
    }
}

/// Speed: one rate for the whole clip, or a curve - speed that changes over
/// the clip, shaped on a graph or picked from a preset (see
/// speed-ramp.slint). Whether the sound's pitch follows is the Audio tab's.
export component SpeedPanel inherits VerticalLayout {
    in property <SelectedClipData> selected;
    /// The panel's first section, with no hairline above it; false where
    /// it follows another, as it does under Basic.
    in property <bool> first: true;

    callback set(field: ClipField, value: float);
    callback commit();

    property <float> speed;
    function seed() {
        root.speed = root.selected.speed;
        root.fastest = SpeedRamp.fastest;
        root.slowest = SpeedRamp.slowest;
    }
    init => { root.seed(); }
    changed selected => { root.seed(); }

    // Rust's word on the mode and the preset.
    property <bool> curved: SpeedRamp.curved;
    property <int> preset: SpeedRamp.preset;
    // The two sliders' values, seeded from Rust's like the rate's: a
    // slider writes its own value as it is dragged, which would end a
    // binding.
    property <float> fastest;
    property <float> slowest;
    property <float> fastest-truth: SpeedRamp.fastest;
    property <float> slowest-truth: SpeedRamp.slowest;
    changed fastest-truth => { root.fastest = root.fastest-truth; }
    changed slowest-truth => { root.slowest = root.slowest-truth; }

    Section {
        first: root.first;
        speed := SectionHeader {
            title: I18n.t("common.speed");
            collapsible: true;
            summary: root.curved
                ? I18n.t("speedRamp.curve")
                : InspectorFmt.format(ParamFormat.rate, root.speed);
            HelpButton {
                text: I18n.t("clipInspector.rateReTimesClip");
            }
        }

        if speed.open: SectionBody {
            if root.selected.reverse-progress >= 0: ReverseRow {
                progress: root.selected.reverse-progress;
            }

            HorizontalLayout {
                padding-left: Theme.pad;
                padding-right: Theme.pad;

                SegmentedControl {
                    // A press assigns `current` inside the control, which
                    // ends a plain binding: so it is set again from Rust's
                    // word whenever the selection or an undo changes it.
                    property <bool> truth: root.curved;
                    changed truth => { self.current = self.truth ? 1 : 0; }

                    options: [I18n.t("speedRamp.constant"), I18n.t("speedRamp.curve")];
                    current: root.curved ? 1 : 0;
                    changed(index) => {
                        SpeedRamp.curve(index == 1);
                        root.commit();
                    }
                }
            }

            if root.curved: Row {
                label: I18n.t("speedRamp.shape");
                Select {
                    // As the mode's: a pick ends the binding, Rust restores it.
                    property <int> truth: root.preset;
                    changed truth => { self.current = self.truth; }

                    options: SpeedRamp.presets;
                    current: root.preset;
                    placeholder: I18n.t("speedRamp.custom");
                    changed(index) => {
                        SpeedRamp.preset-chosen(index);
                        root.commit();
                    }
                }
            }

            if root.curved: SpeedGraph {
                padding-left: Theme.pad;
                padding-right: Theme.pad;
                point(index, x, y) => {
                    SpeedRamp.point(index, x, y);
                    root.commit();
                }
                remove(index) => {
                    SpeedRamp.remove(index);
                    root.commit();
                }
            }

            if root.curved: Row {
                label: I18n.t("speedRamp.bends");
                SegmentedControl {
                    // As the mode's: set again from Rust's word.
                    property <bool> truth: SpeedRamp.smooth;
                    changed truth => { self.current = self.truth ? 0 : 1; }

                    options: [I18n.t("speedRamp.smooth"), I18n.t("speedRamp.straight")];
                    current: SpeedRamp.smooth ? 0 : 1;
                    changed(index) => {
                        SpeedRamp.smoothness(index == 0);
                        root.commit();
                    }
                }
            }

            // The two extremes, for a ramp that is right in shape and too
            // much or too little in strength: the fastest stretch brought
            // down to 4x brings the rest of it along.
            if root.curved && root.fastest > 0: Param {
                label: I18n.t("speedRamp.fastest");
                value <=> root.fastest;
                minimum: 1.1;
                maximum: 16;
                step: 0.05;
                default-value: 2;
                fmt: ParamFormat.rate;
                unit: "x";
                changed(v) => { SpeedRamp.extreme(true, v); root.commit(); }
            }
            if root.curved && root.slowest > 0: Param {
                label: I18n.t("speedRamp.slowest");
                value <=> root.slowest;
                minimum: 0.0625;
                maximum: 0.9;
                step: 0.01;
                default-value: 0.5;
                fmt: ParamFormat.rate;
                unit: "x";
                changed(v) => { SpeedRamp.extreme(false, v); root.commit(); }
            }

            if !root.curved: Param {
                label: I18n.t("common.rate");
                value <=> root.speed;
                // The engine's full range. The track is linear, so the
                // useful 0.25-4x band sits left of centre and the number
                // field beside it is how the extremes are actually dialled
                // in.
                minimum: 0.0625;
                maximum: 16;
                step: 0.05;
                default-value: 1;
                fmt: ParamFormat.rate;
                unit: "x";
                changed(v) => { root.set(ClipField.speed, v); root.commit(); }
            }
        }
    }
}

/// Adjust: the manual colour panel. Every knob is a parameter of the one
/// built-in `concat.adjust` package, which Rust puts at the head of the
/// picture's chain the first time a knob moves; until then the rows show the
/// package's defaults, which are the picture as shot. The rows come from the
/// manifest, so a knob added there appears here without a line of UI.
export component AdjustPanel inherits VerticalLayout {
    in property <[AppliedParamData]> params;
    in property <[WheelData]> wheels;
    in property <[CurveData]> curves;

    callback set(key: string, value: float);
    /// A curve's point moved, or put down when `point` is -1, or taken off.
    callback curve-point(key: string, point: int, x: float, y: float);
    callback curve-remove(key: string, point: int);
    callback commit();

    Section {
        first: true;
        SectionHeader {
            title: I18n.t("common.adjust");
            HelpButton {
                text: I18n.t("clipInspector.exposureStopsRestSigned");
            }
        }

        // The knobs first, the wheels and curves after, at the very
        // bottom: the knobs are what most edits want, and the two big
        // tools below them would push every knob out of sight. See
        // PresetStack for why each knob's row re-seeds it; a subhead opens
        // each run of rows that share a group.
        SectionBody {
            for p[i] in root.params: VerticalLayout {
                spacing: Theme.gap;

                if p.group != "" && (i == 0 || root.params[i - 1].group != p.group): Subhead {
                    title: p.group;
                }

                Rectangle {
                    property <AppliedParamData> data: p;
                    height: knob.preferred-height;
                    changed data => { knob.value = self.data.value; }

                    knob := Param {
                        unit: p.unit;
                        label: p.label;
                        value: p.value;
                        minimum: p.min;
                        maximum: p.max;
                        step: p.step;
                        default-value: p.default-value;
                        fmt: p.fmt;
                        keyable: p.keyable;
                        key-name: p.key;
                        key-state: {
                            field: ClipField.scale,
                            keyed: p.keyed,
                            here: p.here,
                            prev: p.prev,
                            next: p.next,
                        };
                        changed(v) => { root.set(p.key, v); root.commit(); }
                    }
                }
            }

            // The wheels, three in a row: a puck is two knobs of the panel,
            // `<key>.x` and `<key>.y`, and the master a third.
            if root.wheels.length > 0: VerticalLayout {
                spacing: Theme.gap;

                Subhead {
                    title: root.wheels[0].group;
                }

                HorizontalLayout {
                    padding-left: Theme.pad;
                    padding-right: Theme.pad;
                    spacing: 8px;

                    for w in root.wheels: ColorWheel {
                        data: w;
                        moved(x, y) => {
                            root.set(w.key + ".x", x);
                            root.set(w.key + ".y", y);
                            root.commit();
                        }
                        master-changed(v) => {
                            root.set(w.key + ".m", v);
                            root.commit();
                        }
                    }
                }
            }

            if root.curves.length > 0: VerticalLayout {
                spacing: Theme.gap;

                Subhead {
                    title: root.curves[0].group;
                }

                CurveEditor {
                    padding-left: Theme.pad;
                    padding-right: Theme.pad;
                    curves: root.curves;
                    point(key, point, x, y) => {
                        root.curve-point(key, point, x, y);
                        root.commit();
                    }
                    remove(key, point) => {
                        root.curve-remove(key, point);
                        root.commit();
                    }
                }
            }

        }
    }
}

// The panel a filter layer gets instead of Adjust.
//
// A layer is not a clip of anything: it has no picture to frame, no gain to
// set and no rate to change — it treats whatever is playing under it, for as
// long as it runs. So it gets the two things that *are* its own: how hard it
// is applied, and how it comes in and goes out.
//
// Strength is the clip's `opacity`. That is the same number a picture clip
// dissolves with, which is exactly what it means here — how much of the
// treated signal is heard — and one field that means one thing on every kind
// beats a second that means it only on this one.
export component FilterPanel inherits VerticalLayout {
    in property <SelectedClipData> selected;
    /// What the help says the layer does: a picture layer's or a sound
    /// layer's, the panel being the same for both.
    in property <string> help: I18n.t("clipInspector.layerTreatsEverythingUnder");

    callback set(field: ClipField, value: float);
    callback commit();

    /// A ramp longer than half the layer would overlap the other one.
    property <float> ramp-limit: Math.max(0.1, Math.min(10, root.selected.duration / 2));

    // Seeded, not bound, for the reason AdjustPanel's are: a control writes to
    // its own `value`, and an assignment replaces the binding declared here.
    property <float> strength;
    property <float> fade-in;
    property <float> fade-out;

    function seed() {
        root.strength = root.selected.opacity;
        root.fade-in = root.selected.fade-in;
        root.fade-out = root.selected.fade-out;
    }

    init => { root.seed(); }
    changed selected => { root.seed(); }

    Section {
        first: true;
        layer := SectionHeader {
            title: I18n.t("common.layer");
            collapsible: true;
            summary: InspectorFmt.format(ParamFormat.fraction, root.strength);
            HelpButton {
                text: root.help;
            }
        }

        if layer.open: SectionBody {

            Param {
                label: I18n.t("clipInspector.strength");
                value <=> root.strength;
                minimum: 0;
                maximum: 1;
                step: 0.01;
                default-value: 1;
                fmt: ParamFormat.fraction;
                unit: "%";
                unit-scale: 100;
                changed(v) => { root.set(ClipField.opacity, v); root.commit(); }
            }
        }
    }

    Section {
        ramps := SectionHeader {
            title: I18n.t("clipInspector.ramps");
            collapsible: true;
            summary: (root.fade-in == 0 && root.fade-out == 0) ? I18n.t("common.none")
                : InspectorFmt.format(ParamFormat.seconds2, root.fade-in)
                + " / " + InspectorFmt.format(ParamFormat.seconds2, root.fade-out);
        }

        if ramps.open: SectionBody {
            Param {
                label: I18n.t("clipInspector.rampIn");
                value <=> root.fade-in;
                minimum: 0;
                maximum: root.ramp-limit;
                step: 0.05;
                fmt: ParamFormat.seconds2;
                unit: "s";
                changed(v) => { root.set(ClipField.fade-in, v); root.commit(); }
            }

            Param {
                label: I18n.t("clipInspector.rampOut");
                value <=> root.fade-out;
                minimum: 0;
                maximum: root.ramp-limit;
                step: 0.05;
                fmt: ParamFormat.seconds2;
                unit: "s";
                changed(v) => { root.set(ClipField.fade-out, v); root.commit(); }
            }
        }
    }
}

// The catalogues. Data only: the stack renders whatever params a preset
// declares, so adding a processor is one entry here and no change to the
// panel. The ids are written into project files, so they are stable forever.